diff --git a/.github/scripts/pack-package.sh b/.github/scripts/pack-package.sh new file mode 100755 index 00000000..a215f9d3 --- /dev/null +++ b/.github/scripts/pack-package.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash +# Pack the product's package directory exactly as distributed, the module +# channel's input (TEST-SPEC H-2 and C-2; SPEC 7.6: the defineConfig module is +# distributed as a package, and the package directory, exactly as distributed, +# is given to the harness beside the executable). +# +# Usage: pack-package.sh +# +# must be absent or an empty directory. The script packs the +# repository's built product with `npm pack`, which makes the tarball +# `npm publish` uploads (.github/workflows/release.yml), into , +# extracts that tarball there, and prints the package directory, +# /package, on standard output: exactly what the distribution +# carries, with nothing installed into it, and never the development tree, +# whose own node_modules would resolve inside a placed copy (H-2). The tarball +# stays beside it. Build the product first (npm run build): the package +# carries dist/. +# +# The harness reads the package directory from the XSPEC_PACKAGE_DIR +# environment variable: CI sets it from this script's output. Unset, no +# package directory is given, and every test of 7.6 fails as the missing +# product does (H-8). +set -euo pipefail + +me=pack-package.sh + +fail() { + echo "$me: $*" >&2 + exit 1 +} + +[ $# -eq 1 ] || fail "usage: $me " +out=$1 +if [ -e "$out" ] || [ -L "$out" ]; then + if [ -L "$out" ] || [ ! -d "$out" ] || [ -n "$(ls -A "$out")" ]; then + fail "$out exists and is not an empty directory" + fi +else + mkdir -p "$out" +fi +out=$(cd "$out" && pwd -P) + +root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P) +[ -f "$root/dist/cli/bin.js" ] || + fail "no built product at $root/dist (run npm run build first)" + +report=$(cd "$root" && npm pack --json --pack-destination "$out") || + fail "npm pack failed" +tarball=$(node -e ' + const report = JSON.parse(process.argv[1]); + if (!Array.isArray(report) || report.length !== 1 || typeof report[0].filename !== "string") { + throw new Error("unexpected npm pack report"); + } + console.log(report[0].filename); +' "$report") || fail "cannot read npm pack's report" +[ -f "$out/$tarball" ] || fail "npm pack wrote no $out/$tarball" + +tar -xzf "$out/$tarball" -C "$out" --no-same-owner +package="$out/package" +[ -f "$package/package.json" ] || fail "$tarball holds no package/package.json" +node -e ' + const fs = require("node:fs"); + const packed = JSON.parse(fs.readFileSync(process.argv[1], "utf8")); + const source = JSON.parse(fs.readFileSync(process.argv[2], "utf8")); + if (packed.name !== source.name) { + throw new Error("the packed manifest names " + packed.name + " where the repository manifest names " + source.name); + } +' "$package/package.json" "$root/package.json" || fail "the packed manifest does not match the repository's" +echo "$package" diff --git a/.github/scripts/provision-node-releases.sh b/.github/scripts/provision-node-releases.sh new file mode 100755 index 00000000..8e489ae2 --- /dev/null +++ b/.github/scripts/provision-node-releases.sh @@ -0,0 +1,98 @@ +#!/usr/bin/env bash +# Provision the Node.js releases on which the module channel loads the +# defineConfig module (TEST-SPEC E-1 and H-2's module channel; T7.6-6, T7.6-7, +# P-17, S-10; SPEC 7.6), at setup, while the network is still available. +# +# Usage: provision-node-releases.sh +# +# must be absent or an empty directory. The releases are the ones +# test/node-releases.json lists: E-1's list, pinned by exact version. Each is +# installed exactly as nodejs.org distributes it for this platform, at +# /v/, so its executable is /v/bin/node. +# Each archive is checked against the release's published SHA-256 sum, and each +# executable against the version it reports, before the next release is +# fetched. The archives and the sums files stay in /archives/. +# +# The harness finds the releases through the XSPEC_NODE_RELEASES_DIR +# environment variable, naming : CI sets it right after this step. +# No test downloads a runtime, so the runs that need these releases stay +# network-denied (E-1), and a listed release left unprovisioned is a harness +# error for every run needing it (E-1, H-11), never a skip or a product +# failure. Failures here are loud for the same reason. +# +# Linux only: E-1 exercises these releases on the Linux leg alone. +set -euo pipefail + +me=provision-node-releases.sh + +fail() { + echo "$me: $*" >&2 + exit 1 +} + +[ $# -eq 1 ] || fail "usage: $me " +out=$1 +if [ -e "$out" ] || [ -L "$out" ]; then + if [ -L "$out" ] || [ ! -d "$out" ] || [ -n "$(ls -A "$out")" ]; then + fail "$out exists and is not an empty directory" + fi +else + mkdir -p "$out" +fi +out=$(cd "$out" && pwd -P) + +here=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P) +list="$here/../../test/node-releases.json" +[ -f "$list" ] || fail "no release list at $list" + +case "$(uname -s)-$(uname -m)" in + Linux-x86_64) platform=linux-x64 ;; + Linux-aarch64) platform=linux-arm64 ;; + *) fail "no Node.js release archive for $(uname -s) $(uname -m): E-1 provisions these releases on Linux alone" ;; +esac + +# The list's releases, one per line, each an exact version listed once. +releases_text=$(node -e ' + const fs = require("node:fs"); + const list = JSON.parse(fs.readFileSync(process.argv[1], "utf8")); + const releases = list.releases; + if (!Array.isArray(releases) || releases.length === 0) { + throw new Error("no releases listed"); + } + for (const release of releases) { + if (typeof release !== "string" || !/^[0-9]+[.][0-9]+[.][0-9]+$/.test(release)) { + throw new Error("not an exact version: " + JSON.stringify(release)); + } + } + if (new Set(releases).size !== releases.length) { + throw new Error("a release is listed twice"); + } + for (const release of releases) console.log(release); +' "$list") || fail "cannot read the release list $list" +mapfile -t releases <<<"$releases_text" + +fetch() { + curl -fsSL --retry 5 --retry-all-errors --connect-timeout 30 -o "$2" "$1" || + fail "cannot download $1" +} + +mkdir "$out/archives" +for version in "${releases[@]}"; do + archive="node-v$version-$platform.tar.xz" + base="https://nodejs.org/dist/v$version" + sums="$out/archives/SHASUMS256-v$version.txt" + fetch "$base/$archive" "$out/archives/$archive" + fetch "$base/SHASUMS256.txt" "$sums" + expected=$(awk -v name="$archive" '$2 == name { print $1 }' "$sums") + [ -n "$expected" ] || fail "$base/SHASUMS256.txt publishes no SHA-256 sum for $archive" + actual=$(sha256sum "$out/archives/$archive" | awk '{ print $1 }') + [ "$actual" = "$expected" ] || + fail "$archive has SHA-256 $actual where $base/SHASUMS256.txt publishes $expected" + mkdir "$out/v$version" + tar -xJf "$out/archives/$archive" -C "$out/v$version" --strip-components=1 --no-same-owner + node="$out/v$version/bin/node" + [ -x "$node" ] || fail "$archive holds no executable bin/node" + reported=$(env -u NODE_OPTIONS -u NODE_PATH "$node" --version) + [ "$reported" = "v$version" ] || fail "$node reports $reported, expected v$version" + echo "$me: v$version at $node" >&2 +done diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6c7d41b8..390142de 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,14 +5,19 @@ # harness-self Linux. Harness self-tests and certification only (TEST-SPEC # 17, C-1: certification results are part of the harness's CI # output), run through the same wrapper as suite-linux, with -# no product installed: the job builds nothing and confirms -# dist/ absent before they run, so a self-test or -# certification that needs the built product fails here -# (H-8: they must pass before the product exists). This is -# the signal that must be green before the product exists -# (red-green): product-facing tests may still fail while this -# job passes. suite-linux runs the self project again, within -# its full suite, with the product built. +# no product installed: the job builds nothing and packs no +# package directory, and confirms dist/ absent and +# XSPEC_PACKAGE_DIR unset before they run, so a self-test or +# certification that needs the built product or its package +# fails here (H-8: they must pass before the product exists, +# and the module channel counts as part of the product). E-1's +# Node.js releases are provisioned here too (below), for S-10, +# which checks the release driver on each of them before any +# product exists. This is the signal that must be green +# before the product exists (red-green): product-facing tests +# may still fail while this job passes. suite-linux runs the +# self project again, within its full suite, with the product +# built. # # suite-linux Linux. The full suite — sections 1–17, certification # included (E-1) — run through @@ -30,8 +35,10 @@ # outside every product invocation (E-1, H-2). Workspaces # land in /tmp on the image's ext4 root filesystem (TMPDIR # stays unset), whose name-hash listing order T13.5-10(c)'s -# bracketing arm needs. Expected red until the product -# conforms to SPEC.md; green is required from then on. +# bracketing arm needs. The module channel's two inputs are +# set up before the run (below). Expected red until the +# product conforms to SPEC.md; green is required from then +# on. # # suite-windows Windows. The E-6 platform-sensitive subset, the # representative fixture's exclusion probe (13.5's busy @@ -41,6 +48,27 @@ # artifact, exchanged through XSPEC_E6_EXCHANGE_DIR (written # by the harness on the Linux leg, read on the Windows leg). # +# The module channel (TEST-SPEC H-2, C-2, E-1; SPEC 7.6) runs on the Linux leg +# alone. Its inputs are made at setup, while the network is still available, +# and reach the wrapped run unchanged (run-without-network.sh restores the +# caller's environment exactly): +# +# Package directory suite-linux alone. After the build, +# .github/scripts/pack-package.sh packs the product with +# npm pack, the tarball release.yml's npm publish +# uploads, and extracts it under RUNNER_TEMP; +# XSPEC_PACKAGE_DIR names the extracted package +# directory: exactly what the distribution carries, never +# the development tree (H-2). +# Node.js releases Both Linux jobs. .github/scripts/provision-node-releases.sh +# installs each release test/node-releases.json pins (E-1's +# list) under RUNNER_TEMP, each archive checked against +# its published SHA-256 sum, beside the release the suite +# runs on; XSPEC_NODE_RELEASES_DIR names the directory, +# each release's executable at v/bin/node. No +# test downloads a runtime, so those runs stay +# network-denied (E-1). +# # Local-only tests (E-2) form a separately invocable local suite # (`npm run test:local`) and are deliberately excluded here — never silently # skipped (H-9). That set is currently empty. @@ -68,7 +96,11 @@ jobs: harness-self: name: Harness self-tests + certification (Linux) runs-on: ubuntu-24.04 - timeout-minutes: 20 + # A limit of the CI service, not a harness guard (TEST-SPEC S-3). The job + # took 6.5 minutes at 3d8e7ad, before S-10's checks on E-1's six Node.js + # releases and S-4's checks of 7.6's covered setups, and 9.4 at d0ccc8f + # with them, its setup provisioning those releases: 31% of this limit. + timeout-minutes: 30 steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -76,6 +108,10 @@ jobs: node-version: 22 cache: npm - run: npm ci + - name: Provision E-1's Node.js releases (S-10; at setup, before the network is disabled) + run: | + bash .github/scripts/provision-node-releases.sh "$RUNNER_TEMP/node-releases" + echo "XSPEC_NODE_RELEASES_DIR=$RUNNER_TEMP/node-releases" >> "$GITHUB_ENV" - name: Typecheck both programs (product and harness) run: npm run typecheck - name: Confirm no product is installed (H-8; self-tests and certification run before the product exists) @@ -84,20 +120,31 @@ jobs: echo "::error::dist/ exists, but this job runs the harness self-tests and certification with no product installed (TEST-SPEC H-8)" exit 1 fi + if [ -n "${XSPEC_PACKAGE_DIR+set}" ]; then + echo "::error::XSPEC_PACKAGE_DIR is set, but this job gives the harness no package directory: the module channel counts as part of the product (TEST-SPEC H-8)" + exit 1 + fi - name: Run harness self-tests and certification (network disabled, unprivileged, administrative access kept) run: bash .github/scripts/run-without-network.sh npm run test:self suite-linux: name: Full suite (Linux, E-1) runs-on: ubuntu-24.04 - # A limit of the CI service, not a harness guard (TEST-SPEC S-3). The - # suite's Vitest run took 1099.5 s at 3bb3df8 on one hosted-runner class - # and 1951.3-2015.5 s at 80b83aa and f22cc77 on another (transform and - # import times scaling alike; the job up to 34 minutes), before the - # refined TEST-SPEC's twenty new tests, P-16, and the new arms of - # existing tests (T13.3-5(a)'s seeded tampering trials among them) are - # implemented; 90 minutes leaves room for both classes. - timeout-minutes: 90 + # A limit of the CI service, not a harness guard (TEST-SPEC S-3): the job + # is held to GitHub's own per-job limit for hosted runners, 6 hours, and + # to nothing shorter. It took up to 34 minutes at f22cc77 and 46.5 at + # 3d8e7ad, before IP 0002's tests of SPEC 7.6, and 51.4 at d0ccc8f with + # them (14% of this limit), against a product not yet meeting 7.6, each + # of those tests stopping at its first failing setup or run. Against a + # conforming product they type-check every arm in all 173 of 7.6's + # covered setups, a fresh TypeScript 5.9.3 program over a covered file + # taking about 1 s where the scaffold measured it, and load the module on + # each of E-1's six Node.js releases: about 9 minutes more of test time, + # measured locally against a conforming stand-in package. A shorter limit + # could stop a conforming run. Where the suite outgrows the service's + # limit, E-1 splits it across parallel jobs whose union is the whole + # suite, every verdict reported, never trimming it. + timeout-minutes: 360 steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -105,8 +152,16 @@ jobs: node-version: 22 cache: npm - run: npm ci + - name: Provision E-1's Node.js releases (the module channel's; at setup, before the network is disabled) + run: | + bash .github/scripts/provision-node-releases.sh "$RUNNER_TEMP/node-releases" + echo "XSPEC_NODE_RELEASES_DIR=$RUNNER_TEMP/node-releases" >> "$GITHUB_ENV" - name: Build the product run: npm run build + - name: Pack the product's package directory exactly as distributed (H-2's module channel, C-2) + run: | + package=$(bash .github/scripts/pack-package.sh "$RUNNER_TEMP/xspec-package") + echo "XSPEC_PACKAGE_DIR=$package" >> "$GITHUB_ENV" - name: Run the full suite (network disabled after setup, unprivileged, administrative access kept; E-1) run: bash .github/scripts/run-without-network.sh npm test env: diff --git a/AGENTS.md b/AGENTS.md index f54499d8..c0b52774 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,24 +3,41 @@ Build, test, and run instructions for this repository (nothing else belongs in this file). - Requires Node.js >= 22 and npm. Install dependencies: `npm ci`. -- One npm package (`xspec`) holding two distinct programs: the product under `src/` and the test harness under `test/`. The harness never imports product code; it drives the built `xspec` executable as a subprocess. -- Build the product: `npm run build` — compiles `src/` (TypeScript ESM, `src/tsconfig.json`) to `dist/`; the `xspec` bin is `dist/cli/bin.js`. Run it: `node dist/cli/bin.js`. `tsc` never deletes an output whose source is gone, so a long-lived checkout's untracked `dist/` can hold stale modules — at 32f5c06 three, from the sources 5a4617c removed (`dist/workspace/fast-read.js`, `dist/cli/commands/query-fast.js`, `dist/cli/commands/at-fast.js`), inert while no live module imports them; to test a pristine build as CI does, build in a fresh single-branch clone (`git clone -q --branch claude/xspec-ui-apis-4df8fa --single-branch /home/user/xspec /xspec`, then `npm ci` and `npm run build` there) rather than clearing `dist/`. A hand-staged scratch workspace (an `xspec.config.ts` plus sources, anywhere on disk) needs no `node_modules`: the product resolves the configuration's `import … from "xspec"` itself, so `cd && node /abs/path/to/dist/cli/bin.js build --json` works as is — the quickest way to eyeball a finding's exact location before pinning it in a test. A ready-made configuration for such a workspace is the `E6_CONFIG` template literal in `test/helpers/e6.ts` (main specs under `specs/**/*.mdx`, code under `src/**/*.ts`): copy it verbatim into `xspec.config.ts`. For a baseline-taking command (`impact --base `, `review create --base --name `) the scratch workspace must also be a git repository holding the ref: `git init`, an identity (`git config user.email` and `user.name` — the harness's isolated git configuration does not apply to hand staging), `git add -A && git commit`; a `.xspec/journal` committed at the ref is the baseline's journal, and the working copy's uncommitted edits are the current workspace. +- One npm package (`@modularcloud/xspec`, the name `package.json` carries) holding two distinct programs: the product under `src/` and the test harness under `test/`. The harness never imports product code; it drives the built `xspec` executable as a subprocess, and reaches the `defineConfig` module (SPEC 7.6) only through TEST-SPEC H-2's module channel: the packed package directory, placed in a staging under a name the test chooses, type-checked by TypeScript 5.9.3 and loaded by E-1's Node.js releases (both inputs below). +- Build the product: `npm run build` — compiles `src/` (TypeScript ESM, `src/tsconfig.json`) to `dist/`; the `xspec` bin is `dist/cli/bin.js`. Run it: `node dist/cli/bin.js`. The package's root entry is the `defineConfig` module (SPEC 7.6), one file per route that `package.json`'s `exports` names: `import` loads the ES module `dist/index.mjs` (from `src/index.mts`, typed by `dist/index.d.mts`, which the top-level `types` also names for TypeScript's `node10` resolution, which reads no `exports`), and `require` loads the CommonJS module `dist/index.cjs` (from `src/index.cts`, typed by `dist/index.d.cts`), so the module loads through `require` with no option on Node.js 22.0–22.11 as well, where `require` cannot load an ES module. The `import` entry is an `.mjs` file, an ES module by its extension alone: a `.js` entry is one only through the manifest's `"type": "module"`, which Node.js never reads for the package installed under the name `node_modules` (its package-scope lookup stops at a `package.json` sitting directly in a directory named `node_modules`), and 22.0.0 predates module-syntax detection, so there a `.js` entry fails both `import` routes (SPEC 7.6 covers that name; the Phase 10 plan written at b63b527, Measured at planning 1). `src/tsconfig.json` compiles `.mts` and `.cts` sources; under `tsconfig.base.json`'s `verbatimModuleSyntax` a `.cts` source takes CommonJS forms (`export =`), TypeScript rejecting a top-level `export` modifier on a value there (TS1287). `src/index.cts` (since 809a932) is that CommonJS entry: `src/index.mts`'s type aliases and `defineConfig`'s doc comment byte for byte, a plain `function defineConfig`, and `export = { defineConfig };`, which `tsc` emits as `"use strict";`, the function, and `module.exports = { defineConfig };` with no `__esModule` marker (so a `require` result's one own property is `defineConfig`), typed by a `dist/index.d.cts` assigning `export =` a constant of type `{ defineConfig: typeof defineConfig }`. The two entries must not drift: after editing either, `diff <(sed -n '/^type NonEmpty/,/function defineConfig/p' src/index.mts | sed '$d') <(sed -n '/^type NonEmpty/,/function defineConfig/p' src/index.cts | sed '$d')` prints nothing (119 lines at 809a932). `tsc` never deletes an output whose source is gone, so a long-lived checkout's untracked `dist/` can hold stale modules — at 32f5c06 three, from the sources 5a4617c removed (`dist/workspace/fast-read.js`, `dist/cli/commands/query-fast.js`, `dist/cli/commands/at-fast.js`), inert while no live module imports them, and, since ad60726 renamed `src/index.ts` to `src/index.mts`, `dist/index.js` and `dist/index.d.ts`, inert too, as no route of `package.json` names them (a package packed from such a checkout still carries them); to test a pristine build as CI does, build in a fresh single-branch clone (`git clone -q --branch --single-branch /home/user/xspec /xspec`, then `npm ci` and `npm run build` there) rather than clearing `dist/`. A hand-staged scratch workspace (an `xspec.config.ts` plus sources, anywhere on disk) needs no `node_modules`: the product reads the configuration statically and never resolves its import's specifier (SPEC 7), so `cd && node /abs/path/to/dist/cli/bin.js build --json` works as is — the quickest way to eyeball a finding's exact location before pinning it in a test. A ready-made configuration for such a workspace is the `E6_CONFIG` template literal in `test/helpers/e6.ts` (main specs under `specs/**/*.mdx`, code under `src/**/*.ts`): copy it verbatim into `xspec.config.ts`. For a baseline-taking command (`impact --base `, `review create --base --name `) the scratch workspace must also be a git repository holding the ref: `git init`, an identity (`git config user.email` and `user.name` — the harness's isolated git configuration does not apply to hand staging), `git add -A && git commit`; a `.xspec/journal` committed at the ref is the baseline's journal, and the working copy's uncommitted edits are the current workspace. - The built product enables Node's on-disk V8 compile cache (`node:module` `enableCompileCache`; default directory under the OS temp dir, e.g. `/tmp/node-compile-cache`) — in the bin, and since the d2655e3 plan's FIX_PLAN Task 164 also in a call-stack rerun's worker thread before it loads the module graph again (`src/cli/rerun-worker.ts`; the bullet beginning "Hand-probing call-stack depth"). The first invocations after `npm run build` repopulate it, so one-off CLI timings are slower than steady state; the cache affects timing only, never output. Steady-state per-invocation medians on this sandbox at FIX_PLAN Task 7 of the Phase 10 plan written at 6694886 (a two-file spec workspace with a current store): `version` ~66 ms, `inventory` ~220 ms, and ~345–395 ms for every command that analyzes the sources — `at` and `query` included, which no longer answer from the store (Task 7 retired that fast path: ~185 ms before, the read SPEC 13.3 forbids). That cost is mostly module loading: Node's start ~35 ms; the TypeScript compiler ~120 ms (loaded through `createRequire` in `src/core/ts-module.ts` — importing that CJS file through the ESM loader instead costs ~0.2 s more per invocation in format sniffing and named-export lexing; keep any new `typescript` use routed through that module); the MDX toolchain ~75 ms and the product's own modules ~35 ms; then the configuration's parse ~20 ms (its syntax check reads a no-emit single-file program's diagnostics — `ts.transpileModule` spent ~65 ms there, mostly on an emit nothing read) and the analysis, derivation, and store comparison ~55 ms. A module statically imported from `src/cli/main.ts` loads for every command, `version` included (the fast path's imports cost each ~110 ms) — the numbers that matter when a test sweeping many CLI invocations nears its timeout. - Typecheck both programs: `npm run typecheck` (`src/tsconfig.json`, then `test/tsconfig.json`; the harness is not typechecked by Vitest at run time). `test/fixtures/` is excluded from the harness typecheck: fixture projects are data compiled or executed at test run time and may contain deliberate type errors (e.g. the S-4 fixture project's `type-error.ts`, `import-conflict.ts`, `import-duplicate.ts`, and `companion-error.d.ts`, and its five module-settings detection modules — `export-assignment.ts`, `import-assignment.ts`, `type-reexport.ts`, `type-import.ts`, and `top-level-await.ts` — each rejected under one of TEST-SPEC H-2's two configurations and accepted under the other). -- Consumer fixture programs are compiled through the harness's TypeScript tooling driver (`test/helpers/tooling.ts`), whose compiler and language service are the harness's own devDependency `typescript-5.9.3` — `npm ci` (dev dependencies included) must have run for consumer compilation to work. The driver serves TEST-SPEC H-2's two fixed configurations and nothing else: `COMMONJS_CONFIGURATION` (`strict`, `target` ESNext, `module` CommonJS under its default `node10` resolution) and `ES_MODULE_CONFIGURATION` (`strict`, `target` ESNext, `module` ESNext, `moduleResolution` bundler, `isolatedModules`, `verbatimModuleSyntax`), every other option at TypeScript 5.9.3's default — no `skipLibCheck`, `types`, or `typeRoots`. `ConsumerProject.load({ rootDir, rootFiles, configuration })` requires one of the two exactly and refuses any other option (a plain `Error`); `forEachConsumerProject` loads and asserts under each in turn, every diagnosis naming its configuration; verdicts `assertTypeChecksClean` (no diagnostic of any category anywhere in the program, generated modules and companions included) and `assertTypeErrorsAt` (every diagnostic at an expected position, each position covered by an error); runtime `withCompiledConsumer(project, context, (compiled) => compiled.run("src/app.ts"))`, under the CommonJS configuration alone. The NodeNext path the driver kept until the plan written at 2a2b94e's FIX_PLAN Task 27 (`defaultConsumerCompilerOptions`, an unconfigured project, `assertNoCompileErrors`, `assertCompileErrorAt`, `ConsumerProject.emit`, `ConsumerProject.errors`, an exported `runConsumer`) is gone, so no consumer reaches another configuration. Under H-2 nothing supplies `@types/node`: a consumer program writes through `console.log` / `console.error` (ESNext's default library declares `console`) or declares what it reads of `process` itself (`declare const process: { readonly argv: readonly string[] };`, module-scoped in a file holding an import or export). A project's root, and the runtime output directory, must have no `node_modules` entry in any ancestor (`HarnessStagingError`, mode `consumer-isolation`, otherwise), so a fixture project under this repository is compiled from a copy in a `TestWorkspace` (S-4's `stageFixtureProject`), never in place. Each program checks the default library too: about 0.25 s to build and 0.45 s to check a small program on this machine, so a verdict under both configurations costs about 1.4 s, and the S-4 file's 49 tests take ~45 s alone (43.6 s at that Task 27). The runtime output is the compiler's alone — the program's CommonJS JavaScript, the project root's layout kept below it — written into a fresh `xspec-consumer-out-*` directory under the OS temporary directory, outside the workspace, run there under plain Node, and removed afterwards: a product-written plain `.js` file beside a source is no compiler output and never reaches it. From that plan's Task 23 until the re-descent plan written at e049255's FIX_PLAN Task 4 the built product's runtime was such a file (`NAME.xspec.impl.js` beside `NAME.xspec.impl.d.ts`), so a compiled consumer of it type-checked clean under both configurations and then died with `Cannot find module './A.xspec.impl.js'` (exit 1). Since that Task 4 the generated module `NAME.xspec.ts` is the runtime itself (the consumer's compiler emits `NAME.xspec.js` from it beside the consumer's output; ES5 library only, no `Symbol` or `WeakMap`), typed through local aliases of import types naming the interfaces in `NAME.xspec.impl.d.ts` (an `import type` declaration instead draws TS9026 under `isolatedDeclarations` with `declaration`, the companion augmenting the module), whose `declare module "./NAME.xspec" { namespace root {} }` merges the root's documented declaration — declaration-mapped to offset 0 of the `.mdx` — into the module's `root` export (the default export is `export { root as default }`; a default export cannot be augmented): three generated files per source (`NAME.xspec.ts`, `NAME.xspec.impl.d.ts`, `NAME.xspec.impl.d.ts.map`), a rebuild removing a recorded `.impl.js` as an orphan. To check the generated files under configurations beyond H-2's, drive `ts.createLanguageService` from `node_modules/typescript-5.9.3` over a scratch workspace the built product built (a CommonJS script outside the repository, one host per configuration: `program` diagnostics, `getDefinitionAtPosition` mapped through `getSourceMapper().tryGetSourcePosition`, `getQuickInfoAtPosition`, and `program.emit` into a fresh directory run under `node`): at that Task 4 the two H-2 configurations, the release's defaults (`strict` alone: target ES5, CommonJS), ES5 with `lib` es5, ES2015, a pedantic set (`noUnusedLocals`, `noUnusedParameters`, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`, `noPropertyAccessFromIndexSignature`, `noImplicitReturns`, `noImplicitOverride`), `isolatedDeclarations` with `declaration`, `nodenext`, classic resolution (`module` ESNext alone), `module` preserve, and `erasableSyntaxOnly` all carried no diagnostic, every root reference's definitions being the module's `root` constant (unmapped) and the augmentation's namespace (mapped to offset 0). Every consumer test takes H-2's configurations: since that plan's Task 24 the §1–§2 consumer tests (`section-1.1-1.2.ts`, `section-1.4.ts`, `section-1.6-1.7.ts`, `section-2.4.ts`: every verdict through `forEachConsumerProject`, T1.1-2's skeleton reads through `forEachConfiguration` with a project loaded per configuration, each runtime arm a CommonJS project's `withCompiledConsumer`), since its Task 25 the §4 consumer tests (`section-4.ts`, `section-4.1-4.2.ts`, `section-4.3-4.4.ts`, `section-4.5.ts`: T4-3, T4-4, T4.1-1–T4.1-3, T4.2-3, T4.2-4 — its definitions and hovers under each configuration too — T4.3-1, T4.4-1, T4.4-2, and T4.5-1, every stdout-writing consumer declaring `process` as T1.2-2's does; T4.4-1's facet-4 consumer, carrying its expected type error, still compiles through `withCompiledConsumer`, a semantic diagnostic being no emit diagnostic), since its Task 26 T13.1-2 (`section-13.1-13.2.ts`: its clean verdict, missing-path type error, definitions, and hovers under each configuration in turn through `forEachConfiguration`, a project loaded per configuration, before its CommonJS runtime arm), and since its Task 27 the §6.5 and §14 consumers (`section-6.5.ts`'s T6.5-9, `section-6.5-ii.ts`'s T6.5-11 — its (d) one type-error assertion at the type alias's `O` alone — `section-6.5-iii.ts`'s T6.5-18, `section-6.5-v.ts`'s T6.5-23(c), and `section-14.ts`'s T14-2 — its two unresolved references one type-error assertion — every premise and post-move compile under each configuration through `forEachConsumerProject`); against the built product every consumer test passes since the e049255 plan's Task 4 — among them the ten that failed diagnosed at their first runtime arm's exit code before it (exit 1, `Cannot find module './.xspec.impl.js'`): T1.2-2 and T1.6-3 (since that Task 24), T4-3, T4.1-3, T4.3-1, T4.4-1, T4.4-2, and T4.5-1 (since Task 25), T13.1-2 (since Task 26), and T4.1-1 (since Task 36, at its built-in-member runtime arm), at that Task 4 ~3.8 s, ~8.4 s, ~6.2 s, ~6.0 s, ~5.4 s, ~7.2 s, ~6.2 s, ~7.6 s, ~8.6 s, and ~12.2 s in one run of the seven files `section-1.1-1.2`, `section-1.6-1.7`, `section-4`, `section-4.1-4.2`, `section-4.3-4.4`, `section-4.5`, and `section-13.1-13.2` (41 tests, all passing, 109.7 s under the `unshare --map-user` recipe) — and Task 27's five (T6.5-9 ~7 s, T6.5-11 ~30 s, T6.5-18 ~20 s, T6.5-23 ~57 s, T14-2 ~4 s, alone). +- Consumer fixture programs are compiled through the harness's TypeScript tooling driver (`test/helpers/tooling.ts`), whose compiler and language service are the harness's own devDependency `typescript-5.9.3` — `npm ci` (dev dependencies included) must have run for consumer compilation to work. The driver serves TEST-SPEC H-2's two fixed configurations and nothing else: `COMMONJS_CONFIGURATION` (`strict`, `target` ESNext, `module` CommonJS under its default `node10` resolution) and `ES_MODULE_CONFIGURATION` (`strict`, `target` ESNext, `module` ESNext, `moduleResolution` bundler, `isolatedModules`, `verbatimModuleSyntax`), every other option at TypeScript 5.9.3's default — no `skipLibCheck`, `types`, or `typeRoots`. `ConsumerProject.load({ rootDir, rootFiles, configuration })` requires one of the two exactly and refuses any other option (a plain `Error`); `forEachConsumerProject` loads and asserts under each in turn, every diagnosis naming its configuration; verdicts `assertTypeChecksClean` (no diagnostic of any category anywhere in the program, generated modules and companions included) and `assertTypeErrorsAt` (every diagnostic at an expected position, each position covered by an error); runtime `withCompiledConsumer(project, context, (compiled) => compiled.run("src/app.ts"))`, under the CommonJS configuration alone. The NodeNext path the driver kept until the plan written at 2a2b94e's FIX_PLAN Task 27 (`defaultConsumerCompilerOptions`, an unconfigured project, `assertNoCompileErrors`, `assertCompileErrorAt`, `ConsumerProject.emit`, `ConsumerProject.errors`, an exported `runConsumer`) is gone, so no consumer reaches another configuration. Under H-2 nothing supplies `@types/node`: a consumer program writes through `console.log` / `console.error` (ESNext's default library declares `console`) or declares what it reads of `process` itself (`declare const process: { readonly argv: readonly string[] };`, module-scoped in a file holding an import or export). Since the plan written at e57210b's FIX_PLAN Task 8, H-1's isolation is one shared check, `verifyStagingIsolation` (`test/helpers/staging-isolation.ts`; the module channel's stagings are to call it too, with a staging root and, for Node.js runs, their exact environment, working directory, and executables), and refuses (`HarnessStagingError`, mode `consumer-isolation` for consumers): an entry named `package.json` or `node_modules` of any kind (by `lstat`, a dangling link counting) in any ancestor of a project's root or of the runtime output directory, along the spelled and the physical path; a `node_modules` entry in the root itself (T13.1-2); and, before each run, any entry at all in one of Node.js's global module folders under the run's exact environment (its `NODE_PATH` entries, `$HOME/.node_modules`, `$HOME/.node_libraries`, `lib/node` under each executable's prefix, spelled and physical). Only `ENOENT`/`ENOTDIR` count as absence; any other failed examination leaves it unverified, a refusal too. Each `compiled.run` gets a fresh, empty `HOME` (`xspec-consumer-home-*` under the OS temporary directory, `USERPROFILE` too on Windows, removed once the run ends) with `NODE_PATH` dropped; a run's own `env` is merged last (only S-4's probes set one, staging `HOME` or `NODE_PATH` to a global folder the check must refuse). So a fixture project under this repository is compiled from a copy in a `TestWorkspace` (S-4's `stageFixtureProject`), never in place. In this sandbox `/package.json`, `/tmp/package.json`, `/tmp/node_modules`, and `/opt/node22/lib/node` are absent, so the precondition holds for workspaces under `/tmp`. Each program checks the default library too: about 0.25 s to build and 0.45 s to check a small program on this machine, so a verdict under both configurations costs about 1.4 s, and the S-4 file's 51 tests take ~85 s alone on this machine at the e57210b plan's Task 8 (its two run-driven isolation tests ~3.4 s each; the 49 before it took ~88 s on the same machine, ~45 s, 43.6 s, at that Task 27). The runtime output is the compiler's alone — the program's CommonJS JavaScript, the project root's layout kept below it — written into a fresh `xspec-consumer-out-*` directory under the OS temporary directory, outside the workspace, run there under plain Node, and removed afterwards: a product-written plain `.js` file beside a source is no compiler output and never reaches it. From that plan's Task 23 until the re-descent plan written at e049255's FIX_PLAN Task 4 the built product's runtime was such a file (`NAME.xspec.impl.js` beside `NAME.xspec.impl.d.ts`), so a compiled consumer of it type-checked clean under both configurations and then died with `Cannot find module './A.xspec.impl.js'` (exit 1). Since that Task 4 the generated module `NAME.xspec.ts` is the runtime itself (the consumer's compiler emits `NAME.xspec.js` from it beside the consumer's output; ES5 library only, no `Symbol` or `WeakMap`), typed through local aliases of import types naming the interfaces in `NAME.xspec.impl.d.ts` (an `import type` declaration instead draws TS9026 under `isolatedDeclarations` with `declaration`, the companion augmenting the module), whose `declare module "./NAME.xspec" { namespace root {} }` merges the root's documented declaration — declaration-mapped to offset 0 of the `.mdx` — into the module's `root` export (the default export is `export { root as default }`; a default export cannot be augmented): three generated files per source (`NAME.xspec.ts`, `NAME.xspec.impl.d.ts`, `NAME.xspec.impl.d.ts.map`), a rebuild removing a recorded `.impl.js` as an orphan. To check the generated files under configurations beyond H-2's, drive `ts.createLanguageService` from `node_modules/typescript-5.9.3` over a scratch workspace the built product built (a CommonJS script outside the repository, one host per configuration: `program` diagnostics, `getDefinitionAtPosition` mapped through `getSourceMapper().tryGetSourcePosition`, `getQuickInfoAtPosition`, and `program.emit` into a fresh directory run under `node`): at that Task 4 the two H-2 configurations, the release's defaults (`strict` alone: target ES5, CommonJS), ES5 with `lib` es5, ES2015, a pedantic set (`noUnusedLocals`, `noUnusedParameters`, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`, `noPropertyAccessFromIndexSignature`, `noImplicitReturns`, `noImplicitOverride`), `isolatedDeclarations` with `declaration`, `nodenext`, classic resolution (`module` ESNext alone), `module` preserve, and `erasableSyntaxOnly` all carried no diagnostic, every root reference's definitions being the module's `root` constant (unmapped) and the augmentation's namespace (mapped to offset 0). Every consumer test takes H-2's configurations: since that plan's Task 24 the §1–§2 consumer tests (`section-1.1-1.2.ts`, `section-1.4.ts`, `section-1.6-1.7.ts`, `section-2.4.ts`: every verdict through `forEachConsumerProject`, T1.1-2's skeleton reads through `forEachConfiguration` with a project loaded per configuration, each runtime arm a CommonJS project's `withCompiledConsumer`), since its Task 25 the §4 consumer tests (`section-4.ts`, `section-4.1-4.2.ts`, `section-4.3-4.4.ts`, `section-4.5.ts`: T4-3, T4-4, T4.1-1–T4.1-3, T4.2-3, T4.2-4 — its definitions and hovers under each configuration too — T4.3-1, T4.4-1, T4.4-2, and T4.5-1, every stdout-writing consumer declaring `process` as T1.2-2's does; T4.4-1's facet-4 consumer, carrying its expected type error, still compiles through `withCompiledConsumer`, a semantic diagnostic being no emit diagnostic), since its Task 26 T13.1-2 (`section-13.1-13.2.ts`: its clean verdict, missing-path type error, definitions, and hovers under each configuration in turn through `forEachConfiguration`, a project loaded per configuration, before its CommonJS runtime arm), and since its Task 27 the §6.5 and §14 consumers (`section-6.5.ts`'s T6.5-9, `section-6.5-ii.ts`'s T6.5-11 — its (d) one type-error assertion at the type alias's `O` alone — `section-6.5-iii.ts`'s T6.5-18, `section-6.5-v.ts`'s T6.5-23(c), and `section-14.ts`'s T14-2 — its two unresolved references one type-error assertion — every premise and post-move compile under each configuration through `forEachConsumerProject`); against the built product every consumer test passes since the e049255 plan's Task 4 — among them the ten that failed diagnosed at their first runtime arm's exit code before it (exit 1, `Cannot find module './.xspec.impl.js'`): T1.2-2 and T1.6-3 (since that Task 24), T4-3, T4.1-3, T4.3-1, T4.4-1, T4.4-2, and T4.5-1 (since Task 25), T13.1-2 (since Task 26), and T4.1-1 (since Task 36, at its built-in-member runtime arm), at that Task 4 ~3.8 s, ~8.4 s, ~6.2 s, ~6.0 s, ~5.4 s, ~7.2 s, ~6.2 s, ~7.6 s, ~8.6 s, and ~12.2 s in one run of the seven files `section-1.1-1.2`, `section-1.6-1.7`, `section-4`, `section-4.1-4.2`, `section-4.3-4.4`, `section-4.5`, and `section-13.1-13.2` (41 tests, all passing, 109.7 s under the `unshare --map-user` recipe) — and Task 27's five (T6.5-9 ~7 s, T6.5-11 ~30 s, T6.5-18 ~20 s, T6.5-23 ~57 s, T14-2 ~4 s, alone). With the e57210b plan's Task 8 isolation (a fresh `HOME` per run, the `package.json` and global-folder checks) all of them still pass against the built product: the nine files `section-1.1-1.2`, `section-1.4`, `section-1.6-1.7`, `section-2.4`, `section-4`, `section-4.1-4.2`, `section-4.3-4.4`, `section-4.5`, and `section-13.1-13.2` (52 tests) in 178.5 s in one run, and the five in 111.9 s in one run of their files with `-t 'T6.5-9 |T6.5-11 |T6.5-18 |T6.5-23 |T14-2 '`. - Two copies of TypeScript 5.9.3 (the release SPEC 14.20 fixes) are installed: the product's `typescript` dependency, pinned exactly, and the harness's own devDependency `typescript-5.9.3`, an npm alias of `typescript@5.9.3`. Harness code imports `typescript-5.9.3`, never `typescript` — the tooling driver and S-4 do, and so must S-9's TypeScript well-formedness check (its parser must be a harness dependency independent of the product) and any other harness use; product code keeps reaching `typescript` through `src/core/ts-module.ts`. npm cannot list one package name in both dependency sets (the devDependencies entry would replace the product's), hence the alias. After a clean `npm ci`, `node_modules/.bin/tsc` is the product's copy; an incremental `npm install` may relink it to the alias — the bytes are identical either way. -- Full test suite (TEST-SPEC sections 1–17, certification included; the Linux CI leg): `npm test`. Build the product first — tests invoke the built executable. Without a build (`dist/cli/bin.js` absent), every product-facing test fails as a diagnosed `HarnessAssertionError` naming that path, before anything is spawned (H-8's no-product run: `builtProductBinding()` in `test/helpers/subprocess.ts` sets `missingFilesFailDiagnosed`, so its missing artifact is the missing product; `builtProductBindingAt()` is the same binding at another artifact path), each `checkProperty` property (P-1 to P-14) reported as drawn at its first trial with its seed, never shrunk (the failure declines shrinking); any other binding's missing file — a certification fixture's, the S-7 stub's, a compiled consumer's, a temporary runner's scratch build — stays a plain-`Error` harness error (C-1: an unbuilt fixture is a harness defect, never a certified failure), which the certification runner reports as `error`. Measured at the affd85f plan's FIX_PLAN Task 4, under `unshare --map-user` with `NODE_OPTIONS` unset: `test/suite/section-1.1-1.2.test.ts`, `section-16-p1.test.ts`, and `e6-exchange-writer.test.ts` with no build ran 8 tests, all failing so (P-1 "falsified with seed 271828183 (trial 1 of 25)", reported as drawn), in 6.71 s; the certification runner over every registered body and S-7's six layer-4 bodies against `builtProductBindingAt()` ended 352 and 6 `fail`, every diagnosis naming the path, in 7.9 s, and against the unflagged binding of the same shape 348 and 6 `error`, with `fail` for T7-5, T13.4-12, T13.5-6, and P-14 alone (their own conversions of a run's rejection wrap the message). +- The module channel's package directory (TEST-SPEC H-2, C-2; SPEC 7.6): after `npm run build`, `bash .github/scripts/pack-package.sh `, `` absent or an empty directory (a fresh `mktemp -d`), runs `npm pack`, which makes the tarball `release.yml`'s `npm publish` uploads, into ``, extracts it there, and prints the package directory, `/package`: exactly what the distribution carries (`package.json`, `README.md`, `LICENSE`, and `dist/`), with nothing installed into it, never the development tree, whose own `node_modules` would resolve inside a placed copy (H-2). The tarball stays beside it. The harness takes that path from `XSPEC_PACKAGE_DIR` (`export XSPEC_PACKAGE_DIR="$(bash .github/scripts/pack-package.sh )"`), read when the built product's binding is made: `builtProductBinding()` (`test/helpers/subprocess.ts`, the variable's name exported as `PACKAGE_DIR_VARIABLE`) carries it, exactly as spelled, as the binding's `packageDir`, which every body receives unchanged (through `test/suite/declare.ts`, and `runProductTests` in `test/self/certification-runner.ts`); CI's full-suite job sets it after its build. Unset or empty, no package directory is given (no `packageDir`, as on `builtProductBindingAt()` and on every CERTIFICATIONS.md fixture's binding, which `test/self/certification-document.test.ts` pins), and every test of 7.6 fails as H-8's missing product does. The self project runs with the variable set in CI's full-suite job and unset in harness-self, so a self-test pinning the built binding's shape passes it an explicit environment (`builtProductBinding({})`, as `test/self/s3-subprocess-driver.test.ts` does), never the ambient one. The directory is a snapshot of one build, packed from whatever `dist/` holds (a long-lived checkout's stale modules included, as the build bullet above notes): after rebuilding, pack again into a fresh ``. The script refuses a non-empty one, so nothing is ever cleared. +- E-1's Node.js releases (TEST-SPEC E-1, S-10; T7.6-6, T7.6-7, P-17): `test/node-releases.json` pins E-1's list — 22.0.0, 22.11.0, 22.12.0, 22.23.4, 24.22.2, and 26.13.0, set on 2026-10-29 by E-1's rule — and is the one copy CI and the harness both read, so the releases provisioned and the releases exercised cannot drift; it changes only through the normal change process, with E-1. `bash .github/scripts/provision-node-releases.sh `, `` absent or an empty directory, downloads each release's Linux archive from nodejs.org (the agent proxy passes it in this sandbox), checks it against the release's published `SHASUMS256.txt`, installs it at `/v/`, its executable `/v/bin/node` checked against the version it reports, and keeps the archives in `/archives/`: 37 s and 1.4 GB here for the six. The harness takes `` from `XSPEC_NODE_RELEASES_DIR`, reading it and the list through `test/helpers/node-releases.ts` (from the plan written at e57210b's FIX_PLAN Task 9 on): `readNodeReleaseList` finds `test/node-releases.json` relative to the module, never the working directory, and reads it strictly (one JSON object holding a `releases` array of exact `major.minor.patch` versions, no leading zeros, at least one and none twice, beside at most a string `comment`); `resolveNodeRelease()` and `resolveNodeReleases()` (every listed release, in list order) read the variable only when called, by the run needing a release, never at import, so a test needing none passes with it unset, and answer `{ version, executable: /v/bin/node }`, the path as spelled from the variable; the variable unset, empty, relative, or naming no directory (fault `directory`), a listed release's `bin/node` absent, not a file, or not executable by the harness (fault `release`, naming each such release and the path looked at), and a version the list does not hold or a list it cannot read (fault `list`) each throw `NodeReleaseError`, a harness error that `rethrowHarnessError` lets through, never a skip or a diagnosed failure. Nothing there runs a release: that each executable reports its own version is S-10's check. `test/self/node-releases.test.ts` pins the list to E-1's six releases and those errors on stand-in directories under the OS temporary directory, so it passes alike with the variable set or unset (8 tests, about 1.2 s alone under `unshare --map-user`). Both Linux CI jobs provision at setup, before the network is disabled, so no test downloads a runtime, and a listed release missing there is a harness error for every run needing it (E-1, H-11), never a skip. 7.6's runs carry no `NODE_OPTIONS` or `NODE_PATH` (T7.6-6), and this sandbox's own environment sets `NODE_OPTIONS=--use-openssl-ca`, so unset both for every such run. Each release's global module folders (`require("node:module").globalPaths`) are `$HOME/.node_modules`, `$HOME/.node_libraries`, and `/v/lib/node`; the archives create no `lib/node` (their `lib/node_modules` holds npm and corepack, a folder `require` never searches), so under a fresh `HOME` none holds a package (H-1). In CI the six take about 15 s to provision. +- 7.6's covered setups, probed at the scaffold with a stand-in package in the scratchpad (not product code): a stand-in in the dual-entry layout `package.json` then declared (`import`: an ES module typed by a `.d.ts`, since ad60726 the `.mjs` file `dist/index.mjs` typed by `dist/index.d.mts`; `require`: a CommonJS module typed by a `.d.cts`, written either with ESM-syntax declarations or as `export =`; the top-level `types` for `node10`) type-checked a valid covered file clean, and failed its unknown-top-level-key twin with an error in the file, in all 173 of TEST-SPEC 7.6's setups, the three projects and four extensions included (346 programs each way, TypeScript 5.9.3 through the harness's `typescript-5.9.3`). On each of E-1's six releases its `import` namespace's own string keys and its `require` result's own enumerable keys were exactly `defineConfig`, along static `import` from an `.mjs`, dynamic `import()` from a `.cjs`, and `require`. A fresh program over a covered file took about 1 s with `skipLibCheck` off, so an arm whose 173 programs are all fresh costs about 3 minutes; TEST-SPEC 7.6 lets the files a setup and placement share, the libraries and the package's, be checked once, each case's verdict read from its configuration file's own diagnostics beside theirs. The layout since ad60726 (`import`: `dist/index.mjs` typed by `dist/index.d.mts`, which the top-level `types` also names; `require`: `dist/index.cjs` typed by `dist/index.d.cts`) was measured first with the packed product's `dist/` completed by a scratch CommonJS entry standing in for `src/index.cts` (`"use strict";`, the function, and `module.exports = { defineConfig };`, with a `.d.cts` assigning `export =` a constant typed `{ defineConfig: typeof defineConfig }`): T7.6-1 to T7.6-7, P-17, and P-18 all pass (T7.6-1 9.8 s, T7.6-2 5.1 s, and T7.6-3 285 s of test time, that file alone; `section-7.6-ii` with P-17 and P-18, three files in one 158 s run). Since 809a932 the product's own build emits exactly that entry, and the product built in a fresh clone and packed by `pack-package.sh` passes them all too (each test's bullet gives its time). +- Module-channel stagings (TEST-SPEC §7.6 Placement, H-1, H-2, H-8; from the plan written at e57210b's FIX_PLAN Task 12): `test/helpers/module-channel.ts`. `ModuleStaging.create(binding, context)` checks the binding's package directory before staging anything (`modulePackageDirectory`: none given, or an absent one on the built product's binding, fails diagnosed, declining shrinking, the no-package diagnosis naming the binding's command line so that S-7's no-product sweep, which requires each registered body's diagnosis to name the absent artifact, holds for 7.6's bodies; a relative path, an absent one on any other binding, a non-directory, an entry neither a plain file, a directory, nor a symbolic link, or a `node_modules` entry of any kind at its root — the conservative development-tree refusal — is a `HarnessStagingError` of mode `module-channel`), then makes a fresh `xspec-module-staging-*` directory directly under the OS temporary directory, at its physical path, with H-1's ancestor half verified; `verifyIsolation(run)` repeats it with a Node.js run's exact environment, working directory, and executables before that run. `stageProject(rel, kind)` stages `es-module` (`{"type": "module"}`), `commonjs` (`{}`), or `no-manifest`; `place({ name, holdingDir, arm, form, copyDir })` copies the package entry by entry to `/node_modules/N` (or, form `symlink`, to `placed-copies/copy-` with an absolute link at `node_modules/N`), reads the copy back against the package as checked, and refuses later staging writes into it; `placeCanonical(holdingDir, arm)` places under the canonical N, `staged-config-module` (`staged-config-module-alias` where the manifest names the first); `verifyReach({ importingFile, placement, project, alone })` checks the finished staging (physical naming, the holding directory, nothing nearer, no self-reference, well-formed manifests up to the filesystem root, and, where declared, the project kind and nothing else installed). On a runtime arm (`runtimeArm(releases)`) N is put to each release through `runProduct` (`--eval` of `require("node:module").isBuiltin`), so `fs` is refused there and admitted on `TYPE_CHECKING_ARM`. `readManifestName(dir)` reads the manifest's `name` strictly. `copyDirectory(rel, source)` (from the plan written at e57210b's FIX_PLAN Task 27) copies another package beside a placement entry by entry, modes and links kept, given `source`'s own mode — T7.6-4(e)'s TypeScript package — refused at or below a placement, an occupied `rel` failing. `test/self/module-channel-staging.test.ts` (17 tests, about 3–6 s alone under `unshare --map-user`; it needs `XSPEC_NODE_RELEASES_DIR`) pins it over the committed non-xspec stand-in `test/fixtures/module-channel-standin/`. +- 7.6's TypeScript driver (TEST-SPEC §7.6 Covered setups, Verdict, Pairing; from the plan written at e57210b's FIX_PLAN Task 13): `test/helpers/module-channel-ts.ts`, over `typescript-5.9.3` and separate from H-2's `tooling.ts`. `COVERED_SETUPS` is the 173-setup matrix (`PROJECT_KINDS` × `COVERED_EXTENSIONS` × the 14 `STRICT_DEFAULT_OPTION_SETS`, plus `INITIALIZED_PROJECT_OPTION_SET` for files compiled as ES modules; each set spelled as `tsconfig.json` spells it and nothing else set; its composition checked at module load). `stageCoveredFiles({ staging, directory, project, placement, alone, files: [{ label, text }], setups, currentDirectory, context })` writes each file once per extension as `covered-file-` and verifies Reach for each where a placement is named; its `judge(setup)` returns each file's `CoveredVerdict` (`typeChecks`, `failsToTypeCheck`, `errors` by origin, `programFiles`, the program's `compilerOptions` read back), asserted through `assertTypeChecks(verdict, context)` and `assertShapeViolation(twin, arm, context)`; `judgeUnshared(setup, label)` is the one-root reference reading. T7.6-1's export listing (from the plan written at e57210b's FIX_PLAN Task 18): a request with `listExports: true` gives each verdict an `exportListing` (`{ module, exportAssignment, exports }`, `module` the declaration file TypeScript resolves the file's one import declaration to, undefined where it reads none, e.g. S-7's stub package; `exports` sorted, each `{ name, value, typeOnlyValue, type, namespace, listedIn }`, `listedIn` among `"exports"` and `"export assignment"`), stated by `describeExportListing`; every staged file must then hold exactly one import declaration (otherwise a plain `Error` at `judge`). It is read with public checker calls after the program's diagnostics: `getSymbolAtLocation` on the specifier, `getExportsOfModule` (implicit exports of a declaration module without `export {}` or `export =` included, export stars followed, no synthetic default), and, for an `export =` module, `getPropertiesOfType(getTypeOfSymbol())` minus symbol-keyed and private members (escaped names beginning `__` plus a non-`_`); meanings from symbol flags through `getAliasedSymbol` (an unresolvable alias: every meaning); a value reached only through `export type`, `import type`, or `export type *` is `typeOnlyValue`, not `value` (module-type `getPropertyOfType` not returning the export; for an `export =` module's own exports, a type-only declaration along the alias chain). Probed on TypeScript 5.9.3: the internal `getExportsAndPropertiesOfModule` lists nothing for an `export =` value typed as a class instance (also primitives, arrays, tuples), while a named import binds its members, hence not used; the internal `getTypeOnlyAliasDeclaration` misses `export type *`, which the module-type lookup catches. The program condition is read from TypeScript's internal include reasons (`program.getFileIncludeReasons()`, `ts.FileIncludeKind`, a synthetic import's `pos` -1): an automatic `@types` package, a library an installed `@typescript/lib-*` package replaces (5.9.3's `libReplacement` default looks it up from the current directory), or an implicit `react/jsx-runtime` (which, in an ES-module project, resolves only through an `exports` map) is a `HarnessStagingError` before any verdict. Sharing: TypeScript's libraries parsed once per target; a setup's files batched in one program, one program per file where a file brings in other files, touches the global scope, or augments a module (`declare module "N"` in a root, which would leak into the other roots' verdicts and listings); the libraries' own diagnostics remembered per option set and library list wherever no other file touches the global scope (a package's `declare global` can put errors inside `lib.es5.d.ts`). Measured here under `unshare` (es-module project, 59 setups): a process's first sweep ~13 s (each option set's library check ~0.65 s with `skipLibCheck` off), then ~15 ms per setup plus ~0.5 ms per file in its batch — about 2.6 s per 173-setup sweep plus ~90 ms per further file; writing and Reach ~5.5 ms per written file at 1600 files (Reach's `alone` walks the staging). TypeScript resolves a `.cts` file through the `require` entry under `bundler` too, and the top-level `types` under `node10`. `test/self/module-channel-ts.test.ts` (9 tests, ~61 s alone under `unshare`; non-xspec stand-ins under `test/fixtures/module-channel-ts/`, `listing-meanings` and `listing-instance` serving the listing) pins it, the listing included (readings per entry; batched listings equal to the reference reading's). +- S-4's detections of 7.6's covered setups (TEST-SPEC S-4; from the plan written at e57210b's FIX_PLAN Tasks 14 and 15): `test/self/s4-module-channel.test.ts` (19 tests, ~38 s alone under `unshare`; non-xspec stand-ins `exports-only`, `esm-only`, `dual`, `typed`, `declaration-error`, `implicit-any`, `unexported-return`, `implicit-export`, and `export-assignment`, and the `@types` package `ambient-types`, under `test/fixtures/s4-module-channel/`, documented in its header) judges one construct per detection through `stageCoveredFiles` and `judge`, in each setup its setting decides, both sides: a rejection is every program error lying where the construct begins (line and column computed from the text of the file holding it, the configuration file or the stand-in's declaration file TypeScript resolves; the TypeScript code only a diagnostic aid), an admission the driver's `typeChecks`; each detection's counts of setups judged and rejecting are pinned. Release 5.9.3's verdicts, probed: an `exports`-only package TS2307 under `node10` alone; an ES-module-only package imported from a file compiled as CommonJS TS1479 under `module` `node16` and `node18`; import attributes TS2823 under `module` `node16`, `node10`'s default, and `bundler`'s `es2015`–`es2022`, and TS2856 wherever a supporting `module` value compiles the file as CommonJS (`.cts` under `bundler` too); `Object.groupBy` TS2550 under every `module` but `nodenext` (the default target is `es2022` under `node16` and `node18`, `es2023` under `node20`, `esnext` under `nodenext`, `es5` under `node10` and `bundler`); `import.meta` TS1343 under `bundler`'s `es2015` and `node10`, TS1470 in a file compiled as CommonJS under the `node16` and `nodenext` modes; a string-literal import name TS18057 under `es2015` and `es2020`; an import assignment TS1202 under `es2015`–`esnext`, admitted under `preserve`, `node10`, and the node modes. The initialized set's own options, each rejected under that set alone (its 5 setups) and admitted under all 168 strict defaults: a type imported without `type` TS1484 (`verbatimModuleSyntax`); an optional property initialized `undefined` TS2375 (`exactOptionalPropertyTypes`); an indexed read assigned to a `string` TS2322 (`noUncheckedIndexedAccess`); a side-effect import of a missing module TS2307 (`noUncheckedSideEffectImports`); a valid default export of a call returning a package's unexported interface TS4082 at the export, a declaration diagnostic alone (`declaration`; its twin, returning an exported interface, admitted in all 173). Rejected under the strict defaults alone, the initialized set's `skipLibCheck` admitting each: a package declaration file's undeclared type TS2304, and its untyped parameter TS7006 (`strict`), located in whichever of `index.d.ts` and `index.d.cts` TypeScript resolves. An `@types` package beside the placement is included automatically under all 168 strict defaults, where the driver refuses the staging (the program condition), and kept out under the initialized set. The module format: `import.meta` judged under the node modes and the initialized set, 101 setups, TS1470 in the 56 setups of a file compiled as CommonJS. 5.9.3's `node16` and `nodenext` resolvers share one feature set, so those two `moduleResolution` values have no effect of their own to detect. Red-check recipe: a script replacing `programOptions`'s loop line (`for (const [key, value] of Object.entries(set.compilerOptions)) {`) with one over a neighboring strict-default set's options for the sets a condition names, or with one dropping an option from a set or adding one to the strict defaults, the file run, the helper copied back and `cmp`-checked; each break failed exactly the detections guarding it (dropping the initialized set's `strict` fails all nine judged under that set, through TS5052; dropping its `skipLibCheck` fails both declaration-file detections), as did a compiler host forcing `impliedNodeFormat` ESNext (the module-format and ES-module-only detections) and `emitsDeclarations` returning false (the declaration detection alone). T7.6-1's export listing (FIX_PLAN Task 18 of the plan written at e57210b): two detections pin the driver's `exportListing` whole in all 173 setups — `implicit-export` (dual layout, each declaration file declaring `defineConfig` and an interface never marked `export`, named for its entry, no `export {}`) lists both through the declaration file each setup resolves (`index.d.ts` in 102 setups, `index.d.cts` in 71), and `export-assignment` (CommonJS, `types` and `main` alone, `export =` of a constant typed with `defineConfig` and `other`) lists both as the assignment's members in all 173; ~7 s together. Red-checked by one-point breaks of `listModuleExports` (members dropped; implicit exports dropped by keeping only `export`-modified or export-specifier symbols; a name probed with `tryGetMemberInModuleExports`; type meanings read as values), each failing exactly its detection. +- T7.6-1, declared exports (TEST-SPEC T7.6-1; from the plan written at e57210b's FIX_PLAN Task 19): `test/suite/registry/section-7.6.ts`, first in `section76Tests` (wrapper `test/suite/section-7.6.test.ts`). The body stages T7.6-2(d)'s minimal file (its records named `T7.6-1/T7.6-2 (d) ...`) alone in each project beside the canonical placement with `listExports: true`, and holds each of the 173 setups' `exportListing` to exactly `defineConfig` (`value` true; `typeOnlyValue`, `type`, and `namespace` false) through the exported `assertDeclaredExports(verdict, context)`, which T7.6-4's placements and P-17's draws may reuse; it stops at the first setup that deviates, and a listing naming no module fails diagnosed. A test of 7.6 that invokes no executable binds a scratch stand-in package through the suite wrapper alone: `XSPEC_PACKAGE_DIR=` with `-t 'T7.6-1 '` (the wrapper's `builtProductBinding()` reads it), no temporary self-test needed. Locally under `unshare --map-user`: against the conforming scratch stand-in (Task 17's dual-entry layout, ESM-syntax declarations for both entries) it passes all 173 setups in about 10 s (about 18 s with Vitest's start-up), and likewise with the `require` entry's `.d.cts` written as `export =` of a value carrying `defineConfig` alone or of a namespace declaring it (that stand-in passes T7.6-2 too, and the synthetic default TypeScript admits there fails nothing). Red-checked with stand-ins carrying an extra exported type, an unexported interface in a declaration module without `export {}`, a declared default export, an `export =` value with an extra member (failing first at the ES-module project's `.cts` under `node16`, where the `require` entry resolves), `defineConfig` also declared as a namespace, also as a type, and reached only through `export type`: each fails diagnosed, naming exactly its deviation. Against the built product packed by `pack-package.sh` since 809a932 (`dist/index.d.mts`: unexported type aliases, then `export declare function defineConfig(config: Config): Config;` and `export {};`; `dist/index.d.cts`: the same aliases, `declare function defineConfig(config: Config): Config;`, and `export =` of a constant typed `{ defineConfig: typeof defineConfig }`, the assignment's one member) it passes all 173 setups in about 9.6 s of test time; at ad60726, before `src/index.cts`, every listing held in the ES-module project's first 6 setups and it failed diagnosed at its 7th (`.cts`, `node16` with `module` `node16`, the first setup resolving the `require` entry): no module, TS2307, no `dist/index.d.cts`. Against S-7's stub package it fails diagnosed at the first setup in about 0.8 s (TS2307, no module). +- T7.6-2, valid configurations (TEST-SPEC T7.6-2; from the plan written at e57210b's FIX_PLAN Task 16): `test/suite/registry/section-7.6.ts` (`section76Tests`, wrapper `test/suite/section-7.6.test.ts`), the first registered test of 7.6. Its configurations are data — `configObject(...)` maps of strings, booleans, lists, and maps, never harness object literals, whose `__proto__` key would set the prototype — rendered by `renderConfiguration(config, { specifier, binding, keys, comments })` in SPEC 7's example style; module-load checks hold each file valid under 7 (`problemsUnder7`), to its arm's own content, and to 7.6's covered-file conditions read back with the harness's TypeScript (no backslash, no comment carrying `@` or beginning `///`, the import, the specifier exactly N, the argument equal to the data), each throwing a plain `Error` at load; every rendering is a `stagedTs` record per canonical-name candidate (`ts`, beside a `tsx` twin of the same bytes for the `.tsx` name), judged by `test/self/s9-staged-sources.test.ts`. The body stages one project per kind beside its canonical placement, writes its nine files under each extension, and stops at the first setup where any file fails, naming every failing file of that setup. Locally under `unshare --map-user`: against a conforming scratch stand-in (the dual-entry layout, `defineConfig(config: Config): Config` over type aliases alone, so declaration emit inlines them) it passes all 173 setups in about 17 s; against the built product packed by `pack-package.sh` since 809a932 it passes all 173 setups in about 5.4 s of test time (before, with no `dist/index.d.cts` for the `require` entry its `exports` names, it failed diagnosed at the ES-module project's 7th setup, `.cts` under `node16` with `module` `node16`: TS2307). TypeScript 5.9.3 types an object-literal key naming a member of the global `Object` interface (`constructor`, `toString`, ..., not `__proto__`) by that member rather than by the contextual type's index signature, so its value loses tuple contextual typing: a `defineConfig` type whose glob lists are tuple types (`[string, ...string[]] | []`) fails (e) alone. Red-checked with scratch stand-ins lacking `targets` `"all"`, narrowing `emit` either way, demanding a non-empty `coverage`, `policy`, or glob list or repeat-free edge kinds, requiring `outDir`, `boundaryKind`, a rule's `kinds`, or a named spec group, or barring `__proto__` as a group name (each failing exactly its arms). +- T7.6-3, shape violations (TEST-SPEC T7.6-3; from the plan written at e57210b's FIX_PLAN Task 17): `test/suite/registry/section-7.6.ts`, beside T7.6-2 in `section76Tests`. Its 430 arms are edits of T7.6-2(a)'s data at every value of (a)'s file (`singleViolationEdits`, which walks the data against `CONFIG_SHAPE`, 7's shape as the type-error class reads it, and draws on the kind table `T763_KIND_TABLE` and the enumeration, required-key, fixed-key, empty-list, and selector-form tables), then TEST-SPEC's `kinds: [true]` and one file holding seven violations. `checkT763Arms` holds them at module load: the tables to T7.6-3's list, and each arm to its edits, through the harness's own reading of the class over the data (`classViolations`). Each rendering is read back like T7.6-2's files, and each is a `stagedTs` record per canonical-name candidate, as TS and as TSX: 1720 records, which add about 2 s to `test/self/s9-staged-sources.test.ts`. The body stages the twin, T7.6-2(a)'s records, alone in each project and judges it first in each setup. A twin that fails ends the body diagnosed before the arms are staged, so S-7's stub package costs the sweep one program. The body then stages the arms once per project, judges them in one batch per setup, pairs each with the twin through `assertShapeViolation`, and stops at the first setup where any arm type-checks. Locally under `unshare --map-user`, against a conforming scratch stand-in, it passes all 173 setups in about 390 s. That stand-in is the dual-entry layout with `defineConfig(config: Config): Config`, where `Config` is an exact type alias with non-empty tuples for the set-read lists and a selector union whose other forms' keys are `?: never`. Each batch of 430 failing files costs 2–3.5 s per setup, from TypeScript's error elaboration; valid files cost about a third of that. Writing them with Reach verified costs about 8 s per project. Against a permissive stand-in (`config: any`), every arm fails diagnosed through the pairing at the first setup, in about 9 s, and a composition audit there finds the twin and every arm type-checking in all 173 setups (93 s). Against a stand-in admitting `"contains"`, exactly its 15 `"contains"` arms fail. Against the built product packed by `pack-package.sh` since 809a932, whose `defineConfig(config: Config): Config` is a type of that stand-in's form in both entries, it passes all 173 setups in about 296 s of test time (320 s wall, `section-7.6`'s three tests alone); at ad60726, before `src/index.cts`, every arm failed in the ES-module project's first 6 setups, and the body stopped diagnosed in about 15 s at its 7th (`.cts`, `node16` with `module` `node16`), where the twin failed with TS2307 (no `dist/index.d.cts`). Before ad60726 the product's `defineConfig(config: T): T` was generic, and inference into a type parameter checks no excess property: 58 arms type-checked at the first setup (the unknown keys, the selector forms other than `{}` and `kind` alone, and the empty lists). +- The module channel's Node.js release driver (TEST-SPEC H-2, T7.6-6, T7.6-7(a)–(e), §7.6 Pairing, S-3, E-1; from the plan written at e57210b's FIX_PLAN Tasks 20, 21, and 22): `test/helpers/module-channel-node.ts`, its bootstrap `test/helpers/module-channel-bootstrap.cjs`, and its warning calibration `test/helpers/module-channel-warning-calibration.cjs` (harness code, plain CommonJS that Prettier formats and `tsc -p test` leaves out; neither holds a backslash). `runModuleRoute({ staging, placement, route, release, importingDir, project, alone, context })` — or `prepareModuleRun(...)`, then `launch()` and `dispose()`, for a caller staging more in between — writes the route's importing module, `importing-module-.mjs` or `.cjs` (`MODULE_ROUTES`: `static-import`, `dynamic-import-from-module`, `dynamic-import-from-commonjs`, `require`), in the placement's holding directory unless `importingDir` names another, makes the run's own `xspec-module-run-*` directory under the OS temporary directory (the bootstrap's copy, `report.json`, and fresh `home/`, `tmp/`, and `work/`: the run's HOME, TMPDIR, and working directory), verifies Reach and H-1 under the run's exact environment (`HOME`, `TMPDIR`, and the harness's own `PATH`, nothing else, so an ambient `NODE_OPTIONS` or `NODE_PATH` never reaches it), runs `/bin/node ` through `runProduct` under `MODULE_RUN_TIMEOUT_MS` (30 s), and decodes the report (`decodeModuleRunReport`, protocol `xspec-module-run/3`, its members read exactly) into `run.outcome` (`loaded`, `load-failed`, `incomplete`, `no-report`, or `malformed-report`) and `run.report` (arguments, release, pid, environment, working directory, phase — `loading`, `calling` while T7.6-6's calls run, `completed` — the importing module's note, the load with the loaded value's own keys, `load.value.ownKeys`, each `{ kind, name, enumerable }`, T7.6-6's `calls` — `reading` of `defineConfig`, one `results` entry per `CALL_CASES` case in order, each `returned-argument`, `returned-other`, or `threw` by `Object.is` inside the run, and `traps`, each trap either recording Proxy's handler ran through the run's end — T7.6-7(c)'s `state` (exactly where the module loaded and the phase completed), a bootstrap failure, warnings, exit code) beside `run.result`; the `state` (the labels of the objects observed, each difference `{ observation, subject, detail }`, at most 100, and `omitted`) is the bootstrap's own comparison of a baseline read before the importing module loads — itself read once before to settle what the release materializes on a first read: on 22.23.4 and later the first read of the global object's descriptors materializes its lazy globals, `FormData`'s loading the release's fetch, which adds `Symbol(undici.globalDispatcher.1)` (and `.2` on 24 and 26) — with a read once T7.6-6's calls are made, each difference under one of `STATE_OBSERVATIONS` (`global-object`, `built-ins` — every string-keyed own data property of the global object holding an object or a function, and each such function's own `prototype`, 126 to 240 objects across E-1's releases — `extensibility`, `prototype`, `process`, `environment`, `title`, `working-directory`, `exit-code`, `stream-write`, `listeners`, `timers-and-handles`: the active handles of `process._getActiveHandles()` and the `Timeout` and `Immediate` entries of `process.getActiveResourcesInfo()`, never its requests, since the ES-module routes on 22.0–22.12 leave a `FileHandleCloseReq` of the release's own in flight); probes on the six releases found no difference for conforming stand-ins, those drawing DEP0128, DEP0151, and the experimental warning included (setting `process.title` also changes `process`'s own `title`, a native data property, so it is reported under `process` too); the run's conditions (arguments, `process.version` and the physical `execPath`, an empty `execArgv`, the exact environment, the working directory, the importing module's kind and location, and the state's observed labels including `REQUIRED_STATE_SUBJECTS`: the global object, `process`, ECMAScript's namespace objects and constructors, and each constructor's prototype) are checked on every decoded report, a breach a harness error. `assertModuleLoaded(run, "product" | "stand-in")` requires `loaded` and exit code 0 with no signal: otherwise a diagnosed failure for a product and a harness error for a stand-in; the hang-guard kill propagates unchanged. On the `LoadedModuleRun` it returns, `exportsProblems` (T7.6-6(a): an import namespace's string keys, a require result's enumerable ones, exactly `defineConfig`), `identityProblems` ((b)), `examinationProblems` ((c): the Proxies call returning the first, no trap run, the frozen object returned), `pairingProblem` (every call returned its argument), and `outputProblems(run, form)` (T7.6-7(a): the pairing, standard output empty, standard error byte for byte `renderWarnings(report.warnings, report.pid, form)`, and no warning whose `warningFirstFrame` names the placement or its copy, `packageFrame`) return problems in words, each led by the run's description, never throwing; `runtimeOutputProblems(run)` learns the form first; `stateProblems` (T7.6-7(c)), and, for a run requested with `effects: true`, `writeProblems` ((b)) and `fifoProblems` ((e)), each led by the pairing as well: such a run stages a FIFO named `xspec.config.ts` (`RUN_FIFO_NAME`, through helpers/lock-staging.ts's `stageFifo`) in `work/`, in the importing module's directory (staged once per staging, found there by later runs), and in `home/` (`prepared.fifos`, in that order), snapshots the staging, `work/`, `home/`, and `tmp/` (`snapshotPlace`: every entry by its kind, a plain file's bytes, a link's target, a FIFO, a socket, or a device by its kind alone, never opened, a refused read recorded as such) just before and just after the spawn, compares them (`comparePlaceSnapshots`) into `run.effects.writes`, and reads each FIFO back into `run.effects.fifos`; while it is launched, writing into its staging for another run (an importing module, a FIFO) is a usage error, so prepare every run of a staging before launching one with effects, or run them one after another. T7.6-7(d) is the environment's: the runs inherit CI's network-denied namespace. `learnWarningForm(release)` runs the calibration on the release three times, as a module run is run (a warning of its own type first, a `DeprecationWarning` first, an `ExperimentalWarning` first), reads the release's two hint lines off standard error, and confirms each run's whole standard error renders exactly from its delivered warnings, a mismatch a harness error naming the release; it is memoized per release in a process. All six of E-1's releases print warnings alike, one hint after a first deprecation and another after any other first warning; a file URL frame holds its plain path unless the path percent-encodes. A run takes about 40 ms here on 22.0–22.12 and about 70 ms on 22.23.4 and later (the lazy globals' materialization); 24 runs with effects, preparation and disposal included, take about 4 s. `test/self/module-channel-node.test.ts` (6 tests, about 8 s alone under `unshare --map-user`, 3 s of it one run kept alive to its lowered guard) and `test/self/module-channel-node-observations.test.ts` (6 tests, about 7.5 s alone: a conforming dual stand-in on every route and release; the learned forms against stand-ins emitting warnings of their own; DEP0128, DEP0151, and the experimental warning admitted; each observation's deviation end to end on one release; the pure functions on vectors) and `test/self/module-channel-node-effects.test.ts` (5 tests, about 5 s alone: a conforming dual stand-in with effects on every route and release, every observation unchanged; a write into TMPDIR and a global and a timer end to end on one release; `snapshotPlace` on a directory holding a FIFO; and the comparison and problem functions on vectors) need `XSPEC_NODE_RELEASES_DIR`, each test running a release failing as `NodeReleaseError` without it, and pin the driver on stand-in packages they write at run time. +- S-10's check of the release driver (TEST-SPEC S-10; from the plan written at e57210b's FIX_PLAN Tasks 23 and 24): `test/self/s10-node-release-driver.test.ts` runs the driver exactly as the tests do (`runModuleRoute`, `prepareModuleRun`, the canonical placement in a CommonJS project) on each of E-1's releases, over committed stand-ins under `test/fixtures/s10-stand-ins/` (documented in the file's header, since JSON holds no comment; the `dual` stand-in's three entries each write one line to standard output naming themselves and the kind of module they ran as). Its first 4 tests (Task 23): release identity (a `#!/bin/sh` wrapper provisioned under one listed release's name that `exec`s another is refused as a harness error naming both versions; one release left out of a directory of stand-in executables, and the variable unset, are each a `NodeReleaseError`), run conditions (a stray `NODE_OPTIONS` with a user condition and a `--require`d hook, and a stray `NODE_PATH` holding a decoy under N, each shown live by running the release directly, set in the worker's `process.env` around the runs and restored, reach no run), routes (the ES-module-only stand-in's `require` refused with `ERR_REQUIRE_ESM` before 22.12.0, loading from it on), and the runtime's own loading output (state unchanged and the output oracle passing for the minimal stand-ins and the DEP0128 and DEP0151 stand-ins, each warning family required to draw a warning on some release, which release unpinned). Its 23 catches (Task 24), one test per effect of S-10's list, each over a stand-in of its own, pin that the matching observation reports the effect: each stand-in is a dual package (`exports` with `import` to `index.mjs` and `require` to `index.cjs`, each entry having the effect itself and exporting exactly `defineConfig`) run along all four routes on every release, but the two that write a forged warning line on `process.nextTick` after the release's own DEP0128 (`invalid-main`'s layout, require) or DEP0151 (`main-lookup`'s, the import routes); the forged first warning is byte for byte the release's printed form, its hint line built as the release builds it from `path.basename(process.argv0, ".exe")`; the 14 state catches are declared from `STATE_CATCHES`, each pinning its changes' observations and subjects and every other observation empty (`sets-exit-code` sets 0, so the run still exits 0 on its own); `writes-file` runs with `effects: true` and names its files with the pid and `process.hrtime.bigint()`, since the staging, where it writes into its own placement, persists across runs; `opens-fifos` opens all three FIFOs asynchronously, so one run checks each place, and its runs are prepared per route, then launched side by side (`Promise.allSettled`) under a lowered 5 s guard, each rejecting with `ProductRunTimeoutError` whose message's `Partial stdout:` is exactly the three opening lines. About 93 s alone under `unshare --map-user` (the first 4 tests 16 s, each catch about 2.2 s, the timer's 4.6 s, the FIFOs' 21 s; on CI the first 4 took 24.5 s); without `XSPEC_NODE_RELEASES_DIR` each test fails as `NodeReleaseError`, never a skip. With it, the self project (admin files left out) ran 50 files, 7079 tests, all passing, in 384 s. Red-check breaks of the driver and its bootstrap (copied to the scratchpad, broken by a script asserting each target occurs once, copied back and `cmp`-checked): the `require` route loading through `import()`, one release serving every run with the driver's own release checks blinded, the ambient `NODE_OPTIONS` carried into the run (adding `NODE_PATH` too trips H-1's global-folder check first), an oracle admitting none of the runtime's warnings, and the timers-and-handles observation counting the runtime's pending requests each fail the file; removing the bootstrap's settle read does not, since listing the subjects already reads every global's descriptor. Task 24's ten breaks, in two runs of `-t 'S-10, catches'` (a scratchpad script applying a break set, each target asserted once, the helpers copied back and `cmp`-checked in the same command), each failed exactly their catches: the oracle's stdout check; stderr compared as a prefix only (stderr, the forged first warning, the forged line after the release's); the package-frame check; the bootstrap's listeners row; its extensibility comparison; `built-ins` records dropped (Array, Math, String.prototype); `identityProblems` emptied; the traps check; the staging left out of the compared places; and no FIFO staged in HOME (the FIFO catch, and the write catch's FIFO-intact check). +- T7.6-6, runtime exports and identity (TEST-SPEC T7.6-6; from the plan written at e57210b's FIX_PLAN Task 25): `test/suite/registry/section-7.6-ii.ts` (`section76iiTests`, the module for 7.6's runtime tests, spread after `section76Tests`; wrapper `test/suite/section-7.6-ii.test.ts`; H-7 row `"T7.6-6": ["7.6"]`). The body (`runRuntimeRuns`, which T7.6-7 shares: the next bullet) checks the package directory first (`ModuleStaging.create`: none given fails diagnosed, before anything is staged), then resolves every release E-1 lists (`resolveNodeReleases`; `XSPEC_NODE_RELEASES_DIR` unset is `NodeReleaseError`, a harness error) and confirms one is of 22.0–22.11, stages a CommonJS project at `project/` beside the canonical placement (`runtimeArm(releases)`), and makes one `runModuleRoute` run per release and route (24, `project: "commonjs"`, `alone: true`, one after another). Each run goes through `assertModuleLoaded(run, "product")`: the first that does not load and exit 0 on its own stops the body, diagnosed, its message naming the problems the runs before it found, so S-7's stub package ends it at its first run (0.4 s of test time). Each loaded run's `exportsProblems`, `identityProblems`, and `examinationProblems` are collected, and the body fails once naming each distinct problem (the run's description left out) with its runs, each run labelled ` ()`, or "in every one of the N runs". Like T7.6-1, it invokes no executable, so a scratch stand-in binds through the wrapper alone: `XSPEC_NODE_RELEASES_DIR= XSPEC_PACKAGE_DIR= unshare --map-user=1000 --map-group=1000 -- env -u NODE_OPTIONS -u NODE_PATH npx vitest run --config test/vitest.config.ts --project suite test/suite/section-7.6-ii.test.ts`. Locally: against a conforming dual stand-in (`exports` with `import` to an `.mjs` and `require` to a `.cjs`, each exporting an identity `defineConfig`) it passes in 2.2 s of test time (11 s with Vitest's start-up). Red-checked with scratch stand-ins, each failing diagnosed with exactly its deviation: a CommonJS-only entry (the 18 import-route runs; the namespace's string keys `["default", "defineConfig"]`, and on 24.22.2 and 26.13.0 also `"module.exports"`); an enumerable `__esModule` on the `require` entry (the 6 `require` runs); a copying `defineConfig` (the object, array, further-argument, and frozen calls, in every run); `-0` returned as `0`; `Object.isFrozen(arg)` (the `isExtensible` trap on the first Proxy); a frozen object refused (a `TypeError`); a `-0` deviation on 26.13.0's `require` alone (exactly that run, the 24th); and an import-only package also exporting `default` (stopped at 22.0.0's `require`, `ERR_PACKAGE_PATH_NOT_EXPORTED`, naming the three import runs' `default`). Against the built product packed by `pack-package.sh` since 809a932 it passes all 24 runs in about 3.1 s of test time (`section-7.6-ii` beside P-17 and P-18, three files in one 152 s run), its `require` entry `dist/index.cjs` being `module.exports = { defineConfig };` with no `__esModule` marker; before, with no `dist/index.cjs`, it failed diagnosed at run 4 of 24, 22.0.0's `require` (`MODULE_NOT_FOUND`), the three import runs before it holding (a), (b), and (c). +- T7.6-7, runtime: no effect (TEST-SPEC T7.6-7; from the plan written at e57210b's FIX_PLAN Task 26): `test/suite/registry/section-7.6-ii.ts`, beside T7.6-6 in `section76iiTests` (wrapper `test/suite/section-7.6-ii.test.ts`; H-7 row `"T7.6-7": ["7.6"]`). Both tests run one body, `runRuntimeRuns(product, test)`, a `RuntimeTest` record giving what differs, each test making its own 24 runs on its own staging (the CommonJS project at `project/` beside the canonical placement, one `runModuleRoute` run per release and route, one after another, the first run that does not load and exit 0 on its own stopping the body, diagnosed). T7.6-7's runs are of T7.6-6's shape with `effects: true` (a FIFO named `xspec.config.ts` in each run's working directory, in `project/`, and in its HOME; the staging, the working directory, HOME, and TMPDIR snapshotted around each spawn), and each loaded run is read through `runtimeOutputProblems` ((a); the warning form learned once per release, 3 calibration runs each), `writeProblems` ((b)), `stateProblems` ((c)), and `fifoProblems` ((e)), each led by the pairing; (d) is the environment's. Recorded problems have each run's own directory (the parent of its working directory, HOME, and TMPDIR, different in every run) written ``, so an effect found in every run is one problem "in every one of the 24 runs". Locally, against the conforming dual scratch stand-in through the wrapper alone (as T7.6-6's bullet runs it): 4.0 s of test time, and 4.1 s in the network-denied nesting recipe of the bullet beginning "The self project". Red-checked with scratch dual stand-ins (each entry having the effect as it loads), each failing diagnosed with exactly its deviation in every one of the 24 runs: a line on standard output; a line on standard error (11 bytes where the printed forms are 0); a `process.emitWarning` (the package-frame check, two distinct first frames: `index.mjs` in the 18 import runs, `index.cjs` in the 6 `require` runs); a file written into TMPDIR; a global added; and a copying `defineConfig` (the pairing problem alone). A stand-in opening its working directory's FIFO synchronously blocks its first run until the 30 s guard: `ProductRunTimeoutError` ends the test (S-3) in 30.4 s. Against S-7's stub package it fails diagnosed at its first run. Against the built product packed by `pack-package.sh` since 809a932 it passes all 24 runs in about 8.0 s of test time (in the run of the T7.6-6 bullet's figures); before, with no `dist/index.cjs`, it failed diagnosed at run 4 of 24, 22.0.0's `require` (`MODULE_NOT_FOUND`), the three import runs before it holding (a), (b), (c), and (e). +- T7.6-4, placements (TEST-SPEC T7.6-4; from the plan written at e57210b's FIX_PLAN Task 27): `test/suite/registry/section-7.6-ii.ts`, first in `section76iiTests` (wrapper `test/suite/section-7.6-ii.test.ts`; H-7 row `"T7.6-4": ["7.6"]`). One body, `runPlacements(product, T764, T764_PLACEMENTS)` (shared with T7.6-5: the next bullet): the package directory checked first (`modulePackageDirectory`), every release resolved, then the 15 placements of `T764_PLACEMENTS` in TEST-SPEC's order — (a) the manifest's `name` (staged only where it is a name of 7.6's grammar outside the exclusions; its runtime half on the releases that resolve it to no built-in), (b) the canonical N as a symbolic link, (c) 1–7 `@staged-scope/config-module`, `7config`, `staged-config_module`, `a.js` and `a.b` (each beside an unrelated package at `node_modules/a`), and a 214-character unscoped and scoped name, (d) 1–2 the holding directory `ancestor/` above the files' `ancestor/project/`, and `physical/` above `physical/project/`, also reachable through the link `linked/project`, (e) 1–2 TypeScript 5.9.3's package (a copy of the harness's own `typescript-5.9.3`, 23 MB, through `ModuleStaging.copyDirectory`) and `unrelated-package` beside the placement, and `unrelated-package` in the files' own directory below an ancestor placement, (f) 1–2 `fs` and `path`, type-checking only. A placement's type-checking half stages each project kind and judges T7.6-1's covered file (T7.6-2(d)'s, its export listing asked), T7.6-2(a)'s file, and T7.6-3's unknown-top-level-key arm in one program per covered setup, through `assertDeclaredExports`, `assertTypeChecks`, and `assertShapeViolation`; the files come from `placementFiles(N)`, exported by section-7.6.ts (those tests' own files beside any N, byte-equal to their records beside the canonical candidates, checked at module load), as S-9 records named `T7.6-4 …` for every fixed N (66; `T7.6-4/T7.6-5 …` beside the canonical candidates, whose files T7.6-5 stages too), (a)'s composed at run time and judged by `judgeTypeScript` under both grammars before staging. Its runtime half (all but (f)) makes T7.6-6's 24 runs from a CommonJS project in the layout's importing directory through `runRoutes` (shared with `runRuntimeRuns`), reading `exportsProblems` and `identityProblems`. The body stops at its first failing setup or run, naming the placement and the placements held before it. Locally under `unshare --map-user`, against the conforming dual scratch stand-in bound through the wrapper alone (`XSPEC_PACKAGE_DIR=`, `-t 'T7.6-4 '`, as T7.6-6's bullet runs it): passes in 73–75 s of test time (81–83 s with Vitest's start-up) — each placement's 173 setups take about 2–4 s, the process's first sweep about 13 s, a runtime half about 2.5 s. A package whose declarations touch the global scope (an ambient `declare module` file) makes the TypeScript driver check the libraries in every program: such a stand-in took 960 s to reach (f). Red-checked with scratch stand-ins, each failing diagnosed exactly at its placement: `defineConfig` returning `undefined` when its real directory is named for its manifest ((a)'s runtime half, 13 s), lies under no `node_modules` ((b)'s, 18 s), is dotted ((c) 4, 38 s), has a holding directory not named `project` ((d) 1, 59 s), or has `typescript` beside it ((e) 1, 65 s); declarations re-exporting through `../staged-config-module/` beside a manifest naming `staged-config-module` ((b)'s type-checking half, 13.5 s); and an ambient `declare module "fs"` ((f) 1: T7.6-1's listing and T7.6-3's pairing). Against S-7's stub package it fails diagnosed at (a)'s first setup in 1.0–1.2 s. Against the built product packed by `pack-package.sh` since 809a932 it passes (108 s of test time, beside two other files); at ad60726, before `src/index.cts`, it failed diagnosed in about 2.2 s at (a)'s 7th setup (`@modularcloud/xspec`, ES-module project, `.cts`, `node16` with `module` `node16`), its three runs having held in the 6 before: TS2307, no `dist/index.d.cts`. +- T7.6-5, Reach's open cases (TEST-SPEC T7.6-5; from the plan written at e57210b's FIX_PLAN Task 28): `test/suite/registry/section-7.6-ii.ts`, second in `section76iiTests` (wrapper `test/suite/section-7.6-ii.test.ts`; H-7 row `"T7.6-5": ["7.6"]`). T7.6-4's body over T7.6-5's own list, `runPlacements(product, T765, T765_STAGINGS)`: the two tests share the halves through a `StandInTest` (ID, context, rule, and `unit`, placement or staging) and `PlacementSpec` records, whose `projects` (type-checking half, a staging each) and `runtimeProject` default to T7.6-4's three kinds and its CommonJS runtime project as `stageProject` stages them. Six stagings, each the canonical placement in the files' own directory, `alone`, one project staged for both halves: (a) 1–3 `ancestor/package.json` `{"name": "unrelated"}` above `ancestor/project/` holding `{"type": "module"}`, `{}`, or no manifest (that ancestor then the nearest; 59 + 57 + 57 = 173 setups, a project with no package.json at all being impossible beneath a manifest); (b) 1–2 `{"type": "module"}` beneath `{"type": "commonjs"}` and `{}` beneath `{"type": "module"}`; (c) `project/package.json` `{"type": "commonjs"}`, judged in `coveredSetupsOf("commonjs")` with Reach told `nearestType: "commonjs"` (a field of `ReachStaging`, `CoveredFilesRequest`, and `ModuleRunRequest`; without it Reach's `commonjs` confirmation demands no `type`, and beside another kind it is a misuse). A staging with `manifests` writes them itself (`makeDirectory` and `writeFile`, never `stageProject`) and reads them back strictly from the files' directory up to the staging root before any tool runs (`confirmManifests`, a deviation a `HarnessStagingError`); `checkT765Stagings` holds the list to TEST-SPEC's at module load. Locally under `unshare --map-user`, against the conforming dual scratch stand-in bound through the wrapper alone (`XSPEC_PACKAGE_DIR=`, `-t 'T7.6-5 '`): passes in 27–29 s of test time (35–37 s with Vitest's start-up); the whole wrapper file (T7.6-4 to T7.6-7) passes in 108 s of test time. A `-t` pattern naming T7.6-6 also selects T7.6-4 and T7.6-5, whose titles name `T7.6-6 (a), (b)`. Red-checked with scratch runtime stand-ins whose `defineConfig` returns `undefined` where the project's directory holds no manifest and its parent does, where the parent's manifest holds `"type": "module"` above the project's own, or where the project's own holds `"type": "commonjs"`: each fails diagnosed at exactly (a) 3's, (b) 2's, or (c)'s runtime half (20–30 s), naming the stagings before it as held. Against S-7's stub package it fails diagnosed at (a) 1's first setup in 1.1 s. Against the built product packed by `pack-package.sh` since 809a932 it passes (24 s of test time, beside two other files); at ad60726, before `src/index.cts`, it failed diagnosed in about 0.4 s at (a) 1's 7th setup (`.cts`, ES-module project, `node16` with `module` `node16`), its three runs having held in the 6 before: TS2307, as T7.6-4 did. +- P-17, installation names (TEST-SPEC §16 P-17, E-5, H-10; from the plan written at e57210b's FIX_PLAN Task 29): `test/suite/registry/section-16-p17.ts` (wrapper `test/suite/section-16-p17.test.ts`, manifest spread after `section16P16Tests`, H-7 row `"P-17": ["7.6"]`). Each draw (`genP17Draw`) is N (`genP17Name`: scoped at 0.4; segment leads letter or digit 3:2; length classes 1-8, 9-40, 41-213, and 214 weighted 6:3:1:2; the last segment dotted at 0.5, what follows the dot one of `P17_EXTENSION_SUFFIXES` (`js` … `d.ts`, `json`, `node`, `wasm`) or a run; an `@types` or `@typescript` + `lib-` scope mended to begin `u`, and an unscoped name of `P17_NODE_BUILT_IN_NAMES` (the 42 grammar names every listed release lists in `builtinModules`) mended by an appended `-`), a placement form, a holding level (the files in `outer/inner/project`, held there or, at 0.5, in one of its 3 ancestors up to the staging root), a covered setup (the initialized-project set's 5 drawn a quarter of the time), a release from `test/node-releases.json` (read at module load) and a route. The body checks the package directory and resolves every release before any draw; each draw then makes a type-checking staging (T7.6-1's covered file, T7.6-2(a)'s file, and T7.6-3's unknown-top-level-key arm from `placementFiles(N)`, judged in the drawn setup in one program) and a runtime staging (the placement made on `runtimeArm([release])`, so the drawn release confirms N is no built-in, a yes a harness error; one `runModuleRoute` run read for `exportsProblems` and `identityProblems`), each with the drawn setup's project kind, and fails once naming every failing run; where TypeScript resolves no module and the load throws, the failure declines shrinking (S-7's stub package ends P-17 at draw 1, ~1.3 s). 25 runs per seed (75 draws), shrink budget 32 draws. The guard `test/self/p17-fixed-seed-draws.test.ts` (4 tests, ~3 s alone, no namespace, package, or release needed) classifies each fixed-seed N with a scanner of its own (dotted last segment, extension-like suffix, scoped and unscoped, digit-first segment and scope, 214 characters scoped and unscoped), pins both forms, holding levels 0-3, each project kind, covered extension, option-set kind, release, and route, holds every N to the grammar outside the exclusions and the built-in list (which must cover this Node.js's own `builtinModules` grammar names), and replays S-9's per-draw check through `checkProperty`; S-9's TypeScript vectors gained `P17_TS_FORM_VECTORS` (the three files beside `@a0-._/9z-_.d.ts` as `.ts` and `.tsx`; 44 vectors). Locally under `unshare --map-user` (`XSPEC_PACKAGE_DIR=`, `-t 'P-17 '`): the conforming dual scratch stand-in passes all 75 draws in ~23 s of test time (31 s wall); the built product packed by `pack-package.sh` since 809a932 passes all 75 draws in ~69 s of test time (beside two other files); at ad60726, before `src/index.cts`, it failed diagnosed at seed 271828183 trial 4, trials 1–3 holding, shrunk in 32 executions to N `m1wq_ovaaaaaaaaaaaaaaaaaaaaaaaaaaa`, a copy in the files' own directory, a `.cts` file in the CommonJS project with no `package.json` under `bundler` with `module` `es2020`, 22.12.0, dynamic `import()` from a `.cjs` — the three type-checking runs failing with TS2307 (no `dist/index.d.cts`), the runtime run holding — in ~22 s of test time. Red-checked with scratch stand-ins, each failing diagnosed by trial 7 and shrunk: `defineConfig` returning `undefined` where its real directory is dotted, held above the files, under no `node_modules`, or named past 100 characters, and a `.d.cts` exporting one more name (T7.6-1 in a `.cts` setup). A full-matrix probe of that stand-in (173 setups and 24 runs per name) under `a.js`, `a.mjs`, `a.cjs`, `a.jsx`, `a.ts`, `a.mts`, `a.cts`, `a.tsx`, `a.d.ts`, `a.d.mts`, `a.d.cts`, `a.json`, `a.node`, `a.wasm`, `h4.`, `2`, `@1/7`, `@a/b.d.ts`, `@x.y/z.json`, `test`, `sqlite`, `typescript`, `@typescript/x`, `types`, `index`, `index.js`, and `package.json` passed everywhere; under N `node_modules` its three import routes on 22.0.0 threw SyntaxError (Unexpected token 'export'): a copy whose own directory is named `node_modules` stops Node.js's package-scope lookup there, so its `"type": "module"` is not read for a `.js` entry, and 22.0.0 predates module-syntax detection — a package with explicit `.mjs` and `.cjs` entries does not depend on that lookup. P-17's draws never reach that name. Since ad60726 the product's `import` entry is the `.mjs` file `dist/index.mjs`: the packed product, copied to `node_modules/node_modules`, loads along a static `import` and a dynamic `import()` from an `.mjs` and a dynamic `import()` from a `.cjs` on all six of E-1's releases, 22.0.0 included (hand probe). +- P-18, type contract over generated configurations (TEST-SPEC §16 P-18, E-5, H-10; from the plan written at e57210b's FIX_PLAN Task 30): `test/suite/registry/section-16-p18.ts` (wrapper `test/suite/section-16-p18.test.ts`, manifest spread after `section16P17Tests`, H-7 row `"P-18": ["7.6"]`). Each draw (`genP18Draw`) is a configuration valid under 7 by construction held as a spelled tree (`P18Object`: per member its key, identifier or string-literal spelling, and four comment gaps; per list element two; `P18_STATEMENT_GAPS` around the import and the export), a binding (`P18_ALIAS_NAMES` or unaliased), a comment density (none, 0.12, or 0.4 per gap), a covered setup (initialized-project set a quarter of the time), and one mutation (`genP18Mutation`: member among those with a position, then position, then offending value; kind, enumeration, and empty-list violations may also add an optional field the draw omits, never in a selector). It reuses section-7.6.ts's readings, now exported: `problemsUnder7`, `shapeNodes`, `classViolations`, `T763_KIND_TABLE`, `nearMisses`, `readBack`, `scanComments`, `sameValue`, `OBJECT_MEMBER_NAMES`, `BARRED_BINDINGS`. The generator throws a harness error unless the draw reads valid and violation-free and the mutant holds exactly the drawn violation; `p18Texts(draw, N)` renders both files beside each `CANONICAL_MODULE_NAMES` candidate and reads them back with TypeScript (binding, specifier, data, key spellings, the exact comments, no backslash), and `stagedP18Sources` hands all four to S-9. The body (`modulePackageDirectory` first) stages one project of the drawn kind beside `placeCanonical`, judges the draw and the mutant in one program with `listExports`, and fails once naming each failing assertion (`assertTypeChecks`, then `assertShapeViolation`), declining shrinking where the listing names no module. 30 runs per seed (90 draws), shrink budget 96. The guard `test/self/p18-fixed-seed-draws.test.ts` (5 tests, ~2.5 s alone, no namespace, package, or release needed) classifies each fixed-seed draw by reading its text back (keys of both spellings, each `Object` member and `__proto__` as a group name — `constructor` the rarest at 4 draws — non-identifier and non-ASCII names, both bindings, comments in the import and in the argument, empty glob lists, a repeat in each set-read list, each optional key present and absent, each selector form, kinds for names of both kinds, each type-error member — selector form the rarest at 3 — an added field, each project kind, extension, and option-set kind) and replays S-9 through `checkProperty`; S-9's TypeScript vectors gained `P18_TS_FORM_VECTORS` (the vector draw, comments in every gap, and its mutant, as `.ts` and `.tsx`; 48 vectors). Locally under `unshare --map-user` (`-t 'P-18 '`): the conforming dual scratch stand-in passes all 90 draws in ~11 s of test time (20 s wall); a permissive one (`config: any`) fails diagnosed at seed 271828183 trial 1 through the pairing, shrunk within the budget; one narrowing `emit` to `true` fails at trial 4, shrunk to `specs: { app: [] }, markdown: { emit: false }`; the built product packed by `pack-package.sh` since 809a932 passes all 90 draws in ~40 s of test time (beside two other files); before, with no `dist/index.d.cts`, it failed diagnosed at seed 271828183 trial 1 (a `.cts` file under `nodenext`/`node16`: TS2307), nothing resolving, unshrunk, ~1.5 s of test time (10 s wall). TypeScript 5.9.3 facts probed for the pools: it flags every unknown key against an exact type (TS2353), `__proto__` and the `Object` members included, either spelling, at the top level and in `markdown`, a profile, and a selector; it accepts as the alias every name 6.5's first rule admits but `require` and `exports` (TS2441 where it compiles the file as CommonJS) — `undefined`, `string`, `async`, `Object`, `globalThis`, `__esModule`, non-ASCII names; and it accepts names holding control characters, U+0000, U+FEFF, U+0085, and astral characters as string-literal keys and values. `ts.isIdentifierText` exists at run time but not in TypeScript's public typings; `isIdentifierName` (section-16-p18.ts) composes the public `isIdentifierStart` and `isIdentifierPart`. +- Full test suite (TEST-SPEC sections 1–17, certification included; the Linux CI leg): `npm test`. Build the product first — tests invoke the built executable. 7.6's tests also take the module channel's two inputs, `XSPEC_PACKAGE_DIR` and `XSPEC_NODE_RELEASES_DIR` (the bullets above), which `npm test` does not make itself. Without a build (`dist/cli/bin.js` absent), every product-facing test fails as a diagnosed `HarnessAssertionError` naming that path, before anything is spawned (H-8's no-product run: `builtProductBinding()` in `test/helpers/subprocess.ts` sets `missingFilesFailDiagnosed`, so its missing artifact is the missing product; `builtProductBindingAt()` is the same binding at another artifact path), each `checkProperty` property (P-1 to P-14) reported as drawn at its first trial with its seed, never shrunk (the failure declines shrinking); any other binding's missing file — a certification fixture's, the S-7 stub's, a compiled consumer's, a temporary runner's scratch build — stays a plain-`Error` harness error (C-1: an unbuilt fixture is a harness defect, never a certified failure), which the certification runner reports as `error`. Measured at the affd85f plan's FIX_PLAN Task 4, under `unshare --map-user` with `NODE_OPTIONS` unset: `test/suite/section-1.1-1.2.test.ts`, `section-16-p1.test.ts`, and `e6-exchange-writer.test.ts` with no build ran 8 tests, all failing so (P-1 "falsified with seed 271828183 (trial 1 of 25)", reported as drawn), in 6.71 s; the certification runner over every registered body and S-7's six layer-4 bodies against `builtProductBindingAt()` ended 352 and 6 `fail`, every diagnosis naming the path, in 7.9 s, and against the unflagged binding of the same shape 348 and 6 `error`, with `fail` for T7-5, T13.4-12, T13.5-6, and P-14 alone (their own conversions of a run's rejection wrap the message). - Timings on a 4-core machine: the whole suite project (`npx vitest run --config test/vitest.config.ts --project suite`; 91 files, 374 tests, the E-6 writer included, at the end of the plan written at 2a2b94e (its FIX_PLAN Task 139), 89 files and 372 tests with T13.5-10's and T13.5-9's files left out; 88 files, 353 tests at the 13.5 re-descent's Phase 9 end (the plan written at 772854b, its FIX_PLAN Task 50, the plan written at 092db72, its FIX_PLAN Task 3, and the plan written at acfff0b, its FIX_PLAN Task 2), 86 files and 351 tests with T13.5-10's and T13.5-9's files left out where no administrative access is to be had; 79 files, 345 tests at the Phase 9 re-descent's end, FIX_PLAN Task 66; 77 files, 337 tests at 3285994) takes ~34–45 min inside CI's full-suite `npm test`, the self project beside it, at the 2a2b94e plan's end (2015.19 s in run 1545, 2708.40 s in run 1547; no local suite run in that plan), ~20 min at the 13.5 re-descent's Phase 9 end, ~16 min at Phase 10's end, ~11 min before it (637 s at 3285994, 704 s at 3d0f424, 745 s in Phase 10 at FIX_PLAN Task 26, 722 s at Task 27, 724 s at Task 28, 745 s at Task 30, 734 s at Task 31, 771 s at Task 32, 757 s at Task 33, 774 s at Task 34, 819 s at Task 35 — T6.5-16, T6.6-3, and T14-7 now running to completion; 811 s at Task 36, 827 s at Task 37, 849 s at Task 38, 842 s at Task 39, 867 s at Task 40, 860 s at Task 41, 862 s at Task 42, 885 s at Task 43, 903 s at Task 44, 906 s at Task 45, 889 s at Task 46, 936 s at Task 47, 935 s at Task 48 — T13.5-7 and T14-9 now running to completion; 920 s at Task 49; 906 s at Task 50; 925 s at Task 51; 881 s at Task 66, 336 of 337 passing, T14-11 alone failing at its arm (n); 853 s at Task 67, likewise; 842 s at Task 68, all 337 passing (T14-11's arm (n) green); 848 s at Task 69, all 337 passing; 842 s at Task 70, all 337 passing; 853 s at Task 71, all 337 passing; 853 s at Task 72, all 337 passing; 862 s at Task 73, all 337 passing; 927 s at Task 74, all 337 passing; 852 s at Task 75, all 337 passing; 951 s at Task 76, all 337 passing; 887 s at Task 77, all 337 passing; 869 s at Task 78, all 337 passing; 896 s at Task 79, all 337 passing; 914 s at Task 80, all 337 passing; 914 s at Task 81, all 337 passing; 937 s at Task 87, all 337 passing; 938 s at Task 88, all 337 passing; 923 s at Task 89, all 337 passing; 960 s at Task 54, all 337 passing; ~15 min in earlier plans; in the Phase 9 re-descent, 1233 s at its FIX_PLAN Task 15 under the namespace — 338 tests with the E-6 writer, 333 passing, the five diagnosed product failures T1.4-1, T1.4-4, T7-6, T13.4-11, and P-1 — the same five CI's suite job reported at 1d16b45; 1183 s at FIX_PLAN Task 16's TypeScript staging survey, an instrumented run, the same five; 1090 s at FIX_PLAN Task 17 with `--reporter=verbose`, alone, the same five; 1095 s at FIX_PLAN Task 19, likewise, with T6.5-22(a)'s driver hook judging every performed move, the same five; 1240 s at FIX_PLAN Task 66, alone under the namespace with `--reporter=verbose --reporter=json --outputFile.json=` (the JSON report's per-test `failureMessages` open with the error class, so `HarnessAssertionError` — a diagnosed product failure, H-8 — is told from a harness error without reading the log): 345 tests, 317 passing, 28 failing, every failure a `HarnessAssertionError` — P-1, P-5, T1.4-1, T1.4-4, T4-2, T6.4-3, T6.5-4, T6.5-11, T6.5-20, T6.5-21, T6.5-22, T6.5-23, T6.6-3, T7-2, T7-6, T7.1-1, T7.3-1, T12.0-5, T12.0-10, T12.7-2, T13.4-9, T13.4-10, T13.4-11, T14-4, T14-6, T14-7, T14-11, T14-12 — the same 28 CI's suite job reported at a84033e and f8e031e; 1307 s at the re-descent's second plan's FIX_PLAN Task 14, its confirmation run, alone with the same reporters in CI's whole inner stage (network off as well; the unprivileged-identity bullet has the recipe): 345 tests, 317 passing, the same 28 failing, every one a `HarnessAssertionError`, and the same 28 CI's run 871 reported at 79d2013; 1105 s at the third plan's FIX_PLAN Task 11 (fdc3c49), its confirmation run, alone with the same reporters in CI's whole inner stage: 345 tests, 317 passing, the same 28 failing, every one a `HarnessAssertionError`, and the same 28 CI's run 888 reported at fdc3c49; 1288 s at the fourth plan's FIX_PLAN Task 12 (the plan written at 6a4a280), its confirmation run at 8bebeba's trees, alone with the same reporters in CI's whole inner stage: 345 tests, 317 passing, the same 28 failing, every one a `HarnessAssertionError`, and the same 28 CI's run 902 reported at 8bebeba; 1077 s at the fifth plan's FIX_PLAN Task 12 (the plan written at 1e2972e), its confirmation run at 7f59049's trees, alone with the same reporters in CI's whole inner stage: 345 tests, 317 passing, the same 28 failing, every one a `HarnessAssertionError`, and the same 28 CI's run 915 reported at 7f59049; that plan's VERIFY (4117ede) ran `npm test` in CI's inner stage in 1525.51 s; the sixth plan's VERIFY (68f0718) ran `npm test` in CI's inner stage in 1305.81 s, with another agent's Vitest beside it (CI run 917's full-suite job 1228.00 s, its Windows leg 39.50 s); 1102 s at the sixth plan's FIX_PLAN Task 6 (the plan written at 849b69d), its confirmation run at 715dff7's trees, alone with the same reporters in CI's whole inner stage: 345 tests, 317 passing, the same 28 failing, every one a `HarnessAssertionError`, and the same 28 CI's run 923 reported at 715dff7; the seventh plan's VERIFY (b00e7cd) ran `npm test` in CI's inner stage in 1591.70 s, with another agent's Vitest beside it (CI run 924's full-suite job 792.78 s, its Windows leg 39.62 s); in the seventh plan (written at 765d6b4), whose Task 2 made T11-1, T11-2, and T11-3 assert a root's tags absent where the built product reports `[]`, 1151.59 s at its Task 5 and 1180.48 s at its Task 5b, each in CI's inner stage: 345 tests, 314 passing, 31 failing — the same 28 plus T11-1, T11-2, and T11-3 — every one a `HarnessAssertionError`; 1178 s at its Task 6, its confirmation run at 107f624's trees, alone with the same reporters in CI's whole inner stage: 345 tests, 314 passing, 31 failing, every one a `HarnessAssertionError` — P-1, P-5, T1.4-1, T1.4-4, T4-2, T6.4-3, T6.5-4, T6.5-11, T6.5-20, T6.5-21, T6.5-22, T6.5-23, T6.6-3, T7-2, T7-6, T7.1-1, T7.3-1, T11-1, T11-2, T11-3, T12.0-5, T12.0-10, T12.7-2, T13.4-9, T13.4-10, T13.4-11, T14-4, T14-6, T14-7, T14-11, T14-12 — and the same 31 CI's run 933 reported at 107f624 (its full-suite job's `npm test` in 883.45 s, its Windows leg 21.26 s); the eighth plan's VERIFY (34032b5) ran `npm test` in CI's inner stage in 1526.86 s (CI run 934's full-suite job 1066.59 s, its Windows leg 41.80 s); 1214.51 s at the eighth plan's FIX_PLAN Task 4 (the plan written at a2bfdf4), its confirmation run at 97c7c24's trees, alone with the same reporters in CI's whole inner stage: 345 tests, 314 passing, 31 failing, every one a `HarnessAssertionError` — P-1, P-5, T1.4-1, T1.4-4, T4-2, T6.4-3, T6.5-4, T6.5-11, T6.5-20, T6.5-21, T6.5-22, T6.5-23, T6.6-3, T7-2, T7-6, T7.1-1, T7.3-1, T11-1, T11-2, T11-3, T12.0-5, T12.0-10, T12.7-2, T13.4-9, T13.4-10, T13.4-11, T14-4, T14-6, T14-7, T14-11, T14-12 — and the same 31 CI's run 938 reported at 97c7c24 (its full-suite job's `npm test` in 906.32 s, its Windows leg 38.42 s); the ninth plan's VERIFY (f8f38eb) ran `npm test` in CI's inner stage in 1551.82 s, with two compliance reviewers' runs sharing the machine (CI run 939's full-suite job 1167.04 s, its Windows leg 48.46 s); 1165.05 s at the ninth plan's FIX_PLAN Task 10 (the plan written at c0f2915), its confirmation run at 8b20530's trees, alone with the same reporters in CI's whole inner stage: 345 tests, 314 passing, 31 failing, every one a `HarnessAssertionError` — P-1, P-5, T1.4-1, T1.4-4, T4-2, T6.4-3, T6.5-4, T6.5-11, T6.5-20, T6.5-21, T6.5-22, T6.5-23, T6.6-3, T7-2, T7-6, T7.1-1, T7.3-1, T11-1, T11-2, T11-3, T12.0-5, T12.0-10, T12.7-2, T13.4-9, T13.4-10, T13.4-11, T14-4, T14-6, T14-7, T14-11, T14-12 — and the same 31 CI's run 952 reported at 8b20530 (its full-suite job's `npm test` in 1219.67 s, its Windows leg 41.15 s); the tenth plan's VERIFY (7ef10b6) ran `npm test` in CI's inner stage with `NODE_OPTIONS` unset (CI's default heap) in 2034.44 s, with another reviewer's suite run sharing the machine (load about 10; CI run 953's full-suite job 1175.54 s, its Windows leg 40.34 s); 1027.06 s at the tenth plan's FIX_PLAN Task 10 (the plan written at 23e3b4a), its confirmation run at 0ad39cd's trees, alone with the same reporters in CI's whole inner stage, `NODE_OPTIONS` unset: 345 tests, 314 passing, 31 failing, every one a `HarnessAssertionError` — P-1, P-5, T1.4-1, T1.4-4, T4-2, T6.4-3, T6.5-4, T6.5-11, T6.5-20, T6.5-21, T6.5-22, T6.5-23, T6.6-3, T7-2, T7-6, T7.1-1, T7.3-1, T11-1, T11-2, T11-3, T12.0-5, T12.0-10, T12.7-2, T13.4-9, T13.4-10, T13.4-11, T14-4, T14-6, T14-7, T14-11, T14-12 — and the same 31 CI's run 963 reported at 0ad39cd (its full-suite job's `npm test` in 987.31 s, its Windows leg 24.41 s); the eleventh plan's VERIFY (7e232fb) ran `npm test` in CI's inner stage with `NODE_OPTIONS` unset in 1213.86 s (106 files, 4581 tests, the same 31 failing; CI run 964's full-suite job 1186.49 s, its Windows leg 23.22 s); 1119.37 s at the eleventh plan's FIX_PLAN Task 15 (the plan written at 8b068bf), its confirmation run at c88ab04's trees, alone with the same reporters in CI's whole inner stage, `NODE_OPTIONS` unset: 345 tests, 314 passing, 31 failing, every one a `HarnessAssertionError` — P-1, P-5, T1.4-1, T1.4-4, T4-2, T6.4-3, T6.5-4, T6.5-11, T6.5-20, T6.5-21, T6.5-22, T6.5-23, T6.6-3, T7-2, T7-6, T7.1-1, T7.3-1, T11-1, T11-2, T11-3, T12.0-5, T12.0-10, T12.7-2, T13.4-9, T13.4-10, T13.4-11, T14-4, T14-6, T14-7, T14-11, T14-12 — and the same 31 CI's run 979 reported at c88ab04 (its full-suite job's `npm test` in 730.23 s, its Windows leg 23.18 s); the twelfth plan's VERIFY (e6b7cb0) ran `npm test` in CI's inner stage with `NODE_OPTIONS` unset in 1487.16 s, with three harness runs sharing the machine (107 files, 4651 tests; 32 failures — the same 31 and S-2's scale vector timing out at 5408.9 ms against Vitest's 5000 ms default under a load average of about 14, passing alone in 1657–2075 ms and in CI in 2038 ms and 1010 ms; CI run 980's full-suite job 728.21 s, its Windows leg 37.14 s); 1042.68 s at the twelfth plan's FIX_PLAN Task 12 (the plan written at 5bfab19), its confirmation run at bb37aab's trees, alone with the same reporters in CI's whole inner stage, `NODE_OPTIONS` unset: 345 tests, 314 passing, 31 failing, every one a `HarnessAssertionError` — P-1, P-5, T1.4-1, T1.4-4, T4-2, T6.4-3, T6.5-4, T6.5-11, T6.5-20, T6.5-21, T6.5-22, T6.5-23, T6.6-3, T7-2, T7-6, T7.1-1, T7.3-1, T11-1, T11-2, T11-3, T12.0-5, T12.0-10, T12.7-2, T13.4-9, T13.4-10, T13.4-11, T14-4, T14-6, T14-7, T14-11, T14-12 — and the same 31 CI's run 992 reported at bb37aab (its full-suite job's `npm test` in 732.24 s, its Windows leg 39.33 s); the thirteenth plan's VERIFY (9a16fa4) ran `npm test` in CI's inner stage with `NODE_OPTIONS` unset in 1317.90 s (107 files, 4656 tests, the same 31 failing; CI run 993's full-suite job 1116.84 s, about 1.5 times runs 980 and 992 (728.21 s and 732.24 s) across every file — section-16-p12 from 159 s to 245 s — with the file and test counts unchanged, so a slower runner rather than a harness change, 18.6 minutes of the job's 45-minute limit; its Windows leg 37.50 s); 994.80 s at the thirteenth plan's FIX_PLAN Task 3 (the plan written at bff95ed), its confirmation run at 87d419b's trees, alone with the same reporters in CI's whole inner stage, `NODE_OPTIONS` unset: 345 tests, 314 passing, 31 failing, every one a `HarnessAssertionError` — P-1, P-5, T1.4-1, T1.4-4, T4-2, T6.4-3, T6.5-4, T6.5-11, T6.5-20, T6.5-21, T6.5-22, T6.5-23, T6.6-3, T7-2, T7-6, T7.1-1, T7.3-1, T11-1, T11-2, T11-3, T12.0-5, T12.0-10, T12.7-2, T13.4-9, T13.4-10, T13.4-11, T14-4, T14-6, T14-7, T14-11, T14-12 — each with the whole failure message of that VERIFY's run, and the same 31 CI's run 996 reported at 87d419b (its full-suite job's `npm test` in 1129.00 s, near run 993's 1116.84 s, so the slower runner persisted; its Windows leg 30.43 s); the fourteenth plan's VERIFY (bae4ad1) ran `npm test` in CI's inner stage with `NODE_OPTIONS` unset in 1722.68 s, with three other agents' suite runs sharing the 4-core machine (load average up to about 16; 107 files, 4658 tests, the same 31 failing; P-12 took 480.5 s of its 600 s `timeoutMs` there, a load artifact; CI run 997's full-suite job 875.57 s, P-12 189.5 s in it, its Windows leg 23.97 s); 970.60 s at the fourteenth plan's FIX_PLAN Task 4 (the plan written at 633df12), its confirmation run at 31bae80's trees, alone with the same reporters in CI's whole inner stage, `NODE_OPTIONS` unset: 345 tests, 314 passing, 31 failing, every one a `HarnessAssertionError` — P-1, P-5, T1.4-1, T1.4-4, T4-2, T6.4-3, T6.5-4, T6.5-11, T6.5-20, T6.5-21, T6.5-22, T6.5-23, T6.6-3, T7-2, T7-6, T7.1-1, T7.3-1, T11-1, T11-2, T11-3, T12.0-5, T12.0-10, T12.7-2, T13.4-9, T13.4-10, T13.4-11, T14-4, T14-6, T14-7, T14-11, T14-12 — each at that VERIFY's first diagnosis, P-1's and P-5's whole failure messages unchanged, T12.0-14 and P-12 passing (P-12 in 226.7 s), and the same 31 CI's run 1001 reported at 31bae80 (its full-suite job's `npm test` in 1224.09 s, about 1.4 times run 997's 875.57 s across the files (per-file ratios 1.15 to 1.51 over the 76 files taking more than 5 s; section-16-p12 from 189.5 s to 269.7 s, 45% of its 600 s `timeoutMs`), the suite project's 79 files and 345 tests unchanged, so a slower runner rather than a harness change; its Windows leg 38.71 s); in the 13.5 re-descent (the plan written at 772854b, whose FIX_PLAN Tasks 3–48 made 28 registered tests and the E-6 writer test fail against the built product, which predates 13.5's revision: its lock still in the temporary folder, its inventory without `lock`), 1187.32 s at its FIX_PLAN Task 50, its confirmation run at 33e7d0b's trees, alone under `unshare --map-user` with the same reporters, `NODE_OPTIONS` unset, T13.5-10's and T13.5-9's files (`test/suite/section-13.5-ii.test.ts`, `test/suite/section-13.5-v.test.ts`) left out as needing administrative access (their machine arms run `sudo`): 86 files, 351 tests, 324 passing, 27 failing, every one a `HarnessAssertionError` — P-10, P-14, P-15, T6.1-1, T6.6-3, T7-2, T7-4, T10.1-6, T11.6-1, T11.6-3, T11.6-4, T12.7-3, T13.4-12, T13.5-1, T13.5-2, T13.5-3, T13.5-4, T13.5-6, T13.5-7, T13.5-8, T13.5-11, T13.5-12, T13.5-13, T14-6, T14-9, T14-10, and the E-6 writer — the slowest P-12 (248.73 s of its 600 s `timeoutMs`), T6.6-3 (173.94 s of its 420 s), T14-4 (115.73 s), P-8 (110.68 s), P-4 (105.78 s), P-5 (89.87 s), T14-7 (89.71 s), and P-9 (80.16 s); and the same 27 beside T13.5-9 and T13.5-10 CI's run 1203 reported at 33e7d0b (its full-suite job's `npm test`, 127 files, 4797 tests, in 1099.30 s: 29 failed, every one a `HarnessAssertionError`, the same 29 as runs 1200 and 1201 (1475.63 s and 1289.31 s); its slowest suite files section-16-p12 200.9 s, section-14 195.0 s, and section-6.6 112.1 s; T13.5-10's file 7.1 s and T13.5-9's 7.2 s, each failing diagnosed before its machine arms; no `e6-linux-outputs` artifact, the writer failing before it writes one; its Windows leg 29.43 s, 3 files, 9 tests, 2 failing diagnosed — the byte-identity test at the exclusion probe's dead-entry assertion after the Windows kill, T11.6-1's drive-mismatch premise at `$.lock`); in the plan written at 092db72 (iteration 55's, whose FIX_PLAN Tasks 1 and 2 gave each refused T6.6-3 preview a compare of its own and T13.4-12 its count halves), 1233.78 s at its FIX_PLAN Task 3, its confirmation run at b9eb318's trees, alone under `unshare --map-user` with the same reporters, `NODE_OPTIONS` unset, and the same two files left out: 86 files, 351 tests, 324 passing, 27 failing, every one a `HarnessAssertionError`, the same 27 as at 33e7d0b and at iteration 55's VERIFY (9583e3b) — T6.6-3 failing at its runs-while-held arm's count half (172.57 s of its 420 s), T13.4-12 at its leftover-free twin's `inventory` (`$.lock`, 0.76 s) — the slowest of the rest P-12 (255.19 s of its 600 s `timeoutMs`), P-4 (118.98 s), P-8 (117.28 s), T14-4 (107.23 s), T14-7 (101.39 s), P-9 (89.09 s), and P-5 (88.33 s); and the same 27 beside T13.5-9 and T13.5-10 CI's run 1207 reported at b9eb318 (its full-suite job's `npm test`, 127 files, 4797 tests, in 1474.00 s: 29 failed, every one a `HarnessAssertionError`, the same 29 as run 1204 at 9583e3b (1465.13 s); its slowest suite files section-16-p12 273.4 s, section-14 265.1 s, section-6.5-iii 154.2 s, and section-6.6 152.7 s; T13.5-10's file 9.4 s and T13.5-9's 10.0 s, each failing diagnosed before its machine arms; T6.6-3 135.03 s and T13.4-12 0.62 s; its `certification.test.ts` 364.4 s beside the suite project; no `e6-linux-outputs` artifact; its Windows leg 41.66 s, 3 files, 9 tests, the same 2 failing diagnosed); in the plan written at acfff0b (iteration 59's, whose FIX_PLAN Task 1 compared T6.1-1's journal through the certified snapshot machinery and whose Task 3 held P-10's compared view to the session directory's sessions), 1201.64 s at its FIX_PLAN Task 2, its confirmation run at 6ada37b's trees, alone under `unshare --map-user` with the same reporters, `NODE_OPTIONS` unset, and the same two files left out: 86 files, 351 tests, 324 passing, 27 failing, every one a `HarnessAssertionError`, the same 27 as at b9eb318 and at iteration 59's VERIFY (a126add) — T6.1-1 failing at its never-modifies sweep's `inventory` answer (`$.lock`, 9.65 s), P-10 at seed 271828183's trial 3, a `move` killed while held (`found nothing at .xspec/lock`, 37.38 s of its 600 s `timeoutMs`) — the slowest of the rest P-12 (246.17 s of its 600 s `timeoutMs`), T6.6-3 (175.31 s of its 420 s, failing at its runs-while-held arm's count half), T14-4 (110.07 s), P-8 (109.61 s), P-4 (107.03 s), T14-7 (104.13 s), P-5 (91.72 s), and P-9 (88.02 s); and the same 27 beside T13.5-9 and T13.5-10 CI's run 1212 reported at 6ada37b (its full-suite job's `npm test`, 127 files, 4797 tests, in 1518.71 s: 29 failed, every one a `HarnessAssertionError`, the same 29 as runs 1208 at a126add (1458.67 s) and 1210 at ffee710 (1452.67 s); its slowest suite files section-16-p12 289.6 s, section-14 278.4 s, section-6.5-iii 156.9 s, and section-6.6 155.9 s; T13.5-10's file 9.9 s and T13.5-9's 10.3 s, each failing diagnosed before its machine arms; T6.1-1 10.13 s and P-10 58.97 s; its `certification.test.ts` 372.0 s beside the suite project; no `e6-linux-outputs` artifact; its Windows leg 45.92 s, 3 files, 9 tests, the same 2 failing diagnosed); in the plan written at 2d9cdf6 (the 2d9cdf6 determination's, whose FIX_PLAN Task 1 checked the second user's reach against the empty stub and whose Task 2 ran CI's harness-self job with no product installed), no local suite run, no product-facing test having changed, and CI's run 1219 at e55a7a1, its last harness change (its full-suite job's `npm test`, 127 files, 4797 tests, in 1476.27 s: 29 failed, every one a `HarnessAssertionError`, the same 29 as runs 1213 at 1418ab9 (1463.88 s) and 1214 at 2d9cdf6 (1477.03 s), each failing at run 1214's first diagnosis; its slowest suite files section-16-p12 274.3 s, section-14 264.0 s, section-6.6 153.6 s, and section-6.5-iii 152.3 s; T13.5-10's file 9.4 s and T13.5-9's 9.9 s, each failing diagnosed before its machine arms; T6.1-1 10.24 s and P-10 50.65 s; its `certification.test.ts` 363.2 s beside the suite project; the job 24 min 54 s of its 60 minutes; no `e6-linux-outputs` artifact; its Windows leg 35.69 s, 3 files, 9 tests, the same 2 failing diagnosed, the job 63 s); in the plan written at f50cf9f (the f50cf9f determination's, whose FIX_PLAN Task 1 pinned T5.3-1's cross-file dependency cycle's full path and whose Tasks 2 and 3 had P-10 poll the companions and graph data), no local suite run, each changed product test having run alone against the built product, and CI's run 1224 at a1e6ae5, its last harness change (its full-suite job's `npm test`, 127 files, 4797 tests, in 1522.93 s: 29 failed, every one a `HarnessAssertionError`, the same 29 as runs 1220 at f50cf9f (1457.40 s), 1222 at 513f8b5 (1113.92 s), and 1223 at 140178b (1106.19 s), each failing at run 1220's first diagnosis, T5.3-1 passing (2.29 s); its slowest suite files section-16-p12 284.2 s, section-14 274.2 s, section-6.5-iii 163.4 s, and section-6.6 154.0 s; T13.5-10's file 9.8 s and T13.5-9's 10.1 s, each failing diagnosed before its machine arms; T6.1-1 9.96 s and P-10 39.92 s, at seed 271828183's trial 2 of 3, a `move` killed past its hold (`found nothing at .xspec/lock`; run 1220's first failing episode a resolve's, timing's, E-5); its `certification.test.ts` 382.2 s beside the suite project; the job 25 min 41 s of its 60 minutes; no `e6-linux-outputs` artifact; its Windows leg 44.55 s, 3 files, 9 tests, the same 2 failing diagnosed, the job 75 s); in the plan written at d0c8039 (the d0c8039 determination's, whose FIX_PLAN Task 1 had P-10 judge each polled path of a run the kill ended against its start and its reader-free twin's final state, whose Task 2 added the human-report parity matchers, and whose Tasks 3 to 10 had the per-command tests assert the human reports' information, H-3), no local suite run, each changed product test having run alone against the built product, and CI's run 1236 at e9a530a, its last harness change (its full-suite job's `npm test`, 127 files, 4805 tests, in 1460.71 s: 29 failed, every one a `HarnessAssertionError`, the same 29 as run 1225 at d0c8039 (1293.56 s, 4797 tests), each failing at run 1225's first diagnosis but where timing chooses (E-5) — which P-10 episode and which P-14 read first meet the deviation, and which racer T13.5-13's held arm first finds refused — and Tasks 3 to 10's 21 strengthened tests passing; its slowest suite files section-16-p12 269.1 s, section-14 260.7 s, section-6.6 155.9 s, and section-6.5-iii 151.2 s; T13.5-10's file 9.5 s and T13.5-9's 9.5 s, each failing diagnosed before its machine arms; T6.1-1 10.14 s and P-10 37.04 s, at seed 271828183's trial 2 of 3, its shrunk counterexample's episode 1 of 3, a `resolve` killed past its hold (`found nothing at .xspec/lock`; run 1225's first failing episode a rename's); its `certification.test.ts` 359.4 s beside the suite project; the job 24 min 35 s of its 60 minutes; no `e6-linux-outputs` artifact; its Windows leg 46.65 s, 3 files, 9 tests, the same 2 failing diagnosed, the job 84 s); in the plan written at 93e22f1 (the 43c9a5e determination's, whose FIX_PLAN Tasks 1 to 3 had T12.4-1, T12.3-1, and T8.2-1 assert every datum of the human `show`, `ids`, and `coverage` reports, whose Task 4 added the stable-code matcher `codeMention`, and whose Tasks 5 to 7 had T14-1, T14-7, and T13.3-3 assert every human findings report's codes, locations, concerned paths, and identities, H-3), no local suite run, each changed product test having run alone against the built product, and CI's run 1245 at f5f7ab2, its last harness change (its full-suite job's `npm test`, 127 files, 4809 tests, in 1622.63 s: 29 failed, every one a `HarnessAssertionError`, the same 29 as run 1237 at 43c9a5e (1506.77 s, 4805 tests), each failing at run 1237's first diagnosis but where timing chooses (E-5) — which P-10 episode and which P-14 read first meet the deviation — and the six strengthened tests passing, T14-7 in 174.88 s of its 600 s `timeoutMs` (93.12 s of its former 300 s in run 1237, before its 169 human runs) and T13.3-3 in 25.11 s (17.04 s in run 1237); its slowest suite files section-14 360.4 s (265.6 s in run 1237), section-16-p12 296.1 s, section-6.6 169.7 s, and section-6.5-iii 166.9 s; T13.5-10's file 10.3 s and T13.5-9's 10.5 s, each failing diagnosed before its machine arms; T6.1-1 10.74 s and P-10 49.53 s, at seed 271828183's trial 2 of 3, its shrunk counterexample's episode 1 of 3, a `resolve` killed past its hold (`found nothing at .xspec/lock`; run 1237's first failing episode a move's); its `certification.test.ts` 387.3 s beside the suite project; the job 27 min 17 s of its 60 minutes; no `e6-linux-outputs` artifact; its Windows leg 35.30 s, 3 files, 9 tests, the same 2 failing diagnosed, the job 82 s); in the plan written at affd85f (the affd85f determination's, whose FIX_PLAN Task 1 had T1.5-1 ask its human reports every identity and path, whose Tasks 2 and 3 had T10.1-4 and T14-4 decode their corrupt-session reports under `--json`, and whose Tasks 4 and 5 made the built product's missing artifact a diagnosed failure, H-8, and swept every product-facing body against one), no local suite run, each changed product test having run alone against the built product, and CI's run 1253 at 0c927d8, its last harness change (its full-suite job's `npm test`, 127 files, 4813 tests, in 964.37 s: 29 failed, every one a `HarnessAssertionError`, the same 29 as run 1246 at affd85f (1140.50 s, 4809 tests), each failing at run 1246's first diagnosis but where timing chooses (E-5) — which P-14 read first meets the deviation (`query nodes`; run 1246's `view specs/sub/Zo.mdx`) — and the three strengthened tests passing, T1.5-1 in 7.56 s (9.1 s in run 1246), T10.1-4 in 47.59 s of its 360 s `timeoutMs` (38.4 s in run 1246, before its `--json` runs), and T14-4 in 74.45 s of its 480 s (89.1 s in run 1246); the files about 0.83 times run 1246's (the median over the 74 suite files taking more than 5 s there, 0.63 to 1.13, section-10.1 the slowest-growing at 1.13 with T10.1-4's new runs), the suite project's 88 files and 353 tests unchanged, so a faster runner rather than a harness change; its slowest suite files section-14 214.4 s, section-16-p12 176.4 s, section-6.6 96.8 s, and section-6.5-iii 89.6 s; T13.5-10's file 5.8 s and T13.5-9's 6.2 s, each failing diagnosed at its arm (a), before its machine arms; T6.1-1 5.92 s and P-10 26.22 s, at seed 271828183's trial 3 of 3, its shrunk counterexample's episode 1 of 2, a `move` killed while held (`found nothing at .xspec/lock`), run 1246's diagnosis; its `certification.test.ts` 283.4 s beside the suite project; the job 16 min 17 s of its 60 minutes; no `e6-linux-outputs` artifact; its Windows leg 47.33 s, 3 files, 9 tests, the same 2 failing diagnosed, T1.5-1 passing in 16.42 s with its human-form checks, the job 96 s); in the plan written at a71eb0c (the a71eb0c determination's, whose FIX_PLAN Task 1 had the `review list` decoder read a listing's findings in the 12.7 form, required whenever a session is listed corrupt, whose Tasks 2 to 5 had T10.1-4, T10.7-5, T14-10(c), and T14-4 ask the listing's condition-21 findings, whose Task 6 had T13.4-6 decode its refused durable attempts under `--json`, whose Tasks 7 to 9 had T10.5-4, T10.6-2, and T10.7-4 stage SPEC 10.5's absent-scope item-id tie, and whose Task 10 made T13.4-5's never-regenerated arm journal-neutral, the deleted-journal check moving to T6.1-1), no local suite run, each changed product test having run alone against the built product, and CI's run 1266 at 58361cb, its last harness change (its full-suite job's `npm test`, 127 files, 4818 tests, in 934.67 s: 29 failed, every one a `HarnessAssertionError`, the same 29 as run 1254 at a71eb0c (1516.17 s, 4813 tests), each failing at run 1254's first diagnosis but where timing chooses (E-5) — which P-14 read first meets the deviation (`at specs/sub/Zo.mdx 0`, round 1; run 1254's `occurrences`, round 0) — T6.1-1 at its sweep's `inventory`, its new deleted-journal arm passing before it, and T14-10 at its arm (b), before the strengthened (c), both `$.lock` absent, and the other eight strengthened tests passing, T10.1-4 in 45.45 s of its 360 s `timeoutMs` (78.3 s in run 1254), T14-4 in 70.15 s of its 480 s (116.1 s in run 1254), T10.7-5 in 3.84 s, T13.4-6 in 6.20 s, T10.5-4 in 14.71 s, T10.6-2 in 11.77 s, T10.7-4 in 6.80 s, and T13.4-5 in 4.51 s; the files about 0.61 times run 1254's (the median over the 78 suite files taking more than 5 s there, 0.44 to 0.82, section-10.7-i the slowest-growing at 0.82 with T10.7-4's new sub-fixture), the suite project's 88 files and 353 tests unchanged, so a faster runner rather than a harness change; its slowest suite files section-14 200.5 s, section-16-p12 163.6 s, section-6.6 95.7 s, and section-6.5-iii 87.9 s; T13.5-10's file 5.7 s and T13.5-9's 5.8 s, each failing diagnosed at its arm (a), before its machine arms; T6.1-1 6.83 s and P-10 22.39 s, at seed 271828183's trial 2 of 3, its shrunk counterexample's episode 3 of 3, a `resolve` killed past its hold (`found nothing at .xspec/lock`), run 1254's diagnosis; its `certification.test.ts` 280.1 s beside the suite project; the job 15 min 47 s of its 60 minutes; no `e6-linux-outputs` artifact; its Windows leg 38.81 s, 3 files, 9 tests, the same 2 failing diagnosed, the job 71 s); in the plan written at 9bdb418 (the 9bdb418 determination's, whose FIX_PLAN Task 1 had T12.7-2 stage the locations key's proper-prefix rule, whose Task 2 had T12.7-3's physical-resolution arm pass the link as `PWD`, whose Task 3 left T7-6's code-side emit destination `specs/A.md` empty before its `build`, and whose Task 4 had P-10 inspect the lock path only once the episode's readers have settled), no local suite run, each changed product test having run alone against the built product, and CI's run 1272 at b5ac9a8, its last harness change (its full-suite job's `npm test`, 127 files, 4818 tests, in 1536.63 s: 29 failed, every one a `HarnessAssertionError`, the same 29 as run 1267 at 9bdb418 (1602.53 s, 4818 tests), each failing at run 1267's first diagnosis but where timing chooses (E-5) — which P-14 read first meets the deviation (`ids --json`, round 1; run 1267's `occurrences`, round 0), which of T13.5-13's four overlapping commands creates no hold file in its trial 1 (`rename specs/B.mdx b b2`; run 1267's `rename specs/A.mdx g g2`), and which episode of P-10's shrunk counterexample meets the deviation — T12.7-3 at its last arm, the busy workspace, its symlink arm passing before it, in 6.60 s (6.76 s in run 1267), P-10 in 47.40 s of its 600 s `timeoutMs` (44.40 s in run 1267), at seed 271828183's trial 2 of 3, its shrunk counterexample's episode 3 of 3 (run 1267's episode 1 of 3), a `resolve` killed past its hold (`found nothing at .xspec/lock`), its lock path inspected once the episode's readers had settled, and the other two changed tests passing, T12.7-2 in 6.79 s (7.12 s in run 1267) and T7-6 in 5.15 s (5.43 s in run 1267); the files about 0.96 times run 1267's (the median over the 80 suite files taking more than 5 s there, 0.91 to 1.07, section-16-p10 the slowest-growing at 1.07, P-10's shrunk counterexample failing at its episode 3 rather than 1), the suite project's 88 files and 353 tests unchanged; its slowest suite files section-14 339.5 s, section-16-p12 280.9 s, section-6.6 156.3 s, and section-6.5-iii 153.8 s; T13.5-10's file 9.6 s and T13.5-9's 9.8 s, each failing diagnosed at its arm (a), before its machine arms; its `certification.test.ts` 364.6 s beside the suite project; the job 26 min 0 s of its 60 minutes; no `e6-linux-outputs` artifact; its Windows leg 43.79 s, 3 files, 9 tests, the same 2 failing diagnosed, the job 77 s); in the plan written at 2a2b94e (the 2a2b94e determination's, the first after the jump-back revised SPEC.md, TEST-SPEC.md, and CERTIFICATIONS.md, whose FIX_PLAN Tasks 1–138 and 140 brought the harness and its certification fixtures to the revised documents), no local suite run, each changed product test having run alone against the built product, and CI's run 1547 at a3cc3ed, its last task's push, 587b721's harness trees (its full-suite job's `npm test`, 133 files, 5395 tests, in 2708.40 s: 45 failed, every one a `HarnessAssertionError` in the suite project at an arm a task of that plan added or changed, each at the first diagnosis that task recorded — T1.2-2, T1.6-3, T4-3, T4.1-1, T4.1-3, T4.3-1, T4.4-1, T4.4-2, T4.5-1, and T13.1-2 at their CommonJS runtime arm (`Cannot find module './.xspec.impl.js'`); T10.2-1, T10.4-2, T10.5-2, T10.5-3, T10.5-4, T10.7-12, and T10.7-13 at a `metadata-consistency` item's absent metadata pair; T10.5-5, T10.5-8, T10.5-9, T10.6-3, and P-16 (seed 271828183's trial 1, shrunk to a lone root-prose edit) at an absent scope-node list; T6.3-6, T12.7-3, T13.5-8, T14-4, T14-6, and T14-10 at a given baseline's code-less journal error; T2.1-2, T10.1-4, T10.1-6, T10.2-2, T10.4-3, T10.4-6, T10.4-7, T10.4-8, T10.5-1, T10.7-1, T10.7-9, T10.7-15, T11.2-6, T12.0-10, T12.0-13, T12.0-15, and T12.3-1 each at its own — the same 44 as run 1545 at 160b7f5 (2015.19 s, 131 files, 5381 tests, P-16 not yet registered), their first diagnoses identical once temporary names, hashes, and item numbers are masked, and P-16; no harness error, crash, or hang; the files about 1.33 times run 1545's (the median over the 84 suite files taking more than 5 s there, 1.06 to 1.65), P-16's the only new suite file, so a slower runner rather than a harness change; its slowest suite files section-12.0-iv 661.1 s, section-16-p12 513.4 s, section-13.5-ii 440.7 s, section-14 346.7 s, and section-6.6 312.1 s; its slowest tests T12.0-15 661.1 s (failing at T10.1-4's decomposed state), P-12 513.4 s, T13.5-10 440.7 s, P-14 230.7 s, P-4 203.8 s, T6.6-3 164.0 s, T14-7 159.8 s, T11.5-1 149.1 s, and P-16 140.2 s; T13.5-10 and T13.5-9 (33.9 s) passing whole with the job's administrative access; its `certification.test.ts` 377.3 s beside the suite project; the job 45 min 23 s of its 90 minutes; the `e6-linux-outputs` artifact written; its Windows leg 26.42 s, 3 files, 10 tests, 1 failing diagnosed — T7-1's single-casing probe at `build`'s exit code (exit 2 with 14.14 at `xspec.config.ts`, the product reading `XSPEC.config.ts` through the case-insensitive filesystem's lookup: the Phase 10 deviation that plan's FIX_PLAN Task 54 recorded), the byte-identity test and T11.6-1's drive-mismatch arm passing — the job 57 s)) and `npm run test:self` ~6.5 min at the 2a2b94e plan's end, ~5.5–7 min at the 13.5 re-descent's Phase 9 end, ~3 min before it (89 s at 3285994, 113 s at Phase 10's Task 54, 137 s at the third plan's Task 11 in CI's whole inner stage, 179 s at the fourth plan's VERIFY (72d5126) and 177 s at its Task 12, likewise; 192.75 s at the fifth plan's VERIFY (4117ede) and 142 s at its Task 12 (7f59049's trees), likewise; 159.90 s at the sixth plan's VERIFY (68f0718), with another agent's Vitest beside it, and 147 s at its Task 6 (715dff7's trees), likewise; 176.08 s at the seventh plan's VERIFY (b00e7cd), with another agent's Vitest beside it, and 161 s at its Task 6 (107f624's trees, 4234 tests), likewise; 198.74 s at the eighth plan's VERIFY (34032b5), with the reviewers' runs sharing the machine, and 156 s at its Task 4 (97c7c24's trees, 4234 tests), likewise; 181.36 s at the ninth plan's VERIFY (f8f38eb), on a nearly idle machine, and 146 s at its Task 10 (8b20530's trees, 4236 tests), likewise; 206.51 s at the tenth plan's VERIFY (7ef10b6), with another reviewer's run sharing the machine, and 140 s at its Task 10 (0ad39cd's trees, 4236 tests), likewise, each with `NODE_OPTIONS` unset; 188.62 s at the eleventh plan's VERIFY (7e232fb), with another agent's Vitest beside it, and 142 s at its Task 15 (c88ab04's trees, 4306 tests), likewise, each with `NODE_OPTIONS` unset; 188.90 s at the twelfth plan's VERIFY (e6b7cb0), with two other agents' runs sharing the machine, and 146 s at its Task 12 (bb37aab's trees, 4311 tests), likewise, each with `NODE_OPTIONS` unset; 284.08 s at the thirteenth plan's VERIFY (9a16fa4), with two other agents' Vitest runs sharing the machine (load average up to about 15), and 132 s at its Task 3 (87d419b's trees, 4313 tests), likewise, each with `NODE_OPTIONS` unset; 263.33 s at the fourteenth plan's VERIFY (bae4ad1), on the shared machine, and 130 s at its Task 4 (31bae80's trees, 4315 tests), alone in CI's whole inner stage, each with `NODE_OPTIONS` unset; in the 13.5 re-descent (the plan written at 772854b), 334.04 s at its FIX_PLAN Task 48, 370.23 s and 393.49 s at its Task 49, and 350.03 s at its Task 50 (33e7d0b's trees, 37 files, 4434 tests, the `*.admin.test.ts` files left out), each alone under `unshare --map-user` with `NODE_OPTIONS` unset, `test/self/certification.test.ts` its critical path (343.7 s summed at Task 50, the slowest verifications VIOL-READERS-CLAIM's 32.4 s, VIOL-CORE-EARLYRELEASE's 29.2 s, VIOL-MD-CR's 22.0 s, VIOL-CORE-BUILDWAIT's 18.9 s, VIOL-MD-CLASS's 18.5 s, and VIOL-CORE-HOLDLINK's 16.9 s); 362.23 s at iteration 55's VERIFY (9583e3b), and in the plan written at 092db72 (iteration 55's), 344.8 s at its FIX_PLAN Task 1, 357 s at its Task 2, and 360.90 s at its Task 3 (b9eb318's trees, the same 37 files and 4434 tests), likewise, `certification.test.ts` 354.2 s summed at Task 3 (VIOL-READERS-CLAIM's 32.4 s, VIOL-CORE-EARLYRELEASE's 29.3 s, VIOL-MD-CR's 21.7 s, VIOL-CORE-BUILDWAIT's 19.0 s, VIOL-MD-CLASS's 18.0 s); 380.37 s at iteration 59's VERIFY (a126add), and in the plan written at acfff0b (iteration 59's), 415 s at its FIX_PLAN Task 1, 428.90 s at its Task 2's first attempt (ffee710's trees), 394.65 s at its Task 3, and 387.65 s at its Task 2 (6ada37b's trees, the same 37 files and 4434 tests), likewise, `certification.test.ts` 380.4 s summed at Task 2 (VIOL-READERS-CLAIM's 32.5 s, VIOL-CORE-EARLYRELEASE's 30.2 s, VIOL-MD-CR's 24.6 s, VIOL-MD-CLASS's 21.2 s, VIOL-CORE-BUILDWAIT's 19.1 s); 381.92 s at the 2d9cdf6 determination's VERIFY, and in the plan written at 2d9cdf6, with no product installed (`dist/` absent, H-8), 360.47 s at its FIX_PLAN Task 1, 340.80 s at its Task 2 (a4dae69's trees), and 352.89 s and 348.70 s, two runs, at its Task 3 (e55a7a1's trees, the same 37 files and 4434 tests), likewise, `certification.test.ts` 341.9 s summed at Task 3's second run, under the verbose and JSON reporters (VIOL-READERS-CLAIM's 32.2 s, VIOL-CORE-EARLYRELEASE's 29.0 s, VIOL-MD-CR's 20.5 s, VIOL-CORE-BUILDWAIT's 18.4 s, VIOL-MD-CLASS's 17.4 s); 390.37 s at the f50cf9f determination's VERIFY, and in the plan written at f50cf9f, 363.49 s at its FIX_PLAN Task 1, 365.39 s at its Task 2, 360.73 s at its Task 3, and 368.00 s at its Task 4 (a1e6ae5's trees, the same 37 files and 4434 tests), likewise, with no product installed, `certification.test.ts` 360.1 s summed at Task 4, under the default and JSON reporters (VIOL-READERS-CLAIM's 32.3 s, VIOL-CORE-EARLYRELEASE's 29.5 s, VIOL-MD-CR's 23.0 s, VIOL-CORE-BUILDWAIT's 18.9 s, VIOL-MD-CLASS's 18.8 s, CONF-READERS' 16.1 s); 404.31 s at the d0c8039 determination's VERIFY, and in the plan written at d0c8039, 390.4 s at its FIX_PLAN Task 1 (the same 37 files and 4434 tests), 388.11 s and 360.34 s, two runs, at its Task 2 (37 files, 4442 tests from then on), 383.61 s at its Task 3, 368.82 s at its Task 4, 387.89 s at its Task 5, 385.36 s at its Task 6, 403.40 s at its Task 7, 395.13 s at its Task 8, 404.23 s at its Task 9, 392.68 s at its Task 10, and 400.48 s at its Task 11 (e9a530a's trees), likewise, with no product installed, `certification.test.ts` 389.6 s summed at Task 11, under the default and JSON reporters (VIOL-READERS-CLAIM's 32.4 s, VIOL-CORE-EARLYRELEASE's 29.7 s, VIOL-MD-CR's 24.9 s, VIOL-MD-CLASS's 20.9 s, VIOL-CORE-BUILDWAIT's 19.3 s, CONF-READERS' 17.1 s); 614.33 s at the 43c9a5e determination's VERIFY, other agents sharing the machine, and in the plan written at 93e22f1, 391.97 s at its FIX_PLAN Task 1 (the same 37 files and 4442 tests), 382.38 s at its Task 2, 387.70 s at its Task 3, 372.44 s and 364.26 s, two runs, at its Task 4 (37 files, 4446 tests from then on), 355.72 s and 362.38 s, two runs, at its Task 5, 368.71 s at its Task 6, 365.48 s at its Task 7, and 357.49 s at its Task 8 (f5f7ab2's trees), likewise, with no product installed, `certification.test.ts` 350.1 s summed at Task 8, under the default and JSON reporters (VIOL-READERS-CLAIM's 32.2 s, VIOL-CORE-EARLYRELEASE's 29.4 s, VIOL-MD-CR's 21.2 s, VIOL-MD-CLASS's 18.7 s, VIOL-CORE-BUILDWAIT's 18.7 s, CONF-READERS' 15.7 s); 642.83 s at the affd85f determination's VERIFY, on the shared machine, and in the plan written at affd85f, 352.67 s at its FIX_PLAN Task 1 (the same 37 files and 4446 tests), 368.38 s at its Task 2, 351.75 s at its Task 3, 353.95 s at its Task 4 (37 files, 4447 tests), 368.43 s at its Task 5 (37 files, 4450 tests from then on), and 386.94 s at its Task 7 (0c927d8's trees), likewise, with no product installed, `certification.test.ts` 375.3 s summed at Task 7, under the default and JSON reporters (VIOL-READERS-CLAIM's 32.4 s, VIOL-CORE-EARLYRELEASE's 29.9 s, VIOL-MD-CR's 22.3 s, VIOL-MD-CLASS's 20.0 s, VIOL-CORE-BUILDWAIT's 19.0 s, CONF-READERS' 16.5 s), and the S-7 file 50.2 s (its stub registry sweep 39.1 s, its no-product registry sweep 10.1 s, its no-product layer-4 bodies 0.1 s); 922.45 s at the a71eb0c determination's VERIFY, under other agents' load, and in the plan written at a71eb0c, 392.92 s at its FIX_PLAN Task 1 (the same 37 files and 4450 tests), 412.61 s at its Task 2, 399.38 s at its Task 3, 397.09 s at its Task 4, 396.88 s at its Task 5, 393.41 s at its Task 6, 392.72 s at its Task 7 (37 files, 4453 tests), 410.74 s at its Task 8 (37 files, 4454 tests), 407.97 s at its Task 9 (37 files, 4455 tests from then on), 401.89 s at its Task 10, and 403.20 s at its Task 12 (58361cb's trees), likewise, with no product installed, `certification.test.ts` 394.2 s summed at Task 12, under the default and JSON reporters (VIOL-READERS-CLAIM's 32.4 s, VIOL-CORE-EARLYRELEASE's 30.0 s, VIOL-MD-CR's 23.8 s, VIOL-MD-CLASS's 20.5 s, VIOL-CORE-BUILDWAIT's 19.3 s, CONF-READERS' 18.1 s), and the S-7 file 55.8 s (its stub registry sweep 40.5 s, its no-product registry sweep 13.9 s, its no-product layer-4 bodies 0.3 s); 847.97 s at the 9bdb418 determination's VERIFY, under other agents' load, and in the plan written at 9bdb418, 389.00 s at its FIX_PLAN Task 1 (the same 37 files and 4455 tests), 394.47 s at its Task 2, 377.29 s at its Task 3, 363.39 s at its Task 4, and 360.74 s at its Task 5 (b5ac9a8's trees), likewise, with no product installed, `certification.test.ts` 351.3 s summed at Task 5, under the default and JSON reporters (VIOL-READERS-CLAIM's 32.2 s, VIOL-CORE-EARLYRELEASE's 29.2 s, VIOL-MD-CR's 20.7 s, VIOL-MD-CLASS's 17.6 s, VIOL-CORE-BUILDWAIT's 18.4 s, CONF-READERS' 15.5 s, VIOL-DISC-DERIVED's 1.2 s), and the S-7 file 45.1 s (its stub registry sweep 32.9 s, its no-product registry sweep 10.8 s, its no-product layer-4 bodies 0.2 s); 577.89 s at the 2a2b94e determination's VERIFY, under four parallel reviewers' load (37 files, 4455 tests, the C-1 manifest test failing), and in the plan written at 2a2b94e, 446.09 s at its FIX_PLAN Task 1 (the same 37 files and 4455 tests), 266.7–442.3 s at its later tasks (38 files from its Task 20 on, 39 from its Task 137, 40 from its Task 138), 372.77 s at its Task 138, and 386.43 s at its Task 139 (a3cc3ed's trees, 40 files, 5011 tests, all passed, certification 171 PASS / 48 FAIL / 0 error / 0 hang), likewise, an untracked `dist/` standing in the checkout throughout, which no self-test invokes; ~80–135 s in CI's harness-self job before the 13.5 re-descent (83.30 s in run 924, 127.83 s in run 933, 121.93 s in run 934, 131.20 s in run 938, 105.24 s in run 939, 131.21 s in run 952, 128.06 s in run 953, 133.41 s in run 963, 117.46 s in run 964, 114.02 s in run 979, 129.22 s in run 980, 129.27 s in run 992, 84.50 s in run 993, 129.93 s in run 996, 124.68 s in run 997, 122.77 s in run 1001) and ~240–390 s at its Phase 9 end and since, 39 files, 4444 tests, 4452 from the d0c8039 plan's FIX_PLAN Task 2 on, 4456 from the 93e22f1 plan's FIX_PLAN Task 4 on, 4457 from the affd85f plan's FIX_PLAN Task 4 on, 4460 from its Task 5 on, 4463 from the a71eb0c plan's FIX_PLAN Task 7 on, 4464 from its Task 8 on, 4465 from its Task 9 on, 40 files from the 2a2b94e plan's FIX_PLAN Task 20 on, 41 from its Task 137 on, 42 files and 5021 tests from its Task 138 on (322.58 s in run 1200, 321.61 s in run 1201, 254.73 s in run 1202, and 323.59 s in run 1203 — its `certification.test.ts` 271.7 s, VIOL-READERS-CLAIM's verification 31.6 s and VIOL-CORE-EARLYRELEASE's 27.7 s, the job 350 s from start to end; the same file took 307.3 s inside run 1203's full-suite `npm test`, beside the suite project; 323.17 s in run 1204 at 9583e3b, the job 352 s; 316.15 s in run 1207 at b9eb318, the 092db72 plan's last harness change — its `certification.test.ts` 266.5 s, VIOL-READERS-CLAIM's verification 31.6 s and VIOL-CORE-EARLYRELEASE's 27.7 s, the job 342 s from start to end; the same file took 364.4 s inside run 1207's full-suite `npm test`; 320.96 s in run 1208 at a126add, the job 353 s; 328.80 s in run 1210 at ffee710, the job 356 s, one test failing, CONF-READERS' P-10 (the false failure the acfff0b plan's FIX_PLAN Task 3 removed; its `certification.test.ts` 277.8 s); 307.48 s in run 1211 at de35117, ffee710's harness trees, all passing, the job 339 s; and 324.65 s in run 1212 at 6ada37b, the acfff0b plan's last harness change — its `certification.test.ts` 273.5 s, VIOL-READERS-CLAIM's verification 31.6 s and VIOL-CORE-EARLYRELEASE's 27.9 s, the job 355 s from start to end; the same file took 372.0 s inside run 1212's full-suite `npm test`; 298.29 s in run 1214 at 2d9cdf6, the job 326 s; 257.48 s in run 1216 at 06a291c, the job 278 s, and 250.20 s in run 1217 at 58022f6, the job 270 s, the last to build the product first (a 2–3 s step); with no product installed from the 2d9cdf6 plan's FIX_PLAN Task 2 on (no build step; a step confirming `dist/` absent, H-8), 241.54 s in run 1218 at a18abfc, the job 257 s, one test failing by design (that Task's temporary probe, which bound the reach check of `test/self/machine-staging.admin.test.ts` to the absent built product); 245.77 s in run 1219 at e55a7a1, the 2d9cdf6 plan's last harness change — its `certification.test.ts` 211.3 s, VIOL-READERS-CLAIM's verification 31.1 s and VIOL-CORE-EARLYRELEASE's 26.5 s, the job 262 s from start to end, 22% of its 20 minutes; the same file took 363.2 s inside run 1219's full-suite `npm test`; 323.95 s in run 1220 at f50cf9f, the job 346 s; 320.48 s in run 1222 at 513f8b5, the job 350 s; 305.67 s in run 1223 at 140178b, the job 330 s; 243.34 s in run 1224 at a1e6ae5, the f50cf9f plan's last harness change — its `certification.test.ts` 208.9 s, VIOL-READERS-CLAIM's verification 31.1 s, VIOL-CORE-EARLYRELEASE's 26.4 s, and CONF-READERS' 8.6 s, the job 259 s from start to end, 22% of its 20 minutes; the same file took 382.2 s inside run 1224's full-suite `npm test`; 324.02 s in run 1225 at d0c8039, the job 346 s; the jobs 290–363 s in runs 1226 to 1235 (fa4f9c0 to 566b16d), each green; 330.40 s in run 1236 at e9a530a, the d0c8039 plan's last harness change — its `certification.test.ts` 278.7 s, VIOL-READERS-CLAIM's verification 31.6 s, VIOL-CORE-EARLYRELEASE's 27.8 s, and CONF-READERS' 12.3 s, the job 358 s from start to end, 30% of its 20 minutes; the same file took 359.4 s inside run 1236's full-suite `npm test`; 277.76 s in run 1237 at 43c9a5e, the job 300 s; the jobs 274–361 s in runs 1238 to 1244 (93e22f1 to dc29471), each green; 326.36 s in run 1245 at f5f7ab2, the 93e22f1 plan's last harness change — its `certification.test.ts` 275.0 s, VIOL-READERS-CLAIM's verification 31.6 s, VIOL-CORE-EARLYRELEASE's 27.8 s, and CONF-READERS' 12.2 s, the job 351 s from start to end, 29% of its 20 minutes; the same file took 387.3 s inside run 1245's full-suite `npm test`; 315.77 s in run 1246 at affd85f, the job 341 s; the jobs 295–353 s in runs 1247 to 1252 (bf4a878 to 5d980d2), each green; 322.48 s in run 1253 at 0c927d8, the affd85f plan's last harness change — its `certification.test.ts` 263.8 s, VIOL-READERS-CLAIM's verification 31.6 s, VIOL-CORE-EARLYRELEASE's 27.8 s, and CONF-READERS' 11.7 s, the S-7 file 30.8 s (its stub registry sweep 22.1 s, its no-product registry sweep 8.0 s), the job 344 s from start to end, 29% of its 20 minutes; the same certification file took 283.4 s inside run 1253's full-suite `npm test`, and the S-7 file 19.6 s; 341.63 s in run 1254 at a71eb0c, the job 369 s; the jobs 255–378 s in runs 1255 to 1265 (395f7c6 to 32d67ff), each green; 315.96 s in run 1266 at 58361cb, the a71eb0c plan's last harness change — its `certification.test.ts` 259.7 s, VIOL-READERS-CLAIM's verification 31.6 s, VIOL-CORE-EARLYRELEASE's 27.7 s, and CONF-READERS' 11.7 s, the S-7 file 30.2 s (its stub registry sweep 21.9 s, its no-product registry sweep 7.7 s), the job 340 s from start to end, 28% of its 20 minutes; the same certification file took 280.1 s inside run 1266's full-suite `npm test`, and the S-7 file 22.7 s; 332.20 s in run 1267 at 9bdb418, the job 357 s; the jobs 297–346 s in runs 1268 to 1271 (741f7ac to 80c641a), each green; 322.37 s in run 1272 at b5ac9a8, the 9bdb418 plan's last harness change — its `certification.test.ts` 264.0 s, VIOL-READERS-CLAIM's verification 31.6 s, VIOL-CORE-EARLYRELEASE's 27.8 s, CONF-READERS' 11.7 s, and VIOL-DISC-DERIVED's 0.9 s, the S-7 file 31.0 s (its stub registry sweep 22.4 s, its no-product registry sweep 8.0 s), the job 344 s from start to end, 29% of its 20 minutes; the same certification file took 364.6 s inside run 1272's full-suite `npm test`, and the S-7 file 34.6 s; and 327.05 s in run 1339 at a909c5d, the 2a2b94e plan's FIX_PLAN Task 1 and its starting point (job 117004407714): 39 files, 4465 tests, all passed, its `certification.test.ts` 266.9 s, VIOL-READERS-CLAIM's verification 31.6 s, VIOL-CORE-EARLYRELEASE's 24.3 s, CONF-READERS' 12.5 s, and VIOL-DISC-DERIVED's 1.0 s, certification 171 PASS / 48 FAIL / 0 error / 0 hang, the S-7 file 33.2 s (its stub registry sweep 24.6 s, its no-product registry sweep 7.9 s), the job 350 s from start to end, 29% of its 20 minutes; and 387.76 s in run 1547 at a3cc3ed, the 2a2b94e plan's end, 587b721's harness trees (job 119800971857): 42 files, 5021 tests, all passed, its `certification.test.ts` 286.7 s, VIOL-READERS-CLAIM's verification 31.8 s, VIOL-CORE-EARLYRELEASE's 29.8 s, CONF-READERS' 13.2 s, and VIOL-DISC-DERIVED's 1.0 s, certification 171 PASS / 48 FAIL / 0 error / 0 hang, the S-7 file 42.2 s (its stub registry sweep 33.1 s, its no-product registry sweep 8.4 s), the job 414 s from start to end, 35% of its 20 minutes; the same certification file took 377.3 s inside run 1547's full-suite `npm test`, and the S-7 file 40.6 s); ~2.5 min in earlier plans, ~4 min with the suite running beside it; the box is saturated by either alone, so overlapping them risks timing-sensitive flakes). T13.5-2 (`test/suite/registry/section-13.5.ts`) runs on the default 120 s `timeoutMs`: from the 772854b plan's FIX_PLAN Task 15 on a full pass drives about 57 product invocations — the held workspace's staging, ten refusals, and five runs after command 1, two determinism repeats (nine each), and five unheld twins (four each) — 21 of them mutating runs that complete (each lengthened by any post-release dwell, VIOL-CORE-EARLYRELEASE's included) and 20 refused at acquisition; it took 3.7–5.2 s against the CONF-CORE fixtures that pass it, an estimated ~20 s for a conforming built product at the built product's ~0.33 s per invocation, and the 13.5-pre-revision built product fails it at its first held inspection in ~1.3 s. T13.5-3 (`test/suite/registry/section-13.5.ts`) runs on the default 120 s `timeoutMs` too: from the 772854b plan's FIX_PLAN Task 16 on a full pass drives about 68 product invocations — five kill-while-held trials of five runs each (the session staging's `build`, `review create`, and `review status`, the held run killed, the later command), the past-the-hold base's three staging runs, five twins, and seven kills per command (`PAST_THE_HOLD_KILL_FRACTIONS`, 35 in all) — and took 6.2–6.8 s alone against the CONF-CORE fixtures that pass it (8.5 s against VIOL-CORE-PARTIALWRITE, whose 50 ms derived-file intervals stretch `rename`'s and `move`'s lift-to-exit spans to ~134 ms); VIOL-CORE-EARLYRELEASE fails it at its first past-the-hold kill in ~14.4 s, VIOL-CORE-STALELOCK at its first later command in ~0.4 s, and the 13.5-pre-revision built product at its first held kill (`found nothing at .xspec/lock`) in ~1.3 s; an estimated ~30–40 s for a conforming built product at ~0.33 s per invocation. The CONF-CORE conformer's lift-to-exit spans run ~25–45 ms for all five mutating commands (its hold file polled every 15 ms), so its kills land before the last write, after it, and after the exit — every branch of the arm. VIOL-CORE-EARLYRELEASE's 1 s dwell (`EARLY_RELEASE_DWELL_MS` in `test/fixtures/conf-core/product.mjs`) lengthens every mutating run that acquires: against it T13.5-2 took ~25 s, T13.5-1 ~14 s, T13.5-8 ~6 s (~11 s from the 772854b plan's FIX_PLAN Task 20 on, ~14 s from its Task 21 on, ~20 s from the 2a2b94e plan's Task 118 on), T6.1-2, T10.4-5, and T13.4-5 ~4 s each, run one at a time. T13.5-4 (`test/suite/registry/section-13.5.ts`) runs on the default 120 s `timeoutMs`: from the 772854b plan's FIX_PLAN Task 18 on it drives 35 product invocations — its reads arm's 19, its `build` arm's 5 (on a workspace of its own the staging `build`, the held `rename`, and `build --json` while it holds, awaited before the lift; on its twin the staging `build` and the same `rename` held and lifted at once), and the storm's 11 — and took ~1.9 s alone against the CONF-CORE fixtures that pass it (3.1 s against VIOL-CORE-PARTIALWRITE, 5.9 s against VIOL-CORE-EARLYRELEASE, whose 1 s dwell each of the arm's two further held renames adds), VIOL-CORE-BUILDWAIT failing it in ~16.3 s at the `build` arm's 15 s bound (`runBounded`), and VIOL-CORE-CHATTYREADS, VIOL-CORE-READERENTRY, VIOL-CORE-EARLYWRITE, and the built product still at its first read during the hold, before the `build` arm; from its Task 17 its reads arm drove 19 product invocations (the staging `build` and `review create`, eight reads before the hold, the held `rename`, and the same eight reads while it holds, each followed by the held-state comparison and the inclusion check) beside the storm's 11, and took 1.5–2.1 s alone against the CONF-CORE fixtures that pass it (3.7 s against VIOL-CORE-EARLYRELEASE); VIOL-CORE-CHATTYREADS, VIOL-CORE-READERENTRY, and VIOL-CORE-EARLYWRITE fail it at its first read during the hold (`check`) in ~0.8 s, and the 13.5-pre-revision built product there too (`found nothing at .xspec/lock`) in ~3.5 s. From the 2a2b94e plan's FIX_PLAN Task 11 on, the storm's clean-build compare leaves out the lock path alone, the journal compared, and every CORE fixture passes the storm with the reads and `build` arms skipped on a scratch-backed copy (~0.25 s each; VIOL-CORE-PARTIALWRITE 0.65 s). The built product records the journal's SHA-256 in its graph data (`journalHash`, `null` when the journal is absent; `workspaceInputsOf`, `src/workspace/pipeline.ts`), so a stand-in creating or changing `.xspec/journal` before a later `build` or refreshing read changes `.xspec/graph.json` as well, an empty journal included; to red-check a journal-inclusive compare apart from graph data, change the journal only after the workspace's last `build` — scratchpad `t9j2a2_11/standin.mjs`, mode `finaljournal:` (a fresh `mktemp -d` directory per run), counts `build` starts per working directory and creates an empty `.xspec/journal` once the sixth (T13.5-4's storm workspace's final `build`; no other workspace of the test runs more than two) has exited, failing T13.5-4 at the storm compare (`removed .xspec/journal`). T13.5-8 (`test/suite/registry/section-13.5.ts`; no span guard of its own from the plan written at 2a2b94e's FIX_PLAN Task 18 on, S-3) drives 71 product invocations from that plan's Task 118 on (53 from the 772854b plan's FIX_PLAN Task 21 on, 43 before it, 14 before its Task 20) — on the failing workspace (`CORE_DECL`, a BOM-led `specs/B.mdx` added once `s` exists) its staging's four, the held `review resolve`, its four acquisition-first arms beside the holder and again at the obstructed lock path, and the gate's seam arm; on the acquisition-arm valid workspace (`ACQUISITION_DECL`: configured as T13.5-12(d)'s — spec `main: ["specs/**/*.mdx", "src/*.mdx"]`, code `app: ["src/*"]`, both matching any `.mdx` directly under `src` — its code group discovering `src/c.ts`, `specs/sub/S.mdx` beside `specs/A.mdx`) its staging's five (`build`, `review create` of `s` and of `c`, `review status` of each), the held `review resolve`, and its nine acquisition-first and four acquisition-after arms beside the holder and again at the obstructed lock path; the seam workspace's seven (`build`, the four usage-class seam arms, the two previews); and, last, on the journal-failing workspace (`CORE_DECL`; `rename specs/A.mdx g g2` writes the one-line journal before `s` is created, so the leaf item is `specs/A.mdx#g2`, and T6.1-3's garbage line is appended as line 2 once `s` exists) its staging's five (`build`, the rename, `review create` of `s`, `review status`, the premise `build --json`), the held `review resolve`, its five acquisition-first arms (the four, and `review create --base no-such-ref --name n`) beside the holder and again at the obstructed lock path, the journal-staged baseline's seam arm, and the gate's seam arm — and took ~4.7 s alone against the CONF-CORE fixtures that pass it (~5.4 s against VIOL-CORE-PARTIALWRITE, ~19.8 s against VIOL-CORE-EARLYRELEASE; the journal-failing workspace's arms ~1.2 s of it, ~6.2 s against VIOL-CORE-EARLYRELEASE), VIOL-CORE-NOLOCK failing it at the failing workspace's first held arm in ~0.4 s, VIOL-CORE-EARLYWRITE at the valid workspace holder's held-state comparison in ~1.2 s, and VIOL-CORE-LATEHOLD at the first seam-ordering arm (`rename specs/A.mdx nope x --json --test-hold `, its hold file never created) in ~3.2 s, every first line as before that task, the journal-failing workspace running last; on that workspace alone (a scratch copy of the body) VIOL-CORE-NOLOCK fails at its first held arm (the condition-13 finding, exit 1) and, past the four, at the journal-staged baseline (`journal-error` where `workspace-busy` is asserted), VIOL-CORE-LATEHOLD at the journal-staged baseline's seam arm (`journal-error` at once, no hold file), and every other CORE fixture passes; the built product (`src/` at 5a4617c) passes every arm before the journal-staged baseline's seam arm and fails there diagnosed, its error code-less (the ref resolved before the journal is read, as at T6.3-6), in ~20 s alone. Its acquisition-after arms stage `specs/sub` unlistable (mode 0o100, `stageReadRefusalOfDirectory`), so T13.5-8 needs the unprivileged recipe like the other Linux-leg stagings. T13.5-10 (`test/suite/registry/section-13.5-ii.ts`; from the 772854b plan's FIX_PLAN Task 22 on, its arms (a) and (b) of eight, (c) from its Task 23, (d) from its Task 24, (e)'s one-machine parts from its Task 25, and (e)'s other-machine part, (f), and (g) from its Task 26, and (h) from its Task 27) runs on an 1800 s `timeoutMs` (1500 s before its Task 26, 1200 s before its Task 25, 900 s before its Task 24): each of its 5 unstaged twins, 40 (a) runs (8 obstructions, each with the 5 commands), and 45 (b) runs (6 staged leftovers, a dead run's entry readable and with every permission removed, and a dead run's entry carried in by a copy of the whole workspace, each with the 5 commands) starts from a fresh session staging (`build`, `review create`, `review status`), the 15 dead-entry runs after a held `rename` killed under T13.5-3's discipline — 375 product invocations — and (c) adds per command a bracketing trial (the arm's session staging and a twin workspace's, two held `rename`s killed in the twin before the held `review resolve s --status skipped` starts and one once it holds, one more per further dead entry, the refused command, and the command once more), a permission run, and three alteration runs (the dead-content one after a fresh twin's held `rename` killed), about 190 more; arms (a) and (b) took 26.3 s alone against the CONF-CORE conformer (27.0 s against a neutral copy; 26–39 s against the CORE violators that pass it, 167.5 s against VIOL-CORE-EARLYRELEASE, whose 1 s dwell follows every acquiring run), VIOL-CORE-EARLYREFRESH failing it at (a)'s `review create` with `.xspec` a dangling link (its refresh before acquisition, exit 70) in ~5 s before the 2a2b94e plan's FIX_PLAN Task 14 (its foresight now meets that obstruction and refreshes nothing, the run exiting 2 with the conformer's `write-failure` at `.xspec`, hand-probed; T13.5-10 not re-run against it since), VIOL-CORE-EARLYWRITE (the killed `rename`'s writes landed) and VIOL-CORE-STALELOCK (busy, the reuse check finding no identifier listed) at (b)'s first dead-entry run in ~21 s, and the 13.5-pre-revision built product at (a)'s first run (exit 1, the 14.22 finding at `.xspec`) in ~7.7 s; with (c) the whole test took 36–38 s in three runs against the conformer ((c) alone ~14 s against a neutral copy), 40–56 s against the eight CORE violators still passing it and 255.4 s against VIOL-CORE-EARLYRELEASE, VIOL-CORE-NOLOCK failing it at (c)'s first bracketing trial (no refusal at the live entry, then `read-failure` at the unlistable leftovers) in ~25 s, and the built product failing (c), run alone, at its first twin kill (nothing at `.xspec/lock`); a product whose session staging takes the built product's ~2.1 s and whose mutating runs take ~1 s would need ~7.5 min. (d) adds per command ten stagings, each on a fresh workspace of its own — nine on a fresh session staging, the tenth an unbuilt workspace whose root is read-only — and one refused run on each, the two determinism arms (the empty leftover lock directories, `-wx` and `r-x`) two runs more each (a second staging on the same workspace, and one on a byte copy of it at another path): 45 session stagings and 70 refused runs, 205 product invocations; (d) alone took 14.0 s against the conformer, the whole test 53.5–59.5 s in three runs (54.3 s against a neutral copy), and such a product would need ~10.3 min, hence the 1200 s budget. (e)'s one-machine parts add 5 paired twins (a session staging, `rename specs/A.mdx a a2`, then one composing command — `rename specs/A.mdx g g2` in `rename`'s place, then `move`, `review create`, `resolve`, and `split`), 20 interference runs (the held `rename`'s entry deleted, or replaced under its name by a directory holding a file, a FIFO, or a symbolic link to an outside plain file, each with the 5 composing commands: a session staging, the held `rename`, the held command, and one further refused command), and 5 lock-directory-deleted runs (a session staging and the held command, `.xspec/lock` deleted during its hold), about 165 product invocations; (e) alone took 13.9 s against the conformer (T13.5-10's 5 unstaged twins included), the whole test 63.3 s, and such a product would need ~13 min, hence the 1500 s budget. Against the CORE violators (e) alone fails VIOL-CORE-EARLYWRITE at the held `rename`'s held-state comparison (its early graph write) and VIOL-CORE-NOLOCK at the further command (exit 0, no refusal); the other ten pass it (109.3 s against VIOL-CORE-EARLYRELEASE, ~13 s against the rest). Against the built product (e), run alone, fails at the held `rename`'s held-state comparison (count half: nothing at `.xspec/lock`), and the whole test still at (a)'s first run. From its Task 26 on, (e)'s other-machine part, (f), and (g) run last in the body (`machineArms`), so that every arm needing no administrative access runs first: their fresh process-identifier namespaces (launcher B, `openHarnessNamespace`, one per (e) trial; launcher A, `freshNamespaceLauncher`, for (f) and (g)) need the administrative access of E-1, so none of them runs in this sandbox (the self-project bullet's directive). A local run of T13.5-10 against a fixture passing every arm before them would reach `sudo`: cut the body's `await machineArms(product, twins, pairs, renamed);` line out first (scratchpad `t9j2_26/no_machine.py apply|restore `; rebuild it from this description if it is gone; without them the whole test took 60.3 s against the conformer before (h), and 66.7 s with (h) but for its section-form `move`), while S-7's empty stub (at its first twin's `build`) and the built product (at (a)'s first run) fail long before them. In CI they run alone, with the twins they need, through the exported `runT13510MachineArms(product)`, which returns (g)'s outcome per command: a temporary `test/self/zz-*.admin.test.ts` probe hands `runProductTests` a `ProductTestEntry` spread from T13.5-10's with that `run` and prints each result with `console.log`, which the harness-self job's log shows (Task 26's probe, `test/self/zz-t26-machine-arms.admin.test.ts`, is in commit 9b75446's tree; its last commit removed it). They add per command an (e) trial (a session staging, the held `rename`, a harness namespace opened and closed, the entered command), an (f) trial (a session staging, a launcher-A `rename` killed, the launcher-A command), and a (g) run (a session staging, the killed launcher-A `rename`, the command, and, refused, the command again), about 80 product invocations. In CI run 1154 (harness-self job 114364562673) they took 9.4 s alone against the conformer, its 10 twins included, and the whole test 90.9 s there; a product at the built product's speed would need ~15 min, hence the 1800 s budget. The conformer took (g)'s refused outcome for all five commands, and the machine arms alone fail the built product at (e)'s first trial, at the held `rename`'s held-state comparison (count half: nothing at `.xspec/lock`), in 17.4 s. From its Task 27 on, (h) runs between (e)'s one-machine parts and the machine arms: per command a session staging, the command with `.xspec` made `-wx` before it (`stageUnlistableArea`), `build`, and `check --json`, T13.5-10's commands with the section-form `move specs/A.mdx#g specs/A.mdx#a.g` (its own unstaged twin made at its turn) in the file form's place — 34 product invocations; (h) alone took 2.8 s against the conformer with that `move` dropped (it lies outside CONF-CORE's surface: the conformer fails at its twin, exit 70, a fixture scope error) and 17.4 s against the built product, which passes it (its lock in the temporary folder, so nothing it does at acquisition lists `.xspec`); a product at the built product's speed needs about half a minute more, within the 1800 s budget. Scratchpad `t9j2_27/only_h.py apply [onlyh] [nomove]` (then `restore `) cuts the machine arms out, `onlyh` also skipping (a)–(e) and `nomove` dropping the section-form `move`; `t9j2_27/make_standins.py ` writes one-deviation stand-ins over the conformer, each acting only where `.xspec` is unlistable (acquisition listing `.xspec` and reporting the refusal as `read-failure`, failing at the first command's exit; release listing it first; an extra stdout line; the journal append skipped; a stray file in the session directory; a stray file at the root; graph data's path left a directory; a marker `check` reports). Its (b), (c), (d), and (h) stagings remove permissions (mode-0o000 plain files at `.xspec/lock`, as a dead run's entry, and as the held run's live entry; `-wx` leftover directories in the lock directory; (d)'s lock directories, leftover directories, and `.xspec` made `-wx`, `r-x`, `rw-`, or read-only, and an unbuilt root read-only; (h)'s `.xspec` made `-wx`; `test/helpers/acquisition-staging.ts`), each verified on the harness first, so it needs the unprivileged recipe too. (c)'s bracketing needs Node's temporary directory (`os.tmpdir()`, so `TMPDIR`) on a filesystem that does not list a directory in creation order — ext4, which lists by name hash: `/tmp` here and on CI's runner (`stat -f -c %T /tmp` prints `ext2/ext3`); on tmpfs, which lists in creation order, every trial voids and T13.5-10 fails as a harness error (`VoidedTrialsExhaustedError`), so where `/tmp` is tmpfs run it with `TMPDIR` set to a directory on ext4. The order a filesystem lists a directory in is `fs.opendir`'s: Node's `fs.readdir` returns names sorted bytewise (libuv's scandir sorts them). A (c) trial voids about once in seven by design — the holder's entry can lie near one end of the listing order, which names placed at random reach slowly (3 of ~30 trials in one local run, each at the cheap leftover screen) — and reruns with a fresh holder, up to 8 attempts; `/proc/sys/kernel/pid_max` is 32768 here, so the conformer's `-…` entry names cross a digit-count boundary now and then, voiding a trial whose dead entries then fall on one side in byte order. T13.4-12 (`test/suite/registry/section-13.4-ii.ts`, the 772854b plan's FIX_PLAN Task 28; its count halves the 092db72 plan's FIX_PLAN Task 2) runs on a 300 s `timeoutMs`: 93 product invocations, 3 of them held `rename`s killed under T13.5-3's discipline — the leftover-free twin's 7 (`build`, `inventory`, `ids`, `move specs/A.mdx specs/B.mdx --preview`, `build`, then with `g`'s text edited `check` and `ids`), five readable stagings on fresh workspaces (`build`, the kill or the `stageLeftover` stagings, then `check`, `inventory`, `build`, the edit, `check`, `ids`: 31), the clean path's 11, two unreadable stagings (`build`, the kill, then `inventory`, `check`, `ids`, and the preview, each over its permission staged afresh: 12), and the manual remedy's eight obstructions (a session staging's three, then `rename`: 32). Wherever a directory occupies the lock path around a command that acquires nothing, the count half (`assertLockDirectoryEntries`) runs before the inclusion check: after each readable command over the dead run's entry (`{ entries: 1 }`) and over the lock directory's three occupants, each staged on its own at `.xspec/lock/` (`{ entries: 0, staged }`), and in `assertDeadEntryAlone` after each unreadable command, its permission restored (`{ entries: 1 }`). VIOL-CORE-READERENTRY (`test/fixtures/conf-core/bin-readerentry.mjs`, `noinv`) fails it at the readable dead-entry staging's `check --json`, count half (`found 2 entries`); cut to `arms=readable readable=4`, at that arm's `check --json`, count half (`found 1 entry`); to `arms=unreadable unreadable=1`, at `check --json`, count half (`found 2 entries`); `arms=unreadable unreadable=0` (`--x`) passes, its reader's entry creation refused in the unwritable lock directory. The whole body took ~38 s against the built product through the inventory-lock stand-in with its kills made by the CONF-CORE conformer (the built product leaves no entry in `.xspec/lock`), and ~5.5 s against the conformer with every `inventory`, `version`, and preview step cut (outside CONF-CORE's surface: unpatched, the conformer fails at the twin's `inventory`, exit 70, a fixture scope error). The built product fails it at the twin's `inventory` (`$.lock`; ~8 s for the registered test alone, 0.76 s of test time within the whole suite project at the 092db72 plan's FIX_PLAN Task 3, 0.62 s in CI run 1207's full-suite job), and through the inventory-lock stand-in at the readable dead-entry staging's kill (`found nothing at .xspec/lock`), passing every other arm (~34 s with the three dead-entry arms cut). Its unreadable stagings remove permissions (`stageReadRefusalOfDirectory`, `stageReadRefusalOfFile`, each verified on the harness first), so it needs the unprivileged recipe. Scratchpad `t9j55_2/only.py apply [nodead] [noinv] [hybridkill=] [notwin] [arms=readable,clean,unreadable,remedy] [readable=|unreadable=|remedy=]` (then `restore `; `t9j2_28/only.py` unchanged, its anchors holding in the module since) writes the body cut to arm subsets over the real module — `nodead` drops the dead-entry arms, `noinv` every `inventory`, `version`, and preview step, `hybridkill` makes the kills through another bin; `t9j55_2/run_zz.sh '' [only.py flags]` runs it through a temporary self-test (`test/self/zz-t9j55-2.test.ts`, removed again) against `node ` bindings, full diagnoses in `.json`, then restores the module from the pristine copy and checks it with `cmp` — take that copy from the module under test (`git show HEAD:test/suite/registry/section-13.4-ii.ts`, or the edited file), never an older one: it supersedes `t9j2_28/run_zz.sh`, whose fixed restore copy is 9583e3b's module and would overwrite later edits; and `t9j2_28/standin.mjs ` wraps the built product through the inventory-lock stand-in with one deviation per mode (`neutral` none; `checkadd` adds a plain file to the lock directory after `check`, failing the readable dead-entry staging's `check --json` at the count half, `found 2 entries`, through the conformer's kills). T13.5-11 (`test/suite/registry/section-13.5-iii.ts`, the 772854b plan's FIX_PLAN Tasks 29, 29b, and 29c; registered whole) drives 283 product invocations (263 before the plan written at 2a2b94e's FIX_PLAN Task 140; no span guard of its own from that plan's Task 18 on, S-3) — five session stagings each followed by one command's success (20), the usage errors past acquisition on one session staging (3 + 14), the refusals on another (3 + 10, a `review split` success and a `review status` among them), (a)'s failures past acquisition (ten session stagings of T13.5-8's valid workspace, each followed by one held command: 40) and acquisition's own failures (twenty session stagings each followed by one command, and five runs on unbuilt workspaces: 85), the busy refusal (3, the held `rename`, 5), (b)'s five `rename specs/A.mdx nope x` runs on unbuilt workspaces, (c) and (d) each a session staging and a held command per mutating command (20, and with (d)'s next `review create` 25), and last, on the Linux leg, (a)'s write failures on T13.5-7's own workspaces (`write-refusal-staging.ts`: eleven `prepareRefusalWorkspace` preparations of three runs each, then (a)'s held `rename`, (c)'s held `move` and held `rename` (on the emitted-Markdown variant, `out/specs/b/B.md` deleted first), (d)'s held `move`, (e)'s `review create` and `review status` and three held mutators, (f)'s `build` and two refreshing reads, (g)'s two held section moves, and (h)'s `build` and held `rename` (emission disabled first): 49, one `WRITE_FAILURE_ARMS` entry per write failure from that Task 140 on, 29 before it) — ~16 s against the CONF-CORE conformer, which passes every arm but those last write-failure arms, whose first `build` it refuses (exit 70, fixture scope error: `markdown` lies outside its surface; ~21 s in all); the built product passes it whole from the plan written at 2a2b94e on (CI run 1337), ~80 s alone under the namespace before that plan's Task 140 and ~86 s after it (it once failed diagnosed at (a)'s first failure past acquisition, the held-state comparison of `rename specs/A.mdx a a2` before `specs/sub` is made `--x`). Its `--x`, `-wx`, `r-x`, and `rw-` stagings, and the write-failure arms' read-only ones, need the unprivileged recipe. Red check of (a)'s write-failure arms over the built product (the plan written at 2a2b94e's FIX_PLAN Task 140): scratchpad `t9j2a2_140/standin.mjs ` (rebuild it from this description if it is gone) passes the invocation through (`spawnSync`, stdio inherited, exit status mirrored) and, in one mode, writes `.xspec/lock/leak` once one arm's run has exited 2 — `crename` ((c)'s rename, `out/specs/b` a directory), `gorigin` and `gz` ((g)'s two moves), `hbuild` and `hrename` ((h), `out/specs/A.md` and `src/app.ts` present), `all` (the five), each key judged before the run; through `t9j2a2_140/runmodes.sh T13.5-11 …` (the runner copied in from `t9j2a2_140/zz-t9j2a2_140.test.ts.src` and deleted afterwards) `pass` passes (98 s) and each of the five modes fails at its own arm's `.xspec/lock` absence (`a directory is at .xspec/lock, holding ".xspec/lock/leak"`, ~83–105 s each), while `all` passes the module before that Task (91 s). Scratchpad `t9j2_29/make_standins.py ` (rebuild it from this description if it is gone) writes its liveness stand-ins over the conformer, each one deviation in or around release: release listing the lock directory first and, refused, skipping every deletion (fails (c)); listing `.xspec` before deleting it (fails (b)'s `-wx` arm); keeping, or always removing, the area's directory (fail (b)'s first arm, or its empty-`.xspec` arm); removing the lock directory only where its acquisition created it (fails (b)'s empty-`.xspec/lock` arm); no release on success, on a usage error, or on exit 1 (fail (a)'s first success, usage error, or refusal); a busy refusal's release sweeping the lock directory (fails the busy arm); a refused deletion reported as a write failure, at any deletion or at the entry's alone (fail (b)'s read-only-root arm, or (d)); release forcing a refused deletion by giving the lock directory its write permission back (fails (d)'s residue); past the hold, the lock directory listed and a refused listing reported as `read-failure` (admitted by (c): passes); and a neutral copy (passes) — VIOL-CORE-STALELOCK fails (d)'s takeover and VIOL-CORE-NOLOCK the busy arm. `t9j2_29/run_zz.sh ''` runs it through a temporary self-test (`test/self/zz-t9j2-29.test.ts`, removed again) against `node ` bindings under the unprivileged recipe, full diagnoses in `.json`, ~4–16 s a bin. Scratchpad `t9j2_29b/make_standins.py ` writes the stand-ins of (a)'s failure arms, one deviation each over the conformer: no release after a read failure or a configuration error past acquisition, or after either alone (each fails (a)'s first arm past acquisition with that code); no release after acquisition's read or write failures, or after its write failures alone (fail the `-wx`, or the `r-x`, empty lock-directory arm); a refused examination of the lock path crashing (fails the unsearchable `.xspec` arm's premise); the argument checks first on a workspace holding no `.xspec` (fails the unbuilt arm's premise at `resolve`); the first discovery consulted (fails the first arm past acquisition at its premise); and a neutral copy (passes); `t9j2_29b/run_zz.sh` runs like Task 29's, through `test/self/zz-t9j2-29b.test.ts`. The write-failure arms lie outside CONF-CORE's surface, so they are checked around the built product: scratchpad `t9j2_29c/lockdir.mjs ` (rebuild it from this description if it is gone) is a lock-directory stand-in — for each acquiring invocation it creates `.xspec` where absent, `.xspec/lock`, and one empty plain-file entry before running the product, and afterwards deletes the entry, the lock directory, and a `.xspec` it created, ignoring refused deletions; modes `neutral`, `skip2` (no deletions when the product exits 2), `skip2:[:]` (the same for that command alone), `wrongpath` (an exit-2 `write-failure` document's `path` rewritten), and `buildlock` (the same around `build`, `query`, and `view`, kept on exit 2) — and `t9j2_29c/only.py apply [arms=]` (then `restore `) cuts the registered body to those arms (`WRITE_FAILURE_ARMS` indexes: 0 (a), 1 (c), 2 (d), 3 (e), 4 (f)'s `build`, 5 (f)'s reads) for `t9j2_29c/run_zz.sh` (through `test/self/zz-t9j2-29c.test.ts`): the cut passes against `neutral` (~12 s); `skip2` fails its first arm, and each held arm alone (`skip2`, `skip2:review:create`, `skip2:review:split`) at its own absence; `buildlock` fails (f)'s `build`, while (f)'s reads pass there (their read-only `.xspec` forbids creating the lock path, so only their premise can fail); `wrongpath` fails the premise of (a) and of the reads; and the bare built product fails (a)'s held-state comparison (`found nothing at .xspec/lock`) while (f)'s two arms, which take no hold, pass vacuously. T13.5-12 (`test/suite/registry/section-13.5-iv.ts`, the 772854b plan's FIX_PLAN Task 30; registered whole) runs on a 600 s `timeoutMs`: 67 product invocations — 23 `build`s, the 20 runs of (d)'s and (e)'s ten session stagings, 17 held runs, 6 twins' runs, and one `review status` — ~4 s against the CONF-CORE conformer, which passes its 13 arms within CONF-CORE's surface, run first ((c)'s two, (a)'s session-scope arm, (d)'s and (e)'s five each), and then fails at (a)'s `specs/R.mdx` arm, its twin's `rename` refused exit 1 (its parser takes the unquoted `d` prop for a 14.20 finding: outside its surface); run arm by arm it also fails (a)'s code-source arm at the twin's rewrite premise (it rewrites no marker) and (b)'s spec-source arm at its `build`, and passes (b)'s code-source arm; ~26 s against the built product inside the hold-first stand-in below, which passes it whole; the bare built product fails it diagnosed at its first held arm's held-state comparison (`found nothing at .xspec/lock`, ~1.4 s). Its (e) staging (`specs/sub` made `--x` during each hold) needs the unprivileged recipe. Scratchpad `t9j2_30/holdfirst.mjs ` (rebuild it from this description if it is gone) is a hold-first stand-in: for each acquiring invocation it creates `.xspec` where absent, `.xspec/lock`, and one empty plain-file entry, creates the `--test-hold` file itself (exclusively) and waits for its deletion, and only then runs the product with that pair removed — the built product's discoveries then all following the hold, as 13.5's second does (one discovery until FIX_PLAN Task 5 of the Phase 10 plan written at 6694886, two since) — releasing as `t9j2_29c/lockdir.mjs` does; `lockdir.mjs neutral` around the built product is a first-discovery product over the whole surface (it fails every T13.5-12 arm, (b)'s and (c)'s deletion arms included, reporting the vanished source as a 14.20 finding), and `t9j2_30/firstdisc/` (`product.mjs` with `rediscover` returning the first discovery, and `bin.mjs`) is one within CONF-CORE's surface (it fails every arm there, (c)'s deletion arm by crashing, exit 70, and (b)'s code-source arm at its graph data); `t9j2_30/tweak.mjs ` wraps the conformer with one deviation per mode — `stray-on-exit2` and `keep-lock-exit2` (a file in `.xspec`, or an entry left in the lock directory, after a mutating run exiting 2), `held-stdout`, `held-session` (a newline appended to a held `review create`'s session file), and `held-file` (a stray file after a held run) — each failing exactly the comparison it targets; `t9j2_30/run_zz.sh ''` runs T13.5-12 whole (`ZZ_MODE=whole`) or the arms `ZZ_ARMS` lists (indexes into the exported `T13_5_12_ARMS`, in body order: 0–1 (c), 2 (a)'s session scope, 3–7 (d), 8–12 (e), 13–14 (a)'s referencing sources, 15–16 (b)) against `node ` bindings through a temporary `test/self/zz-t9j2-30.test.ts`, which it always removes, under the unprivileged recipe, full diagnoses in `.json`. T13.5-9 (`test/suite/registry/section-13.5-v.ts`, wrapper `test/suite/section-13.5-v.test.ts`, the 772854b plan's FIX_PLAN Task 31; registered whole) runs on a 600 s `timeoutMs`: 83 product invocations — the five unheld twins' session stagings and operations (20), then per arm a session staging (`build`, `review create`, `review status`), the held `review resolve`, and five second runs (63 over its seven arms) — beside (d)'s three second-user probes and twelve `reclaimForHarness` calls. Its twins and its arms needing no administrative access ((a), (b)'s two working directories, (c)'s symbolic link: the exported `runT1359PlainArms`) run first and took 4.1 s against the CONF-CORE conformer here; its arms needing E-1's administrative access ((c)'s second mount, (d), and (d) again: the exported `runT1359MachineArms`) run last, so none of them runs in this sandbox, where a local run of the whole test against a conforming fixture would reach `sudo`: run the plain arms alone through a temporary `test/self/zz-*.test.ts` handing `runProductTests` an entry spread from T13.5-9's whose `run` calls `runT1359PlainArms` (scratchpad `t9j2_31/zz-t31-local.test.ts.saved`, which also builds the stand-ins below; rebuild it from this description if it is gone), and the machine arms in CI through a temporary `*.admin.test.ts` probe calling `runT1359MachineArms` (Task 31's, `test/self/zz-t31-reach.admin.test.ts`, is in commit cd9ba79's tree; the scratchpad keeps a copy beside the local one). In CI run 1167 (harness-self job 114418941946) the conformer passed the whole test in 8.6 s: every second run of (a)–(c), the second mount's included, `workspace-busy`; (d)'s five `write-failure` (the holder's own lock directory, 0755 under the runner's umask, refusing the second user's entry); and (d) again's five exactly `workspace-busy` (the second user still able to create and remove a file in the harness's 0770 lock directory once the holder held). One-deviation stand-ins of the conformer's `product.mjs` — acquisition judging no in-workspace entry, `judgeLockDirectory` replaced by an exclusive plain file outside the workspace (removed at release) keyed under `TMPDIR` (the plan's red check), by the working directory, by the root's path as `PWD` spells it, or per user (the uid with the root's device and inode); or the liveness judge replaced by a signal-0 probe reading `EPERM` as dead — fail diagnosed at (a), at (b)'s subdirectory, at (c)'s symbolic link (here; the machine arms alone, at (c)'s second mount in CI), at (d) again, and at (d) again (both in CI, the second user's `rename` proceeding, exit 0, its writes reclaimed). The built product fails it diagnosed at (a)'s held-state comparison (count half: `found nothing at .xspec/lock`; 7.6 s here), the machine arms alone at (c)'s second mount's (0.9 s in CI); S-7's sweep fails it diagnosed (its first product run is the first twin's staging `build`). With stdout redirected to a file (a background run), Vitest's default reporter prints nothing between the `RUN` banner and the final summary — passed files never get a line and failed files appear only at the end — so a silent log is not a hang; pass `--reporter=verbose` for per-test lines as they complete. T13.5-13 (`test/suite/registry/section-13.5-vi.ts`, wrapper `test/suite/section-13.5-vi.test.ts`, the 772854b plan's FIX_PLAN Task 32; registered whole, §CONF-RACE's one in-scope test) runs on a 600 s `timeoutMs`: its held arm, four trials on a freshly built and four on an unbuilt workspace, each starting its four held runs together (`startRuns`: every run spawned before any is awaited), then its unheld arm, one trial per spread fraction (0, 0.1, 0.25, 0.5, 0.75, 1 of the span the series' first command takes alone on its twin) for each of two series (three renames; three `review resolve`s on a session staging), twins made once per staging and order of the successes (`TwinCache`, at most 38). Against the CONF-RACE conformer (`test/fixtures/conf-race/bin.mjs`, ~80 ms a run) the whole test took 6.5 s here (7.4 s as its certification verification alone), every held trial one success, the unheld trials one to three; VIOL-RACE-LISTFIRST fails it at the first held trial, four hold files standing (3.2 s: its 3 s interval); the built product (~0.35 s a run) fails it diagnosed at the first held trial's first refused run, its error document's `code` and `path` `null` (0.75 s); S-7's sweep fails it diagnosed at the first trial's staging `build`. A conforming product at the built product's speed would take ~100 s, ~300 s at three times the load. Probe its arms through a temporary `test/self/zz-*.test.ts` that imports the registry index first and calls the exported `runT13513HeldArm(binding)` and `runT13513UnheldArm(binding)` inside `runProductTestBody("T13.5-13", …)` (each returns per-trial reports: a held trial's success, an unheld trial's successes in exit order; scratchpad `t9j2_32/zz-t32.test.ts.saved`, `ZZ_MODE` held|unheld|arms|body, `ZZ_BIN` a bin path or `dist`; rebuild it from this description if it is gone). Red and green checks with copies of the conformer's `product.mjs` changed once (scratchpad `t9j2_32/standins/`): VIOL-CORE-EARLYRELEASE and VIOL-CORE-NOLOCK fail the unheld arm alone at its resolve series (a resolution lost); NOLOCK with the journal rewritten from its reading (read, 20 ms, write whole) fails its rename series (appends lost) and passes with exclusion kept; a conforming slow lister (300 ms between adding its entry and listing) passes the held arm with no-success trials on both workspaces, and fails it at `.xspec/lock` (an empty directory) when its release keeps the lock directory; VIOL-CORE-EARLYWRITE fails the held arm at the held-state comparison's byte half; a creation race reported as a write failure passed all eight held trials (its window microseconds wide: caught on some runs only, E-5). T13.5-6 (`test/suite/registry/section-13.5-vii.ts`, wrapper `test/suite/section-13.5-vii.test.ts`, the 772854b plan's FIX_PLAN Task 33, which moved it out of `section-13.5.ts`) runs on a 600 s `timeoutMs`: four held arms — the sibling pair and the nested pair (`NESTED_DECL`: an inner root `in` within the outer root, each with its own `xspec.config.ts`), either workspace held — each on a fresh pair: two session stagings (`build`, `review create`, `review status`), the held `rename`, and the other workspace's five mutating commands (12 runs, ~4.1 s an arm at the built product's speed); then per pair a concurrent arm: a serial reference of two nine-step scripts and three trials (start offsets 0 and plus and minus a third of the first script's serial span; ~18.5 s a pair at the built product's speed). Against the CONF-CORE conformer (~75 ms a run) the whole test took 10.5 s; the built product (~0.35 s a run, its lock in the temporary folder) fails it diagnosed at the first held arm's held-state comparison (count half: nothing at `.xspec/lock`) in 2.2 s, and with that comparison and the only-entry check stubbed out (a scratch diagnostic, `t9j2_33/nolockchecks.py apply|restore `) it passed every arm, 54 s in all; S-7's sweep fails it diagnosed at the first staging `build`. A conforming product at the built product's speed would take ~55 s, ~165 s at three times the load. Probe its arms through a temporary `test/self/zz-*.test.ts` that imports the registry index first and calls the exported `runT1356HeldArm(binding, pair, held)` (`held` 0 or 1) and `runT1356ConcurrentArm(binding, pair)` over `T13_5_6_PAIRS` inside `runProductTestBody("T13.5-6", …)` (scratchpad `t9j2_33/zz-t33.test.ts.saved`, run by `t9j2_33/run_zz.sh body|arms|concurrent [repetitions]`, which always removes the probe; rebuild them from this description if they are gone). Red checks with copies of the conformer's `product.mjs` changed once (`t9j2_33/make_standins.py `): acquisition keyed by the outermost enclosing root holding an `xspec.config.ts` passes both sibling arms and fails both nested held arms (the outer root held: the inner root's first command refused; the inner held: its held-state comparison, its entry made under the outer root) and the nested concurrent arm in 5 of 5 repetitions (a busy refusal in some trial), while the conformer passed 10 of 10 concurrent arms; the same keying for `review split` alone fails only the outer-held nested arm, at its fifth command; acquisition that also removes every entry of enclosing roots' lock directories fails the outer-held nested arm at the count half once the inner root's commands have ended; a journal append mirrored into the outermost root's journal fails it at the byte half, and the nested concurrent arm at the outer journal. T13.5-7 (`test/suite/registry/section-13.5.ts`, its arms and kill arm in `test/suite/registry/write-refusal-staging.ts`; the 772854b plan's FIX_PLAN Task 34 added its lock-path assertions) runs on its 600 s `timeoutMs`: after each staged run but (b)'s, `.xspec/lock` absent (`assertNoLockPathAfter`); in (b), the residue — `assertLockDirectoryEntries(root, { entries: 0 })`, the emptied lock directory the read-only `.xspec` keeps — right after the run and again after `check`, `impact`, and `build`, then `review create --strategy audit --name r` (exit 0) and `.xspec/lock` absent; its kill arm kills the held rename's process group (`killHeldRun` at the held point; `startHeldAndLift`, now exported from `write-refusal-staging.ts` and imported by T13.5-3, then `killGroup` at the fixed delays 0–160 ms after the lift) and judges the lock path after each post-lift kill with the shared `assertLockPathAfterKill` (`test/helpers/lock-state.ts`, T13.5-3's past-the-hold judgement) before its journal and `check` assertions. The built product's rename spans ~95–110 ms here from lift to exit, so the 160 ms kill lands after its exit and the others before it. The bare built product fails T13.5-7 diagnosed at (b)'s residue (`found nothing at .xspec/lock`) in ~5 s; through the lock-directory stand-in (`t9j2_29c/lockdir.mjs neutral`, copied with extra modes to scratchpad `t9j2_34/lockdir2.mjs`) it passes whole in ~58 s, its kill arm alone ~31 s (each group kill waiting ~1 s for the stand-in's orphaned product to be reaped). Probe it through `t9j2_34/run_zz.sh ''` (`ZZ_MODE=whole`, or `ZZ_ARMS` from `a`, `b`, `c`, `d`, `e`, `fbuild`, `freads`, `kill`, `span`; it copies `t9j2_34/zz-t9j2-34.test.ts.saved` to `test/self/zz-t9j2-34.test.ts` and always removes it; rebuild them from this description if they are gone). Red checks: `lockdir2.mjs skip2` fails (a), (c), (d), and (e) at their absence checks and (b) at its residue (`found 1 entry`); `skip2:review:create` and `skip2:review:split` fail (e) at those commands; `buildlock` fails (f)'s `build`, while (f)'s reads pass (their read-only `.xspec` forbids creating the lock path: premise only); in (b), `busydir` (an acquiring run finding `.xspec/lock` exits 2 at once) fails the remover's exit, `sweepbuild` (`rmdir .xspec/lock` before a `build`) the residue's persistence, and `skipremover` (no release for an unheld `review create`) the final absence; the kill arm fails against the bare built product at the held-point kill (`found nothing at .xspec/lock`), against `keephold` (no release for a held run) at the 160 ms kill (the run ended first, its lock directory left), and against `t9j2_34/earlyrel.mjs ` (it releases once the hold file it saw is deleted) at the 0 ms kill (paths short, nothing at `.xspec/lock`), and passes through `neutral`. T10.1-6 (`test/suite/registry/section-10.1.ts`, the 772854b plan's FIX_PLAN Task 35) keeps its 360 s `timeoutMs`: its two `.xspec` stagings (`withT1016AreaStagings`: `build`, `review create --strategy audit --name s`, `review status s --json`, the link staging's journaled rename first — since the plan written at 2a2b94e's FIX_PLAN Task 65 the commit `c1` before all of them, and the link staging's second session `t` before the status read and its garbage journal line and corrupt `c.json` after it, the `arms` callback receiving `{ items, c1 }`) each run the reads', `build`'s, and (since that Task) `impact --base c1`'s sweep, then the five mutating commands under `--json` (`assertMutatingCommandsFailAtAcquisition`, a whole-root compare bracketing each run). Through the inventory-lock stand-in with its mutating commands on an occupied area answered by CONF-CORE (scratchpad `t9j2_35/acq.mjs `) the whole test passes in ~19 s (~16 s before the arm); the bare built product fails it diagnosed at `$.lock` (~1.7 s), and through the inventory-lock stand-in alone at the arm's first command, `rename specs/A.mdx a a2 --json` on the plain-file staging (exit 1 with the condition-22 finding; ~12 s). Probe it through `t9j2_35/run_zz.sh ''` (`ZZ_MODE=arm`: both stagings and the five commands alone, which the CONF-CORE reference serves, unlike `inventory` and `view`, in ~1 s; `ZZ_MODE=whole`: the whole test; it copies `t9j2_35/zz-t9j2-35.test.ts.saved` to `test/self/zz-t9j2-35.test.ts` and always removes it; rebuild them from this description if they are gone); `t9j2_35/perturb.mjs ` red-checks the arm (`path`, `code`, and `locs` fail at the error document's assertion, `exit1` at the exit, `file` and `link` at the compare; `pass` passes). T11.6-3 (`test/suite/registry/section-11.6.ts`, the 772854b plan's FIX_PLAN Task 36) keeps the default 120 s `timeoutMs`: its lock-path arms, last in its body (the exported `runT1163AreaArms`, `runT1163LeftoverArms`, and `runT1163HeldArm`), add five CONF-CORE-shaped workspaces and ~16 product runs. Through the hybrid reference (scratchpad `t9j2_36/standin.mjs hybrid `: every invocation answered by the built product with the inventory-lock stand-in's `lock` insertion, but one carrying `--test-hold` answered by CONF-CORE, so held and killed runs keep their entries in `.xspec/lock`) the whole test passes in ~11 s (~4.5 s before the arms) and T11.6-1, T11.6-2, and T11.6-4 pass as well; the bare built product fails it diagnosed at `$.lock` (~0.4 s), `standin.mjs lock` (the inventory-lock stand-in alone) at the dead-entry staging (~10 s), and the held arm alone at the held-state comparison's count half (`found nothing at .xspec/lock`). Probe it through `t9j2_36/run_zz.sh ''` (`ZZ_MODE=whole`, with `ZZ_IDS` naming other tests to run instead, or `ZZ_MODE=runT1163AreaArms`, `runT1163LeftoverArms`, or `runT1163HeldArm` for one runner alone; it copies `t9j2_36/zz-t9j2-36.test.ts.saved` to `test/self/zz-t9j2-36.test.ts` and always removes it; rebuild them from this description if they are gone). `standin.mjs`'s other modes red-check the arms: `recordlock` (the lock path's occupants added to `recorded`) fails the plain file at the lock path at the members check, `recordentries` (the lock directory's plain files alone) the dead entry there, and the held arm alone likewise, `badlock1` the `.xspec`-a-plain-file arm at its `lock` check, `clearlock` (a plain file at the lock path deleted before `inventory`) that leftover's inclusion check, and, the held arm alone, `readerentry` (an entry added beside the holder's) its held-state comparison's count half and `touchentry` (the holder's entry altered) its inclusion check. T11.6-1 (`test/suite/registry/section-11.6.ts`, the 772854b plan's FIX_PLAN Task 37) keeps the default 120 s `timeoutMs`: its member-invariance staging (`test/helpers/inventory-invariance.ts` `stageInvarianceWorkspace`: `build`, a journaled `rename`, `review create --strategy audit`) adds three product runs before its eleven `inventory` runs, each now decoded whole. Through the inventory-lock stand-in it passes in ~5 s (~3.5 s before the arm); the bare built product fails it diagnosed at the root run's `$.lock` (~1.2 s). Probe it through `t9j2_37/run_zz.sh ''` (`ZZ_MODE=whole`, `ZZ_IDS` defaulting to T11.6-1, or `ZZ_MODE=drive` for the drive-mismatch arm `runT1161DriveMismatchArm`, which on Linux ends at its platform gate's loud error once its premise passes; it copies `t9j2_37/zz-t9j2-37.test.ts.saved` to `test/self/zz-t9j2-37.test.ts` and always removes it; rebuild them from this description if they are gone); `t9j2_37/relinv.mjs ` (the inventory-lock stand-in's `lock` insertion plus one deviation in the answers of runs away from the workspace root, its modes listed in its header) red-checks the arm: `rellock` fails from `a/b` at the `lock` exactness check, `relall` and `relgraph` at the `graphData` one, each `rel` and `cwd` mode at the member compare naming its member, `vacuous` and `nomarkdown` at the root run's premise; `lock` passes. The Windows leg's half (`runT1161DriveMismatchArm`'s drive-mismatch runs held to its same-drive root run) runs only in CI: CI run 1181 (ID 38143523723, Windows job 114485585638, 44.70 s for 4 files and 17 tests) ran it through a temporary probe (`test/windows/zz-t9j2-37-probe.test.ts` with a copy of `relinv.mjs`, commit 31680c2, removed by the next commit), where `lock` passed the whole arm (~4.2 s) and `rellock`, `relall`, `relsessions`, `cwdjournal`, `cwdrecorded`, `relconfig`, and `vacuous` each failed diagnosed at the check they target, while the real `test/windows/e6-drive-mismatch.test.ts` failed against the bare built product diagnosed at its premise run's `$.lock`; in that run the full-suite job failed exactly run 1179's tests plus T11.6-1 (23 failed / 4740 passed, 4763 tests, 1071.42 s) and the harness-self job only the two accepted C-1 self-tests (4412 tests, 266.82 s). T12.7-3 (`test/suite/registry/section-12.7.ts`) runs on the default 120 s `timeoutMs`: from the 772854b plan's FIX_PLAN Task 38 on, its busy arm (`runErrorBusyWorkspaceArm`, last in the body, staged through `judgeBusyRefusal` in `test/suite/registry/section-13.5.ts`: `build`, a held `rename`, the refused `--json` run, the lift, the operation rerun) adds five product runs, and the whole test takes ~5.4 s under the unprivileged namespace both against the built product, which fails it diagnosed at the busy arm's error document (`code` and `path` null), and through the scratch stand-in `t9j2_38/standin.mjs hybrid ` (CONF-CORE in-process on a CORE_DECL workspace, whose `specs/A.mdx` spells `Gamma text.`, the built product everywhere else), which passes it; the arm alone takes ~0.3 s against CONF-CORE. Probe it through `t9j2_38/run_zz.sh ''` (`ZZ_MODE=whole`, `ZZ_IDS` defaulting to T12.7-3, or `ZZ_MODE=runErrorBusyWorkspaceArm` for the arm alone; it copies `t9j2_38/zz-t9j2-38.test.ts.saved` to `test/self/zz-t9j2-38.test.ts` and always removes it; rebuild them from this description if they are gone); `t9j2_38/standin.mjs ` runs CONF-CORE's `runXspec` in-process, so a held run stays the one process the harness started, and rewrites the busy refusal's answer: `none` passes the arm, and `path`, `code`, `write`, `loc`, `stderr`, `exit1`, `after`, and `early` (listed in its header) each fail it diagnosed at the check they target. T14-6 (`test/suite/registry/section-14.ts`) keeps its 300 s `timeoutMs`: from the 772854b plan's FIX_PLAN Task 39 on, its 14.26 arm (`runStableCodeBusyArm`, exported, last in the body, staged through `judgeBusyRefusal` as T12.7-3's busy arm is) adds five product runs, and the whole test's run time is ~24 s under the unprivileged namespace against the built product (~23 s before the arm), which fails it diagnosed at the arm's exact-token check (`code` null), and ~27 s through `t9j2_39/standin.mjs hybrid `, which passes it; the arm alone takes ~0.35 s against CONF-CORE and ~0.9 s against the built product. Probe it through `t9j2_39/run_zz.sh ''` (`ZZ_MODE=whole`, `ZZ_IDS` defaulting to T14-6, or `ZZ_MODE=runStableCodeBusyArm` for the arm alone; it copies `t9j2_39/zz-t9j2-39.test.ts.saved` to `test/self/zz-t9j2-39.test.ts` and always removes it); `t9j2_39/standin.mjs` is `t9j2_38/standin.mjs` plus the modes `misspell` (`workspace_busy`), `numeral` (`26 workspace-busy`), `findings` (the finding in a findings array instead), and `both` (an error document beside a findings array), which fail the arm diagnosed at the form-exact decode, as `code` and `write` fail it at the exact-token check and `exit1`, `after`, and `early` at theirs, while `none`, `path`, `loc`, and `stderr` pass it (T14-6 asserts the code alone; the concerned path is T12.7-3's). T14-9 (`test/suite/registry/section-14-ii.ts`) keeps its 600 s `timeoutMs`: from the 772854b plan's FIX_PLAN Task 40 on, its reporters arm runs `review create` held at the seam (`runHeldWithStaging`: the area-form `.xspec` staging applied after acquisition, so a conforming product's release meets it and leaves its entry a leftover, no outcome changed), and six acquisition-write arms (`runT149AcquisitionArms`, exported, last in the body: the entry's addition, a leftover's removal twice, the lock directory's creation, the area directory's creation, and an occupant of the area's own path, each on a fresh CORE_DECL workspace staged through `test/helpers/acquisition-staging.ts` or `obstructArea`, each with the next of T13.5-10's five mutating commands) add six workspaces and about 35 product runs. The whole test takes ~33 s under the unprivileged namespace against the built product (~32 s before the task), which fails it diagnosed at the first acquisition arm (`rename` exit 0 where 2), every earlier arm passing, and ~37 s through `t9j2_40/standin.mjs none ` (CONF-CORE in-process on a CORE_DECL workspace, whose `specs/A.mdx` spells `Gamma text.`; elsewhere the built product behind a model of 13.5's in-workspace acquisition that reports acquisition's refused writes), which passes it and fails the pre-Task-40 reporters arm diagnosed (its `review create`, staged before the invocation, meets the refused lock-directory creation, `.xspec/lock`); the acquisition arms alone take ~2.3 s against CONF-CORE. Probe it through `t9j2_40/run_zz.sh ''` (`ZZ_MODE=whole`, `ZZ_IDS` defaulting to T14-9, or `ZZ_MODE=runT149AcquisitionArms` for the acquisition arms alone; it copies `t9j2_40/zz-t9j2-40.test.ts.saved` to `test/self/zz-t9j2-40.test.ts` and always removes it; rebuild them from this description if they are gone); the stand-in's other modes (its header lists them) fail the arms diagnosed at the check each targets: `entrypath`, `swap`, `nested`, and `areaswap` at the concerned-path check, `stderr` at the diagnostic, `exit1` at the exit, `nullcode` at the code, `findings` at the form-exact decode, `touch` and `rmocc` at the modifies-nothing compare, `proceedafter:` (the built product run in place of the k+1-th refusal, its counter `t9j2_40/count-.txt` deleted before each probe) at arm k+1, and `relfail` (release's refused deletion reported at `.xspec/lock`) at the reporters arm's held `review create`. T14-10 (`test/suite/registry/section-14-ii.ts`) keeps its 600 s `timeoutMs`: from the 772854b plan's FIX_PLAN Task 41 on, its arm (i) (`runT1410ArmI`, exported, last in the body) adds six CONF-CORE-shaped workspaces, each session-staged (`stageArmWorkspace`) and driven once, about 24 product runs: five refused reads at acquisition staged through `test/helpers/acquisition-staging.ts` (the lock directory `-wx`, a leftover subdirectory `-wx`, `.xspec` `rw-` holding no `lock` and, separately, an empty lock directory, and the lock directory `rw-`), one per mutating command of T13.5-10 in turn, and a held `rename specs/A.mdx a a2` on `ACQUISITION_DECL` with `specs/sub` made `--x` during its hold. The arm alone takes ~1.8 s against CONF-CORE, which passes it (answering `read-failure` at `.xspec/lock` for the first four stagings, `write-failure` for the unsearchable lock directory, and `read-failure` at `specs/sub` at the second discovery); the whole test takes ~38 s under the unprivileged namespace through `t9j2_41/standin.mjs none ` (CONF-CORE in-process on a CONF-CORE-shaped workspace, whose `specs/A.mdx` spells `Gamma text.`; elsewhere the built product behind the inventory-lock rewrite), which passes it, and ~8.5 s against the built product, which fails it, as before the task, at arm (b)'s `inventory` decode (`$.lock`), arm (i) alone failing there diagnosed at its first staging (`rename` exit 0 where 2). Probe it through `t9j2_41/run_zz.sh ''` (`ZZ_MODE=whole`, `ZZ_IDS` defaulting to T14-10, or `ZZ_MODE=runT1410ArmI` for arm (i) alone; it copies `t9j2_41/zz-t9j2-41.test.ts.saved` to `test/self/zz-t9j2-41.test.ts` and always removes it; rebuild them from this description if they are gone); the stand-in's other modes (its header lists them) fail the arm diagnosed at the check each targets: `nested`, `nestedsub` (the subdirectory staging alone), and `area` at the concerned-path check, `loc` at the locations, `stderr` at the diagnostic, `exit1` at the exit, `nullcode`, `busycode`, and `writecode` at the code, `findings` at the form-exact decode, `touch` at the modifies-nothing compare, `subpath` and the faults suffixed `@sub` (applied to the `specs/sub` answer alone: `touch@sub`, `stderr@sub`, `exit1@sub`, `writecode@sub`, `nullcode@sub`, `findings@sub`) at the second-discovery arm's matching check, and `proceedafter:` (the built product run in place of the k+1-th refusal, its counter `t9j2_41/count-.txt` deleted before each probe) at the k+1-th staging; `t9j2_41/firstdisc/bin.mjs` (CONF-CORE's `product.mjs` copied with its rediscovery returning the first discovery) fails the second-discovery arm diagnosed (exit 0 where 2). T6.6-3 (`test/suite/registry/section-6.6.ts`) runs on a 420 s `timeoutMs` from the 772854b plan's FIX_PLAN Task 42 on (240 s before, which ran out locally under a load average of 4–7): its runs-while-held arm goes through T13.5-2's `whileCommand1Holds` and the step T13.5-4's reads and `build` take while held, `nonMutatingRunWhileHeld` (both exported from `section-13.5.ts`: the held-state comparison once command 1 holds and again once the preview has exited, and the inclusion check around the preview), and its acquisition arms (`runT663AcquisitionArms`, exported, last in the body, after `runT663SchedulingArms`; `t663UnobstructedTwin`, `runT663AcquisitionOutcomeArm`, `runT663AreaArm`, `runT663LeftoverArm`, `T6_6_3_ACQUISITION_OUTCOME_ARMS`, and `T6_6_3_SURVIVING_LEFTOVERS` exported too) add an unobstructed twin and seven CONF-CORE-shaped workspaces, about 24 product runs, each arm ~1 s; (a)'s permission stagings come from `test/helpers/acquisition-staging.ts`, whose stagings gained `reapply()` (the modes changed again, verified anew, once the harness has inspected the staging between the preview and the real operation). Whole, T6.6-3 takes ~171 s alone under the unprivileged namespace (from the 092db72 plan's FIX_PLAN Task 1 on, each refused or usage-error preview inside its own compare; ~166 s just before it) through `t9j2_42/standin.mjs hybrid ` (a real `rename`, `move`, or `review create|resolve|split` run — no `--preview` token — on a CONF-CORE-shaped workspace, whose `specs/A.mdx` spells `Gamma text.`, answered by CONF-CORE's executable; every other invocation by the built product), which passes it, and ~141 s against the built product, which fails it diagnosed at the runs-while-held arm's first held-state comparison (nothing at `.xspec/lock`: its lock is kept in the temporary folder) — 134.3 s to that failure in CI run 1187's full-suite job (a slower runner than run 1186's, whose job took ~17 min against this one's ~24), 172.57 s within the whole suite project alone under the unprivileged recipe at the 092db72 plan's FIX_PLAN Task 3 and 135.03 s in CI run 1207's full-suite job, each acquisition arm alone failing at its real operation (exit 0, or exit 1 for (b), where 2 is due; for (c), the leftover still at `.xspec/lock` once it has ended). Probe it through `t9j2_42/run_zz.sh ''` (`ZZ_MODE=whole`, `ZZ_IDS` defaulting to T6.6-3; `ZZ_MODE=sched` for the scheduling arms; `ZZ_MODE=acqeach` for the twin and then each acquisition arm separately, `ZZ_ARMS=a0,a1,a2,a3,b,c0,c1` narrowing it; `ZZ_MODE=oldsnap` for a plain whole-root snapshot while a run holds; it copies `t9j2_42/zz-t9j2-42.test.ts.saved` to `test/self/zz-t9j2-42.test.ts` and always removes it; rebuild them from this description if they are gone). `standin.mjs ref` (every real mutating run answered by CONF-CORE) passes the scheduling and acquisition arms; its other modes (its header lists them) fail them diagnosed at the check each targets: `previewlists` (a preview listing the lock directory and every directory under it, a refused listing answered `read-failure` at `.xspec/lock`) at (a)'s read-failure pair's preview exit, the two other stagings passing; `previewremoves` (a preview removing the leftovers) at (c)'s inclusion check (the plain file) and staged-occupant check (the lock directory), and at the held arm's count half; `previewentry` (a preview adding an entry) at (a)'s `-wx` stagings' lock-path check and (c)'s count half, and at the held arm's count half; `previewtouch` at the held arm's inclusion check; `previewbusy` at the held arm's busy rule; `previewarea` at (b)'s preview exit; `previewlink` at (a)'s link-target check; `realcode` at (a)'s and (b)'s code checks; `realareapath` at (b)'s path check; and `entry000` (the held run's entry made mode 000 once it holds) passes the scheduling arms, every read of the entry made under H-4's grant (`test/helpers/snapshot.ts` has read files under the lock path that way since this plan's Task 5, 5ac195d, after the A-G3 probe at bb3081a, so a plain whole-root snapshot while the run holds — `ZZ_MODE=oldsnap` — passes too). Red-checking each preview's own compare (`expectRefusedPreviewEquivalence`; `expectUsageErrorEitherWay` for the usage pairs): `t9j55_1/strayhybrid.mjs ` (compliance reviewer A's: the hybrid plus a `--preview` answered exit 1 or 2 leaving `.xspec/lock/stray-from-refused-preview` where `.xspec` stands as a directory, a real mutating run first removing a stray standing alone; each such preview logged to `strayhybrid.log` beside it) fails T6.6-3 at the T6.4-3 staging's first refused preview, at that preview's own compare (`added .xspec/lock`, then the stray), while `t9j2_7/standin.mjs acquiring` equals the bare built product in outcome and full diagnosis, a real run's residue being the preview's baseline; `t9j55_1/run_zz.sh` is `t9j2_42/run_zz.sh` pointed at `t9j55_1/` (`ZZ_MODE=whole`), and `t9j55_1/run_usage.sh ''` runs one usage pair as T6.6-3's callers do (T6.5-5's first U+FFFD destination operand, `expectUsageErrorEitherWay` inside an outer whole-root compare, on a freshly built valid workspace: the ordering staging without `specs/Bad.mdx`, so `.xspec` stands) through `t9j55_1/zz-t9j55-1u.test.ts.saved` in a scratch copy of the checkout at `t9j55_1/repo` (`.git` left out, `node_modules` a symlink to the checkout's, the two helpers exported there alone; deleted after use, so rebuild it from this description), where the stray stand-in fails at the preview's own compare and the hybrid, the residue stand-in, and the bare built product pass. T1.5-1 (`test/suite/registry/section-1.5.ts`) keeps the default 120 s `timeoutMs` from the 772854b plan's FIX_PLAN Task 43 on: 16 commands, each run from the workspace root and from `specs/sub` (32 product runs: `query node`, `query nodes`, `show` of alpha and of gamma in both forms, `ids`, `coverage`, and `impact --base HEAD` in both forms, `occurrences`, `view`, `view specs/sub/B.mdx`, and `at specs/sub/B.mdx 47`), ~12–13 s alone under the unprivileged namespace against the built product, which passes it (7.7 s in CI run 1189's full-suite job, 15.7 s on its Windows leg, passing on both). Probe it through `t9j2_43/run_zz.sh ''` (`ZZ_IDS` defaulting to T1.5-1; it copies `t9j2_43/zz-t9j2-43.test.ts.saved` to `test/self/zz-t9j2-43.test.ts` and always removes it; rebuild them from this description if they are gone); `t9j2_43/pathform.mjs ` wraps the built product and rewrites the first matching path member of one command's JSON document (every matching one in the two `-all` modes) to a `./`-prefixed or `\`-separated form (its header lists the modes; `nested:occ-file-relative` instead relativizes an occurrence's `file` to `B.mdx` in runs away from the root alone), re-serializing in the built product's own layout (`reserialize` alone is byte-faithful); every deviation fails T1.5-1 diagnosed — three of the single-member ones in the form-exact adapters' occurrence-order or own-file checks, before the test's own exact check, which the two `-all` modes, rewriting consistently, reach — while `pass` and `reserialize` pass. P-10 (`test/suite/registry/section-16-p10.ts`, rewritten by the 772854b plan's FIX_PLAN Task 44: per-episode reader-free twins copied with the lock path left out, pre-start readers confirmed running — listed, never a zombie — as each command starts, kills under T13.5-3's discipline, and its polling reader `test/helpers/path-poller.ts`, shared with T13.5-5, over the journal, the session file, the sources, their modules, and — since the f50cf9f plan's FIX_PLAN Tasks 2 and 3 — the companions beside them and graph data, never the lock path) keeps its 600 s `timeoutMs`: at its fixed seeds it draws 9 trials of 2–5 episodes, 30 in all, holding every kind with every held fate and unheld runs of `rename` and `resolve`, each episode a twin and a command plus up to eight reads. Under the unprivileged namespace it passes against the CONF-READERS conformer in ~15–17 s alone (~32 s with six busy loops on the four cores; its certification verification 17.4 s, 17.2 s at the acfff0b plan's FIX_PLAN Task 2, 16.1 s at the f50cf9f plan's FIX_PLAN Task 4, 17.1 s at the d0c8039 plan's FIX_PLAN Task 11, 15.7 s at the 93e22f1 plan's FIX_PLAN Task 8, 16.5 s at the affd85f plan's FIX_PLAN Task 7, 18.1 s at the a71eb0c plan's FIX_PLAN Task 12, 15.5 s at the 9bdb418 plan's FIX_PLAN Task 5, 12.0 s in CI run 1212, 8.6 s in run 1224, 12.3 s in run 1236, 12.2 s in run 1245, 11.7 s in run 1253, 11.7 s in run 1266, and 11.7 s in run 1272), fails against VIOL-READERS-CLAIM at seed 271828183's trial 1 — the first command, an unheld `rename` with an `ids --json` reader started 25 ms before it, refused `workspace-busy` — in ~32 s with its four shrink executions (its verification 32.4 s, 32.5 s at that Task 2, 32.3 s at the f50cf9f plan's Task 4, 32.4 s at the d0c8039 plan's Task 11, 32.2 s at the 93e22f1 plan's Task 8, 32.4 s at the affd85f plan's Task 7, 32.4 s at the a71eb0c plan's Task 12, 32.2 s at the 9bdb418 plan's Task 5, 31.6 s in run 1212, 31.1 s in run 1224, 31.6 s in run 1236, 31.6 s in run 1245, 31.6 s in run 1253, 31.6 s in run 1266, and 31.6 s in run 1272; the pair adds ~40–50 s to certification), and fails diagnosed against the built product at seed 271828183's trial 2, a resolve killed past its hold (`found nothing at .xspec/lock`, ~37–46 s alone, 44.6 s at the acfff0b plan's FIX_PLAN Task 3; 37.38 s within the whole suite project at its FIX_PLAN Task 2, whose run met the assertion first at seed 271828183's trial 3, a `move` killed while held, and 58.97 s in CI run 1212's full-suite job, at trial 2, a `move` killed past its hold, and 39.92 s in run 1224's, the companions and graph data polled, at trial 2, a `move` killed past its hold, and 37.04 s in run 1236's, each polled path of a run the kill ended judged against its start and its twin's final state too (the d0c8039 plan's FIX_PLAN Task 1), at trial 2, a `resolve` killed past its hold, 49.53 s in run 1245's, at trial 2, a `resolve` killed past its hold, 26.22 s in run 1253's, at trial 3, a `move` killed while held, as in run 1246, 22.39 s in run 1266's, at trial 2, a `resolve` killed past its hold, as in run 1254, 44.40 s in run 1267's, likewise, and 47.40 s in run 1272's, likewise, its lock-path inspections made once the episode's readers had settled (which trial first catches a nonconforming product is timing's, E-5); it passed there before the task, 33.4 s in CI run 1189). A reader's start to the acquisition of a mutating command started once that reader is confirmed running spans 65–92 ms on the CONF-CORE product, idle (`t9j2_44/span.mjs `, the held command's hold file bounding its acquisition); CLAIM's dwell is 3000 ms. Probe P-10 through `t9j2_44/run_zz.sh ''` (`ZZ_IDS` defaulting to P-10; it copies `t9j2_44/zz-t9j2-44.test.ts.saved` to `test/self/zz-t9j2-44.test.ts` and always removes it; `python3 -I t9j2_44/summ.py .json` summarizes), dry-run its draws with `t9j2_44/zz-dryrun.test.ts.saved` (copied to `test/self/zz-dryrun.test.ts`, `ZZ_OUT` naming a text file, then removed; `t9j2_44/cover.py` tallies kinds and fates), and hand-probe CLAIM with `t9j2_44/claimprobe.sh`; `t9j2_44/standin.mjs ` wraps the CONF-CORE product with one change each (`neutral` passes P-10; `pidout` fails its stdout comparison, `journal2` its journal accounting, `sessiontouch` its no-session rule, `journalgap` its poller's journal order — the CORE violators fail it too: PARTIALWRITE at the poller's prior-or-complete check, STALELOCK at the reuse check's diagnosed branch, READERENTRY at the absence of `.xspec/lock` after a command, CHATTYREADS at the journal accounting of an episode beside a `check` reader (`expected 0 entries added, found 1`, seed 271828183's trial 1, ~3 s; at the bracketed accounting read before the 2a2b94e plan's FIX_PLAN Task 10 narrowed its appends to `check`), EARLYRELEASE, on the runs whose kills land after its early release, at a past-the-hold kill); rebuild them from this description if they are gone. In CI run 1192 (7a83fb5) P-10 failed diagnosed against the built product at seed 271828183's trial 3 (a `move` killed while held, `found nothing at .xspec/lock`, 40.3 s; locally its trial 2 — which trial first catches a nonconforming product is timing's, E-5), and the harness-self job's verifications took 11.6 s (CONF-READERS) and 31.5 s (VIOL-READERS-CLAIM). Since that task the CONF-CORE product, which the CONF-READERS conformer runs, reads a spec source found absent at its content read as undiscovered (SPEC 14.25; a reader beside a `move` meets one) and appends to the journal atomically, a temporary file renamed over it, so no empty journal is observable at its creation. P-10's compared view (`isComparedKey`; the acfff0b plan's FIX_PLAN Task 3) holds `.xspec/` to the journal and SPEC 10.1's sessions (`isSessionKey`), the walk pruning every other entry in the session directory unread: CONF-CORE's atomic writes (`writeFileAtomic`) leave a `.xspec.tmp--` entry beside their target when a kill lands between the temporary file's write and its rename, as P-10's past-the-hold kills of a resolve can (CI run 1210; locally the conformer met it at seed 161803399's trial 3), and that entry stays in the workspace the schedule continues on. Probe P-10 over such entries through `t9j59_3/run_zz.sh P-10 '' [pool]` (it copies `t9j59_3/zz-t9j59-3.test.ts.saved` to `test/self/zz-t9j59-3.test.ts` and always removes it; results in `t9j59_3/zz_.json`, printed by `python3 -I t9j59_3/show.py [chars]`), binding `t9j59_3/standin.mjs `, which runs the CONF-CORE product from `t9j59_3/core/product.mjs` (regenerate it with `python3 -I t9j59_3/make_standin.py`: CONF-CORE's own with one dwell hook in `writeFileAtomic`): `none`, `dwell:1000` (each session write dwells 1000 ms between its temporary entry and the rename, so past-the-hold kills of resolves land inside that window; ~41 s) and `beside` (each resolve then leaves seven non-session entries in the session directory) pass P-10; `resolve-journal` fails it at the journal accounting, and `resolve-source`, `resolve-session2` (a copy of `s.json` at `t.1.json`) and `rename-session` at `assertWritesItsOwnFilesAlone`; rebuild them from this description if they are gone. P-15 (`test/suite/registry/section-16-p15.ts`, registered by the 772854b plan's FIX_PLAN Task 45: seeded leftover trees staged at `.xspec/lock` by `stageLeftover` (helpers/lock-staging.ts, names as exact bytes) on T13.5-10's session staging, fresh per draw, one of T13.5-10's five commands per draw under `--json`, judged by T13.5-10(b)'s own `assertTakeover` — exported from `section-13.5-ii.ts` with `unstagedTwin`, which takes the test's name — against the command's leftover-free twin, the five twins run once before any draw) has a 600 s `timeoutMs`: at its fixed seeds (`P15_RUNS_PER_SEED` 4) it draws 12 trees, 90 leftovers in all, up to five levels deep, every class a CONF-LEFTOVER violator turns on reached at the lock directory's top level and nested in a listed directory — pinned without a product by `test/self/p15-fixed-seed-draws.test.ts`, which replays the draws (a name that is not valid UTF-8 first at seed 271828183's trial 1, one beginning with `.` at its trial 3, a link to a directory at seed 314159265's trial 3). Under the unprivileged namespace it passes against the CONF-LEFTOVER conformer in ~5.5 s (its certification verification 5.2 s); VIOL-LEFTOVER-BYTENAMES fails it at seed 271828183's trial 1, shrunk to an empty directory named `ff 2d 30` left standing in `.xspec/lock` (~4.3 s with its eight shrink executions; its verification 4.1 s), VIOL-LEFTOVER-DOTNAMES at its trial 3, shrunk to a FIFO `.leftover-0` left standing (~4.9 s; its verification 5.0 s), and VIOL-LEFTOVER-FOLLOWLINK at seed 314159265's trial 3, a nested link's target emptied (~6.5 s; its verification 6.6 s; the family adds ~21 s to certification); the built product fails it diagnosed at seed 271828183's trial 1 (`.xspec/lock` left standing, the product keeping its lock in the temporary folder; ~12 s), and the empty stub at the first twin's staging `build`. Probe P-15 through `t9j2_45/run_zz.sh ''` (`ZZ_IDS` defaulting to P-15; it copies `t9j2_45/zz-t9j2-45.test.ts.saved` to `test/self/zz-t9j2-45.test.ts` and always removes it), hand-probe a fixture over six fixed shapes with `t9j2_45/probe.sh ` (a name beginning with `.`, a name that is not valid UTF-8, or a link to a directory, at the top level or nested: the conformer removes each; DOTNAMES and BYTENAMES leave their class standing at the top level, exit 0, and fail nested with `write-failure` at `.xspec/lock`, exit 2; FOLLOWLINK empties the target either way), and tabulate the fixed-seed draws with `t9j2_45/zz-t9j2-45-draws.test.ts.saved` (copied to `test/self/zz-t9j2-45-draws.test.ts` and removed; `ZZ_RENDER=1` renders each tree); `t9j2_45/standin.mjs ` wraps the CONF-CORE product with one change each, patching `node:fs/promises` on paths under `.xspec/lock/` (the product's ESM bindings follow through `syncBuiltinESMExports`): `neutral` passes P-15; `shallow` (listings three levels down empty) and `readcontent` (each leftover file read first: EACCES on one with every permission removed) fail its exit 0, `write-failure`, at seed 271828183's trials 3 and 2; `linkwrite` (a dangling link written through) fails its link-target check at trial 2; and `fifoopen` (each FIFO opened for reading first) fails its promptness at trial 2, each hanging run cut at `runBounded`'s 15 s guard (~48 s with shrinking); rebuild them from this description if they are gone. In CI run 1194 (df03943) P-15 failed diagnosed against the built product at seed 271828183's trial 1 (10.8 s), and the harness-self job's CONF-LEFTOVER verifications took 2.9 s (the conformer), 3.4 s (FOLLOWLINK), 2.6 s (DOTNAMES), and 2.3 s (BYTENAMES). P-14 (`test/suite/registry/section-16-p14.ts`, registered by the 772854b plan's FIX_PLAN Task 46 with its read arms, completed by its Task 47 with the commands driven alone) runs two `checkProperty` series, the spec-source series and the code-source series, each `P14_RUNS_PER_SEED` (2) trials per fixed seed; a trial builds a fresh draw and keeps a byte copy of the built state (`keepBuiltState`, in the workspace's temporary directory), runs the series' read menu (six reads, or four) quiescently with the flipped source F present and then parked (the references), then `P14_WORKERS` (3) workers each run `P14_ROUNDS` (2) rounds of the menu back to back — 36 concurrent reads per spec-source trial, 24 per code-source trial — while `SourceFlipper` parks and restores F every drawn period (`FLIP_PERIODS_MS`, 2–40 ms); then `build --json`, `check --json`, the drawn `rename w --json`, and `review create --strategy audit --name n --json` (`soloCommands`), each run alone on fresh byte copies of the built state — twice quiescently (F present, F parked), then `P14_SOLO_RUNS` (3) times while F flips — each run's exit code, stdout, and (but for `check`) the files it leaves, the flipped paths and the lock path aside, together equal to one reference's; every run under a 60 s guard (`RUN_TIMEOUT_MS`; a hang declines shrinking; any other falsification shrinks within 4 trials). Its `timeoutMs` is 900 s (600 s with the read arms alone): under the unprivileged namespace it passes in ~231 s against a P-14-conforming stand-in — the built product re-running any run its own race answer spoiled, a command driven alone after restoring the workspace (every path but F's, `parked/`, and `.xspec/lock`) to the state the spoiled run began in (`t9j2_47/standin.mjs`, `ZZ_STANDIN_MODE=retry`) — the spec-source series ~122 s and the code-source series ~108 s, 17–22 s a trial; the commands driven alone take ~127 s of it (run alone, `ZZ_READS=0`), each command's flipped runs meeting F present's and F absent's outcomes 0–3 of 3 a trial and both across the fixed seeds; with Task 46's read arms alone it passed in ~101–106 s (`t9j2_46/standin.mjs`, `retry`) — the spec-source series ~58–61 s, the code-source series ~43–45 s — per trial 171–2286 flips, and the reads meeting F present and absent (those whose two references differ) 3–15 and 15–27 of the 30 per spec-source trial, 0–3 and 3–6 of the 6 per code-source trial, where `occurrences` alone tells the states apart. The built product fails it diagnosed at the reads' arm, the spec-source series' seed 271828183 trial 1 (~37–40 s with its four shrink executions; 39.6 s at Task 47): reads meeting the vanish answer condition 20 for F at offset 0, the built product's `changed or vanished` finding (`at`, `view`, `ids`, `occurrences` alike — which read first meets the window is timing's, E-5; the code-source series, run alone, fails the same way at its trial 1 at `ids --json`); its commands driven alone, run without the reads (`ZZ_READS=0`), each fail diagnosed with the same condition 20 for F at offset 0 — `build` and `check` at seed 271828183 trial 1 in both series, the `rename` at seed 314159265 trial 1 in both, `review create` at seed 314159265 trial 1 (spec-source) and 271828183 trial 1 (code-source) — ~8–18 s a series with shrinking. In CI run 1196 (555e28d) P-14 failed diagnosed against the built product likewise (seed 271828183, trial 1 of 2, shrunk 4 steps, its first deviant read `occurrences`, 9 of 36 concurrent reads deviating; the file 57.9 s); the harness-self job ran 38 files, 4440 tests, all passed, in 267.36 s, and the full-suite job 126 files, 4793 tests, in 1490.30 s: 28 failed, every one a diagnosed product failure — run 1194's twenty-seven and P-14; its Windows leg failed only at its known `$.lock` (T11.6-1's drive-mismatch premise). In CI run 1198 (b9601fb, Task 47's commit) P-14 failed diagnosed against the built product at the reads' arm likewise (spec-source series, seed 271828183, trial 1 of 2; its first deviant read `query nodes`, 5 of 36 concurrent reads deviating, 2172 flips; the file 47.0 s); the harness-self job ran 38 files, 4440 tests, all passed, in 269.93 s, and the full-suite job 126 files, 4793 tests, in 1221.10 s: 28 failed, every one a diagnosed product failure, run 1196's set; its Windows leg (3 files, 9 tests, 45.81 s) failed only at its known `$.lock`. Task 46's stand-in's other modes: `opmissing` (a read naming a missing F answers condition 20) fails at the quiescent absent reference, `oprace` (a 30 ms window after the operand check, then condition 20 where F vanished) and `readrace` (a 30 ms window after listing the sources, then `read-failure` where one vanished) in the concurrent phase, each at seed 271828183's trial 1 (~45–49 s with shrinking). Task 47's stand-in's fault modes, each failing diagnosed in both series unless noted: `readfail` (`build`/`check`/`rename`/`review create`: a source gone after a 30 ms window answers `read-failure` for it, exit 2), `crash` (the same window, then SIGKILL), and `mixed` (`build`/`rename`: once the run has ended, every derived module or companion whose `.mdx` source is absent is deleted — derived files of one reference, graph data of the other: the files half's fault; the spec-source series alone fails, the code-source series, with no derived files of F, passing by design). Probe P-14 through `t9j2_47/run_zz.sh ` (it copies `t9j2_47/zz-t9j2-47.test.ts.saved` to `test/self/zz-t9j2-47.test.ts` and always removes it): it runs both series as registered against `ZZ_BIN` (a Node script; default the built product) with `ZZ_STANDIN_MODE`, `ZZ_SERIES` (`spec` or `code`), `ZZ_READS=0` (skip the reads' arm), and `ZZ_SOLO` (a comma list of `build`, `check`, `rename`, `review create`: the commands driven alone; default all), writing each trial's `P14Observation` (its `solo` member per command) and the outcome to `ZZ_OUT`; Task 46's `t9j2_46/run_zz.sh` (`ZZ_MODE=draws` judges the fixed-seed draws, `ZZ_RUNS=` draws n per seed over five other seeds, and their structural invariants into `ZZ_OUT`; `ZZ_MODE=run` runs every arm) still works; rebuild them from this description if they are gone. - Run a subset of a test project by appending file paths, e.g. `npx vitest run --config test/vitest.config.ts --project suite test/suite/section-1.1-1.2.test.ts` — the way to observe new product-facing tests failing-as-diagnosed against the stub product (Phase 9 red-green). Append `--reporter=verbose` to see each test's duration — the quick check that a many-invocation sweep (e.g. T6.1-1's ~34 CLI runs, ~9 s at steady state) actually drove every arm rather than short-circuiting. Vitest's `-t ` name filter narrows further but matches substrings of the whole title, so filtering on a test ID (`-t "T6.5-5"`) also runs every test whose title cites that ID (T6.5-4's title mentions T6.5-5, adding its ~9 s) — read the verbose list to see what actually ran. To select one registered test inside a file, add `-t ' '` with a trailing space (Vitest's name filter is a regex over the declared name ` `, so `-t 'T6\.5-1 '` runs T6.5-1 alone, not T6.5-10 through T6.5-19). - Running tests also requires the system `git` executable on PATH: harness fixtures script local git repositories (`test/helpers/workspace.ts`). No git configuration is needed — the builder isolates all ambient git config and identity. The builder's `gitInit`/`gitCommitAll` serve the workspace root's repository only; a nested repository (T6.3-5's stagings in `test/suite/registry/section-6.3.ts`, its nested-repository one shared with T6.3-6(b) and (e) through `stageNestedRepositories`) is scripted through the public `git([...])` with `-C <subdir>` and an inline `-c user.name=… -c user.email=…` identity (the isolated environment has none), and `git -c protocol.file.allow=always submodule --quiet add ./<subdir> <subdir>` registers an already-initialized in-place repository as a submodule without cloning (the gitlink is staged; `.git` stays a directory) — the `protocol.file.allow` override is what git 2.38+ demands for a local-path submodule. The Linux leg's lock-path leftover stagings (`stageLeftover` in `test/helpers/lock-staging.ts`) and its FIFO staging at any other path whose parent directory stands (`stageFifo`, the same route; T6.3-6(c)'s `.xspec/journal`, since the plan written at 2a2b94e's FIX_PLAN Task 48) also need coreutils' `mkfifo` on PATH: Node has no API for FIFOs, so each is made by `mkfifo -m <mode>` under an ASCII name in a scratch directory beside the workspace root (the `TestWorkspace`'s `tempRoot`) and hard-linked into place, which never replaces an occupant and takes a name that is not valid UTF-8 as its bytes; a missing or failing `mkfifo` is a `HarnessStagingError` (mode `lock-path-leftover`), never a skip. TEST-SPEC H-1's ancestor precondition (`assertSelfContainedRoot`, `test/helpers/self-contained-root.ts`, since the plan written at 2a2b94e's FIX_PLAN Task 21) runs git too, and it requires the OS temporary directory (`os.tmpdir()`, so `TMPDIR`) to lie inside no git working tree, with no entry named `xspec.config.ts` in any directory above it: before every arm presuming nothing above its workspace root — T7-1's failed upward search, T12.7-3's `.`-path arm, T6.3-5(c), T12.0-12's sweep, T13.5-8's baseline arms (its journal-failing workspace's from the 2a2b94e plan's FIX_PLAN Task 118 on), T11.6-4's arm B, T12.6-2's no-configuration context, and T12.0-14's `--config`-first premise (T6.3-6(b) and T14-10(k) call it as they land) — it `lstat`s `xspec.config.ts` in every directory above the root, along the root's spelling and its physical path, and asks `git -C <root> rev-parse --show-toplevel` under the environment the driver gives the product (`productEnvironment`, `test/helpers/subprocess.ts`) with `LC_ALL=C`, only git's "not a git repository" verifying the repository half; an unmet or unverified half is a `HarnessStagingError` (mode `self-contained-root`), a harness error, never a pass or a product failure, so a run with `TMPDIR` inside a repository or below a stray `xspec.config.ts` errors exactly those tests (to check by hand: run them through a temporary runner — the bullet beginning "To run a selection of product tests against one fixture executable" — with `TMPDIR` set to a directory below one holding an empty `xspec.config.ts`, or inside a scratch `git init` repository: each ends `error`, its diagnosis the staging error naming the entry or the working tree; the scratch trees go in the scratchpad, never in the checkout, which is itself a working tree). -- Harness self-tests and certification only (TEST-SPEC 17): `npm run test:self`, which needs no product build (TEST-SPEC H-8: self-tests and certification pass before the product exists); CI's harness-self job runs it with no `dist/`. Its S-7 file, `test/self/s7-red-green-sweep.test.ts`, sweeps every product-facing body (the registered ones and the seven layer-4 bodies outside the registry, T7-1's single-casing probe, synthetic entry T99.7-8, the seventh from the plan written at 2a2b94e's FIX_PLAN Task 54 on) against the empty stub and, from the affd85f plan's FIX_PLAN Task 5 on, against an absent built-product artifact as well (`builtProductBindingAt(<dist/cli/bin.js inside a fresh temporary directory>)`, absent whatever the checkout's `dist/` holds, so it checks the same with or without a build), each body required to fail diagnosed, every no-product diagnosis naming the artifact (the file's 7 tests took 30.95 s alone under `unshare --map-user` at that Task, 7.1 s of it the no-product registry sweep). Its certification runner prints one `PASS`/`FAIL` line per (test, fixture) pair as it drives each fixture executable; a violator's `FAIL` lines are its expected outcomes, not failures — Vitest's own failures are the `×` lines and the final `Tests` summary, so when piping the output through `grep`, filter on those rather than on `FAIL` (the runner's lines are indented — ` FAIL T…` — so a line-anchored `grep -v '^FAIL '` does not drop them; match `×` and the `Tests` summary instead, and never cap the output with `head -N`: the runner's 30-odd per-pair lines precede the summary, so redirect the run to a log file and grep that afterwards). To certify one fixture family alone, filter `test/self/certification.test.ts` on the family name every one of its test titles carries: `npx vitest run --config test/vitest.config.ts --project self test/self/certification.test.ts -t CORE` runs the CONF-CORE conformer and each VIOL-CORE-* violator (~150 s in all from the 772854b plan's FIX_PLAN Task 21 on — 149.93 s, and 152.84 s with `--reporter=verbose`, whose per-verification times were the conformer's 8.5 s, VIOL-CORE-NOLOCK's 7.8 s, VIOL-CORE-EARLYWRITE's 8.0 s, VIOL-CORE-EARLYREFRESH's 9.1 s, VIOL-CORE-STALELOCK's 6.1 s, VIOL-CORE-PARTIALWRITE's 10.2 s, VIOL-CORE-CHATTYREADS's 8.0 s, VIOL-CORE-PERSISTREADS's 8.4 s, VIOL-CORE-LATEHOLD's 8.7 s, VIOL-CORE-EARLYRELEASE's 29.2 s, VIOL-CORE-HOLDLINK's 16.6 s, VIOL-CORE-READERENTRY's 8.0 s, and VIOL-CORE-BUILDWAIT's 18.3 s, 146.9 s summed, its T13.5-8 driving 10 more product invocations per fixture than before; ~147 s from its Task 20 on, its T13.5-8 driving 29 more product invocations per fixture than before — in a full self run the conformer's verification 12.4 s, VIOL-CORE-EARLYWRITE's 9.8 s, VIOL-CORE-HOLDLINK's 16.7 s, VIOL-CORE-BUILDWAIT's 18.4 s, VIOL-CORE-EARLYRELEASE's 28.9 s, about 167 s summed; ~149 s from its Task 18 on — the conformer's verification 8.4 s, VIOL-CORE-PARTIALWRITE's 10.0 s, VIOL-CORE-HOLDLINK's 16.9 s, VIOL-CORE-BUILDWAIT's 18.5 s, whose T13.5-4 fails only through its `build` arm's 15 s hang guard, VIOL-CORE-EARLYRELEASE's 29.0 s, T13.5-4 driving 5 more product invocations per fixture than at Task 17; ~127 s from its Task 17 — the conformer's verification 8.2 s, VIOL-CORE-PARTIALWRITE's 9.6 s, VIOL-CORE-HOLDLINK's 16.5 s, VIOL-CORE-EARLYRELEASE's 28.7 s, VIOL-CORE-READERENTRY's 8.0 s, its T13.5-4 ~0.4 s longer per fixture than at Task 16 (~1.7 s against the conformer); ~119 s from its Task 16 — its T13.5-3 driving about 68 product invocations per fixture, the conformer's verification 8.7 s, VIOL-CORE-PARTIALWRITE's 10.2 s, VIOL-CORE-HOLDLINK's 16.9 s, VIOL-CORE-EARLYRELEASE's 29.2 s; ~59 s from its Task 15 — its T13.5-2 driving about 57 product invocations per fixture, the conformer's verification 4.8 s, VIOL-CORE-PARTIALWRITE's 7.4 s; ~43 s from its Task 14 — ~17 s of it VIOL-CORE-HOLDLINK's, whose T13.5-1 fails only through its dangling-link arm's 15 s hang guard, `runBounded` in `test/suite/registry/section-13.5.ts`) and skips every other family; `-t ORPHAN` runs the CONF-ORPHAN conformer (`test/fixtures/conf-orphan/`) and its VIOL-ORPHAN-* violators over T13.4-11 alone (~4 s per fixture, ~12 s with Vitest's start-up); `-t LEFTOVER` runs the CONF-LEFTOVER conformer (`test/fixtures/conf-leftover/`) and its VIOL-LEFTOVER-* violators over P-15 alone (the conformer's verification 5.2 s, FOLLOWLINK's 6.6 s, DOTNAMES' 5.0 s, BYTENAMES' 4.1 s at the 772854b plan's FIX_PLAN Task 45; ~27 s with Vitest's start-up). Certification's time budget (the 772854b plan's FIX_PLAN Task 49): `test/self/certification.test.ts` runs its 39 verifications one after another in one file, the self project's critical path — 271.2 s of the Vitest run's 321.61 s in CI run 1201 at 0ce40a7, whose harness-self job took 351 s from start to end (29% of its 20-minute `timeout-minutes`; 352 s at b265134, run 1200; 276 s at 3786c66, run 1202, its self project 254.73 s and `certification.test.ts` 219.3 s, VIOL-READERS-CLAIM's verification 31.2 s; 350 s at 33e7d0b, run 1203, its self project 323.59 s and `certification.test.ts` 271.7 s, VIOL-READERS-CLAIM's verification 31.6 s; 352 s at 9583e3b, run 1204, its self project 323.17 s; 342 s at b9eb318, run 1207, its self project 316.15 s and `certification.test.ts` 266.5 s, VIOL-READERS-CLAIM's verification 31.6 s; 355 s at 6ada37b, run 1212, its self project 324.65 s and `certification.test.ts` 273.5 s, VIOL-READERS-CLAIM's verification 31.6 s; 326 s at 2d9cdf6, run 1214, its self project 298.29 s and `certification.test.ts` 251.6 s; with no product installed and no build step, 262 s at e55a7a1, run 1219 (22%), its self project 245.77 s and `certification.test.ts` 211.3 s, VIOL-READERS-CLAIM's verification 31.1 s; 350 s at 513f8b5, run 1222 (29%), its self project 320.48 s and `certification.test.ts` 270.3 s; 259 s at a1e6ae5, run 1224 (22%), its self project 243.34 s and `certification.test.ts` 208.9 s, VIOL-READERS-CLAIM's verification 31.1 s; 358 s at e9a530a, run 1236 (30%), its self project 330.40 s and `certification.test.ts` 278.7 s, VIOL-READERS-CLAIM's verification 31.6 s; 351 s at f5f7ab2, run 1245 (29%), its self project 326.36 s and `certification.test.ts` 275.0 s, VIOL-READERS-CLAIM's verification 31.6 s; 344 s at 0c927d8, run 1253 (29%), its self project 322.48 s and `certification.test.ts` 263.8 s, VIOL-READERS-CLAIM's verification 31.6 s; 340 s at 58361cb, run 1266 (28%), its self project 315.96 s and `certification.test.ts` 259.7 s, VIOL-READERS-CLAIM's verification 31.6 s; 344 s at b5ac9a8, run 1272 (29%), its self project 322.37 s and `certification.test.ts` 264.0 s, VIOL-READERS-CLAIM's verification 31.6 s; 350 s at a909c5d, run 1339 (29%), its self project 327.05 s and `certification.test.ts` 266.9 s, VIOL-READERS-CLAIM's verification 31.6 s; 414 s at a3cc3ed, run 1547, the 2a2b94e plan's end (35%), its self project 387.76 s and `certification.test.ts` 286.7 s, VIOL-READERS-CLAIM's verification 31.8 s), and 362.6 s summed of 370.23 s locally under `unshare --map-user` (354.2 s of 360.90 s at the 092db72 plan's FIX_PLAN Task 3, 380.4 s of 387.65 s at the acfff0b plan's FIX_PLAN Task 2, 341.9 s of 348.70 s at the 2d9cdf6 plan's FIX_PLAN Task 3, 360.1 s of 368.00 s at the f50cf9f plan's FIX_PLAN Task 4, 389.6 s of 400.48 s at the d0c8039 plan's FIX_PLAN Task 11, 350.1 s of 357.49 s at the 93e22f1 plan's FIX_PLAN Task 8, 375.3 s of 386.94 s at the affd85f plan's FIX_PLAN Task 7, 394.2 s of 403.20 s at the a71eb0c plan's FIX_PLAN Task 12, 351.3 s of 360.74 s at the 9bdb418 plan's FIX_PLAN Task 5) — the slowest verifications VIOL-READERS-CLAIM's (31.6 s in CI, 32.3 s locally), VIOL-CORE-EARLYRELEASE's (27.8 s, 30.0 s), VIOL-MD-CR's (14.6 s, 22.4 s), VIOL-MD-CLASS's (12.8 s, 19.5 s), VIOL-CORE-BUILDWAIT's (18.3 s, 18.8 s), and VIOL-CORE-HOLDLINK's (16.6 s, 17.1 s), each under a tenth of the 600 s `RUN_TIMEOUT_MS` every verification ran under until the plan written at 2a2b94e's FIX_PLAN Task 18 removed it (S-3: a verification carries no guard of its own); so the file stays whole and the job's timeout stays at 20 minutes. Revisit by measurement once the job passes ~15 minutes (75%): raise `timeout-minutes` (`.github/workflows/ci.yml`) or split the file per conformer family so Vitest runs the families in parallel — whose sustained intervals and kills must then not overlap into flakiness (E-5). Current totals (Phase 9 re-descent, from the 772854b plan's FIX_PLAN Task 45 on, nine conformers and thirty violators wired — every fixture CERTIFICATIONS.md defines, CONF-LEFTOVER and its VIOL-LEFTOVER-FOLLOWLINK, -DOTNAMES, and -BYTENAMES joining the eight conformers and twenty-seven violators wired from its Task 44, CONF-READERS and VIOL-READERS-CLAIM joining the seven conformers and twenty-six violators wired from its Task 32, CONF-RACE and VIOL-RACE-LISTFIRST joining the six conformers and twenty-five violators wired from its Task 18, twenty-four violators from its Task 17, twenty-three from its Task 16, twenty-two from its Task 14): the self project runs 42 files, 5021 tests from the plan written at 2a2b94e's FIX_PLAN Task 138 on (the new `test/self/p16-fixed-seed-draws.test.ts`, 2 tests — P-16's fixed-seed shapes and S-9 replay; P-16's five rendering forms and their count test in `test/self/s9-fixture-well-formedness.test.ts`, 6; its configuration and two code-source forms in `test/self/s9-typescript-well-formedness.test.ts`, 3, the vector-set count 31; S-8's P-16 answer-scale test, 1; and the configuration record `P16_CONFIG` in the S-9 staged-sources judge, 1; the full suite, `npm test`, 133 files, 5395 tests, the suite wrapper `test/suite/section-16-p16.test.ts` among them; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 40 files, 5011 tests: all passed, in 372.77 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 41 files, 5008 tests from its Task 137 on (the new `test/self/s6-path-blocks-oracle.test.ts`, 19 tests — the path-blocks oracle's twelve vectors (S-6's eleven and T10.5-3's origin counting), two tolerance vectors, and five misuse-guard tests — and four new tests in `test/self/s6-graph-diff-oracle.test.ts`, 16 now — the graph-diff oracle's relocation tolerance, three, and an unknown setting's refusal; the full suite, `npm test`, 131 files, 5381 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 39 files, 4998 tests: all passed, in 346.91 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4985 from its Task 135's first part on (one new staged-source record, T12.7-3's config-paths arm's invalid configuration at `xspec.config.ts` and `cfg/broken.config.ts`, a plain string before, which T12.0-15's exit-2 family restages after its earlier invocations — the S-9 judge now 1988 tests; the full suite, `npm test`, 130 files, 5358 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4975 tests: all passed, in 328.43 s at that part, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical; unchanged by its second part, which adds no self-test and no record, nine renamed: locally 38 files, 4975 tests, all passed, in 356.05 s, the certification lines and the 219 per-pair lines as before; and by its third, ten renamed: locally 38 files, 4975 tests, all passed, in 379.19 s, the certification lines and the 219 per-pair lines as before), 4984 from its Task 134 on (nine new S-5 tests, the human coverage, ids, and show decoders', and nine new staged-source records, T8.2-1's report fixture, T12.3-1's ordering workspace, and T12.4-1's workspace, which T12.0-15 restages after its earlier invocations — the S-9 judge now 1987 tests, S-5 165; the full suite, `npm test`, 130 files, 5357 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4974 tests: all passed, in 316.40 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4966 from its Task 133's third part on (three new staged-source records, T10.7-9's path-blocks baseline and its edit of N and N.a and T10.7-10's first-workspace source, which T12.0-15 restages after its earlier invocations — the S-9 judge now 1978 tests; the full suite, `npm test`, 130 files, 5339 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4956 tests: all passed, in 313.75 s at that part, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4963 from its Task 133's second part on (six new S-5 tests, the human review-item and review-next decoders', and two new staged-source records, T10.7-7's order-arm and T10.7-8's first-workspace sources, which T12.0-15 restages after its earlier invocations — the S-9 judge now 1975 tests, S-5 156; the full suite, `npm test`, 130 files, 5336 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4953 tests: all passed, in 312.61 s at that part, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4955 from its Task 133's first part on (six new S-5 tests, the human review-list and review-status decoders', and two new staged-source records, T10.7-5's and T10.7-6's first-workspace sources, which T12.0-15 restages after its earlier invocations — the S-9 judge now 1973 tests, S-5 150; the full suite, `npm test`, 130 files, 5328 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4945 tests: all passed, in 311.45 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4947 from its Task 132 on (three new S-5 tests, the human impact decoder's, and 77 more staged-source records — 78 new, every source the impact stagings of T5.6-1 through T5.6-6 and T9-1 through T9.3-3 staged plain before, first-workspace files and `file()` stagings alike, which T12.0-15 restages after its earlier invocations, and `section-9.3.ts`'s `T9_3_3_ARM_2_CONFIG` retired for `section-5.6.ts`'s `IMPACT_SPECS_ONLY_CONFIG` — the S-9 judge now 1971 tests, S-5 144; the full suite, `npm test`, 130 files, 5320 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4937 tests: all passed, in 325.60 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4867 from its Task 131 on (three new S-5 tests, the human performed-report decoder's, and five new staged-source records, T6.4-1's `specs/Core.mdx`, `specs/Refs.mdx`, and `src/app.ts` and T6.4-6's invalid-workspace `specs/A.mdx` and `specs/Other.mdx`, formerly plain first-workspace files that T12.0-15 restages after its earlier invocations — the S-9 judge now 1894 tests, S-5 141; the full suite, `npm test`, 130 files, 5240 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4857 tests: all passed, in 345.00 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4859 from its Task 130 on (three new staged-source records, T12.2-2's build-validations `specs/B.mdx` and T13.3-3's invalid-sources `specs/A.mdx` and `specs/B.mdx`, formerly plain first-workspace files that T12.0-15 restages after its earlier invocations — the S-9 judge now 1889 tests; the full suite, `npm test`, 130 files, 5232 tests, T12.0-15 registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4849 tests: all passed, in 329.41 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4856 from its Task 129 on (four new S-5 tests, the human preview decoder's, and five new staged-source records, T6.6-4(a)'s configuration and three sources and T6.6-6's `specs/Origin.mdx` — the S-9 judge now 1886 tests; the full suite, `npm test`, 129 files, 5228 tests, T6.6-7 registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4846 tests: all passed, in 340.24 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4847 from its Task 128 on (six new staged-source records, T14-11's arms (y)'s and (ab)'s `specs/A.mdx` sources and the four code files of (z) and (aa) — the S-9 judge now 1881 tests; the full suite, `npm test`, 129 files, 5218 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4837 tests: all passed, in 343.08 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4841 from its Task 124 on (three new staged-source records, T14-8's twice-spelled cycle arm's and its `embeds` twin's `specs/A.mdx` sources and their shared `specs/B.mdx` — the S-9 judge now 1875 tests; the full suite, `npm test`, 129 files, 5212 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4831 tests: all passed, in 351.89 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4838 from its Task 122 on (two new staged-source records, T14-7's twice-spelled cycle arms' `specs/A.mdx` sources — the S-9 judge then 1872 tests; the full suite, `npm test`, 129 files, 5209 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4828 tests: all passed, in 324.01 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4836 from its Task 121 on (one new staged-source record, T14-5's `.TSX` arm's configuration, its code file sharing the `.mts` arm's record — the S-9 judge then 1870 tests; the full suite, `npm test`, 129 files, 5207 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4826 tests: all passed, in 323.99 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4835 from its Task 120 on (one new staged-source record, T14-4's baseline arm's `specs/A.mdx` — the S-9 judge then 1869 tests; the full suite, `npm test`, 129 files, 5206 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4825 tests: all passed, in 327.70 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4834 from its Task 119 on (four new staged-source records, T14-1's pairs' two configurations and their `specs/A.mdx` before and after the edit — the S-9 judge now 1868 tests; the full suite, `npm test`, 129 files, 5205 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4824 tests: all passed, in 336.30 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4830 from its Task 117 on (three new staged-source records, T13.5-7(g)'s section-move configuration and origin and (h)'s emission-disabled move configuration — the S-9 judge now 1864 tests; the full suite, `npm test`, 129 files, 5201 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4820 tests: all passed, in 324.65 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4827 from its Task 116 on (one new staged-source record, the `xspec.config.ts` of T13.5-7(c)'s emitted-Markdown rename variant — the S-9 judge now 1861 tests; the full suite, `npm test`, 129 files, 5198 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4817 tests: all passed, in 277.21 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4826 from its Task 115 on (four new staged-source records for T13.4-13's arms (e)–(i) — the `outDir: "out"` configuration (f) and (g) share, (h)'s configuration as built and once emission is disabled, and (g)'s `specs/A.mdx` — the S-9 judge now 1860 tests; the full suite, `npm test`, 129 files, 5197 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4816 tests: all passed, in 275.16 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4822 from its Task 113 on (its Task 114 registered T13.4-13, adding no self-test — S-7's sweep, one test over the whole registry, takes it in — and no staged-source record, its workspaces staging `section-10.1.ts`'s `CORE_FILES` records, renamed for it: the full suite, `npm test`, 129 files, 5193 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4812 tests: all passed, in 281.93 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical; at Task 113, four new staged-source records — T13.4-5's identity arm: its configuration, the baseline commit's `specs/A.mdx` and `specs/B.mdx`, and `specs/A.mdx` with a.x's text edited — the S-9 judge now 1856 tests; the full suite, `npm test`, 129 files, 5192 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4812 tests: all passed, in 341.55 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4818 from its Task 112 on (four new staged-source records — `REFRESH_CONFIG`, the configuration T13.3-2's workspace and T13.3-5's share, T13.3-5(b)'s `specs/C.mdx` and `src/marker.ts`, and T13.3-5(c)'s `specs/A.mdx` — the S-9 judge now 1852 tests; the full suite, `npm test`, 129 files, 5188 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4808 tests: all passed, in 312.17 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4814 from its Task 111 on (one new self-test — S-3's T13.3-5(a) tampering spans in `test/self/s3-hang-guards.test.ts`, now 11 tests — and two new staged-source records — T13.3-5(a)'s twin `specs/A.mdx`, alpha's own text edited, and its `specs/B.mdx` — the S-9 judge now 1848 tests; the full suite, `npm test`, 129 files, 5184 tests, T13.3-5 registered (the suite project 89 files, 370 tests); under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4804 tests: all passed, in 312.19 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4811 from its Task 110 on (two new staged-source records — T13.3-3's stale twins' `specs/A.mdx`, beta's text edited, and its write-path twin's configuration, emission under outDir `out` — the S-9 judge now 1846 tests; the full suite, `npm test`, 129 files, 5180 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4801 tests: all passed, in 314.48 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4809 from its Task 108 on (four new staged-source records — T12.3-1's entries workspace: `specs/held.mdx`, `specs/prose.mdx`, `specs/user.mdx`, and `src/x.ts` — the S-9 judge now 1844 tests; the full suite, `npm test`, 129 files, 5178 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4799 tests: all passed, in 325.29 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4805 from its Task 107 on (four new staged-source records — T12.0-16's narrowed configuration, its `specs/base.mdx` with both children's text edited and with both children deleted, and its `src/c.ts` — the S-9 judge now 1840 tests; the full suite, `npm test`, 129 files, 5174 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4795 tests: all passed, in 338.88 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4801 from its Task 106 on (nine new staged-source records — T12.0-16's byte-order fixture: its configuration, `specs/base.mdx`, its two `x`-holding spec sources, its one code-source record staged at both code paths, and the two `x`-holding sources of each of its unresolved and import-cycle twins — the S-9 judge now 1836 tests; the full suite, `npm test`, 129 files, 5170 tests, T12.0-16 registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4791 tests: all passed, in 348.75 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4792 from its Task 104 on (three new staged-source records — T12.0-10's code-unit masking workspace's configuration, `specs/A.mdx`, and the declared-unparseable `src/bad.ts` — the S-9 judge now 1827 tests; the full suite, `npm test`, 129 files, 5160 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4782 tests: all passed, in 384.79 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4789 from its Task 102 on (one new staged-source record — T12.0-5's `move` arms' origin, `specs/A.mdx` — the S-9 judge now 1824 tests; the full suite, `npm test`, 129 files, 5157 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4779 tests: all passed, in 355.12 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4788 from its Task 100 on (two staged-source records removed — T11.6-3's former order workspace's configuration and `lib/deux.ts`, its order arm now on T11.6-3's order fixture — the S-9 judge now 1823 tests; the full suite, `npm test`, 129 files, 5156 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4778 tests: all passed, in 338.98 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4790 from its Task 99 on (three new staged-source records — T11.6-2's selectors workspace's configuration, `specs/a.mdx`, and `src/a.ts` — the S-9 judge now 1825 tests; the full suite, `npm test`, 129 files, 5158 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4780 tests: all passed, in 362.13 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4787 from its Task 96 on (six new staged-source records — T11.6-3's order fixture's configuration, its three spec sources, and its two code sources, staged by T11.4-1 and T11.4-2 — the S-9 judge now 1822 tests; the full suite, `npm test`, 129 files, 5155 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4777 tests: all passed, in 350.15 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4781 from its Task 95 on (four new staged-source records — T11.2-7's `specs/A.mdx` and its three arms' `specs/B.mdx` — the S-9 judge now 1816 tests; the full suite, `npm test`, 129 files, 5149 tests, T11.2-7 the one new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4771 tests: all passed, in 409.86 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4777 from its Task 94 on (six new staged-source records — T11.2-6's passing-side policy fixture's configuration, `specs/A.mdx`, and `lo/L.mdx`, and its unreadable-emit-directory fixture's configuration, `src/x.ts`, and failing-side `specs/A.mdx` — the S-9 judge now 1812 tests; the full suite, `npm test`, 129 files, 5144 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4767 tests: all passed, in 339.92 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4771 from its Task 93 on (two new staged-source records — T11.2-4's own-versus-subtree `specs/P.mdx`, its unresolved-embedding and ancestor-embedding-cycle stagings — the S-9 judge now 1806 tests; the full suite, `npm test`, 129 files, 5138 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4761 tests: all passed, in 390.90 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4769 from its Task 92 on (four new staged-source records — T11.2-3's target-side workspace's configuration, `specs/a'b.mdx`, `specs/A.mdx`, and `src/use.ts` — the S-9 judge now 1804 tests; the full suite, `npm test`, 129 files, 5136 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4759 tests: all passed, in 338.16 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4765 from its Task 90 on (five new staged-source records — T11-2's node-kind workspace's configuration, `specs/x.mdx`, `specs/shared/S.mdx`, `src/x.ts`, and `src/y.ts` — the S-9 judge now 1800 tests; the full suite, `npm test`, 129 files, 5132 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4755 tests: all passed, in 334.33 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4760 from its Task 89 on (one new staged-source record — T10.7-15's (f)(i) and (g) `specs/A.mdx` holding u's edit and a section with no id — the S-9 judge now 1795 tests; the full suite, `npm test`, 129 files, 5127 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4750 tests: all passed, in 347.11 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4759 from its Task 88 on (four new staged-source records — T10.7-15's (c) hand edits of `specs/A.mdx` (P.c's text, Q.r's deletion, s.t authored under s) and (d)'s `specs/B.mdx` holding a section with no id — the S-9 judge now 1794 tests; the full suite, `npm test`, 129 files, 5126 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4749 tests: all passed, in 340.92 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4755 from its Task 87 on (six new staged-source records — T10.7-15's configuration, fixture (A)'s `specs/A.mdx` and its u edit, and fixture (B)'s `specs/B.mdx`, its G.N edit, and its v edit — the S-9 judge now 1790 tests; the full suite, `npm test`, 129 files, 5122 tests, T10.7-15 registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4745 tests: all passed, in 335.60 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4749 from its Task 86 on (seven new staged-source records — T10.7-12's split sub-fixture's `specs/S.mdx` and its edit, its resolve-state sub-fixture's `specs/N.mdx` and its three stagings, and its second d2 edit over T10.4-7(a)'s fixture, made in `section-10.4.ts`; its provenance sub-fixture's three records renamed — the S-9 judge now 1784 tests; the full suite, `npm test`, 129 files, 5115 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4739 tests: all passed, in 330.76 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4742 from its Task 84 on (two new staged-source records — T10.4-8's p.q edit in its (a) workspace and its N.c.y edit in its (b) workspace — the S-9 judge now 1777 tests; the full suite, `npm test`, 129 files, 5108 tests, T10.4-8 registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4732 tests: all passed, in 323.91 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4740 from its Task 83 on (one new staged-source record net — T10.7-9's audit fixture's `specs/N.mdx` and its authoring of N.c, N.c.y, and N.b.z, and its Q session's `specs/Q.mdx` and Q.r's deletion, the three h/h.a/h.b audit-arm records gone — the S-9 judge now 1775 tests; the full suite, `npm test`, 129 files, 5105 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4730 tests: all passed, in 308.77 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4739 from its Task 82 on (five new staged-source records net — T10.7-9's six, its path-blocks fixture's M.k edit, (f)'s `specs/P.mdx` and its children's deletion, and (g)'s `specs/G.mdx` and its two edits, its `T10_7_9_G_WITH_Z` gone — the S-9 judge now 1774 tests; the full suite, `npm test`, 129 files, 5104 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4729 tests: all passed, in 307.52 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4734 from its Task 81 on (one new staged-source record — T10.7-7's `specs/U.mdx` holding the one section u — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1769 tests; the full suite, `npm test`, 129 files, 5099 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4724 tests: all passed, in 295.49 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4733 from its Task 78 on (three new staged-source records — T10.2-2's `specs/A.mdx` with a top-level b authored after `create` and with b's text edited, and T10.2-4's `specs/P.mdx` with p.q's further edit — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1768 tests; the full suite, `npm test`, 129 files, 5098 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4723 tests: all passed, in 336.36 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4730 from its Task 77 on (three new staged-source records — T10.5-9's `specs/D.mdx` at the baseline and with A.B.C's section deleted, and its `specs/R.mdx` at the baseline — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1765 tests; the full suite, `npm test`, 129 files, 5095 tests, T10.5-9 registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4720 tests: all passed, in 323.83 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4727 from its Task 76 on (five new staged-source records — T10.5-8's `specs/R.mdx` at the baseline, in its four-edit staging, and in its twin, and its `specs/S.mdx` at the baseline and with x.y edited — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1762 tests, and one new S-5 test — `decodeRecordedState` over show, next, and export — `test/self/s5-output-adapters.test.ts` now 134 tests; the full suite, `npm test`, 129 files, 5091 tests, T10.5-8 registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4717 tests: all passed, in 325.92 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4721 from its Task 74 on (its Task 75 registered T10.5-7, adding no self-test — S-7's sweep, one test over the whole registry, takes it in — and no staged-source record, its one workspace plain: the full suite, `npm test`, 129 files, 5084 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4711 tests: all passed, in 350.61 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical; at Task 74, ten new staged-source records — T10.5-5's matching arm's `specs/M.mdx` at the baseline, edited, and with n.c authored, its kept-blockedBy arm's `specs/B.mdx` at the baseline, edited, and with a.k1 reverted, and its P/Q arms' `specs/P.mdx` at the baseline, with p edited, with p and p.q edited, and with p reverted and p.q edited again — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1757 tests, and one new S-5 test — `requireScopeNodes` over show, next, and export — `test/self/s5-output-adapters.test.ts` now 133 tests; the full suite, `npm test`, 129 files, 5083 tests, no new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4711 tests: all passed, in 316.00 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4710 from its Task 73 on (fourteen new staged-source records — T10.5-3's current-graph-edges arm's `specs/G.mdx` at the baseline and edited, its origin-counting arm's `specs/O.mdx` at the baseline and in its tags staging, coverage staging, and d-set twin and its `src/o.ts`, its one-item-per-location arm's T9.2-4 staging (`specs/Direct.mdx` and `specs/Up.mdx` at v1 and v2, `specs/Trans.mdx`, `src/both.ts`), and those workspaces' `xspec.config.ts` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1747 tests; the full suite, `npm test`, 129 files, 5072 tests, no new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4700 tests: all passed, in 361.27 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4696 from its Task 72 on (one new staged-source record — T10.5-1's `specs/Y.mdx` with a.b's own text and a.b.c at v1, its chain fixture's both-edited twin — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1733 tests; the full suite, `npm test`, 129 files, 5058 tests, no new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4686 tests: all passed, in 277.26 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4695 from its Task 71 on (eight new staged-source records — T10.4-7's four initial sources (`specs/X.mdx`, `specs/T.mdx`, `specs/D1.mdx`, and `specs/D2.mdx` at the baseline), d1 at v1, d2 at v1, and the removal edit's `specs/T.mdx` without its reference to D2.d2 and emptied `specs/D2.mdx` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1732 tests; the full suite, `npm test`, 129 files, 5057 tests, T10.4-7 the one new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4685 tests: all passed, in 315.37 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4687 from its Task 70 on (four new staged-source records — T10.4-6's `specs/G.mdx` with u1 at v1, with u1 and u2 at v1, with u1 reverted and u2 at v1, and at the baseline, the twin's initial source — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1724 tests; the full suite, `npm test`, 129 files, 5048 tests, T10.4-6 the one new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4677 tests: all passed, in 316.33 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4683 from its Task 69 on (one new staged-source record — T10.4-4's decomposition arm's `specs/F.mdx` with top-level `a` holding `a.x` and a top-level leaf `s` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1720 tests; the full suite, `npm test`, 129 files, 5043 tests, no new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4673 tests: all passed, in 318.09 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4682 from its Task 67 on (one new staged-source record — T10.4-2's journal arm's `specs/J.mdx` with top-level leaves `a` and `s` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1719 tests; the full suite, `npm test`, 129 files, 5042 tests, no new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4672 tests: all passed, in 324.59 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4681 from its Task 66 on (one new S-5 test — every review decode of an item ID rejecting one that is no well-formed argument value, `test/self/s5-output-adapters.test.ts` now 132 tests; the full suite, `npm test`, 129 files, 5041 tests, no new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4671 tests: all passed, in 323.08 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4680 from its Task 64 on (two new S-5 tests — the session-corruption staging's two 10.2-field deletions and its re-insertion of an item entry copied from an earlier session file, `test/self/s5-output-adapters.test.ts` now 131 tests — and one new staged-source record — T10.1-4's `specs/A.mdx` with `a`'s own text edited since the baseline — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1718 tests; the full suite, `npm test`, 129 files, 5040 tests, no new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4670 tests: all passed, in 319.48 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4677 from its Task 63 on (two new S-5 tests — the decoder entry `review show (metadata-consistency item: the metadata pair)`, `test/self/s5-output-adapters.test.ts` now 129 tests — and six new staged-source records — T10.7-13's configuration, its `specs/M.mdx` with m's section deleted, and its `specs/GH.mdx` and `specs/K.mdx` baselines and edits — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1717 tests; the full suite, `npm test`, 129 files, 5037 tests, T10.7-13 the one new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4667 tests: all passed, in 327.92 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4669 from its Task 62 on (one new staged-source record — T10.7-14's edited `specs/A.mdx` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1711 tests; the full suite, `npm test`, 129 files, 5028 tests, T10.7-14 the one new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4659 tests: all passed, in 315.11 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4668 from its Task 61 on (four staged-source records leaving the ledger — T8-5's former required-set fixture, its configuration, `tgt/T.mdx`, `bnd/B.mdx`, and `oth/O.mdx`, now plain initial files of T8.1-1's one workspace, created before any product invocation — `test/self/s9-staged-sources.test.ts`'s judge now 1710 tests; the full suite, `npm test`, 128 files, 5026 tests, T8.1-1 the one new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4658 tests: all passed, in 314.24 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4672 from its Task 60 on (seven new staged-source records — T7.5-1's three outside-root selector-glob configurations (`../x/*.ts`, `a/../../$1.ts`, `/src/*.ts`), T7.5-2's twice-spelled-edge configuration and its `hi/H.mdx`, and T7.5-4's two inside-root selector-spelling configurations (`./src/*.ts` and its `src/*.ts` twin) — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1714 tests; the full suite, `npm test`, 128 files, 5029 tests, no new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4662 tests: all passed, in 361.66 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4665 from its Task 59 on (six new staged-source records — T7.1-1's wrong-case extension configuration and its `specs/A.MDX`, T7.3-1's two wrong-type configurations (`emit: "true"`, `outDir: true`) and its two Linux-leg single-casing `outDir` configurations (`".XSPEC"`, `".XSPEC/md"`) — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1707 tests; the full suite, `npm test`, 128 files, 5022 tests, no new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4655 tests: all passed, in 324.76 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4659 from its Task 58 on (six new staged-source records — T7-8's three configurations `T7_8_CONFIG`, `T7_8_DOCS_CONFIG`, and `T7_8_AREA_GLOB_CONFIG`, its `specs/A.mdx` and `specs/B.mdx`, and its code source `src/app.ts` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1701 tests; the full suite, `npm test`, 128 files, 5016 tests, T7-8 the one new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4649 tests: all passed, in 315.71 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4653 from its Task 57 on (three new staged-source records — T7-7's configuration `T7_7_CONFIG`, its code source `src/impl.ts`, and arm (b)'s `src/x.mdx` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1695 tests; the full suite, `npm test`, 128 files, 5009 tests, T7-7 the one new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4643 tests: all passed, in 339.81 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4650 from its Task 56 on (four new staged-source records — the `xspec.config.ts` of T7-6's extension twin and of its two single-casing arms, and those arms' one code source — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1692 tests; the full suite, `npm test`, 128 files, 5005 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4640 tests: all passed, in 352.60 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4646 from its Task 55 on (eight new staged-source records — the `xspec.config.ts` of T7-2's `"XSPEC"` specifier, `outDir: null`, `targetTags: null`, `defineConfig()`, `defineConfig({…}, {})`, numeric-literal key, and empty code-group-name arms and of T7-3's U+FFFD code-group-name arm — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1688 tests; the full suite, `npm test`, 128 files, 5001 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4636 tests: all passed, in 301.64 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4638 from its Task 54 on (one new staged-source record — T7-1's name-casing probe's `sub/XSPEC.config.ts`, declared unparseable — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1680 tests; the full suite, `npm test`, 128 files, 4993 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4628 tests: all passed, in 299.48 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4637 from its Task 52 on (one new staged-source record — T6.5-16(g)'s twice-spelled arm's `specs/a.mdx` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1679 tests, and seven new T6.5-16 vectors in `test/self/s9-fixture-well-formedness.test.ts` — six joining `R16_FORM_VECTORS`, now 168, and one `R16_REFUSED_VECTORS`, now 39; the full suite, `npm test`, 128 files, 4992 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4627 tests: all passed, in 294.94 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4629 from its Task 51 on (three new staged-source records — T6.5-2's `/ >` parent arm's `specs/P.mdx` and T6.5-4's casing arm's `xspec.config.ts` and `specs/a.mdx` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1678 tests, and two new composed forms — that T6.5-2 arm's `specs/A.mdx` and `specs/P.mdx` after the move — joining `test/self/s9-fixture-well-formedness.test.ts`'s `X2_COMPOSED_FORMS` judge; the full suite, `npm test`, 128 files, 4984 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4619 tests: all passed, in 282.95 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4624 from its Task 50 on (two new staged-source records — T6.4-6's refused-writes arm's `xspec.config.ts` and `specs/A.mdx` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1675 tests, and the full suite, `npm test`, 128 files, 4979 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4614 tests: all passed, in 296.09 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4622 from its Task 49 on (two new staged-source records — T6.4-4's braced-`id` and valueless-`id` arms' `specs/Braced.mdx` and `specs/Valueless.mdx` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1673 tests, and the full suite, `npm test`, 128 files, 4977 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4612 tests: all passed, in 275.10 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4620 from its Task 48 on (one new test, `test/self/lock-staging.test.ts`'s `stageFifo` test, and the full suite, `npm test`, 128 files, 4975 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4610 tests: all passed, in 284.93 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4619 from its Task 47 on (two new staged-source records — T6.3-6's `specs/A.mdx`, every arm's valid source, and its arm (d)'s failing `specs/A.mdx`, the renamed section's unresolved `d` reference — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1671 tests, and the full suite, `npm test`, 128 files, 4974 tests, T6.3-6 among them; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4609 tests: all passed, in 284.07 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4617 from its Task 46 on (two new staged-source records — T6.3-4's baseline-configuration arms' `c1` configurations, the working tree's configuration plus an unknown top-level key and with its `defineConfig` call's closing parenthesis removed, the second declared unparseable — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1669 tests, and the full suite, `npm test`, 128 files, 4971 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4607 tests: all passed, in 293.37 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4615 from its Task 44 on (four new staged-source records — T5.7-4's collision workspace `specs/C.mdx`, `src/mixed.ts`, `src/mixed-decl.ts`, and `src/twoimports.ts`; its `specs/B.mdx` record now holding `a` and `b` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1667 tests, and the full suite, `npm test`, 128 files, 4969 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4605 tests: all passed, in 288.36 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4611 from its Task 43 on (six new staged-source records — T5.5-5's tie-break arm's `specs/A.mdx` at T5.4-1's first fixture's baseline, after N2 is authored with `h` declaring `d={["b", "a"]}`, and with that array reordered, and T5.5-7's arm (a) edit `specs/B.mdx` and arm (b) `specs/A.mdx` and its edit; the shared configuration record renamed `T5.5-2/T5.5-5/T5.5-7 xspec.config.ts …` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1663 tests, and the full suite, `npm test`, 128 files, 4965 tests, the registered T5.5-7 among them; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4601 tests: all passed, in 295.41 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4605 from its Task 41 on (seven new staged-source records — T4.6-3's declaration-file controls `src/a.d.b/x.ts`, `src/x.d.tsx`, and `src/x.d.css.mts` and its single-casing controls `src/c1/x.D.ts`, `src/c2/x.d.TS`, `src/c3/x.d.MTS`, and `src/c4/x.d.CTS`; its configuration record renamed — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1657 tests, and the full suite, `npm test`, 128 files, 4958 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4595 tests: all passed, in 308.32 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4598 from its Task 40 on (fourteen new staged-source records — T4.5-8's type-only side's `src/app.ts`, twelve with the spec import type-only beside each colliding form and two with `text` bound type-only as `t` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1650 tests, and the full suite, `npm test`, 128 files, 4951 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4588 tests: all passed, in 301.32 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4584 from its Task 39 on (five new staged-source records — T4.5-3's numeric-literal, whole-chain parenthesized, partly parenthesized, and parenthesized-index arms' `src/app.ts` and the numeric-literal arm's `specs/A.mdx`; its `(SPEC.a).b;` arm's record renamed — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1636 tests, and the full suite, `npm test`, 128 files, 4937 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4574 tests: all passed, in 308.82 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4579 from its Task 38 on (six new staged-source records — T4.3-2's numeric-literal, parenthesized-chain, partly parenthesized, parenthesized-index, and cross-module arms' `src/app.ts` and the cross-module arm's `specs/B.mdx`; its shared `specs/A.mdx` record now holding `b` and `1` beside `a`, and its two-argument arm's record renamed for `text(SPEC.a, SPEC.b)` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1631 tests, and the full suite, `npm test`, 128 files, 4932 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4569 tests: all passed, in 313.09 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4573 from its Task 35 on (seven new staged-source records — T4-4's `specs/A.mdx` (`T4_4_SPEC_SOURCE`, plain before) and its two mixed-combination arms' `src/mixed.ts` and `src/mixed-decl.ts`, and T4-5's four value-level arms' `src/app.ts`; the shared configuration record renamed `T4-2/T4-4/T4-5 xspec.config.ts …` and T4-5's arm records' order label `(the import of A declared first)` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1625 tests, and the full suite, `npm test`, 128 files, 4926 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4563 tests: all passed, in 313.95 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4566 from its Task 34 on (T4-2's five new staged-source records — its root-re-entering arm's `src/app.ts`, the `**` positive's `src/three.ts`, the suffix casing arm's `src/b.ts` and `specs/B.mdx`, and the derived-name casing arm's `src/d.ts`; the no-other-construct arm's `specs/NAME.mdx` record became the shared `SPECS_NAME_SOURCE`, renamed — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1618 tests, and the full suite, `npm test`, 128 files, 4919 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4556 tests: all passed, in 320.47 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4561 from its Task 33 on (T2.5-2's three new staged-source records — its excluded-as-a-target-only arm's `xspec.config.ts`, `base/A.mdx`, and `derived/B.mdx` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1613 tests, and the full suite, `npm test`, 128 files, 4914 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4551 tests: all passed, in 311.76 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4558 from its Task 32 on (T2.4-2's five new staged-source records — its numeric-literal and parenthesized index arms' four `specs/A.mdx` stagings and their `specs/BASE.mdx`, holding `1` and `a` beside `auth` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1610 tests, and the full suite, `npm test`, 128 files, 4911 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4548 tests: all passed, in 310.77 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4553 from its Task 31 on (T2.1-2's and T2.1-3's nine new staged-source records — the `**` importer, the case-only arm's importer and `specs/B.mdx`, the re-entering arm's two sources, and the colliding-chain arms' two targets and two importers — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1605 tests, and the full suite, `npm test`, 128 files, 4906 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4543 tests: all passed, in 314.27 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4544 from its Task 29 on (T1.5-2's two new staged-source records — its code-group arms' code source and its located arm's spec source — joining `test/self/s9-staged-sources.test.ts`'s judge, and the full suite, `npm test`, 128 files, 4897 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4534 tests: all passed, in 310.90 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4542 from its Task 28 on (the human-report decoders' six S-5 vectors joining — `test/self/s5-output-adapters.test.ts` now 127 tests, 121 before — and the full suite, `npm test`, 128 files, 4895 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4532 tests: all passed, in 312.21 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4536 from its Task 27 on (the NodeNext path's two transitional S-4 vectors removed with that path, its misuse vectors brought to the one path left — `test/self/s4-typescript-tooling.test.ts` now 49 tests — and the full suite, `npm test`, 128 files, 4889 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4526 tests: all passed, in 313.50 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4538 from its Task 23 on (S-4 under both of H-2's configurations, its detection, companion, runtime, isolation, and transitional vectors joining — `test/self/s4-typescript-tooling.test.ts` now 51 tests, 16 before — and the full suite, `npm test`, 128 files, 4891 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4528 tests: all passed, in 277.44 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4503 from its Task 22 on (the entered-directory run's six vectors and mode 000's two joining — `test/self/s3-subprocess-driver.test.ts` now 46 tests, `test/self/permission-staging.test.ts` 18 — and the full suite, `npm test`, 128 files, 4856 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4493 tests: all passed, in 270.48 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4495 from its Task 21 on (H-1's ancestor precondition's five vectors joining, `test/self/s2-workspace-builder.test.ts` now 26 tests — and the full suite, `npm test`, 128 files, 4848 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4485 tests: all passed, in 275.49 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4490 from its Task 20 on (S-3's ten pre-product checks joining, the new `test/self/s3-hang-guards.test.ts` — and the full suite, `npm test`, 128 files, 4843 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4480 tests: all passed, in 266.70 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 39 files, 4480 tests from its Task 19 on (six S-3 self-tests joining — `test/self/s3-subprocess-driver.test.ts` now 40 tests: the hold-file wait's new contract and its refusal of a wait beside a held run in place of the old wait-timeout vector, and five harness-step guard vectors — and the full suite, `npm test`, 127 files, 4833 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 37 files, 4470 tests: all passed, in 291.86 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4474 from its Task 18 on (five S-3 hang-guard self-tests joining — `test/self/certification-runner.test.ts` now 16 tests, `test/self/property-infrastructure.test.ts` 21, `test/self/s3-subprocess-driver.test.ts` 34 — and the full suite, `npm test`, 127 files, 4827 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 37 files, 4464 tests: all passed, in 267.42 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4469 from its Task 8 on (four self-tests of T14-9's graph-data staging joining, `test/self/permission-staging.test.ts` now 16 tests, and the full suite, `npm test`, 127 files, 4822 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 37 files, 4459 tests: all passed, in 273.00 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4465 from the plan written at a71eb0c's FIX_PLAN Task 9 on (one S-9 staged-source record joining — T10.7-4's item-id tie sub-fixture's initial `specs/A.mdx`, `test/self/s9-staged-sources.test.ts` now 1594 tests — and the full suite, `npm test`, 127 files, 4818 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, with no product installed (`dist/` absent), 37 files, 4455 tests: all passed, in 407.97 s at its Task 9, in 401.89 s at its Task 10, in 403.20 s at its Task 12, and in 360.74 s at the 9bdb418 plan's FIX_PLAN Task 5, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures in each, `compare_cert.py` 0 discrepancies; CI's harness-self job ran 39 files, 4465 tests, the admin files included, in 315.96 s at 58361cb, run 1266, and in 322.37 s at b5ac9a8, run 1272: all passed, certification 0 discrepancies, its outcome lines identical to Task 12's local run's and, at run 1272, to the 9bdb418 plan's Task 5's; certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures from the plan written at 2a2b94e's FIX_PLAN Task 1 on, T13.4-5 and T11.4-1 out of the CONF-CORE and CONF-AVAIL scopes (CERTIFICATIONS.md at 7226090): 37 files, 4455 tests, all passed, in 446.09 s at that Task, and CI's harness-self job's 39 files, 4465 tests, all passed, in 327.05 s at a909c5d, run 1339, `compare_cert.py` 0 discrepancies in both, their 219 per-pair lines identical), 4464 from that plan's Task 8 on (one S-9 staged-source record joining — T10.6-2's item-id tie sub-fixture's initial `specs/A.mdx`, `test/self/s9-staged-sources.test.ts` then 1593 tests — and the full suite, `npm test`, 127 files, 4817 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, with no product installed (`dist/` absent), 37 files, 4454 tests: all passed, in 410.74 s at its Task 8, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies), 4463 from that plan's Task 7 on (three S-9 staged-source records joining — T10.5-4's item-id tie sub-fixture's initial `specs/A.mdx` and its two `specs/X.mdx` stagings, `test/self/s9-staged-sources.test.ts` then 1592 tests — and the full suite, `npm test`, 127 files, 4816 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, with no product installed (`dist/` absent), 37 files, 4453 tests: all passed, in 392.72 s at its Task 7, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies), 4460 from the plan written at affd85f's FIX_PLAN Task 5 on (S-7's three no-product tests joining — layer 5 of `test/self/s7-red-green-sweep.test.ts`, now 7 tests: the sweep-premise probe, the registry, and the six bodies outside it against `builtProductBindingAt(<an absent path>)` — and the full suite, `npm test`, 127 files, 4813 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, with no product installed (`dist/` absent), 37 files, 4450 tests: all passed, in 368.43 s at its Task 5 and in 386.94 s at its Task 7, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures in each, VERIFY's comparison 0 discrepancies; CI's harness-self job ran 39 files, 4460 tests, the admin files included, in 322.48 s at 0c927d8, run 1253: all passed, certification 0 discrepancies, its outcome lines identical to Task 7's local run's), 4457 from the plan written at affd85f's FIX_PLAN Task 4 on (S-3's no-product vector joining — `builtProductBindingAt(<an absent path>)` rejecting `runProduct` and `startProduct` with a `HarnessAssertionError` declining shrinking, nothing noted or spawned — `test/self/s3-subprocess-driver.test.ts` now 31 tests, and the full suite, `npm test`, 127 files, 4810 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, with no product installed (`dist/` absent), 37 files, 4447 tests: all passed, in 353.95 s at its Task 4, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures, VERIFY's comparison 0 discrepancies), 4456 from the plan written at 93e22f1's FIX_PLAN Task 4 on (the four S-5 tests of the stable-code matcher `codeMention` joining, `test/self/s5-output-adapters.test.ts` now 121 tests, and the full suite, `npm test`, 127 files, 4809 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, with no product installed (`dist/` absent), 37 files, 4446 tests: all passed, in 372.44 s and 364.26 s at its Task 4, two runs, at its Task 5 in 355.72 s and 362.38 s, two runs, at its Tasks 6 and 7 in 368.71 s and 365.48 s, and at its Task 8 in 357.49 s, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures in each, VERIFY's comparison 0 discrepancies; CI's harness-self job ran 39 files, 4456 tests, the admin files included, in 326.36 s at f5f7ab2, run 1245: all passed, certification 0 discrepancies, its outcome lines identical to Task 8's local run's), 4452 from the plan written at d0c8039's FIX_PLAN Task 2 on (the eight S-5 vectors of the human-report parity matchers joining, `test/self/s5-output-adapters.test.ts` now 117 tests, and the full suite, `npm test`, 127 files, 4805 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, with no product installed (`dist/` absent), 37 files, 4442 tests: all passed, in 388.11 s and 360.34 s at its Task 2, two runs, at its Tasks 3 to 10 in 383.61 s, 368.82 s, 387.89 s, 385.36 s, 403.40 s, 395.13 s, 404.23 s, and 392.68 s, and at its Task 11 in 400.48 s, at the 43c9a5e determination's VERIFY in 614.33 s, other agents sharing the machine, and in the plan written at 93e22f1 at its Tasks 1, 2, and 3 in 391.97 s, 382.38 s, and 387.70 s, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures in each, VERIFY's comparison 0 discrepancies; CI's harness-self job ran 39 files, 4452 tests, the admin files included, in 330.40 s at e9a530a, run 1236: all passed, certification 0 discrepancies, its outcome lines identical to Task 11's local run's), 4444 from the 13.5 re-descent plan written at 772854b's FIX_PLAN Task 48 on (`test/self/e6-exclusion.test.ts`'s four tests joining; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 37 files, 4434 tests: all passed, in 334.04 s at its Task 48, at its Task 49 in 370.23 s and 393.49 s, two runs, at its Task 50 in 350.03 s, at iteration 55's VERIFY (9583e3b) in 362.23 s, in the plan written at 092db72 at its Tasks 1, 2, and 3 in 344.8 s, 357 s, and 360.90 s, at iteration 59's VERIFY (a126add) in 380.37 s, in the plan written at acfff0b at its Task 1, its Task 2's first attempt, its Task 3, and its Task 2 in 415 s, 428.90 s, 394.65 s, and 387.65 s, at the 2d9cdf6 determination's VERIFY in 381.92 s, in the plan written at 2d9cdf6, with no product installed (`dist/` absent), at its Task 1 in 360.47 s, its Task 2 in 340.80 s, and its Task 3 in 352.89 s and 348.70 s, two runs, at the f50cf9f determination's VERIFY in 390.37 s, and in the plan written at f50cf9f, likewise, at its Task 1 in 363.49 s, its Task 2 in 365.39 s, its Task 3 in 360.73 s, and its Task 4 in 368.00 s, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures in each, VERIFY's comparison 0 discrepancies, VIOL-RACE-LISTFIRST, VIOL-READERS-CLAIM, and VIOL-CORE-EARLYRELEASE failing their certified tests in each; CI's harness-self job ran 39 files, 4444 tests, in 322.58 s at b265134, run 1200, in 321.61 s at 0ce40a7, run 1201, in 254.73 s at 3786c66, run 1202, in 323.59 s at 33e7d0b, run 1203, in 323.17 s at 9583e3b, run 1204, in 316.15 s at b9eb318, run 1207, in 320.96 s at a126add, run 1208, in 307.48 s at de35117, run 1211, in 324.65 s at 6ada37b, run 1212, in 298.29 s at 2d9cdf6, run 1214, in 257.48 s at 06a291c, run 1216, in 250.20 s at 58022f6, run 1217, and, with no product installed, in 245.77 s at e55a7a1, run 1219, in 323.95 s at f50cf9f, run 1220, in 320.48 s at 513f8b5, run 1222, in 305.67 s at 140178b, run 1223, and in 243.34 s at a1e6ae5, run 1224: all passed, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures, VERIFY's comparison 0 discrepancies, its outcome lines identical to the local runs'; at ffee710, run 1210, in 328.80 s, one test failed, CONF-READERS' P-10, whose `review resolve` killed past its hold left a temporary entry in `.xspec/reviews` that P-10 then counted as a write beside the session — the false failure the acfff0b plan's FIX_PLAN Task 3 removed; at a18abfc, run 1218, with no product installed, in 241.54 s, one test failed by design, the 2d9cdf6 plan's FIX_PLAN Task 2 probe binding the reach check of `test/self/machine-staging.admin.test.ts` to the built product again (`HarnessStagingError`, `dist/cli/bin.js` absent), its certification unchanged), 4440 from its Task 46 (S-9's five P-14 spec-source vectors and their count test, five P-14 TypeScript vectors, and the two P-14 configuration records joining; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 36 files, 4430 tests, in 336 s: all passed, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures, VERIFY's comparison 0 discrepancies — unchanged by its Task 47, 339.68 s, and in CI run 1198 at b9601fb, 269.93 s; CI's harness-self job ran 38 files, 4440 tests, in 267.36 s at 555e28d, run 1196: all passed; its full-suite job 126 files, 4793 tests, in 1490.30 s: 28 failed, every one a diagnosed product failure — run 1194's twenty-seven and P-14; its Windows leg failed only at its known `$.lock`), 4427 from its Task 45 (`test/self/p15-fixed-seed-draws.test.ts`'s four tests, the four CONF-LEFTOVER verifications, and S-9's P-15 configuration vector joining; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 36 files, 4417 tests, in 341 s: all passed — the manifest mirror and the registration check green, the accepted red gone, the manifest equal to the document — certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures, VERIFY's comparison 0 discrepancies; CI's harness-self job ran 38 files, 4427 tests, in 265.33 s at df03943, run 1194: all passed, its certification lines the local run's own; its full-suite job 125 files, 4779 tests, in 1124.70 s: 27 failed, every one a diagnosed product failure (`HarnessAssertionError`) — run 1192's twenty-six and P-15; its Windows leg 1 failed / 8 passed, its known `$.lock`), 4418 from its Task 44 (its two new certification verifications, CONF-READERS' and VIOL-READERS-CLAIM's, 17.4 s and 32.4 s alone; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4408 tests, in 327 s: 2 failed / 4406 passed, the accepted red — the manifest mirror, and the registration check naming `§CONF-LEFTOVER: P-15` alone — certification 185 PASS / 47 FAIL / 0 error / 0 hang over 35 fixtures, VERIFY's comparison listing only the four CONF-LEFTOVER fixtures; CI's harness-self job ran 37 files, 4418 tests, in 304.54 s at 7a83fb5, run 1192: 2 failed / 4416 passed, the same accepted red, its certification lines the local run's own; its full-suite job 123 files, 4769 tests, in 1419.32 s: 28 failed, the accepted red and twenty-six diagnosed product failures, run 1189's twenty-five and P-10; its Windows leg 1 failed / 8 passed, its known `$.lock`), 4416 from its Task 43, 4412 from its Task 34, 4411 from its Task 32, 4407 from its Task 31, 4406 from its Task 30, 4403 from its Task 28 (its Task 34 added one self test, `test/self/lock-state.test.ts`'s post-kill judgement (`assertLockPathAfterKill`, moved out of T13.5-3's `pastTheHoldKill` and shared with T13.5-7's kill arm), the suite project's counts unchanged: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4402 tests, in 272.53 s: 2 failed / 4400 passed, the accepted red (the manifest mirror, and the registration check naming `§CONF-LEFTOVER: P-15` alone), certification 184 PASS / 46 FAIL / 0 error / 0 hang over 33 fixtures, its lines Task 33's; CI's harness-self job ran 37 files, 4412 tests, in 253.28 s at 3bae84f, run 1174: 2 failed / 4410 passed, the same accepted red, its certification lines the local run's own; its full-suite job 123 files, 4763 tests, in 1417.59 s: 22 failed, the accepted red and twenty diagnosed product failures, the nineteen before and T13.5-7 at (b)'s residue (`found nothing at .xspec/lock`, 5.9 s, the local diagnosis); its Windows leg green; its Task 33 moved T13.5-6 into a new suite module, `test/suite/registry/section-13.5-vii.ts` with its wrapper `test/suite/section-13.5-vii.test.ts` — the suite project 86 files, 351 tests — leaving the self project's counts unchanged: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4401 tests, in 286 s: 2 failed / 4399 passed, the accepted red, certification 184 PASS / 46 FAIL / 0 error / 0 hang over 33 fixtures, its lines Task 32's; CI's harness-self job ran 37 files, 4411 tests, in 215.28 s at 0273964, run 1172: 2 failed / 4409 passed, the same accepted red, its certification lines the local run's own; its full-suite job 123 files, 4762 tests, in 1456.75 s: 21 failed, the accepted red and nineteen diagnosed product failures, the eighteen before and T13.5-6 at its first held arm's held-state comparison (count half: nothing at `.xspec/lock`, the local diagnosis); its Windows leg green; its Task 32 registered T13.5-13 in a new suite module, `test/suite/registry/section-13.5-vi.ts` with its wrapper `test/suite/section-13.5-vi.test.ts` — the suite project 85 files, 351 tests — its two new staged-source records two more S-9 tests, and wired CONF-RACE and VIOL-RACE-LISTFIRST, two more certification verifications: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4401 tests, in two consecutive runs of 262.54 s and 280.46 s: 2 failed / 4399 passed each, the accepted red (the manifest mirror, and the registration check naming `§CONF-LEFTOVER: P-15` alone), certification 184 PASS / 46 FAIL / 0 error / 0 hang over 33 fixtures, the two runs' lines identical, CONF-RACE's conformer passing T13.5-13 and VIOL-RACE-LISTFIRST failing it in both; CI's harness-self job ran 37 files, 4411 tests, in 264.22 s at f236a1c, run 1170: 2 failed / 4409 passed, the same accepted red, its certification lines the local runs' own; its full-suite job 122 files, 4762 tests, in 1424.52 s: 20 failed, the accepted red and eighteen diagnosed product failures, the seventeen before and T13.5-13 at the held arm's first refused run (its error document's `code` and `path` `null`, the local diagnosis); its Windows leg green; its Task 31 registered T13.5-9 in a new suite module, `test/suite/registry/section-13.5-v.ts` with its wrapper `test/suite/section-13.5-v.test.ts` — the suite project 84 files, 350 tests — and added `reclaimForHarness`'s self-test to `test/self/machine-staging.admin.test.ts`, now 7 tests: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4397 tests, 246.46 s: 2 failed / 4395 passed, the same accepted red, the same certification lines; CI's harness-self job ran 38 files, 4413 tests — the temporary probe's 6 among them — in 200.92 s at cd9ba79, run 1167: 2 failed / 4411 passed, the same accepted red, the same certification lines; at 0e8c126, run 1168, the probe removed, 37 files, 4407 tests, in 194.85 s: 2 failed / 4405 passed, the same accepted red; its full-suite job 121 files, 4757 tests, in 881.67 s: 19 failed, the accepted red and seventeen diagnosed product failures, the sixteen before and T13.5-9 at (a)'s held-state comparison (`found nothing at .xspec/lock`, 5.9 s); its Windows leg green; its Task 30 registered T13.5-12 in a new suite module, `test/suite/registry/section-13.5-iv.ts` with its wrapper `test/suite/section-13.5-iv.test.ts` — the suite project 83 files, 349 tests — its three new staged-source records three more S-9 tests: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4397 tests, 257.58 s: 2 failed / 4395 passed, the same accepted red, the same certification lines; CI's harness-self job ran 37 files, 4406 tests, in 207.96 s at 446a977, run 1165: 2 failed / 4404 passed, the same accepted red, the same certification lines; its full-suite job 120 files, 4755 tests, in 1428.62 s: 18 failed, the accepted red and sixteen diagnosed product failures, the fifteen before and T13.5-12 at (c)'s creation arm's held-state comparison (`found nothing at .xspec/lock`, 1.5 s); its Windows leg green; its Task 29c completed T13.5-11 with (a)'s write failures but (b)'s, adding no self test: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4394 tests, 286.89 s: 2 failed / 4392 passed, the same accepted red, the same certification lines; CI's harness-self job ran 37 files, 4403 tests, in 211.32 s at 44b18da, run 1163 (192.79 s at its Task 29b's dd8d5cc, run 1162): 2 failed / 4401 passed, the same accepted red, the same certification lines; its full-suite job 119 files, 4751 tests, in 908.44 s (1438.56 s in run 1162): 17 failed, the accepted red and the same fifteen diagnosed product failures, T13.5-11 at (a)'s first failure past acquisition, the held-state comparison of `rename specs/A.mdx a a2` before `specs/sub` is made `--x` (`found nothing at .xspec/lock`, 13.6 s); its Windows leg green; its Task 29b extended T13.5-11 with (a)'s failures past acquisition and acquisition's own failures, adding no self test: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4394 tests, 243.33 s: 2 failed / 4392 passed, the same accepted red, the same certification lines; its Task 29 registered T13.5-11 in a new suite module, `test/suite/registry/section-13.5-iii.ts` with its wrapper `test/suite/section-13.5-iii.test.ts` — the suite project 82 files, 348 tests — adding no self test: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4394 tests, 246.43 s: 2 failed / 4392 passed, the same accepted red, the certification runner's lines 183 PASS / 45 FAIL, 0 error, 0 hang, 31 fixtures; CI's harness-self job ran 37 files, 4403 tests, in 251.71 s at b11a8ed, run 1160: 2 failed / 4401 passed, the same accepted red, the same certification lines; its full-suite job 119 files, 4751 tests, in 1447.62 s: 17 failed, the accepted red and fifteen diagnosed product failures, the fourteen before and T13.5-11 at (a)'s busy arm's held-state comparison (`found nothing at .xspec/lock`); its Windows leg green; its Task 28 registered T13.4-12 in a new suite module, `test/suite/registry/section-13.4-ii.ts` with its wrapper `test/suite/section-13.4-ii.test.ts` — the suite project 81 files, 347 tests — its staleness edit one more staged-source record, so one more S-9 test, and extended two tests of `test/self/permission-staging.test.ts` (a staging's restore restoring nothing where its object was removed or renamed away): under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4394 tests, 230.27 s: 2 failed / 4392 passed, the same accepted red, the certification runner's lines 183 PASS / 45 FAIL, 0 error, 0 hang, 31 fixtures; CI's harness-self job ran 37 files, 4403 tests, in 206.98 s at 3bd1348, run 1158: 2 failed / 4401 passed, the same accepted red, the same certification lines; its full-suite job 118 files, 4750 tests, in 1421.45 s (the job 24 min, where run 1157's took 15.5 min and run 1156's 21.5 min: runner variance): 16 failed, the accepted red and fourteen diagnosed product failures, the thirteen before and T13.4-12 at its twin's `inventory` (`$.lock`); its Windows leg green) — 37 files, 4402 tests from its Task 26 on (its Task 27 added T13.5-10(h), adding no test; its Task 26 added T13.5-10's machine arms and one test of `test/self/lock-staging.test.ts`, `killHeldRun`'s launcher and observation: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4393 tests, 238.53 s: 2 failed / 4391 passed, the same accepted red, the certification runner's lines 183 PASS / 45 FAIL, 0 error, 0 hang, 31 fixtures; CI's harness-self job ran 38 files, 4409 tests — the temporary probe's 7 among them — in 270.29 s at 9b75446, run 1154: 2 failed / 4407 passed, the same accepted red; with the probe removed, at 98f7b7c, run 1155, it ran 37 files, 4402 tests, in 256.39 s: 2 failed / 4400 passed, the same accepted red, and its full-suite job 117 files, 4748 tests, in 853.77 s: 15 failed, the accepted red and the same thirteen diagnosed product failures) — 37 files, 4401 tests from its Task 24 on (its Task 25 added T13.5-10(e)'s one-machine parts, adding no test: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4392 tests, 238.60 s: 2 failed / 4390 passed, the same accepted red, the certification runner's lines 183 PASS / 45 FAIL, 0 error, 0 hang, 31 fixtures; its Task 24 added T13.5-10(d) and two tests of `test/self/permission-staging.test.ts`, the directory-mode staging's (`stageDirectoryMode`, `test/helpers/permissions.ts`): under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4392 tests, 246.59 s: 2 failed / 4390 passed, the same accepted red, the certification runner's lines 183 PASS / 45 FAIL, 0 error, 0 hang, 31 fixtures; CI's harness-self job ran all 37 files, 4401 tests, in 262.74 s at b405e86, run 1150: 2 failed / 4399 passed, the same accepted red) — 37 files, 4399 tests from its Task 21 on (its Task 23 added T13.5-10(c), adding no test: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4390 tests, 236.15 s: 2 failed / 4388 passed, the same accepted red, the certification runner's lines 183 PASS / 45 FAIL, 0 error, 0 hang, 31 fixtures; its Task 22 registered T13.5-10 in a new suite module, `test/suite/registry/section-13.5-ii.ts` with its wrapper `test/suite/section-13.5-ii.test.ts`, adding no self-test — S-7's sweep, one test over the whole registry, takes it in: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4390 tests, 253.78 s: 2 failed / 4388 passed, the same accepted red, the certification runner's lines 183 PASS / 45 FAIL, 0 error, 0 hang, 31 fixtures; its Task 21 added T13.5-8's acquisition-after arms, whose three staged-source records — the invalid configuration, `specs/sub/S.mdx`, and `src/both.mdx` — add three S-9 tests, and replaced VIOL-CORE-LATELOCK with VIOL-CORE-LATEHOLD; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4390 tests, 255.51 s: 2 failed / 4388 passed, the same accepted red, the certification runner's lines 183 PASS / 45 FAIL, 0 error, 0 hang, 31 fixtures; CI's harness-self job ran all 37 files, 4399 tests, in 250.60 s at 2392f18, run 1146: 2 failed / 4397 passed, the same accepted red and certification lines, its CORE verifications 143.3 s summed (the conformer's 13.3 s, VIOL-CORE-EARLYRELEASE's 27.7 s), and its full-suite job 116 files, 4744 tests, in 1397.22 s: 14 failed, the accepted red and the same twelve diagnosed product failures) — 37 files, 4396 tests from its Task 20 on (its Task 20 added T13.5-8's acquisition-first arms, whose two staged-source records — the code-group configuration and `src/c.ts` — add two S-9 tests, and gave VIOL-CORE-EARLYWRITE T13.5-8; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4387 tests, 252.98 s: 2 failed / 4385 passed, the same accepted red, the certification runner's lines 183 PASS / 45 FAIL, 0 error, 0 hang, 31 fixtures; CI's harness-self job ran all 37 files, 4396 tests, in 259.63 s at 921681b, run 1144: 2 failed / 4394 passed, the same accepted red and certification lines, and its full-suite job 116 files, 4741 tests, in 1394.81 s: 14 failed, the accepted red and the twelve diagnosed product failures) — 37 files, 4394 tests from its Task 18 on (its Task 18 added T13.5-4's `build` arm and the VIOL-CORE-BUILDWAIT verification to `test/self/certification.test.ts`; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4385 tests, 257.32 s: 2 failed / 4383 passed, the same accepted red, the certification runner's lines 184 PASS / 44 FAIL, 0 error, 0 hang, 31 fixtures; CI's harness-self job ran all 37 files, 4394 tests, in 249.82 s at dde8ecf, run 1141: 2 failed / 4392 passed, the same accepted red and certification lines) — 37 files, 4393 tests from its Task 17 on (its Task 17 strengthened T13.5-4's reads during a hold, gave VIOL-CORE-CHATTYREADS T13.5-4, and added the VIOL-CORE-READERENTRY verification to `test/self/certification.test.ts`; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4384 tests, 228.99 s: 2 failed / 4382 passed, the same accepted red, the certification runner's lines 176 PASS / 43 FAIL, 0 error, 0 hang, 30 fixtures; CI's harness-self job ran all 37 files, 4393 tests, in 230.87 s at 2138ff1, run 1139: 2 failed / 4391 passed, the same accepted red and certification lines) — 37 files, 4392 tests from its Task 16 on (its Task 16 rewrote T13.5-3 and added the VIOL-CORE-EARLYRELEASE verification to `test/self/certification.test.ts`; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4383 tests, 223.17–227.51 s: 2 failed / 4381 passed, the same accepted red, the certification runner's lines 169 PASS / 41 FAIL, 0 error, 0 hang, 29 fixtures; CI's harness-self job ran all 37 files, 4392 tests, in 214.32 s at bb6ea10, run 1137: 2 failed / 4390 passed, the same accepted red and certification lines) — 37 files, 4391 tests from its Task 15 on (its Task 15 rewrote T13.5-2 and gave VIOL-CORE-EARLYWRITE T13.5-2, adding no test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4382 tests, 165.11 s: 2 failed / 4380 passed, the same accepted red, the certification runner's lines 161 PASS / 40 FAIL, 0 error, 0 hang, 28 fixtures; CI's harness-self job ran all 37 files, 4391 tests, in 141.97 s at 294cbe1, run 1135: 2 failed / 4389 passed, the same accepted red and certification lines) — and from its Task 14 on (its Task 14 added the VIOL-CORE-HOLDLINK verification to `test/self/certification.test.ts`, ~16.6 s; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4382 tests, 163.32 s: 2 failed / 4380 passed, the same accepted red, the certification runner's lines 162 PASS / 39 FAIL, 0 error, 0 hang, 28 fixtures, the certification file alone 135.78 s) — 37 files, 4390 tests from its Task 12 on (its Task 12 added `test/self/pid-namespace-staging.test.ts`, 8 tests needing no administrative access — launcher A's and B's command lines, NSpid and first-process answer parsing, `hasAllocated`, the first process's script run as a plain child, T13.5-10(g)'s check, and the failure paths through stand-in sudo commands; about 0.4 s of tests, 1.9 s alone with Vitest's start-up — and `test/self/pid-namespace-staging.admin.test.ts`, 3 tests needing the job's administrative access (a launcher-A run as identifier 1 with the harness's identity and no capability, two launcher-A runs' identical in-namespace identifiers and the kills that empty a namespace, and a launcher-B namespace opened fresh, listing only its own processes, its (e) verification, an entered run's kill, and its close), which run in CI only here (the stagings II bullet below); under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4381 tests, 144.22 s: 2 failed / 4379 passed, the same accepted red, the certification runner's lines 154 PASS / 38 FAIL, 0 error, 0 hang, 27 fixtures; CI's harness-self job ran all 37 files, 4390 tests, in 135.09 s at 6a2bdd8, run 1131: 2 failed / 4388 passed, the same accepted red, every admin test passing) — 35 files, 4379 tests from its Task 11 on (its Task 11 added `test/self/machine-staging.test.ts`, 11 tests needing no administrative access — E-1's access check through stand-in commands, `/proc/self/mountinfo` parsing, the second mount's verification failing on a plain directory, the group staging and its restore, the second user's launcher command line with its umask and `env -i` fragments run, and the driver's `launcher` run option through a stand-in launcher, T12.7-1's walk of a launched run's stdout included; about 9 s of tests, 10.9 s alone with Vitest's start-up — and `test/self/machine-staging.admin.test.ts`, 6 tests needing the job's administrative access (the second user made by four makers at once, a run launched as it, its verification, the unjudged create check, kills through `sudo`, the bind mount), which run in CI only here (the bullet below); under `unshare --map-user` with `NODE_OPTIONS` unset and the admin file left out, 34 files, 4373 tests, 141.85 s: 2 failed / 4371 passed, the same accepted red, the certification runner's lines 154 PASS / 38 FAIL, 0 error, 0 hang, 27 fixtures; CI's harness-self job ran all 35 files, then 4378 tests, in 141.36 s at 6544faa, run 1127: 2 failed / 4376 passed, the same accepted red, every admin test passing) — 33 files, 4362 tests from its Task 10 on (its Task 10 added `test/self/lock-state.test.ts`, 7 tests: the held-state comparison and the lock-state assertions of `test/helpers/lock-state.ts` over synthetic trees, no product run — the count half (entries present, absent, doubled; a directory, symbolic links, a FIFO counted as no entry), the byte half (the root's lock path alone excluded, `.xspec` itself new only where the baseline had none), staged occupants in place, a mode-0o000 entry read through H-4's grant, entry identity, the only entry, names apart, the lock path absent or holding exactly a tree, and the H-6 inclusion check; two of its tests verify a refusal on this process first and so fail as root by design; about 0.3 s of tests, 2 s alone with Vitest's start-up; 137.59 s for the whole project under `unshare --map-user` with `NODE_OPTIONS` unset: 2 failed / 4360 passed, the same accepted red, the certification runner's lines 154 PASS / 38 FAIL, 0 error, 0 hang, 27 fixtures; CI's harness-self job ran it in 137.77 s at 20bef2b, run 1124, with the same result, the new file's tests passing there, unprivileged through the wrapper on ext4) — 32 files, 4355 tests from its Task 9 on (its Task 9 added `test/self/lock-staging.test.ts`, 9 tests: the lock-path leftover and obstruction stagings of `test/helpers/lock-staging.ts` — every kind round-tripping by bytes, `.`-names and names that are not valid UTF-8 included, read back with raw `lstat`/`readdir`/`readlink`; permission removals verified on this process, so that one test fails as root by design; the in-place, outside-target, and FIFO checks; the placement refusals; `copyEntryIn` — and the dead-entry helper `killHeldRun` through stand-ins honoring `--test-hold`; about 2 s of tests, 3.5 s alone with Vitest's start-up; 134.74 s for the whole project under `unshare --map-user` with `NODE_OPTIONS` unset: 2 failed / 4353 passed, the same accepted red, the certification runner's lines 154 PASS / 38 FAIL, 0 error, 0 hang, 27 fixtures; CI's harness-self job ran it in 89.33 s at 6637013, run 1121, with the same result, the new file's tests passing there, unprivileged through the wrapper on ext4) — 31 files, 4346 tests from its Task 8 on (its Task 8 added `test/self/kill-discipline.test.ts`, 9 tests: T13.5-3's exit-collection discipline — the driver's `processGroup` run option and `RunningProduct.killGroup`, the Linux process list of `test/helpers/kill-discipline.ts` with a zombie counted as listed, the hang guard's kill reaching the whole group — the reuse check `applyReuseCheck`, and the voidable-trial runner `runVoidableTrial`; the process tests take about 2 s each here, because this sandbox's first process (`process_api`, PID 1) reaps orphaned zombies only about once a second and a group kill waits until its orphaned members leave the process list, where CI's runner reaps at once (the file's 9 tests took 3.2 s in CI's harness-self job, 12 to 16 s here); 133.70 s under `unshare --map-user` with `NODE_OPTIONS` unset: 2 failed / 4344 passed, the same accepted red, the certification runner's lines 154 PASS / 38 FAIL, 0 error, 0 hang, 27 fixtures; CI's harness-self job ran it in 135.53 s at af15d09, run 1119, with the same result) — 30 files, 4337 tests from its Task 7 on (its Task 7 added `test/self/lock-path-exclusion.test.ts`, 10 tests: 12.0's reading of a mutating command and of `--config`, H-6's classification of compares over noted runs — a run between the snapshots, one held throughout, one in another workspace, a nested root, a `--config` root, a working directory below the root, a configless workspace, a snapshot rooted in the area or under the lock path — the near-miss names, the across-directories form, and, through a stub product, the driver's notes, `assertLeavesUnchanged`, and the determinism protocol; 131 s under `unshare --map-user` with `NODE_OPTIONS` unset: 2 failed / 4335 passed, the same accepted red, the certification runner's lines 154 PASS / 38 FAIL, 0 error, 0 hang, 27 fixtures) — 29 files, 4327 tests from its Task 6 on (its Task 6 added three tests to `test/self/s5-output-adapters.test.ts`, now 109: T13.3-2's operational path set in `isGraphDataKey`, the transient lock path and everything under it no graph data; the corrupt-record staging sparing whatever occupies the lock path; the one graph-data file collector `collectGraphDataFiles`; 132.27 s under `unshare --map-user` with `NODE_OPTIONS` unset: 2 failed / 4325 passed, the same accepted red, the certification runner's lines 154 PASS / 38 FAIL, 0 error, 0 hang, 27 fixtures) — 4324 tests from its Task 5 on (its Task 5 added `test/self/lock-path.test.ts`, 8 tests: the lock-path predicate and H-6's exclusion options, and H-4's grant-and-restore in the snapshot walk and the read, in-place write, and copy helpers of `test/helpers/lock-path.ts`; 122.34 s under `unshare --map-user` with `NODE_OPTIONS` unset: 2 failed / 4322 passed, the same accepted red, the certification runner's lines 154 PASS / 38 FAIL, 0 error, 0 hang, 27 fixtures) — 28 files, 4316 tests from its Task 4 on (its Task 4 added one test to `test/self/s5-output-adapters.test.ts`, now 106 tests: the usage-error conditions 14.24 to 14.26 (`write-failure`, `read-failure`, `workspace-busy`) decode as the error document's code and are rejected inside a findings array by the usage-error rule, never as unknown tokens; 140.62 s under `unshare --map-user` with `NODE_OPTIONS` unset: 2 failed / 4314 passed, the failures being the C-1 manifest-mirror and registration self-tests that plan accepts as red until its Tasks 49, 32 and 45, the certification runner's lines 154 PASS / 38 FAIL, 0 error, 0 hang, 27 fixtures) — 4315 tests from the fourteenth plan's FIX_PLAN Task 3 on (the plan written at 633df12: its Task 3 added one test to `test/self/property-infrastructure.test.ts`, now 20 tests, a shrink candidate whose failure declines shrinking ending the shrink as the reported counterexample, the report saying so; 128.99 s at Task 3 in CI's whole inner stage with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; 130.44 s at its Task 4, its confirmation run at 31bae80's trees, alone in CI's whole inner stage with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before (27 fixtures, 0 error, 0 hang); CI's harness-self job ran it in 122.77 s at 31bae80, run 1001) — 4314 tests from the fourteenth plan's FIX_PLAN Task 1 on (the plan written at 633df12: its Task 1 added one test to `test/self/s5-output-adapters.test.ts`, now 105 tests, the human-report omission matcher `assertReportOmits` (`test/helpers/adapters/human.ts`, the negative counterpart of `assertReportMentions`) accepting a report without the named information, stdout alone being the report, and rejecting one carrying it or an empty mention list; 141.25 s at Task 1 with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before) — 4313 tests from the thirteenth plan's FIX_PLAN Task 2 on (the plan written at bff95ed: its Task 2 added one test to `test/self/property-infrastructure.test.ts`, now 19 tests, a generator that throws while a falsification is shrunk being a harness error `while shrinking (the generator threw while replaying a shrink candidate's choices)` carrying the property, the seed, and `XSPEC_PROPERTY_SEED=<seed>`; 131.77 s at Task 2 with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; 131.69 s at its Task 3, its confirmation run at 87d419b's trees, alone in CI's whole inner stage with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; CI's harness-self job ran it in 129.93 s at 87d419b, run 996; unchanged at the fourteenth plan's VERIFY (bae4ad1): 263.33 s on the shared machine, `NODE_OPTIONS` unset, and 124.68 s in CI run 997) — 4312 tests from its Task 1 on (its Task 1 added one test to `test/self/assertion-protocol.test.ts`, `parseJsonStdout` failing diagnosed on a stdout led by a UTF-8 byte-order mark; 126.94 s at Task 1 with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before) — 4311 tests from the twelfth plan's FIX_PLAN Task 11 on (the plan written at 5bfab19: its Task 11 added four refused-shape tests to `test/self/p5-fixed-seed-draws.test.ts`, now 6 tests — see the P-5 fixed-seed bullet below; 139.82 s at Task 11 with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; 145.65 s at its Task 12, its confirmation run at bb37aab's trees, alone in CI's whole inner stage with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; CI's harness-self job ran it in 129.27 s at bb37aab, run 992; unchanged at the thirteenth plan's VERIFY (9a16fa4): 284.08 s, with two other agents' Vitest runs sharing the machine (load average up to about 15), `NODE_OPTIONS` unset, and 84.50 s in CI run 993) — 4307 tests from its Task 10 on (its Task 10 added S-9's per-draw replay of P-5's fixed-seed section moves, one test in `test/self/p5-fixed-seed-draws.test.ts`, then 2 tests; 147.42 s at Task 10 with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before) — 4306 tests from the eleventh plan's FIX_PLAN Task 14 on (the plan written at 8b068bf: its Task 14 added P-5's fixed-seed draw guard, `test/self/p5-fixed-seed-draws.test.ts`, one test — see the P-5 fixed-seed bullet below; 144.26 s at Task 14 with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; 141.87 s at its Task 15, its confirmation run at c88ab04's trees, alone in CI's whole inner stage with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; CI's harness-self job ran it in 114.02 s at c88ab04, run 979; unchanged at the twelfth plan's VERIFY (e6b7cb0): 188.90 s, with two other agents' runs sharing the machine, `NODE_OPTIONS` unset, and 129.22 s in CI run 980; unchanged through the twelfth plan (written at 5bfab19) to its Task 9, which added no test: its S-6 vetting of the section-move oracle's would-be-text composer, `composeSectionMoveTexts`, is the closing assertion of each of the 30 after-text vectors in `test/self/s6-section-move-oracle.test.ts`, still 36 tests; 142.01 s at Task 9 with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before) — 27 files, 4305 tests from its Task 13 on (its Task 13 added 66 S-9 vectors to `P5_FORM_VECTORS` in `test/suite/registry/section-16-p5-p6.ts`, one test each in `test/self/s9-fixture-well-formedness.test.ts`, now 2056 tests — P-5's text-position target parent in each shape over the second fixed model `P5_TEXT_POSITION_MODEL`: the target file as staged, as each landed collapse form leaves it, and the coincident file with each collapse decoration before and after the move; 140.09 s at Task 13 with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before) — 4239 from its Task 12 on (its Task 12 added three S-6 vectors in `test/self/s6-section-move-oracle.test.ts`, now 36 tests, each moving a single-line in-line section holding prose outside its tags into one of T6.5-16(c)'s text-position target parent shapes; 149.39 s at Task 12 with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before) — 4236 from the ninth plan's FIX_PLAN Task 4 on (the plan written at c0f2915: its Task 4 added one E-1 test in `test/self/permission-staging.test.ts`, Linux-only, each permission staging reaching entries named by bytes that are not valid UTF-8, or not ASCII, at their exact bytes — red against d585f7c's `test/helpers/permissions.ts`, whose area staging left the 0xFF-named file at mode 0o644; 137.75 s at Task 4, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; unchanged through its Tasks 5–9, which added none; 146.18 s at its Task 10, its confirmation run at 8b20530's trees, alone in CI's whole inner stage, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; CI's harness-self job ran it in 131.21 s at 8b20530, run 952; unchanged at the tenth plan's VERIFY (7ef10b6): 206.51 s, with another reviewer's run sharing the machine, `NODE_OPTIONS` unset, and 128.06 s in CI run 953; unchanged through that plan (written at 23e3b4a), whose Tasks 1–9 added none: 139.68 s at its Task 10, its confirmation run at 0ad39cd's trees, alone in CI's whole inner stage with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; CI's harness-self job ran it in 133.41 s at 0ad39cd, run 963; unchanged at the eleventh plan's VERIFY (7e232fb): 188.62 s, with another agent's Vitest sharing the machine, `NODE_OPTIONS` unset, and 117.46 s in CI run 964, and through that plan's Tasks 1–11, which added none) — 4235 from its Task 1 on (its Task 1 added one S-5 test in `test/self/s5-output-adapters.test.ts`, Linux-only, the corrupt-record staging reaching every graph-data file at its exact name bytes, and assertions only to two existing S-2 tests; 159.04 s at Task 1, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before) — 4234 from the seventh plan's FIX_PLAN Task 5b on (the plan written at 765d6b4: its Task 5b added S-3's three driver-walk tests in `test/self/s3-subprocess-driver.test.ts` — two rejecting runs, a near-marker in a captured JSON-output stdout and a crash of the walk itself, and one accepting control; 159.70 s at Task 5b; 161.38 s at its Task 6, its confirmation run at 107f624's trees, alone in CI's whole inner stage, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; CI's harness-self job ran it in 127.83 s at 107f624, run 933; unchanged through the eighth plan (written at a2bfdf4), whose Tasks 1–3 added none: 198.74 s at its VERIFY (34032b5), with the reviewers' runs sharing the machine, and 121.93 s in CI run 934 there; 156.01 s at its Task 4, its confirmation run at 97c7c24's trees, alone in CI's whole inner stage, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; CI's harness-self job ran it in 131.20 s at 97c7c24, run 938; unchanged at the ninth plan's VERIFY (f8f38eb): 181.36 s, on a nearly idle machine, and 105.24 s in CI run 939) — 4231 from its Task 5 on (it added one S-5 test in `test/self/s5-output-adapters.test.ts`, `parseJsonStdout`'s marker walk; 154.87 s at Task 5) — 4230 from the fifth plan's FIX_PLAN Task 11 on (the plan written at 1e2972e: its Task 11 added one S-7 test, `test/self/s7-red-green-sweep.test.ts`'s sweep of the product-facing bodies outside the registry — the E-6 fixture, the four single-casing probes, and T11.6-1's drive-mismatch arm, synthetic entries T99.7-2 through T99.7-7; 134 s at Task 11, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; 142 s at its Task 12, its confirmation run at 7f59049's trees, alone in CI's whole inner stage, all passing, 0 skipped; CI's harness-self job ran it in 126 s at 7f59049, run 915; unchanged through the sixth plan, written at 849b69d, whose Tasks 1–5 added none: 159.90 s at its VERIFY (68f0718), with another agent's Vitest beside it, and 126.63 s in CI run 917 there; 147 s at its Task 6, its confirmation run at 715dff7's trees, alone in CI's whole inner stage, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; CI's harness-self job ran it in 99 s at 715dff7, run 923; unchanged at the seventh plan's VERIFY (b00e7cd) — 176.08 s, with another agent's Vitest beside it, and 83.30 s in CI run 924 — and through that plan's Tasks 1–4, which added none: 149.58 s at Task 4) — 4229 from its Task 9 on (its Task 9 added two S-9 TypeScript records, T11.6-3's order-workspace `xspec.config.ts` and `lib/deux.ts`; 132 s at Task 9, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before) — 4227 from its Task 2 on (its Task 1 added S-4's three skeleton vectors, 4223 tests, and its Task 2 four vectors of the shared fresh-identifier reader in `test/self/added-import-identifiers.test.ts`; 191 s at Task 2, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before) — 4220 from the fourth plan's FIX_PLAN Task 10 on (the plan written at 6a4a280: its Task 10 added S-3's three vectors for a crash of T6.5-22(a)'s own MDX parse, and its Task 11 only rows to CONF-ORPHAN's grammar-guard table, still one test; 177 s at that plan's Task 12, its confirmation run at 8bebeba's trees, alone in CI's whole inner stage, all passing, 0 skipped; CI's harness-self job ran it in 124 s at 8bebeba, run 902, and in 129 s at 4117ede, run 903, where the fifth plan's VERIFY ran it in 192.75 s in CI's whole inner stage) — 4217 from the third plan's FIX_PLAN Task 9 on (179 s at the fourth plan's VERIFY, 72d5126, and 107 s in CI there; the plan written at ad9eb42; its Tasks 5 through 9 each added one table to the grammar guard, one test per table — CONF-AVAIL's at Task 5, 4213 tests, 151 s alone; CONF-DISC's at Task 6, 4214; CONF-VALID's at Task 7, 4215; CONF-MD's at Task 8, 4216; CONF-CORE's at Task 9, 4217 — and its Tasks 10 and 10a only added rows to CONF-CORE's table; 137 s at that plan's Task 11, its confirmation run at fdc3c49, alone in CI's whole inner stage (network off, uid 1000, no capabilities), all passing, 0 skipped; CI's harness-self job ran it in 97 s at fdc3c49, run 888) — 4212 from that plan's Task 4 on (it added the 27th file, `test/self/certification-fixture-grammar.test.ts`, with one test; 137 s alone, all passing, 0 skipped) — 26 files and 4211 tests from that plan's Task 3 on (it added S-3's four in-run-evaluation vectors and S-8's item-6 test; 136 s alone, all passing, 0 skipped) — 4206 from the re-descent's second plan's FIX_PLAN Task 13 on (it added that file's sixth test, pinning every command's run under JSON output and the mutating commands' performed, preview, and section forms; 172 s alone at that plan's Task 14, its confirmation run, all passing, 0 skipped; CI's harness-self job ran it in 133 s at 79d2013) (4205 at that plan's Task 12, which added the fifth, pinning `armSteps`; 4204 at its Task 11, which added the fourth, the JSON-output reading guard; ~181 s) (4203 at that plan's Task 10, which added the 26th file, `test/self/p8-fixed-seed-draws.test.ts`, with three tests; ~177 s) (25 files and 4200 tests at that plan's Task 9, which added S-5's three correction-judge tests), 4197 tests from that plan's Task 7 on (iteration 82; it added one staged-source ledger record, T4.5-3's `SPEC?.a;` arm, one more test of `test/self/s9-staged-sources.test.ts`, 1570 there; ~184 s; unchanged at that plan's Task 8, which restaged two records in place, ~181 s) (4196 at that plan's Tasks 4 through 6, Task 4 adding two staged-source ledger records, each one more test of that file, 1569 there; 4194 at that plan's Task 3, which added five S-9 builder vectors for spec-group files not named `.mdx` — four in `test/self/s9-fixture-well-formedness.test.ts`, one in `test/self/s9-undeclared-staging.test.ts`; 4189 at that plan's Task 2b, which added S-3's two capture-limit vectors and S-8's helper-conversion vector; 4186 at its Task 2, which added S-8's capture-limit vector; 4185 from the first plan's Task 64 through Task 66, its last, 4158 at Task 63, 4094 at Task 62, 3983 at Task 61, 3955 at Task 60, 3950 at Tasks 58 and 59, 3947 at Task 57, 3940 at Tasks 52 through 56, 3935 at Task 51, 3933 at Task 50, 3929 at Task 49, 3925 at Task 48, 3921 at Task 47, 3911 at Task 46, 3905 at Task 45, 3895 at Task 44, 3881 at Task 43, 3862 at Task 42, 3857 at Task 41, 3844 at Task 40, 3840 at Task 39, 3833 at Task 38, 3826 at Task 37, 3823 at Task 36, 3821 at Task 35, 3796 at Task 34, 3784 at Tasks 32 and 33, 3770 at Task 31, 3767 at Tasks 29 and 30, 3762 at Task 28, 3761 at Task 27, 3759 at Task 26, 3757 at Task 25, 3744 at Task 24, 3743 at Task 23, 3740 at Task 21, 3731 at Task 19, 24 files and 3693 tests at Task 18, 3621 at Task 17, 3550 at Task 16o, 3542 at Task 16n, 3534 at Task 16m, 3494 at Task 16l, 3452 at Task 16k, 3424 at Task 16j, 3401 at Task 16i, 3338 at Task 16h, 3289 at Task 16g, 3242 at Task 16f, 3221 at Task 16e, 3199 at Task 16d, 3128 at Task 16c, 3078 at Task 16b, 3061 at Task 16, 3023 at Task 15, 3017 at Task 14, 22 files and 2961 tests at Task 13, 2960 at Task 12, 2959 before it: S-9's staged-sources self-test runs one test per staged-source record, so each new record adds one; Task 13 added one S-5 test, Task 14 the new file `test/self/s9-typescript-well-formedness.test.ts`, 56 tests, Task 15 six S-2 tests, and Task 16 the TypeScript records' tests — 17 fixed ones plus one per TypeScript judgement, 21 at Task 16, 38 at Task 16b, 88 at Task 16c, 159 at Task 16d, 181 at Task 16e, 202 at Task 16f, 249 at Task 16g, 298 at Task 16h, 361 at Task 16i, 384 at Task 16j, 412 at Task 16k, 454 at Task 16l, 494 at Task 16m, 502 at Task 16n, and 503 from Task 16o; Task 16o also added five `test/self/s9-undeclared-staging.test.ts` tests, one fixed TypeScript-records test, and one MDX record's judgement — the Windows leg's drive-mismatch fixture's two records; Task 17 added the 71 tests of S-9's Unicode 15.1 block in `test/self/s9-fixture-well-formedness.test.ts`, Task 18 the new file `test/self/s6-name-analysis.test.ts`, 72 tests, Task 19 the new file `test/self/added-import-identifiers.test.ts`, 38 tests, Task 21 nine S-9 staged-source tests, one per T1.4-5 record, Task 23 three, one per record of T2.4-5's escaped-root workspace, Task 25 thirteen, one per record of T4-2's eleven new arm rows, its no-other-construct `src/c.ts`, and its `specs/NAME.mdx`, Task 26 two, one per record of T4.3-2's template-literal arm's `src/app.ts` and T4.5-3's `login-v2` spec source, Task 28 one, the record of T5.7-2's U+3000/U+202F arm's `specs/MAIN.mdx`, Task 34 twelve, one per record of T6.5-7's CRLF and lone-CR re-runs — three MDX and three TypeScript records per kind, Task 35 twenty-five — five `test/self/import-insertion.test.ts` tests and one per record of T6.5-8's restaged arms and their CRLF and lone-CR re-runs, thirteen MDX net and seven TypeScript, Task 36 two — two `test/self/import-insertion.test.ts` tests of the `pinnedOffsets` set, T6.5-9's code-arm origin record replaced one for one, Task 38 seven, one per record of T6.5-18's configuration, origin, target, and four `src/c.ts` stagings, Task 39 seven, one per record of T6.5-20's three configurations and four spec sources, Task 40 four, one per record of T6.5-20 (c)'s two configurations, its code source, and `specs/B.md/C.mdx`, Task 41 thirteen, one per record of T6.5-20 (d)'s two configurations and nine `src/c.ts` stagings and of (e)'s configuration and `specs/A.mdx`, Task 42 five, one per record of T6.5-21's three configurations, its `specs/A.mdx`, and (b)'s `specs/A.md`, Task 43 nineteen, one per record of T6.5-22's configuration, `specs/A.mdx`, and fourteen receivers, and three `test/self/added-import-identifiers.test.ts` tests of `judgeAddedImportsOfFile`, Task 44 fourteen, one per record of T6.5-23's configuration, `specs/origin.mdx`, `specs/target.mdx`, `specs/c.mdx`, and ten `src/c.ts` stagings, Task 45 ten, one per record of T6.5-23 (f)'s `specs/A.mdx`, `specs/B.mdx`, and seven `src/c.ts` stagings and (g)'s `specs/target.mdx`, Task 46 six, one per record of T6.5-23 (h)–(k)'s six `src/c.ts` stagings, Task 47 ten, one per record of T6.5-23 (l)–(p)'s eight `src/c.ts` stagings, (l)/(m)'s `specs/A.mdx`, and (o)'s `specs/third.mdx`, Task 48 four, one per record of T7-2's four import-modifier arms, Task 49 four, one per record of T7.1-1's path-character configuration and spec source and its code-source control's configuration and code source, Task 50 four, one per record of T7.3-1's graph-data-area and look-alike outDir configurations, Task 51 two, one per record of T11.6-2's invalid-path `.mdx` sources, Task 52 five, one per record of T12.0-5's positive side of the backslash — two MDX (`specs/a`, backslash, `b.mdx` and the code side's `specs/A.mdx`) and three TypeScript (the code side's configuration, `src/a`, backslash, `b.ts`, and `src/ab.ts`), Task 60 five, one per record of T14-11 (x)'s five code sources, Task 61 twenty-eight — eleven, one per record of T14-12's new arms (four MDX: (ae)–(ag)'s and (aa)'s `specs/S.mdx`; seven TypeScript: the five new code arms', (ab)'s configuration, and (ac)'s code source), four S-9 MDX form vectors, and thirteen S-9 TypeScript tests — the ten `T14_12_CODE_FORM_VECTORS`, their count, and (ac)'s judgement and offset pin), Task 62 one hundred eleven — S-9 P-2/P-3 form vectors over P-2's full brace-side whitespace set (fifteen new own-line `{X}` vectors, nineteen own-line block-comment sequences with X in every gap, and seventy-six inline ones, both forms per code point with and without a tail) and one test pinning that set and its vectors' coverage, Task 63 sixty-four — one S-9 P-5 import-header form vector per drawn spec basename, Task 64 twenty-seven — three property-runner self-tests of the TypeScript per-draw check (`test/self/property-infrastructure.test.ts`, 18 tests) and twenty-four S-9 TypeScript tests of the §16 generators' forms in `test/self/s9-typescript-well-formedness.test.ts` (twenty-two vectors and two coverage tests), all passing (~137–172 s, 146 s at Task 17, 144 s at Task 18, 144 s at Task 19, 147 s at Task 21, 138 s at Task 23, 131 s at Task 25, 136 s at Task 26, 143 s at Task 28, 134 s at Task 34, 132 s at Task 35, 130 s at Task 36, 152 s at Task 38, 155 s at Task 39, 159 s at Task 40, 156 s at Task 41, 157 s at Task 42, 155 s at Task 43, 155 s at Task 44, 153 s at Task 45, 153 s at Task 46, 153 s at Task 47, 154 s at Task 48, 154 s at Task 49, 149 s at Task 50, 148 s at Task 51, 152 s at Task 52, 152 s at Task 55 (3940 tests, unchanged), 154 s at Task 56 (3940 tests, unchanged), 157 s at Task 58 (3950 tests), 161 s at Task 59 (3950 tests, unchanged), 159 s at Task 60 (3955 tests), 159 s at Task 61 (3983 tests), 155 s at Task 62 (4094 tests), 156 s at Task 64 (4185 tests), 164 s at Task 66 (4185 tests, unchanged), 171 s at the second plan's Task 2 (4186 tests), 171 s at its Task 2b (4189 tests), 170 s at its Task 3 (4194 tests), 176 s at its Task 4 (4196 tests); CI's harness-self job ~108 s), and certification summed — before the 13.5 re-descent's new fixtures; Current totals above give today's 171 PASS / 48 FAIL / 0 error / 0 hang over 39 lines, the 9 conformers' 40 (test, fixture) pairs all PASS and the 30 violators' 179 pairs 131 PASS and 48 FAIL (186 PASS / 50 FAIL, 42 and 194 pairs, before the plan written at 2a2b94e's FIX_PLAN Task 1) — to 154 PASS / 38 FAIL / 0 error / 0 hang over 27 `certification run against` lines, every FAIL a violator's expected outcome: the 6 conformers' 39 (test, fixture) pairs all PASS, and the 21 violators' 153 pairs are 115 PASS and 38 FAIL, unchanged at Task 66, at the re-descent's second plan's Task 14, at the third plan's Task 11 (fdc3c49, locally and in CI run 888's harness-self job), at the fourth plan's Task 12 (8bebeba's trees, locally and in CI run 902's harness-self and suite-linux jobs), at the fifth plan's Task 12 (7f59049's trees, locally and in CI run 915's harness-self and suite-linux jobs), and at the sixth plan's Task 6 (715dff7's trees, locally and in CI run 923's harness-self and suite-linux jobs), at the seventh plan's VERIFY (b00e7cd, locally and in CI run 924), at its Task 6 (107f624's trees, locally and in CI run 933's harness-self and suite-linux jobs), at the eighth plan's VERIFY (34032b5, locally and in CI run 934), at its Task 4 (97c7c24's trees, locally and in CI run 938's harness-self and suite-linux jobs), at the ninth plan's VERIFY (f8f38eb, locally and in CI run 939), at its Task 10 (8b20530's trees, locally and in CI run 952's harness-self and suite-linux jobs), at the tenth plan's VERIFY (7ef10b6, locally and in CI run 953), at its Task 10 (0ad39cd's trees, locally and in CI run 963's harness-self and suite-linux jobs), at the eleventh plan's VERIFY (7e232fb, locally and in CI run 964), at its Task 15 (c88ab04's trees, locally and in CI run 979's harness-self and suite-linux jobs), at the twelfth plan's VERIFY (e6b7cb0, locally and in CI run 980), and at its Task 12 (bb37aab's trees, locally and in CI run 992's harness-self and suite-linux jobs) (`grep 'certification run against' <log> | grep -oE '[0-9]+ pass, [0-9]+ fail, [0-9]+ error, [0-9]+ hang' | awk '{p+=$1; f+=$3; e+=$5; h+=$7} END {print p, f, e, h}'`; for one kind's sum, insert `| grep ' conformer:'` or `| grep ' violator:'` after the first `grep`). +- Harness self-tests and certification only (TEST-SPEC 17): `npm run test:self`, which needs no product build (TEST-SPEC H-8: self-tests and certification pass before the product exists); CI's harness-self job runs it with no `dist/` and no `XSPEC_PACKAGE_DIR` (the module channel counts as part of the product, H-8), but with E-1's Node.js releases provisioned (`XSPEC_NODE_RELEASES_DIR`), on which S-10 checks the release driver before any product exists. Its S-7 file, `test/self/s7-red-green-sweep.test.ts`, sweeps every product-facing body (the registered ones and the seven layer-4 bodies outside the registry, T7-1's single-casing probe, synthetic entry T99.7-8, the seventh from the plan written at 2a2b94e's FIX_PLAN Task 54 on) against the empty stub — from the e57210b plan's FIX_PLAN Task 11 on in two sweeps (`STUB_SWEEPS`): beside the empty stub package `test/fixtures/empty-stub-package/` (one file, `package.json`, naming no entry, its only members `name`, `xspec-empty-stub`, and `version`, `0.0.0`; its contract pinned by the file's layer 1 and documented in its header, since JSON holds no comment), given as the binding's `packageDir` and found unchanged after each sweep beside it, and with no package directory given (TEST-SPEC S-7, H-8), each report naming its sweep — and, from the affd85f plan's FIX_PLAN Task 5 on, against an absent built-product artifact as well (`builtProductBindingAt(<dist/cli/bin.js inside a fresh temporary directory>)`, absent whatever the checkout's `dist/` holds, so it checks the same with or without a build), each body required to fail diagnosed, every no-product diagnosis naming the artifact (the file's 10 tests took 90.11 s alone under `unshare --map-user` at the e57210b plan's FIX_PLAN Task 11 — 35.1 s the registry sweep beside the stub package, 33.7 s the one with no package directory, 9.1 s the no-product registry sweep — where its 7 tests had taken 58.54 s just before, and 30.95 s at the affd85f plan's FIX_PLAN Task 5, 7.1 s of it the no-product registry sweep; with the second stub sweep the self project, `XSPEC_PACKAGE_DIR` unset and the admin files left out, ran 43 files, 5234 tests, 5233 passing and S-1's unmapped `7.6` (that plan's Task 16) failing, in 480.85 s at Task 11, certification 172 PASS / 50 FAIL / 0 error / 0 hang, so CI's harness-self job stays far inside its 30-minute `timeout-minutes`, its critical path still `certification.test.ts`; to red-check the sweeps, perturb a scratch-saved copy of the file — a synthetic body that passes wherever `product.packageDir` is set, appended to the registry sweep's entries and to layer 4's list, must fail the two sweeps beside the stub package alone, and one writing a file into `product.packageDir` must fail the registry sweep's unchanged-package check — run `-t 'S-7, '`, copy the saved file back, `cmp` it, and remove any file a perturbation wrote by its absolute path). Its certification runner prints one `PASS`/`FAIL` line per (test, fixture) pair as it drives each fixture executable; a violator's `FAIL` lines are its expected outcomes, not failures — Vitest's own failures are the `×` lines and the final `Tests` summary, so when piping the output through `grep`, filter on those rather than on `FAIL` (the runner's lines are indented — ` FAIL T…` — so a line-anchored `grep -v '^FAIL '` does not drop them; match `×` and the `Tests` summary instead, and never cap the output with `head -N`: the runner's 30-odd per-pair lines precede the summary, so redirect the run to a log file and grep that afterwards). To certify one fixture family alone, filter `test/self/certification.test.ts` on the family name every one of its test titles carries: `npx vitest run --config test/vitest.config.ts --project self test/self/certification.test.ts -t CORE` runs the CONF-CORE conformer and each VIOL-CORE-* violator (~150 s in all from the 772854b plan's FIX_PLAN Task 21 on — 149.93 s, and 152.84 s with `--reporter=verbose`, whose per-verification times were the conformer's 8.5 s, VIOL-CORE-NOLOCK's 7.8 s, VIOL-CORE-EARLYWRITE's 8.0 s, VIOL-CORE-EARLYREFRESH's 9.1 s, VIOL-CORE-STALELOCK's 6.1 s, VIOL-CORE-PARTIALWRITE's 10.2 s, VIOL-CORE-CHATTYREADS's 8.0 s, VIOL-CORE-PERSISTREADS's 8.4 s, VIOL-CORE-LATEHOLD's 8.7 s, VIOL-CORE-EARLYRELEASE's 29.2 s, VIOL-CORE-HOLDLINK's 16.6 s, VIOL-CORE-READERENTRY's 8.0 s, and VIOL-CORE-BUILDWAIT's 18.3 s, 146.9 s summed, its T13.5-8 driving 10 more product invocations per fixture than before; ~147 s from its Task 20 on, its T13.5-8 driving 29 more product invocations per fixture than before — in a full self run the conformer's verification 12.4 s, VIOL-CORE-EARLYWRITE's 9.8 s, VIOL-CORE-HOLDLINK's 16.7 s, VIOL-CORE-BUILDWAIT's 18.4 s, VIOL-CORE-EARLYRELEASE's 28.9 s, about 167 s summed; ~149 s from its Task 18 on — the conformer's verification 8.4 s, VIOL-CORE-PARTIALWRITE's 10.0 s, VIOL-CORE-HOLDLINK's 16.9 s, VIOL-CORE-BUILDWAIT's 18.5 s, whose T13.5-4 fails only through its `build` arm's 15 s hang guard, VIOL-CORE-EARLYRELEASE's 29.0 s, T13.5-4 driving 5 more product invocations per fixture than at Task 17; ~127 s from its Task 17 — the conformer's verification 8.2 s, VIOL-CORE-PARTIALWRITE's 9.6 s, VIOL-CORE-HOLDLINK's 16.5 s, VIOL-CORE-EARLYRELEASE's 28.7 s, VIOL-CORE-READERENTRY's 8.0 s, its T13.5-4 ~0.4 s longer per fixture than at Task 16 (~1.7 s against the conformer); ~119 s from its Task 16 — its T13.5-3 driving about 68 product invocations per fixture, the conformer's verification 8.7 s, VIOL-CORE-PARTIALWRITE's 10.2 s, VIOL-CORE-HOLDLINK's 16.9 s, VIOL-CORE-EARLYRELEASE's 29.2 s; ~59 s from its Task 15 — its T13.5-2 driving about 57 product invocations per fixture, the conformer's verification 4.8 s, VIOL-CORE-PARTIALWRITE's 7.4 s; ~43 s from its Task 14 — ~17 s of it VIOL-CORE-HOLDLINK's, whose T13.5-1 fails only through its dangling-link arm's 15 s hang guard, `runBounded` in `test/suite/registry/section-13.5.ts`) and skips every other family; `-t ORPHAN` runs the CONF-ORPHAN conformer (`test/fixtures/conf-orphan/`) and its VIOL-ORPHAN-* violators over T13.4-11 alone (~4 s per fixture, ~12 s with Vitest's start-up); `-t LEFTOVER` runs the CONF-LEFTOVER conformer (`test/fixtures/conf-leftover/`) and its VIOL-LEFTOVER-* violators over P-15 alone (the conformer's verification 5.2 s, FOLLOWLINK's 6.6 s, DOTNAMES' 5.0 s, BYTENAMES' 4.1 s at the 772854b plan's FIX_PLAN Task 45; ~27 s with Vitest's start-up). Certification's time budget (the 772854b plan's FIX_PLAN Task 49): `test/self/certification.test.ts` runs its 42 verifications one after another in one file (39 until the e57210b plan's FIX_PLAN Task 7 wired CONF-IMPORT, VIOL-IMPORT-BRACED, and VIOL-IMPORT-SINGLE, ~28 s more locally), the self project's critical path — 271.2 s of the Vitest run's 321.61 s in CI run 1201 at 0ce40a7, whose harness-self job took 351 s from start to end (29% of its 20-minute `timeout-minutes`; 352 s at b265134, run 1200; 276 s at 3786c66, run 1202, its self project 254.73 s and `certification.test.ts` 219.3 s, VIOL-READERS-CLAIM's verification 31.2 s; 350 s at 33e7d0b, run 1203, its self project 323.59 s and `certification.test.ts` 271.7 s, VIOL-READERS-CLAIM's verification 31.6 s; 352 s at 9583e3b, run 1204, its self project 323.17 s; 342 s at b9eb318, run 1207, its self project 316.15 s and `certification.test.ts` 266.5 s, VIOL-READERS-CLAIM's verification 31.6 s; 355 s at 6ada37b, run 1212, its self project 324.65 s and `certification.test.ts` 273.5 s, VIOL-READERS-CLAIM's verification 31.6 s; 326 s at 2d9cdf6, run 1214, its self project 298.29 s and `certification.test.ts` 251.6 s; with no product installed and no build step, 262 s at e55a7a1, run 1219 (22%), its self project 245.77 s and `certification.test.ts` 211.3 s, VIOL-READERS-CLAIM's verification 31.1 s; 350 s at 513f8b5, run 1222 (29%), its self project 320.48 s and `certification.test.ts` 270.3 s; 259 s at a1e6ae5, run 1224 (22%), its self project 243.34 s and `certification.test.ts` 208.9 s, VIOL-READERS-CLAIM's verification 31.1 s; 358 s at e9a530a, run 1236 (30%), its self project 330.40 s and `certification.test.ts` 278.7 s, VIOL-READERS-CLAIM's verification 31.6 s; 351 s at f5f7ab2, run 1245 (29%), its self project 326.36 s and `certification.test.ts` 275.0 s, VIOL-READERS-CLAIM's verification 31.6 s; 344 s at 0c927d8, run 1253 (29%), its self project 322.48 s and `certification.test.ts` 263.8 s, VIOL-READERS-CLAIM's verification 31.6 s; 340 s at 58361cb, run 1266 (28%), its self project 315.96 s and `certification.test.ts` 259.7 s, VIOL-READERS-CLAIM's verification 31.6 s; 344 s at b5ac9a8, run 1272 (29%), its self project 322.37 s and `certification.test.ts` 264.0 s, VIOL-READERS-CLAIM's verification 31.6 s; 350 s at a909c5d, run 1339 (29%), its self project 327.05 s and `certification.test.ts` 266.9 s, VIOL-READERS-CLAIM's verification 31.6 s; 414 s at a3cc3ed, run 1547, the 2a2b94e plan's end (35%), its self project 387.76 s and `certification.test.ts` 286.7 s, VIOL-READERS-CLAIM's verification 31.8 s), and 362.6 s summed of 370.23 s locally under `unshare --map-user` (354.2 s of 360.90 s at the 092db72 plan's FIX_PLAN Task 3, 380.4 s of 387.65 s at the acfff0b plan's FIX_PLAN Task 2, 341.9 s of 348.70 s at the 2d9cdf6 plan's FIX_PLAN Task 3, 360.1 s of 368.00 s at the f50cf9f plan's FIX_PLAN Task 4, 389.6 s of 400.48 s at the d0c8039 plan's FIX_PLAN Task 11, 350.1 s of 357.49 s at the 93e22f1 plan's FIX_PLAN Task 8, 375.3 s of 386.94 s at the affd85f plan's FIX_PLAN Task 7, 394.2 s of 403.20 s at the a71eb0c plan's FIX_PLAN Task 12, 351.3 s of 360.74 s at the 9bdb418 plan's FIX_PLAN Task 5) — the slowest verifications VIOL-READERS-CLAIM's (31.6 s in CI, 32.3 s locally), VIOL-CORE-EARLYRELEASE's (27.8 s, 30.0 s), VIOL-MD-CR's (14.6 s, 22.4 s), VIOL-MD-CLASS's (12.8 s, 19.5 s), VIOL-CORE-BUILDWAIT's (18.3 s, 18.8 s), and VIOL-CORE-HOLDLINK's (16.6 s, 17.1 s), each under a tenth of the 600 s `RUN_TIMEOUT_MS` every verification ran under until the plan written at 2a2b94e's FIX_PLAN Task 18 removed it (S-3: a verification carries no guard of its own); so the file stays whole. The job's timeout, 20 minutes until 7e7119b raised it to 30 for IP 0002's checks, stays at 30: the job took 562 s at d0ccc8f, run 1892, IP 0002's Phase 9 end (31%), its self project 515.23 s and `certification.test.ts` 307.4 s over 42 verifications, VIOL-READERS-CLAIM's verification 31.8 s (the bullet beginning "CI: " gives both Linux jobs' times). Revisit by measurement once the job passes ~22.5 minutes (75%): raise `timeout-minutes` (`.github/workflows/ci.yml`) or split the file per conformer family so Vitest runs the families in parallel — whose sustained intervals and kills must then not overlap into flakiness (E-5). Current totals (from the e57210b plan's FIX_PLAN Task 7 on, ten conformers and thirty-two violators wired — every fixture CERTIFICATIONS.md defines, CONF-IMPORT and its VIOL-IMPORT-BRACED and -SINGLE joining the rest: under `unshare --map-user` with `NODE_OPTIONS` and `XSPEC_PACKAGE_DIR` unset and the admin files left out, the self project ran 42 files, 5218 tests, 5217 passing and S-1's unmapped `7.6` (that plan's Task 16) failing, in 548.27 s at that Task, certification 172 PASS / 50 FAIL / 0 error / 0 hang over 42 lines, the 10 conformers' 41 (test, fixture) pairs all PASS and the 32 violators' 181 pairs 131 PASS and 50 FAIL; Phase 9 re-descent, from the 772854b plan's FIX_PLAN Task 45 on, nine conformers and thirty violators wired — every fixture CERTIFICATIONS.md then defined, CONF-LEFTOVER and its VIOL-LEFTOVER-FOLLOWLINK, -DOTNAMES, and -BYTENAMES joining the eight conformers and twenty-seven violators wired from its Task 44, CONF-READERS and VIOL-READERS-CLAIM joining the seven conformers and twenty-six violators wired from its Task 32, CONF-RACE and VIOL-RACE-LISTFIRST joining the six conformers and twenty-five violators wired from its Task 18, twenty-four violators from its Task 17, twenty-three from its Task 16, twenty-two from its Task 14): the self project runs 42 files, 5021 tests from the plan written at 2a2b94e's FIX_PLAN Task 138 on (the new `test/self/p16-fixed-seed-draws.test.ts`, 2 tests — P-16's fixed-seed shapes and S-9 replay; P-16's five rendering forms and their count test in `test/self/s9-fixture-well-formedness.test.ts`, 6; its configuration and two code-source forms in `test/self/s9-typescript-well-formedness.test.ts`, 3, the vector-set count 31; S-8's P-16 answer-scale test, 1; and the configuration record `P16_CONFIG` in the S-9 staged-sources judge, 1; the full suite, `npm test`, 133 files, 5395 tests, the suite wrapper `test/suite/section-16-p16.test.ts` among them; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 40 files, 5011 tests: all passed, in 372.77 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 41 files, 5008 tests from its Task 137 on (the new `test/self/s6-path-blocks-oracle.test.ts`, 19 tests — the path-blocks oracle's twelve vectors (S-6's eleven and T10.5-3's origin counting), two tolerance vectors, and five misuse-guard tests — and four new tests in `test/self/s6-graph-diff-oracle.test.ts`, 16 now — the graph-diff oracle's relocation tolerance, three, and an unknown setting's refusal; the full suite, `npm test`, 131 files, 5381 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 39 files, 4998 tests: all passed, in 346.91 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4985 from its Task 135's first part on (one new staged-source record, T12.7-3's config-paths arm's invalid configuration at `xspec.config.ts` and `cfg/broken.config.ts`, a plain string before, which T12.0-15's exit-2 family restages after its earlier invocations — the S-9 judge now 1988 tests; the full suite, `npm test`, 130 files, 5358 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4975 tests: all passed, in 328.43 s at that part, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical; unchanged by its second part, which adds no self-test and no record, nine renamed: locally 38 files, 4975 tests, all passed, in 356.05 s, the certification lines and the 219 per-pair lines as before; and by its third, ten renamed: locally 38 files, 4975 tests, all passed, in 379.19 s, the certification lines and the 219 per-pair lines as before), 4984 from its Task 134 on (nine new S-5 tests, the human coverage, ids, and show decoders', and nine new staged-source records, T8.2-1's report fixture, T12.3-1's ordering workspace, and T12.4-1's workspace, which T12.0-15 restages after its earlier invocations — the S-9 judge now 1987 tests, S-5 165; the full suite, `npm test`, 130 files, 5357 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4974 tests: all passed, in 316.40 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4966 from its Task 133's third part on (three new staged-source records, T10.7-9's path-blocks baseline and its edit of N and N.a and T10.7-10's first-workspace source, which T12.0-15 restages after its earlier invocations — the S-9 judge now 1978 tests; the full suite, `npm test`, 130 files, 5339 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4956 tests: all passed, in 313.75 s at that part, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4963 from its Task 133's second part on (six new S-5 tests, the human review-item and review-next decoders', and two new staged-source records, T10.7-7's order-arm and T10.7-8's first-workspace sources, which T12.0-15 restages after its earlier invocations — the S-9 judge now 1975 tests, S-5 156; the full suite, `npm test`, 130 files, 5336 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4953 tests: all passed, in 312.61 s at that part, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4955 from its Task 133's first part on (six new S-5 tests, the human review-list and review-status decoders', and two new staged-source records, T10.7-5's and T10.7-6's first-workspace sources, which T12.0-15 restages after its earlier invocations — the S-9 judge now 1973 tests, S-5 150; the full suite, `npm test`, 130 files, 5328 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4945 tests: all passed, in 311.45 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4947 from its Task 132 on (three new S-5 tests, the human impact decoder's, and 77 more staged-source records — 78 new, every source the impact stagings of T5.6-1 through T5.6-6 and T9-1 through T9.3-3 staged plain before, first-workspace files and `file()` stagings alike, which T12.0-15 restages after its earlier invocations, and `section-9.3.ts`'s `T9_3_3_ARM_2_CONFIG` retired for `section-5.6.ts`'s `IMPACT_SPECS_ONLY_CONFIG` — the S-9 judge now 1971 tests, S-5 144; the full suite, `npm test`, 130 files, 5320 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4937 tests: all passed, in 325.60 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4867 from its Task 131 on (three new S-5 tests, the human performed-report decoder's, and five new staged-source records, T6.4-1's `specs/Core.mdx`, `specs/Refs.mdx`, and `src/app.ts` and T6.4-6's invalid-workspace `specs/A.mdx` and `specs/Other.mdx`, formerly plain first-workspace files that T12.0-15 restages after its earlier invocations — the S-9 judge now 1894 tests, S-5 141; the full suite, `npm test`, 130 files, 5240 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4857 tests: all passed, in 345.00 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4859 from its Task 130 on (three new staged-source records, T12.2-2's build-validations `specs/B.mdx` and T13.3-3's invalid-sources `specs/A.mdx` and `specs/B.mdx`, formerly plain first-workspace files that T12.0-15 restages after its earlier invocations — the S-9 judge now 1889 tests; the full suite, `npm test`, 130 files, 5232 tests, T12.0-15 registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4849 tests: all passed, in 329.41 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4856 from its Task 129 on (four new S-5 tests, the human preview decoder's, and five new staged-source records, T6.6-4(a)'s configuration and three sources and T6.6-6's `specs/Origin.mdx` — the S-9 judge now 1886 tests; the full suite, `npm test`, 129 files, 5228 tests, T6.6-7 registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4846 tests: all passed, in 340.24 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4847 from its Task 128 on (six new staged-source records, T14-11's arms (y)'s and (ab)'s `specs/A.mdx` sources and the four code files of (z) and (aa) — the S-9 judge now 1881 tests; the full suite, `npm test`, 129 files, 5218 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4837 tests: all passed, in 343.08 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4841 from its Task 124 on (three new staged-source records, T14-8's twice-spelled cycle arm's and its `embeds` twin's `specs/A.mdx` sources and their shared `specs/B.mdx` — the S-9 judge now 1875 tests; the full suite, `npm test`, 129 files, 5212 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4831 tests: all passed, in 351.89 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4838 from its Task 122 on (two new staged-source records, T14-7's twice-spelled cycle arms' `specs/A.mdx` sources — the S-9 judge then 1872 tests; the full suite, `npm test`, 129 files, 5209 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4828 tests: all passed, in 324.01 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4836 from its Task 121 on (one new staged-source record, T14-5's `.TSX` arm's configuration, its code file sharing the `.mts` arm's record — the S-9 judge then 1870 tests; the full suite, `npm test`, 129 files, 5207 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4826 tests: all passed, in 323.99 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4835 from its Task 120 on (one new staged-source record, T14-4's baseline arm's `specs/A.mdx` — the S-9 judge then 1869 tests; the full suite, `npm test`, 129 files, 5206 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4825 tests: all passed, in 327.70 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4834 from its Task 119 on (four new staged-source records, T14-1's pairs' two configurations and their `specs/A.mdx` before and after the edit — the S-9 judge now 1868 tests; the full suite, `npm test`, 129 files, 5205 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4824 tests: all passed, in 336.30 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4830 from its Task 117 on (three new staged-source records, T13.5-7(g)'s section-move configuration and origin and (h)'s emission-disabled move configuration — the S-9 judge now 1864 tests; the full suite, `npm test`, 129 files, 5201 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4820 tests: all passed, in 324.65 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4827 from its Task 116 on (one new staged-source record, the `xspec.config.ts` of T13.5-7(c)'s emitted-Markdown rename variant — the S-9 judge now 1861 tests; the full suite, `npm test`, 129 files, 5198 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4817 tests: all passed, in 277.21 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4826 from its Task 115 on (four new staged-source records for T13.4-13's arms (e)–(i) — the `outDir: "out"` configuration (f) and (g) share, (h)'s configuration as built and once emission is disabled, and (g)'s `specs/A.mdx` — the S-9 judge now 1860 tests; the full suite, `npm test`, 129 files, 5197 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4816 tests: all passed, in 275.16 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4822 from its Task 113 on (its Task 114 registered T13.4-13, adding no self-test — S-7's sweep, one test over the whole registry, takes it in — and no staged-source record, its workspaces staging `section-10.1.ts`'s `CORE_FILES` records, renamed for it: the full suite, `npm test`, 129 files, 5193 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4812 tests: all passed, in 281.93 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical; at Task 113, four new staged-source records — T13.4-5's identity arm: its configuration, the baseline commit's `specs/A.mdx` and `specs/B.mdx`, and `specs/A.mdx` with a.x's text edited — the S-9 judge now 1856 tests; the full suite, `npm test`, 129 files, 5192 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4812 tests: all passed, in 341.55 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4818 from its Task 112 on (four new staged-source records — `REFRESH_CONFIG`, the configuration T13.3-2's workspace and T13.3-5's share, T13.3-5(b)'s `specs/C.mdx` and `src/marker.ts`, and T13.3-5(c)'s `specs/A.mdx` — the S-9 judge now 1852 tests; the full suite, `npm test`, 129 files, 5188 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4808 tests: all passed, in 312.17 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4814 from its Task 111 on (one new self-test — S-3's T13.3-5(a) tampering spans in `test/self/s3-hang-guards.test.ts`, now 11 tests — and two new staged-source records — T13.3-5(a)'s twin `specs/A.mdx`, alpha's own text edited, and its `specs/B.mdx` — the S-9 judge now 1848 tests; the full suite, `npm test`, 129 files, 5184 tests, T13.3-5 registered (the suite project 89 files, 370 tests); under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4804 tests: all passed, in 312.19 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4811 from its Task 110 on (two new staged-source records — T13.3-3's stale twins' `specs/A.mdx`, beta's text edited, and its write-path twin's configuration, emission under outDir `out` — the S-9 judge now 1846 tests; the full suite, `npm test`, 129 files, 5180 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4801 tests: all passed, in 314.48 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4809 from its Task 108 on (four new staged-source records — T12.3-1's entries workspace: `specs/held.mdx`, `specs/prose.mdx`, `specs/user.mdx`, and `src/x.ts` — the S-9 judge now 1844 tests; the full suite, `npm test`, 129 files, 5178 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4799 tests: all passed, in 325.29 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4805 from its Task 107 on (four new staged-source records — T12.0-16's narrowed configuration, its `specs/base.mdx` with both children's text edited and with both children deleted, and its `src/c.ts` — the S-9 judge now 1840 tests; the full suite, `npm test`, 129 files, 5174 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4795 tests: all passed, in 338.88 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4801 from its Task 106 on (nine new staged-source records — T12.0-16's byte-order fixture: its configuration, `specs/base.mdx`, its two `x`-holding spec sources, its one code-source record staged at both code paths, and the two `x`-holding sources of each of its unresolved and import-cycle twins — the S-9 judge now 1836 tests; the full suite, `npm test`, 129 files, 5170 tests, T12.0-16 registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4791 tests: all passed, in 348.75 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4792 from its Task 104 on (three new staged-source records — T12.0-10's code-unit masking workspace's configuration, `specs/A.mdx`, and the declared-unparseable `src/bad.ts` — the S-9 judge now 1827 tests; the full suite, `npm test`, 129 files, 5160 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4782 tests: all passed, in 384.79 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4789 from its Task 102 on (one new staged-source record — T12.0-5's `move` arms' origin, `specs/A.mdx` — the S-9 judge now 1824 tests; the full suite, `npm test`, 129 files, 5157 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4779 tests: all passed, in 355.12 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4788 from its Task 100 on (two staged-source records removed — T11.6-3's former order workspace's configuration and `lib/deux.ts`, its order arm now on T11.6-3's order fixture — the S-9 judge now 1823 tests; the full suite, `npm test`, 129 files, 5156 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4778 tests: all passed, in 338.98 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4790 from its Task 99 on (three new staged-source records — T11.6-2's selectors workspace's configuration, `specs/a.mdx`, and `src/a.ts` — the S-9 judge now 1825 tests; the full suite, `npm test`, 129 files, 5158 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4780 tests: all passed, in 362.13 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4787 from its Task 96 on (six new staged-source records — T11.6-3's order fixture's configuration, its three spec sources, and its two code sources, staged by T11.4-1 and T11.4-2 — the S-9 judge now 1822 tests; the full suite, `npm test`, 129 files, 5155 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4777 tests: all passed, in 350.15 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4781 from its Task 95 on (four new staged-source records — T11.2-7's `specs/A.mdx` and its three arms' `specs/B.mdx` — the S-9 judge now 1816 tests; the full suite, `npm test`, 129 files, 5149 tests, T11.2-7 the one new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4771 tests: all passed, in 409.86 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4777 from its Task 94 on (six new staged-source records — T11.2-6's passing-side policy fixture's configuration, `specs/A.mdx`, and `lo/L.mdx`, and its unreadable-emit-directory fixture's configuration, `src/x.ts`, and failing-side `specs/A.mdx` — the S-9 judge now 1812 tests; the full suite, `npm test`, 129 files, 5144 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4767 tests: all passed, in 339.92 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4771 from its Task 93 on (two new staged-source records — T11.2-4's own-versus-subtree `specs/P.mdx`, its unresolved-embedding and ancestor-embedding-cycle stagings — the S-9 judge now 1806 tests; the full suite, `npm test`, 129 files, 5138 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4761 tests: all passed, in 390.90 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4769 from its Task 92 on (four new staged-source records — T11.2-3's target-side workspace's configuration, `specs/a'b.mdx`, `specs/A.mdx`, and `src/use.ts` — the S-9 judge now 1804 tests; the full suite, `npm test`, 129 files, 5136 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4759 tests: all passed, in 338.16 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4765 from its Task 90 on (five new staged-source records — T11-2's node-kind workspace's configuration, `specs/x.mdx`, `specs/shared/S.mdx`, `src/x.ts`, and `src/y.ts` — the S-9 judge now 1800 tests; the full suite, `npm test`, 129 files, 5132 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4755 tests: all passed, in 334.33 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4760 from its Task 89 on (one new staged-source record — T10.7-15's (f)(i) and (g) `specs/A.mdx` holding u's edit and a section with no id — the S-9 judge now 1795 tests; the full suite, `npm test`, 129 files, 5127 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4750 tests: all passed, in 347.11 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4759 from its Task 88 on (four new staged-source records — T10.7-15's (c) hand edits of `specs/A.mdx` (P.c's text, Q.r's deletion, s.t authored under s) and (d)'s `specs/B.mdx` holding a section with no id — the S-9 judge now 1794 tests; the full suite, `npm test`, 129 files, 5126 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4749 tests: all passed, in 340.92 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4755 from its Task 87 on (six new staged-source records — T10.7-15's configuration, fixture (A)'s `specs/A.mdx` and its u edit, and fixture (B)'s `specs/B.mdx`, its G.N edit, and its v edit — the S-9 judge now 1790 tests; the full suite, `npm test`, 129 files, 5122 tests, T10.7-15 registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4745 tests: all passed, in 335.60 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4749 from its Task 86 on (seven new staged-source records — T10.7-12's split sub-fixture's `specs/S.mdx` and its edit, its resolve-state sub-fixture's `specs/N.mdx` and its three stagings, and its second d2 edit over T10.4-7(a)'s fixture, made in `section-10.4.ts`; its provenance sub-fixture's three records renamed — the S-9 judge now 1784 tests; the full suite, `npm test`, 129 files, 5115 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4739 tests: all passed, in 330.76 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4742 from its Task 84 on (two new staged-source records — T10.4-8's p.q edit in its (a) workspace and its N.c.y edit in its (b) workspace — the S-9 judge now 1777 tests; the full suite, `npm test`, 129 files, 5108 tests, T10.4-8 registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4732 tests: all passed, in 323.91 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4740 from its Task 83 on (one new staged-source record net — T10.7-9's audit fixture's `specs/N.mdx` and its authoring of N.c, N.c.y, and N.b.z, and its Q session's `specs/Q.mdx` and Q.r's deletion, the three h/h.a/h.b audit-arm records gone — the S-9 judge now 1775 tests; the full suite, `npm test`, 129 files, 5105 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4730 tests: all passed, in 308.77 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4739 from its Task 82 on (five new staged-source records net — T10.7-9's six, its path-blocks fixture's M.k edit, (f)'s `specs/P.mdx` and its children's deletion, and (g)'s `specs/G.mdx` and its two edits, its `T10_7_9_G_WITH_Z` gone — the S-9 judge now 1774 tests; the full suite, `npm test`, 129 files, 5104 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4729 tests: all passed, in 307.52 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4734 from its Task 81 on (one new staged-source record — T10.7-7's `specs/U.mdx` holding the one section u — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1769 tests; the full suite, `npm test`, 129 files, 5099 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4724 tests: all passed, in 295.49 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4733 from its Task 78 on (three new staged-source records — T10.2-2's `specs/A.mdx` with a top-level b authored after `create` and with b's text edited, and T10.2-4's `specs/P.mdx` with p.q's further edit — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1768 tests; the full suite, `npm test`, 129 files, 5098 tests, no test registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4723 tests: all passed, in 336.36 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4730 from its Task 77 on (three new staged-source records — T10.5-9's `specs/D.mdx` at the baseline and with A.B.C's section deleted, and its `specs/R.mdx` at the baseline — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1765 tests; the full suite, `npm test`, 129 files, 5095 tests, T10.5-9 registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4720 tests: all passed, in 323.83 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4727 from its Task 76 on (five new staged-source records — T10.5-8's `specs/R.mdx` at the baseline, in its four-edit staging, and in its twin, and its `specs/S.mdx` at the baseline and with x.y edited — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1762 tests, and one new S-5 test — `decodeRecordedState` over show, next, and export — `test/self/s5-output-adapters.test.ts` now 134 tests; the full suite, `npm test`, 129 files, 5091 tests, T10.5-8 registered; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4717 tests: all passed, in 325.92 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4721 from its Task 74 on (its Task 75 registered T10.5-7, adding no self-test — S-7's sweep, one test over the whole registry, takes it in — and no staged-source record, its one workspace plain: the full suite, `npm test`, 129 files, 5084 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4711 tests: all passed, in 350.61 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical; at Task 74, ten new staged-source records — T10.5-5's matching arm's `specs/M.mdx` at the baseline, edited, and with n.c authored, its kept-blockedBy arm's `specs/B.mdx` at the baseline, edited, and with a.k1 reverted, and its P/Q arms' `specs/P.mdx` at the baseline, with p edited, with p and p.q edited, and with p reverted and p.q edited again — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1757 tests, and one new S-5 test — `requireScopeNodes` over show, next, and export — `test/self/s5-output-adapters.test.ts` now 133 tests; the full suite, `npm test`, 129 files, 5083 tests, no new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4711 tests: all passed, in 316.00 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4710 from its Task 73 on (fourteen new staged-source records — T10.5-3's current-graph-edges arm's `specs/G.mdx` at the baseline and edited, its origin-counting arm's `specs/O.mdx` at the baseline and in its tags staging, coverage staging, and d-set twin and its `src/o.ts`, its one-item-per-location arm's T9.2-4 staging (`specs/Direct.mdx` and `specs/Up.mdx` at v1 and v2, `specs/Trans.mdx`, `src/both.ts`), and those workspaces' `xspec.config.ts` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1747 tests; the full suite, `npm test`, 129 files, 5072 tests, no new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4700 tests: all passed, in 361.27 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4696 from its Task 72 on (one new staged-source record — T10.5-1's `specs/Y.mdx` with a.b's own text and a.b.c at v1, its chain fixture's both-edited twin — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1733 tests; the full suite, `npm test`, 129 files, 5058 tests, no new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4686 tests: all passed, in 277.26 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4695 from its Task 71 on (eight new staged-source records — T10.4-7's four initial sources (`specs/X.mdx`, `specs/T.mdx`, `specs/D1.mdx`, and `specs/D2.mdx` at the baseline), d1 at v1, d2 at v1, and the removal edit's `specs/T.mdx` without its reference to D2.d2 and emptied `specs/D2.mdx` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1732 tests; the full suite, `npm test`, 129 files, 5057 tests, T10.4-7 the one new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4685 tests: all passed, in 315.37 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4687 from its Task 70 on (four new staged-source records — T10.4-6's `specs/G.mdx` with u1 at v1, with u1 and u2 at v1, with u1 reverted and u2 at v1, and at the baseline, the twin's initial source — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1724 tests; the full suite, `npm test`, 129 files, 5048 tests, T10.4-6 the one new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4677 tests: all passed, in 316.33 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4683 from its Task 69 on (one new staged-source record — T10.4-4's decomposition arm's `specs/F.mdx` with top-level `a` holding `a.x` and a top-level leaf `s` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1720 tests; the full suite, `npm test`, 129 files, 5043 tests, no new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4673 tests: all passed, in 318.09 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4682 from its Task 67 on (one new staged-source record — T10.4-2's journal arm's `specs/J.mdx` with top-level leaves `a` and `s` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1719 tests; the full suite, `npm test`, 129 files, 5042 tests, no new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4672 tests: all passed, in 324.59 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4681 from its Task 66 on (one new S-5 test — every review decode of an item ID rejecting one that is no well-formed argument value, `test/self/s5-output-adapters.test.ts` now 132 tests; the full suite, `npm test`, 129 files, 5041 tests, no new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4671 tests: all passed, in 323.08 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4680 from its Task 64 on (two new S-5 tests — the session-corruption staging's two 10.2-field deletions and its re-insertion of an item entry copied from an earlier session file, `test/self/s5-output-adapters.test.ts` now 131 tests — and one new staged-source record — T10.1-4's `specs/A.mdx` with `a`'s own text edited since the baseline — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1718 tests; the full suite, `npm test`, 129 files, 5040 tests, no new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4670 tests: all passed, in 319.48 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4677 from its Task 63 on (two new S-5 tests — the decoder entry `review show (metadata-consistency item: the metadata pair)`, `test/self/s5-output-adapters.test.ts` now 129 tests — and six new staged-source records — T10.7-13's configuration, its `specs/M.mdx` with m's section deleted, and its `specs/GH.mdx` and `specs/K.mdx` baselines and edits — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1717 tests; the full suite, `npm test`, 129 files, 5037 tests, T10.7-13 the one new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4667 tests: all passed, in 327.92 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4669 from its Task 62 on (one new staged-source record — T10.7-14's edited `specs/A.mdx` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1711 tests; the full suite, `npm test`, 129 files, 5028 tests, T10.7-14 the one new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4659 tests: all passed, in 315.11 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4668 from its Task 61 on (four staged-source records leaving the ledger — T8-5's former required-set fixture, its configuration, `tgt/T.mdx`, `bnd/B.mdx`, and `oth/O.mdx`, now plain initial files of T8.1-1's one workspace, created before any product invocation — `test/self/s9-staged-sources.test.ts`'s judge now 1710 tests; the full suite, `npm test`, 128 files, 5026 tests, T8.1-1 the one new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4658 tests: all passed, in 314.24 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4672 from its Task 60 on (seven new staged-source records — T7.5-1's three outside-root selector-glob configurations (`../x/*.ts`, `a/../../$1.ts`, `/src/*.ts`), T7.5-2's twice-spelled-edge configuration and its `hi/H.mdx`, and T7.5-4's two inside-root selector-spelling configurations (`./src/*.ts` and its `src/*.ts` twin) — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1714 tests; the full suite, `npm test`, 128 files, 5029 tests, no new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4662 tests: all passed, in 361.66 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4665 from its Task 59 on (six new staged-source records — T7.1-1's wrong-case extension configuration and its `specs/A.MDX`, T7.3-1's two wrong-type configurations (`emit: "true"`, `outDir: true`) and its two Linux-leg single-casing `outDir` configurations (`".XSPEC"`, `".XSPEC/md"`) — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1707 tests; the full suite, `npm test`, 128 files, 5022 tests, no new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4655 tests: all passed, in 324.76 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4659 from its Task 58 on (six new staged-source records — T7-8's three configurations `T7_8_CONFIG`, `T7_8_DOCS_CONFIG`, and `T7_8_AREA_GLOB_CONFIG`, its `specs/A.mdx` and `specs/B.mdx`, and its code source `src/app.ts` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1701 tests; the full suite, `npm test`, 128 files, 5016 tests, T7-8 the one new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4649 tests: all passed, in 315.71 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4653 from its Task 57 on (three new staged-source records — T7-7's configuration `T7_7_CONFIG`, its code source `src/impl.ts`, and arm (b)'s `src/x.mdx` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1695 tests; the full suite, `npm test`, 128 files, 5009 tests, T7-7 the one new product test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4643 tests: all passed, in 339.81 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4650 from its Task 56 on (four new staged-source records — the `xspec.config.ts` of T7-6's extension twin and of its two single-casing arms, and those arms' one code source — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1692 tests; the full suite, `npm test`, 128 files, 5005 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4640 tests: all passed, in 352.60 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4646 from its Task 55 on (eight new staged-source records — the `xspec.config.ts` of T7-2's `"XSPEC"` specifier, `outDir: null`, `targetTags: null`, `defineConfig()`, `defineConfig({…}, {})`, numeric-literal key, and empty code-group-name arms and of T7-3's U+FFFD code-group-name arm — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1688 tests; the `"XSPEC"` record, with T7-2's `"not-xspec"` arm's, withdrawn by IP 0002's first plan's FIX_PLAN Task 1, SPEC 7 accepting any static string literal as the specifier, the judge two tests fewer from then on; the full suite, `npm test`, 128 files, 5001 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4636 tests: all passed, in 301.64 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4638 from its Task 54 on (one new staged-source record — T7-1's name-casing probe's `sub/XSPEC.config.ts`, declared unparseable — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1680 tests; the full suite, `npm test`, 128 files, 4993 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4628 tests: all passed, in 299.48 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4637 from its Task 52 on (one new staged-source record — T6.5-16(g)'s twice-spelled arm's `specs/a.mdx` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1679 tests, and seven new T6.5-16 vectors in `test/self/s9-fixture-well-formedness.test.ts` — six joining `R16_FORM_VECTORS`, now 168, and one `R16_REFUSED_VECTORS`, now 39; the full suite, `npm test`, 128 files, 4992 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4627 tests: all passed, in 294.94 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4629 from its Task 51 on (three new staged-source records — T6.5-2's `/ >` parent arm's `specs/P.mdx` and T6.5-4's casing arm's `xspec.config.ts` and `specs/a.mdx` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1678 tests, and two new composed forms — that T6.5-2 arm's `specs/A.mdx` and `specs/P.mdx` after the move — joining `test/self/s9-fixture-well-formedness.test.ts`'s `X2_COMPOSED_FORMS` judge; the full suite, `npm test`, 128 files, 4984 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4619 tests: all passed, in 282.95 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4624 from its Task 50 on (two new staged-source records — T6.4-6's refused-writes arm's `xspec.config.ts` and `specs/A.mdx` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1675 tests, and the full suite, `npm test`, 128 files, 4979 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4614 tests: all passed, in 296.09 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4622 from its Task 49 on (two new staged-source records — T6.4-4's braced-`id` and valueless-`id` arms' `specs/Braced.mdx` and `specs/Valueless.mdx` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1673 tests, and the full suite, `npm test`, 128 files, 4977 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4612 tests: all passed, in 275.10 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4620 from its Task 48 on (one new test, `test/self/lock-staging.test.ts`'s `stageFifo` test, and the full suite, `npm test`, 128 files, 4975 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4610 tests: all passed, in 284.93 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4619 from its Task 47 on (two new staged-source records — T6.3-6's `specs/A.mdx`, every arm's valid source, and its arm (d)'s failing `specs/A.mdx`, the renamed section's unresolved `d` reference — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1671 tests, and the full suite, `npm test`, 128 files, 4974 tests, T6.3-6 among them; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4609 tests: all passed, in 284.07 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4617 from its Task 46 on (two new staged-source records — T6.3-4's baseline-configuration arms' `c1` configurations, the working tree's configuration plus an unknown top-level key and with its `defineConfig` call's closing parenthesis removed, the second declared unparseable — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1669 tests, and the full suite, `npm test`, 128 files, 4971 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4607 tests: all passed, in 293.37 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4615 from its Task 44 on (four new staged-source records — T5.7-4's collision workspace `specs/C.mdx`, `src/mixed.ts`, `src/mixed-decl.ts`, and `src/twoimports.ts`; its `specs/B.mdx` record now holding `a` and `b` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1667 tests, and the full suite, `npm test`, 128 files, 4969 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4605 tests: all passed, in 288.36 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4611 from its Task 43 on (six new staged-source records — T5.5-5's tie-break arm's `specs/A.mdx` at T5.4-1's first fixture's baseline, after N2 is authored with `h` declaring `d={["b", "a"]}`, and with that array reordered, and T5.5-7's arm (a) edit `specs/B.mdx` and arm (b) `specs/A.mdx` and its edit; the shared configuration record renamed `T5.5-2/T5.5-5/T5.5-7 xspec.config.ts …` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1663 tests, and the full suite, `npm test`, 128 files, 4965 tests, the registered T5.5-7 among them; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4601 tests: all passed, in 295.41 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4605 from its Task 41 on (seven new staged-source records — T4.6-3's declaration-file controls `src/a.d.b/x.ts`, `src/x.d.tsx`, and `src/x.d.css.mts` and its single-casing controls `src/c1/x.D.ts`, `src/c2/x.d.TS`, `src/c3/x.d.MTS`, and `src/c4/x.d.CTS`; its configuration record renamed — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1657 tests, and the full suite, `npm test`, 128 files, 4958 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4595 tests: all passed, in 308.32 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4598 from its Task 40 on (fourteen new staged-source records — T4.5-8's type-only side's `src/app.ts`, twelve with the spec import type-only beside each colliding form and two with `text` bound type-only as `t` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1650 tests, and the full suite, `npm test`, 128 files, 4951 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4588 tests: all passed, in 301.32 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4584 from its Task 39 on (five new staged-source records — T4.5-3's numeric-literal, whole-chain parenthesized, partly parenthesized, and parenthesized-index arms' `src/app.ts` and the numeric-literal arm's `specs/A.mdx`; its `(SPEC.a).b;` arm's record renamed — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1636 tests, and the full suite, `npm test`, 128 files, 4937 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4574 tests: all passed, in 308.82 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4579 from its Task 38 on (six new staged-source records — T4.3-2's numeric-literal, parenthesized-chain, partly parenthesized, parenthesized-index, and cross-module arms' `src/app.ts` and the cross-module arm's `specs/B.mdx`; its shared `specs/A.mdx` record now holding `b` and `1` beside `a`, and its two-argument arm's record renamed for `text(SPEC.a, SPEC.b)` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1631 tests, and the full suite, `npm test`, 128 files, 4932 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4569 tests: all passed, in 313.09 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4573 from its Task 35 on (seven new staged-source records — T4-4's `specs/A.mdx` (`T4_4_SPEC_SOURCE`, plain before) and its two mixed-combination arms' `src/mixed.ts` and `src/mixed-decl.ts`, and T4-5's four value-level arms' `src/app.ts`; the shared configuration record renamed `T4-2/T4-4/T4-5 xspec.config.ts …` and T4-5's arm records' order label `(the import of A declared first)` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1625 tests, and the full suite, `npm test`, 128 files, 4926 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4563 tests: all passed, in 313.95 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4566 from its Task 34 on (T4-2's five new staged-source records — its root-re-entering arm's `src/app.ts`, the `**` positive's `src/three.ts`, the suffix casing arm's `src/b.ts` and `specs/B.mdx`, and the derived-name casing arm's `src/d.ts`; the no-other-construct arm's `specs/NAME.mdx` record became the shared `SPECS_NAME_SOURCE`, renamed — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1618 tests, and the full suite, `npm test`, 128 files, 4919 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4556 tests: all passed, in 320.47 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4561 from its Task 33 on (T2.5-2's three new staged-source records — its excluded-as-a-target-only arm's `xspec.config.ts`, `base/A.mdx`, and `derived/B.mdx` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1613 tests, and the full suite, `npm test`, 128 files, 4914 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4551 tests: all passed, in 311.76 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4558 from its Task 32 on (T2.4-2's five new staged-source records — its numeric-literal and parenthesized index arms' four `specs/A.mdx` stagings and their `specs/BASE.mdx`, holding `1` and `a` beside `auth` — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1610 tests, and the full suite, `npm test`, 128 files, 4911 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4548 tests: all passed, in 310.77 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4553 from its Task 31 on (T2.1-2's and T2.1-3's nine new staged-source records — the `**` importer, the case-only arm's importer and `specs/B.mdx`, the re-entering arm's two sources, and the colliding-chain arms' two targets and two importers — joining `test/self/s9-staged-sources.test.ts`'s judge, now 1605 tests, and the full suite, `npm test`, 128 files, 4906 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4543 tests: all passed, in 314.27 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4544 from its Task 29 on (T1.5-2's two new staged-source records — its code-group arms' code source and its located arm's spec source — joining `test/self/s9-staged-sources.test.ts`'s judge, and the full suite, `npm test`, 128 files, 4897 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4534 tests: all passed, in 310.90 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4542 from its Task 28 on (the human-report decoders' six S-5 vectors joining — `test/self/s5-output-adapters.test.ts` now 127 tests, 121 before — and the full suite, `npm test`, 128 files, 4895 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4532 tests: all passed, in 312.21 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4536 from its Task 27 on (the NodeNext path's two transitional S-4 vectors removed with that path, its misuse vectors brought to the one path left — `test/self/s4-typescript-tooling.test.ts` now 49 tests — and the full suite, `npm test`, 128 files, 4889 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4526 tests: all passed, in 313.50 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4538 from its Task 23 on (S-4 under both of H-2's configurations, its detection, companion, runtime, isolation, and transitional vectors joining — `test/self/s4-typescript-tooling.test.ts` now 51 tests, 16 before — and the full suite, `npm test`, 128 files, 4891 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4528 tests: all passed, in 277.44 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4503 from its Task 22 on (the entered-directory run's six vectors and mode 000's two joining — `test/self/s3-subprocess-driver.test.ts` now 46 tests, `test/self/permission-staging.test.ts` 18 — and the full suite, `npm test`, 128 files, 4856 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4493 tests: all passed, in 270.48 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4495 from its Task 21 on (H-1's ancestor precondition's five vectors joining, `test/self/s2-workspace-builder.test.ts` now 26 tests — and the full suite, `npm test`, 128 files, 4848 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4485 tests: all passed, in 275.49 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4490 from its Task 20 on (S-3's ten pre-product checks joining, the new `test/self/s3-hang-guards.test.ts` — and the full suite, `npm test`, 128 files, 4843 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 38 files, 4480 tests: all passed, in 266.70 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 39 files, 4480 tests from its Task 19 on (six S-3 self-tests joining — `test/self/s3-subprocess-driver.test.ts` now 40 tests: the hold-file wait's new contract and its refusal of a wait beside a held run in place of the old wait-timeout vector, and five harness-step guard vectors — and the full suite, `npm test`, 127 files, 4833 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 37 files, 4470 tests: all passed, in 291.86 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4474 from its Task 18 on (five S-3 hang-guard self-tests joining — `test/self/certification-runner.test.ts` now 16 tests, `test/self/property-infrastructure.test.ts` 21, `test/self/s3-subprocess-driver.test.ts` 34 — and the full suite, `npm test`, 127 files, 4827 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 37 files, 4464 tests: all passed, in 267.42 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4469 from its Task 8 on (four self-tests of T14-9's graph-data staging joining, `test/self/permission-staging.test.ts` now 16 tests, and the full suite, `npm test`, 127 files, 4822 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 37 files, 4459 tests: all passed, in 273.00 s at that Task, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies, its 219 per-pair lines identical), 4465 from the plan written at a71eb0c's FIX_PLAN Task 9 on (one S-9 staged-source record joining — T10.7-4's item-id tie sub-fixture's initial `specs/A.mdx`, `test/self/s9-staged-sources.test.ts` now 1594 tests — and the full suite, `npm test`, 127 files, 4818 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, with no product installed (`dist/` absent), 37 files, 4455 tests: all passed, in 407.97 s at its Task 9, in 401.89 s at its Task 10, in 403.20 s at its Task 12, and in 360.74 s at the 9bdb418 plan's FIX_PLAN Task 5, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures in each, `compare_cert.py` 0 discrepancies; CI's harness-self job ran 39 files, 4465 tests, the admin files included, in 315.96 s at 58361cb, run 1266, and in 322.37 s at b5ac9a8, run 1272: all passed, certification 0 discrepancies, its outcome lines identical to Task 12's local run's and, at run 1272, to the 9bdb418 plan's Task 5's; certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 fixtures from the plan written at 2a2b94e's FIX_PLAN Task 1 on, T13.4-5 and T11.4-1 out of the CONF-CORE and CONF-AVAIL scopes (CERTIFICATIONS.md at 7226090): 37 files, 4455 tests, all passed, in 446.09 s at that Task, and CI's harness-self job's 39 files, 4465 tests, all passed, in 327.05 s at a909c5d, run 1339, `compare_cert.py` 0 discrepancies in both, their 219 per-pair lines identical), 4464 from that plan's Task 8 on (one S-9 staged-source record joining — T10.6-2's item-id tie sub-fixture's initial `specs/A.mdx`, `test/self/s9-staged-sources.test.ts` then 1593 tests — and the full suite, `npm test`, 127 files, 4817 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, with no product installed (`dist/` absent), 37 files, 4454 tests: all passed, in 410.74 s at its Task 8, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies), 4463 from that plan's Task 7 on (three S-9 staged-source records joining — T10.5-4's item-id tie sub-fixture's initial `specs/A.mdx` and its two `specs/X.mdx` stagings, `test/self/s9-staged-sources.test.ts` then 1592 tests — and the full suite, `npm test`, 127 files, 4816 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, with no product installed (`dist/` absent), 37 files, 4453 tests: all passed, in 392.72 s at its Task 7, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures, `compare_cert.py` 0 discrepancies), 4460 from the plan written at affd85f's FIX_PLAN Task 5 on (S-7's three no-product tests joining — layer 5 of `test/self/s7-red-green-sweep.test.ts`, now 7 tests: the sweep-premise probe, the registry, and the six bodies outside it against `builtProductBindingAt(<an absent path>)` — and the full suite, `npm test`, 127 files, 4813 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, with no product installed (`dist/` absent), 37 files, 4450 tests: all passed, in 368.43 s at its Task 5 and in 386.94 s at its Task 7, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures in each, VERIFY's comparison 0 discrepancies; CI's harness-self job ran 39 files, 4460 tests, the admin files included, in 322.48 s at 0c927d8, run 1253: all passed, certification 0 discrepancies, its outcome lines identical to Task 7's local run's), 4457 from the plan written at affd85f's FIX_PLAN Task 4 on (S-3's no-product vector joining — `builtProductBindingAt(<an absent path>)` rejecting `runProduct` and `startProduct` with a `HarnessAssertionError` declining shrinking, nothing noted or spawned — `test/self/s3-subprocess-driver.test.ts` now 31 tests, and the full suite, `npm test`, 127 files, 4810 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, with no product installed (`dist/` absent), 37 files, 4447 tests: all passed, in 353.95 s at its Task 4, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures, VERIFY's comparison 0 discrepancies), 4456 from the plan written at 93e22f1's FIX_PLAN Task 4 on (the four S-5 tests of the stable-code matcher `codeMention` joining, `test/self/s5-output-adapters.test.ts` now 121 tests, and the full suite, `npm test`, 127 files, 4809 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, with no product installed (`dist/` absent), 37 files, 4446 tests: all passed, in 372.44 s and 364.26 s at its Task 4, two runs, at its Task 5 in 355.72 s and 362.38 s, two runs, at its Tasks 6 and 7 in 368.71 s and 365.48 s, and at its Task 8 in 357.49 s, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures in each, VERIFY's comparison 0 discrepancies; CI's harness-self job ran 39 files, 4456 tests, the admin files included, in 326.36 s at f5f7ab2, run 1245: all passed, certification 0 discrepancies, its outcome lines identical to Task 8's local run's), 4452 from the plan written at d0c8039's FIX_PLAN Task 2 on (the eight S-5 vectors of the human-report parity matchers joining, `test/self/s5-output-adapters.test.ts` now 117 tests, and the full suite, `npm test`, 127 files, 4805 tests; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, with no product installed (`dist/` absent), 37 files, 4442 tests: all passed, in 388.11 s and 360.34 s at its Task 2, two runs, at its Tasks 3 to 10 in 383.61 s, 368.82 s, 387.89 s, 385.36 s, 403.40 s, 395.13 s, 404.23 s, and 392.68 s, and at its Task 11 in 400.48 s, at the 43c9a5e determination's VERIFY in 614.33 s, other agents sharing the machine, and in the plan written at 93e22f1 at its Tasks 1, 2, and 3 in 391.97 s, 382.38 s, and 387.70 s, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures in each, VERIFY's comparison 0 discrepancies; CI's harness-self job ran 39 files, 4452 tests, the admin files included, in 330.40 s at e9a530a, run 1236: all passed, certification 0 discrepancies, its outcome lines identical to Task 11's local run's), 4444 from the 13.5 re-descent plan written at 772854b's FIX_PLAN Task 48 on (`test/self/e6-exclusion.test.ts`'s four tests joining; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 37 files, 4434 tests: all passed, in 334.04 s at its Task 48, at its Task 49 in 370.23 s and 393.49 s, two runs, at its Task 50 in 350.03 s, at iteration 55's VERIFY (9583e3b) in 362.23 s, in the plan written at 092db72 at its Tasks 1, 2, and 3 in 344.8 s, 357 s, and 360.90 s, at iteration 59's VERIFY (a126add) in 380.37 s, in the plan written at acfff0b at its Task 1, its Task 2's first attempt, its Task 3, and its Task 2 in 415 s, 428.90 s, 394.65 s, and 387.65 s, at the 2d9cdf6 determination's VERIFY in 381.92 s, in the plan written at 2d9cdf6, with no product installed (`dist/` absent), at its Task 1 in 360.47 s, its Task 2 in 340.80 s, and its Task 3 in 352.89 s and 348.70 s, two runs, at the f50cf9f determination's VERIFY in 390.37 s, and in the plan written at f50cf9f, likewise, at its Task 1 in 363.49 s, its Task 2 in 365.39 s, its Task 3 in 360.73 s, and its Task 4 in 368.00 s, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures in each, VERIFY's comparison 0 discrepancies, VIOL-RACE-LISTFIRST, VIOL-READERS-CLAIM, and VIOL-CORE-EARLYRELEASE failing their certified tests in each; CI's harness-self job ran 39 files, 4444 tests, in 322.58 s at b265134, run 1200, in 321.61 s at 0ce40a7, run 1201, in 254.73 s at 3786c66, run 1202, in 323.59 s at 33e7d0b, run 1203, in 323.17 s at 9583e3b, run 1204, in 316.15 s at b9eb318, run 1207, in 320.96 s at a126add, run 1208, in 307.48 s at de35117, run 1211, in 324.65 s at 6ada37b, run 1212, in 298.29 s at 2d9cdf6, run 1214, in 257.48 s at 06a291c, run 1216, in 250.20 s at 58022f6, run 1217, and, with no product installed, in 245.77 s at e55a7a1, run 1219, in 323.95 s at f50cf9f, run 1220, in 320.48 s at 513f8b5, run 1222, in 305.67 s at 140178b, run 1223, and in 243.34 s at a1e6ae5, run 1224: all passed, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures, VERIFY's comparison 0 discrepancies, its outcome lines identical to the local runs'; at ffee710, run 1210, in 328.80 s, one test failed, CONF-READERS' P-10, whose `review resolve` killed past its hold left a temporary entry in `.xspec/reviews` that P-10 then counted as a write beside the session — the false failure the acfff0b plan's FIX_PLAN Task 3 removed; at a18abfc, run 1218, with no product installed, in 241.54 s, one test failed by design, the 2d9cdf6 plan's FIX_PLAN Task 2 probe binding the reach check of `test/self/machine-staging.admin.test.ts` to the built product again (`HarnessStagingError`, `dist/cli/bin.js` absent), its certification unchanged), 4440 from its Task 46 (S-9's five P-14 spec-source vectors and their count test, five P-14 TypeScript vectors, and the two P-14 configuration records joining; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 36 files, 4430 tests, in 336 s: all passed, certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures, VERIFY's comparison 0 discrepancies — unchanged by its Task 47, 339.68 s, and in CI run 1198 at b9601fb, 269.93 s; CI's harness-self job ran 38 files, 4440 tests, in 267.36 s at 555e28d, run 1196: all passed; its full-suite job 126 files, 4793 tests, in 1490.30 s: 28 failed, every one a diagnosed product failure — run 1194's twenty-seven and P-14; its Windows leg failed only at its known `$.lock`), 4427 from its Task 45 (`test/self/p15-fixed-seed-draws.test.ts`'s four tests, the four CONF-LEFTOVER verifications, and S-9's P-15 configuration vector joining; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 36 files, 4417 tests, in 341 s: all passed — the manifest mirror and the registration check green, the accepted red gone, the manifest equal to the document — certification 186 PASS / 50 FAIL / 0 error / 0 hang over 39 fixtures, VERIFY's comparison 0 discrepancies; CI's harness-self job ran 38 files, 4427 tests, in 265.33 s at df03943, run 1194: all passed, its certification lines the local run's own; its full-suite job 125 files, 4779 tests, in 1124.70 s: 27 failed, every one a diagnosed product failure (`HarnessAssertionError`) — run 1192's twenty-six and P-15; its Windows leg 1 failed / 8 passed, its known `$.lock`), 4418 from its Task 44 (its two new certification verifications, CONF-READERS' and VIOL-READERS-CLAIM's, 17.4 s and 32.4 s alone; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4408 tests, in 327 s: 2 failed / 4406 passed, the accepted red — the manifest mirror, and the registration check naming `§CONF-LEFTOVER: P-15` alone — certification 185 PASS / 47 FAIL / 0 error / 0 hang over 35 fixtures, VERIFY's comparison listing only the four CONF-LEFTOVER fixtures; CI's harness-self job ran 37 files, 4418 tests, in 304.54 s at 7a83fb5, run 1192: 2 failed / 4416 passed, the same accepted red, its certification lines the local run's own; its full-suite job 123 files, 4769 tests, in 1419.32 s: 28 failed, the accepted red and twenty-six diagnosed product failures, run 1189's twenty-five and P-10; its Windows leg 1 failed / 8 passed, its known `$.lock`), 4416 from its Task 43, 4412 from its Task 34, 4411 from its Task 32, 4407 from its Task 31, 4406 from its Task 30, 4403 from its Task 28 (its Task 34 added one self test, `test/self/lock-state.test.ts`'s post-kill judgement (`assertLockPathAfterKill`, moved out of T13.5-3's `pastTheHoldKill` and shared with T13.5-7's kill arm), the suite project's counts unchanged: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4402 tests, in 272.53 s: 2 failed / 4400 passed, the accepted red (the manifest mirror, and the registration check naming `§CONF-LEFTOVER: P-15` alone), certification 184 PASS / 46 FAIL / 0 error / 0 hang over 33 fixtures, its lines Task 33's; CI's harness-self job ran 37 files, 4412 tests, in 253.28 s at 3bae84f, run 1174: 2 failed / 4410 passed, the same accepted red, its certification lines the local run's own; its full-suite job 123 files, 4763 tests, in 1417.59 s: 22 failed, the accepted red and twenty diagnosed product failures, the nineteen before and T13.5-7 at (b)'s residue (`found nothing at .xspec/lock`, 5.9 s, the local diagnosis); its Windows leg green; its Task 33 moved T13.5-6 into a new suite module, `test/suite/registry/section-13.5-vii.ts` with its wrapper `test/suite/section-13.5-vii.test.ts` — the suite project 86 files, 351 tests — leaving the self project's counts unchanged: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4401 tests, in 286 s: 2 failed / 4399 passed, the accepted red, certification 184 PASS / 46 FAIL / 0 error / 0 hang over 33 fixtures, its lines Task 32's; CI's harness-self job ran 37 files, 4411 tests, in 215.28 s at 0273964, run 1172: 2 failed / 4409 passed, the same accepted red, its certification lines the local run's own; its full-suite job 123 files, 4762 tests, in 1456.75 s: 21 failed, the accepted red and nineteen diagnosed product failures, the eighteen before and T13.5-6 at its first held arm's held-state comparison (count half: nothing at `.xspec/lock`, the local diagnosis); its Windows leg green; its Task 32 registered T13.5-13 in a new suite module, `test/suite/registry/section-13.5-vi.ts` with its wrapper `test/suite/section-13.5-vi.test.ts` — the suite project 85 files, 351 tests — its two new staged-source records two more S-9 tests, and wired CONF-RACE and VIOL-RACE-LISTFIRST, two more certification verifications: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4401 tests, in two consecutive runs of 262.54 s and 280.46 s: 2 failed / 4399 passed each, the accepted red (the manifest mirror, and the registration check naming `§CONF-LEFTOVER: P-15` alone), certification 184 PASS / 46 FAIL / 0 error / 0 hang over 33 fixtures, the two runs' lines identical, CONF-RACE's conformer passing T13.5-13 and VIOL-RACE-LISTFIRST failing it in both; CI's harness-self job ran 37 files, 4411 tests, in 264.22 s at f236a1c, run 1170: 2 failed / 4409 passed, the same accepted red, its certification lines the local runs' own; its full-suite job 122 files, 4762 tests, in 1424.52 s: 20 failed, the accepted red and eighteen diagnosed product failures, the seventeen before and T13.5-13 at the held arm's first refused run (its error document's `code` and `path` `null`, the local diagnosis); its Windows leg green; its Task 31 registered T13.5-9 in a new suite module, `test/suite/registry/section-13.5-v.ts` with its wrapper `test/suite/section-13.5-v.test.ts` — the suite project 84 files, 350 tests — and added `reclaimForHarness`'s self-test to `test/self/machine-staging.admin.test.ts`, now 7 tests: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4397 tests, 246.46 s: 2 failed / 4395 passed, the same accepted red, the same certification lines; CI's harness-self job ran 38 files, 4413 tests — the temporary probe's 6 among them — in 200.92 s at cd9ba79, run 1167: 2 failed / 4411 passed, the same accepted red, the same certification lines; at 0e8c126, run 1168, the probe removed, 37 files, 4407 tests, in 194.85 s: 2 failed / 4405 passed, the same accepted red; its full-suite job 121 files, 4757 tests, in 881.67 s: 19 failed, the accepted red and seventeen diagnosed product failures, the sixteen before and T13.5-9 at (a)'s held-state comparison (`found nothing at .xspec/lock`, 5.9 s); its Windows leg green; its Task 30 registered T13.5-12 in a new suite module, `test/suite/registry/section-13.5-iv.ts` with its wrapper `test/suite/section-13.5-iv.test.ts` — the suite project 83 files, 349 tests — its three new staged-source records three more S-9 tests: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4397 tests, 257.58 s: 2 failed / 4395 passed, the same accepted red, the same certification lines; CI's harness-self job ran 37 files, 4406 tests, in 207.96 s at 446a977, run 1165: 2 failed / 4404 passed, the same accepted red, the same certification lines; its full-suite job 120 files, 4755 tests, in 1428.62 s: 18 failed, the accepted red and sixteen diagnosed product failures, the fifteen before and T13.5-12 at (c)'s creation arm's held-state comparison (`found nothing at .xspec/lock`, 1.5 s); its Windows leg green; its Task 29c completed T13.5-11 with (a)'s write failures but (b)'s, adding no self test: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4394 tests, 286.89 s: 2 failed / 4392 passed, the same accepted red, the same certification lines; CI's harness-self job ran 37 files, 4403 tests, in 211.32 s at 44b18da, run 1163 (192.79 s at its Task 29b's dd8d5cc, run 1162): 2 failed / 4401 passed, the same accepted red, the same certification lines; its full-suite job 119 files, 4751 tests, in 908.44 s (1438.56 s in run 1162): 17 failed, the accepted red and the same fifteen diagnosed product failures, T13.5-11 at (a)'s first failure past acquisition, the held-state comparison of `rename specs/A.mdx a a2` before `specs/sub` is made `--x` (`found nothing at .xspec/lock`, 13.6 s); its Windows leg green; its Task 29b extended T13.5-11 with (a)'s failures past acquisition and acquisition's own failures, adding no self test: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4394 tests, 243.33 s: 2 failed / 4392 passed, the same accepted red, the same certification lines; its Task 29 registered T13.5-11 in a new suite module, `test/suite/registry/section-13.5-iii.ts` with its wrapper `test/suite/section-13.5-iii.test.ts` — the suite project 82 files, 348 tests — adding no self test: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4394 tests, 246.43 s: 2 failed / 4392 passed, the same accepted red, the certification runner's lines 183 PASS / 45 FAIL, 0 error, 0 hang, 31 fixtures; CI's harness-self job ran 37 files, 4403 tests, in 251.71 s at b11a8ed, run 1160: 2 failed / 4401 passed, the same accepted red, the same certification lines; its full-suite job 119 files, 4751 tests, in 1447.62 s: 17 failed, the accepted red and fifteen diagnosed product failures, the fourteen before and T13.5-11 at (a)'s busy arm's held-state comparison (`found nothing at .xspec/lock`); its Windows leg green; its Task 28 registered T13.4-12 in a new suite module, `test/suite/registry/section-13.4-ii.ts` with its wrapper `test/suite/section-13.4-ii.test.ts` — the suite project 81 files, 347 tests — its staleness edit one more staged-source record, so one more S-9 test, and extended two tests of `test/self/permission-staging.test.ts` (a staging's restore restoring nothing where its object was removed or renamed away): under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4394 tests, 230.27 s: 2 failed / 4392 passed, the same accepted red, the certification runner's lines 183 PASS / 45 FAIL, 0 error, 0 hang, 31 fixtures; CI's harness-self job ran 37 files, 4403 tests, in 206.98 s at 3bd1348, run 1158: 2 failed / 4401 passed, the same accepted red, the same certification lines; its full-suite job 118 files, 4750 tests, in 1421.45 s (the job 24 min, where run 1157's took 15.5 min and run 1156's 21.5 min: runner variance): 16 failed, the accepted red and fourteen diagnosed product failures, the thirteen before and T13.4-12 at its twin's `inventory` (`$.lock`); its Windows leg green) — 37 files, 4402 tests from its Task 26 on (its Task 27 added T13.5-10(h), adding no test; its Task 26 added T13.5-10's machine arms and one test of `test/self/lock-staging.test.ts`, `killHeldRun`'s launcher and observation: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4393 tests, 238.53 s: 2 failed / 4391 passed, the same accepted red, the certification runner's lines 183 PASS / 45 FAIL, 0 error, 0 hang, 31 fixtures; CI's harness-self job ran 38 files, 4409 tests — the temporary probe's 7 among them — in 270.29 s at 9b75446, run 1154: 2 failed / 4407 passed, the same accepted red; with the probe removed, at 98f7b7c, run 1155, it ran 37 files, 4402 tests, in 256.39 s: 2 failed / 4400 passed, the same accepted red, and its full-suite job 117 files, 4748 tests, in 853.77 s: 15 failed, the accepted red and the same thirteen diagnosed product failures) — 37 files, 4401 tests from its Task 24 on (its Task 25 added T13.5-10(e)'s one-machine parts, adding no test: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4392 tests, 238.60 s: 2 failed / 4390 passed, the same accepted red, the certification runner's lines 183 PASS / 45 FAIL, 0 error, 0 hang, 31 fixtures; its Task 24 added T13.5-10(d) and two tests of `test/self/permission-staging.test.ts`, the directory-mode staging's (`stageDirectoryMode`, `test/helpers/permissions.ts`): under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4392 tests, 246.59 s: 2 failed / 4390 passed, the same accepted red, the certification runner's lines 183 PASS / 45 FAIL, 0 error, 0 hang, 31 fixtures; CI's harness-self job ran all 37 files, 4401 tests, in 262.74 s at b405e86, run 1150: 2 failed / 4399 passed, the same accepted red) — 37 files, 4399 tests from its Task 21 on (its Task 23 added T13.5-10(c), adding no test: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4390 tests, 236.15 s: 2 failed / 4388 passed, the same accepted red, the certification runner's lines 183 PASS / 45 FAIL, 0 error, 0 hang, 31 fixtures; its Task 22 registered T13.5-10 in a new suite module, `test/suite/registry/section-13.5-ii.ts` with its wrapper `test/suite/section-13.5-ii.test.ts`, adding no self-test — S-7's sweep, one test over the whole registry, takes it in: under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4390 tests, 253.78 s: 2 failed / 4388 passed, the same accepted red, the certification runner's lines 183 PASS / 45 FAIL, 0 error, 0 hang, 31 fixtures; its Task 21 added T13.5-8's acquisition-after arms, whose three staged-source records — the invalid configuration, `specs/sub/S.mdx`, and `src/both.mdx` — add three S-9 tests, and replaced VIOL-CORE-LATELOCK with VIOL-CORE-LATEHOLD; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4390 tests, 255.51 s: 2 failed / 4388 passed, the same accepted red, the certification runner's lines 183 PASS / 45 FAIL, 0 error, 0 hang, 31 fixtures; CI's harness-self job ran all 37 files, 4399 tests, in 250.60 s at 2392f18, run 1146: 2 failed / 4397 passed, the same accepted red and certification lines, its CORE verifications 143.3 s summed (the conformer's 13.3 s, VIOL-CORE-EARLYRELEASE's 27.7 s), and its full-suite job 116 files, 4744 tests, in 1397.22 s: 14 failed, the accepted red and the same twelve diagnosed product failures) — 37 files, 4396 tests from its Task 20 on (its Task 20 added T13.5-8's acquisition-first arms, whose two staged-source records — the code-group configuration and `src/c.ts` — add two S-9 tests, and gave VIOL-CORE-EARLYWRITE T13.5-8; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4387 tests, 252.98 s: 2 failed / 4385 passed, the same accepted red, the certification runner's lines 183 PASS / 45 FAIL, 0 error, 0 hang, 31 fixtures; CI's harness-self job ran all 37 files, 4396 tests, in 259.63 s at 921681b, run 1144: 2 failed / 4394 passed, the same accepted red and certification lines, and its full-suite job 116 files, 4741 tests, in 1394.81 s: 14 failed, the accepted red and the twelve diagnosed product failures) — 37 files, 4394 tests from its Task 18 on (its Task 18 added T13.5-4's `build` arm and the VIOL-CORE-BUILDWAIT verification to `test/self/certification.test.ts`; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4385 tests, 257.32 s: 2 failed / 4383 passed, the same accepted red, the certification runner's lines 184 PASS / 44 FAIL, 0 error, 0 hang, 31 fixtures; CI's harness-self job ran all 37 files, 4394 tests, in 249.82 s at dde8ecf, run 1141: 2 failed / 4392 passed, the same accepted red and certification lines) — 37 files, 4393 tests from its Task 17 on (its Task 17 strengthened T13.5-4's reads during a hold, gave VIOL-CORE-CHATTYREADS T13.5-4, and added the VIOL-CORE-READERENTRY verification to `test/self/certification.test.ts`; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4384 tests, 228.99 s: 2 failed / 4382 passed, the same accepted red, the certification runner's lines 176 PASS / 43 FAIL, 0 error, 0 hang, 30 fixtures; CI's harness-self job ran all 37 files, 4393 tests, in 230.87 s at 2138ff1, run 1139: 2 failed / 4391 passed, the same accepted red and certification lines) — 37 files, 4392 tests from its Task 16 on (its Task 16 rewrote T13.5-3 and added the VIOL-CORE-EARLYRELEASE verification to `test/self/certification.test.ts`; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4383 tests, 223.17–227.51 s: 2 failed / 4381 passed, the same accepted red, the certification runner's lines 169 PASS / 41 FAIL, 0 error, 0 hang, 29 fixtures; CI's harness-self job ran all 37 files, 4392 tests, in 214.32 s at bb6ea10, run 1137: 2 failed / 4390 passed, the same accepted red and certification lines) — 37 files, 4391 tests from its Task 15 on (its Task 15 rewrote T13.5-2 and gave VIOL-CORE-EARLYWRITE T13.5-2, adding no test; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4382 tests, 165.11 s: 2 failed / 4380 passed, the same accepted red, the certification runner's lines 161 PASS / 40 FAIL, 0 error, 0 hang, 28 fixtures; CI's harness-self job ran all 37 files, 4391 tests, in 141.97 s at 294cbe1, run 1135: 2 failed / 4389 passed, the same accepted red and certification lines) — and from its Task 14 on (its Task 14 added the VIOL-CORE-HOLDLINK verification to `test/self/certification.test.ts`, ~16.6 s; under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4382 tests, 163.32 s: 2 failed / 4380 passed, the same accepted red, the certification runner's lines 162 PASS / 39 FAIL, 0 error, 0 hang, 28 fixtures, the certification file alone 135.78 s) — 37 files, 4390 tests from its Task 12 on (its Task 12 added `test/self/pid-namespace-staging.test.ts`, 8 tests needing no administrative access — launcher A's and B's command lines, NSpid and first-process answer parsing, `hasAllocated`, the first process's script run as a plain child, T13.5-10(g)'s check, and the failure paths through stand-in sudo commands; about 0.4 s of tests, 1.9 s alone with Vitest's start-up — and `test/self/pid-namespace-staging.admin.test.ts`, 3 tests needing the job's administrative access (a launcher-A run as identifier 1 with the harness's identity and no capability, two launcher-A runs' identical in-namespace identifiers and the kills that empty a namespace, and a launcher-B namespace opened fresh, listing only its own processes, its (e) verification, an entered run's kill, and its close), which run in CI only here (the stagings II bullet below); under `unshare --map-user` with `NODE_OPTIONS` unset and the admin files left out, 35 files, 4381 tests, 144.22 s: 2 failed / 4379 passed, the same accepted red, the certification runner's lines 154 PASS / 38 FAIL, 0 error, 0 hang, 27 fixtures; CI's harness-self job ran all 37 files, 4390 tests, in 135.09 s at 6a2bdd8, run 1131: 2 failed / 4388 passed, the same accepted red, every admin test passing) — 35 files, 4379 tests from its Task 11 on (its Task 11 added `test/self/machine-staging.test.ts`, 11 tests needing no administrative access — E-1's access check through stand-in commands, `/proc/self/mountinfo` parsing, the second mount's verification failing on a plain directory, the group staging and its restore, the second user's launcher command line with its umask and `env -i` fragments run, and the driver's `launcher` run option through a stand-in launcher, T12.7-1's walk of a launched run's stdout included; about 9 s of tests, 10.9 s alone with Vitest's start-up — and `test/self/machine-staging.admin.test.ts`, 6 tests needing the job's administrative access (the second user made by four makers at once, a run launched as it, its verification, the unjudged create check, kills through `sudo`, the bind mount), which run in CI only here (the bullet below); under `unshare --map-user` with `NODE_OPTIONS` unset and the admin file left out, 34 files, 4373 tests, 141.85 s: 2 failed / 4371 passed, the same accepted red, the certification runner's lines 154 PASS / 38 FAIL, 0 error, 0 hang, 27 fixtures; CI's harness-self job ran all 35 files, then 4378 tests, in 141.36 s at 6544faa, run 1127: 2 failed / 4376 passed, the same accepted red, every admin test passing) — 33 files, 4362 tests from its Task 10 on (its Task 10 added `test/self/lock-state.test.ts`, 7 tests: the held-state comparison and the lock-state assertions of `test/helpers/lock-state.ts` over synthetic trees, no product run — the count half (entries present, absent, doubled; a directory, symbolic links, a FIFO counted as no entry), the byte half (the root's lock path alone excluded, `.xspec` itself new only where the baseline had none), staged occupants in place, a mode-0o000 entry read through H-4's grant, entry identity, the only entry, names apart, the lock path absent or holding exactly a tree, and the H-6 inclusion check; two of its tests verify a refusal on this process first and so fail as root by design; about 0.3 s of tests, 2 s alone with Vitest's start-up; 137.59 s for the whole project under `unshare --map-user` with `NODE_OPTIONS` unset: 2 failed / 4360 passed, the same accepted red, the certification runner's lines 154 PASS / 38 FAIL, 0 error, 0 hang, 27 fixtures; CI's harness-self job ran it in 137.77 s at 20bef2b, run 1124, with the same result, the new file's tests passing there, unprivileged through the wrapper on ext4) — 32 files, 4355 tests from its Task 9 on (its Task 9 added `test/self/lock-staging.test.ts`, 9 tests: the lock-path leftover and obstruction stagings of `test/helpers/lock-staging.ts` — every kind round-tripping by bytes, `.`-names and names that are not valid UTF-8 included, read back with raw `lstat`/`readdir`/`readlink`; permission removals verified on this process, so that one test fails as root by design; the in-place, outside-target, and FIFO checks; the placement refusals; `copyEntryIn` — and the dead-entry helper `killHeldRun` through stand-ins honoring `--test-hold`; about 2 s of tests, 3.5 s alone with Vitest's start-up; 134.74 s for the whole project under `unshare --map-user` with `NODE_OPTIONS` unset: 2 failed / 4353 passed, the same accepted red, the certification runner's lines 154 PASS / 38 FAIL, 0 error, 0 hang, 27 fixtures; CI's harness-self job ran it in 89.33 s at 6637013, run 1121, with the same result, the new file's tests passing there, unprivileged through the wrapper on ext4) — 31 files, 4346 tests from its Task 8 on (its Task 8 added `test/self/kill-discipline.test.ts`, 9 tests: T13.5-3's exit-collection discipline — the driver's `processGroup` run option and `RunningProduct.killGroup`, the Linux process list of `test/helpers/kill-discipline.ts` with a zombie counted as listed, the hang guard's kill reaching the whole group — the reuse check `applyReuseCheck`, and the voidable-trial runner `runVoidableTrial`; the process tests take about 2 s each here, because this sandbox's first process (`process_api`, PID 1) reaps orphaned zombies only about once a second and a group kill waits until its orphaned members leave the process list, where CI's runner reaps at once (the file's 9 tests took 3.2 s in CI's harness-self job, 12 to 16 s here); 133.70 s under `unshare --map-user` with `NODE_OPTIONS` unset: 2 failed / 4344 passed, the same accepted red, the certification runner's lines 154 PASS / 38 FAIL, 0 error, 0 hang, 27 fixtures; CI's harness-self job ran it in 135.53 s at af15d09, run 1119, with the same result) — 30 files, 4337 tests from its Task 7 on (its Task 7 added `test/self/lock-path-exclusion.test.ts`, 10 tests: 12.0's reading of a mutating command and of `--config`, H-6's classification of compares over noted runs — a run between the snapshots, one held throughout, one in another workspace, a nested root, a `--config` root, a working directory below the root, a configless workspace, a snapshot rooted in the area or under the lock path — the near-miss names, the across-directories form, and, through a stub product, the driver's notes, `assertLeavesUnchanged`, and the determinism protocol; 131 s under `unshare --map-user` with `NODE_OPTIONS` unset: 2 failed / 4335 passed, the same accepted red, the certification runner's lines 154 PASS / 38 FAIL, 0 error, 0 hang, 27 fixtures) — 29 files, 4327 tests from its Task 6 on (its Task 6 added three tests to `test/self/s5-output-adapters.test.ts`, now 109: T13.3-2's operational path set in `isGraphDataKey`, the transient lock path and everything under it no graph data; the corrupt-record staging sparing whatever occupies the lock path; the one graph-data file collector `collectGraphDataFiles`; 132.27 s under `unshare --map-user` with `NODE_OPTIONS` unset: 2 failed / 4325 passed, the same accepted red, the certification runner's lines 154 PASS / 38 FAIL, 0 error, 0 hang, 27 fixtures) — 4324 tests from its Task 5 on (its Task 5 added `test/self/lock-path.test.ts`, 8 tests: the lock-path predicate and H-6's exclusion options, and H-4's grant-and-restore in the snapshot walk and the read, in-place write, and copy helpers of `test/helpers/lock-path.ts`; 122.34 s under `unshare --map-user` with `NODE_OPTIONS` unset: 2 failed / 4322 passed, the same accepted red, the certification runner's lines 154 PASS / 38 FAIL, 0 error, 0 hang, 27 fixtures) — 28 files, 4316 tests from its Task 4 on (its Task 4 added one test to `test/self/s5-output-adapters.test.ts`, now 106 tests: the usage-error conditions 14.24 to 14.26 (`write-failure`, `read-failure`, `workspace-busy`) decode as the error document's code and are rejected inside a findings array by the usage-error rule, never as unknown tokens; 140.62 s under `unshare --map-user` with `NODE_OPTIONS` unset: 2 failed / 4314 passed, the failures being the C-1 manifest-mirror and registration self-tests that plan accepts as red until its Tasks 49, 32 and 45, the certification runner's lines 154 PASS / 38 FAIL, 0 error, 0 hang, 27 fixtures) — 4315 tests from the fourteenth plan's FIX_PLAN Task 3 on (the plan written at 633df12: its Task 3 added one test to `test/self/property-infrastructure.test.ts`, now 20 tests, a shrink candidate whose failure declines shrinking ending the shrink as the reported counterexample, the report saying so; 128.99 s at Task 3 in CI's whole inner stage with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; 130.44 s at its Task 4, its confirmation run at 31bae80's trees, alone in CI's whole inner stage with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before (27 fixtures, 0 error, 0 hang); CI's harness-self job ran it in 122.77 s at 31bae80, run 1001) — 4314 tests from the fourteenth plan's FIX_PLAN Task 1 on (the plan written at 633df12: its Task 1 added one test to `test/self/s5-output-adapters.test.ts`, now 105 tests, the human-report omission matcher `assertReportOmits` (`test/helpers/adapters/human.ts`, the negative counterpart of `assertReportMentions`) accepting a report without the named information, stdout alone being the report, and rejecting one carrying it or an empty mention list; 141.25 s at Task 1 with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before) — 4313 tests from the thirteenth plan's FIX_PLAN Task 2 on (the plan written at bff95ed: its Task 2 added one test to `test/self/property-infrastructure.test.ts`, now 19 tests, a generator that throws while a falsification is shrunk being a harness error `while shrinking (the generator threw while replaying a shrink candidate's choices)` carrying the property, the seed, and `XSPEC_PROPERTY_SEED=<seed>`; 131.77 s at Task 2 with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; 131.69 s at its Task 3, its confirmation run at 87d419b's trees, alone in CI's whole inner stage with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; CI's harness-self job ran it in 129.93 s at 87d419b, run 996; unchanged at the fourteenth plan's VERIFY (bae4ad1): 263.33 s on the shared machine, `NODE_OPTIONS` unset, and 124.68 s in CI run 997) — 4312 tests from its Task 1 on (its Task 1 added one test to `test/self/assertion-protocol.test.ts`, `parseJsonStdout` failing diagnosed on a stdout led by a UTF-8 byte-order mark; 126.94 s at Task 1 with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before) — 4311 tests from the twelfth plan's FIX_PLAN Task 11 on (the plan written at 5bfab19: its Task 11 added four refused-shape tests to `test/self/p5-fixed-seed-draws.test.ts`, now 6 tests — see the P-5 fixed-seed bullet below; 139.82 s at Task 11 with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; 145.65 s at its Task 12, its confirmation run at bb37aab's trees, alone in CI's whole inner stage with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; CI's harness-self job ran it in 129.27 s at bb37aab, run 992; unchanged at the thirteenth plan's VERIFY (9a16fa4): 284.08 s, with two other agents' Vitest runs sharing the machine (load average up to about 15), `NODE_OPTIONS` unset, and 84.50 s in CI run 993) — 4307 tests from its Task 10 on (its Task 10 added S-9's per-draw replay of P-5's fixed-seed section moves, one test in `test/self/p5-fixed-seed-draws.test.ts`, then 2 tests; 147.42 s at Task 10 with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before) — 4306 tests from the eleventh plan's FIX_PLAN Task 14 on (the plan written at 8b068bf: its Task 14 added P-5's fixed-seed draw guard, `test/self/p5-fixed-seed-draws.test.ts`, one test — see the P-5 fixed-seed bullet below; 144.26 s at Task 14 with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; 141.87 s at its Task 15, its confirmation run at c88ab04's trees, alone in CI's whole inner stage with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; CI's harness-self job ran it in 114.02 s at c88ab04, run 979; unchanged at the twelfth plan's VERIFY (e6b7cb0): 188.90 s, with two other agents' runs sharing the machine, `NODE_OPTIONS` unset, and 129.22 s in CI run 980; unchanged through the twelfth plan (written at 5bfab19) to its Task 9, which added no test: its S-6 vetting of the section-move oracle's would-be-text composer, `composeSectionMoveTexts`, is the closing assertion of each of the 30 after-text vectors in `test/self/s6-section-move-oracle.test.ts`, still 36 tests; 142.01 s at Task 9 with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before) — 27 files, 4305 tests from its Task 13 on (its Task 13 added 66 S-9 vectors to `P5_FORM_VECTORS` in `test/suite/registry/section-16-p5-p6.ts`, one test each in `test/self/s9-fixture-well-formedness.test.ts`, now 2056 tests — P-5's text-position target parent in each shape over the second fixed model `P5_TEXT_POSITION_MODEL`: the target file as staged, as each landed collapse form leaves it, and the coincident file with each collapse decoration before and after the move; 140.09 s at Task 13 with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before) — 4239 from its Task 12 on (its Task 12 added three S-6 vectors in `test/self/s6-section-move-oracle.test.ts`, now 36 tests, each moving a single-line in-line section holding prose outside its tags into one of T6.5-16(c)'s text-position target parent shapes; 149.39 s at Task 12 with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before) — 4236 from the ninth plan's FIX_PLAN Task 4 on (the plan written at c0f2915: its Task 4 added one E-1 test in `test/self/permission-staging.test.ts`, Linux-only, each permission staging reaching entries named by bytes that are not valid UTF-8, or not ASCII, at their exact bytes — red against d585f7c's `test/helpers/permissions.ts`, whose area staging left the 0xFF-named file at mode 0o644; 137.75 s at Task 4, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; unchanged through its Tasks 5–9, which added none; 146.18 s at its Task 10, its confirmation run at 8b20530's trees, alone in CI's whole inner stage, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; CI's harness-self job ran it in 131.21 s at 8b20530, run 952; unchanged at the tenth plan's VERIFY (7ef10b6): 206.51 s, with another reviewer's run sharing the machine, `NODE_OPTIONS` unset, and 128.06 s in CI run 953; unchanged through that plan (written at 23e3b4a), whose Tasks 1–9 added none: 139.68 s at its Task 10, its confirmation run at 0ad39cd's trees, alone in CI's whole inner stage with `NODE_OPTIONS` unset, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; CI's harness-self job ran it in 133.41 s at 0ad39cd, run 963; unchanged at the eleventh plan's VERIFY (7e232fb): 188.62 s, with another agent's Vitest sharing the machine, `NODE_OPTIONS` unset, and 117.46 s in CI run 964, and through that plan's Tasks 1–11, which added none) — 4235 from its Task 1 on (its Task 1 added one S-5 test in `test/self/s5-output-adapters.test.ts`, Linux-only, the corrupt-record staging reaching every graph-data file at its exact name bytes, and assertions only to two existing S-2 tests; 159.04 s at Task 1, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before) — 4234 from the seventh plan's FIX_PLAN Task 5b on (the plan written at 765d6b4: its Task 5b added S-3's three driver-walk tests in `test/self/s3-subprocess-driver.test.ts` — two rejecting runs, a near-marker in a captured JSON-output stdout and a crash of the walk itself, and one accepting control; 159.70 s at Task 5b; 161.38 s at its Task 6, its confirmation run at 107f624's trees, alone in CI's whole inner stage, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; CI's harness-self job ran it in 127.83 s at 107f624, run 933; unchanged through the eighth plan (written at a2bfdf4), whose Tasks 1–3 added none: 198.74 s at its VERIFY (34032b5), with the reviewers' runs sharing the machine, and 121.93 s in CI run 934 there; 156.01 s at its Task 4, its confirmation run at 97c7c24's trees, alone in CI's whole inner stage, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; CI's harness-self job ran it in 131.20 s at 97c7c24, run 938; unchanged at the ninth plan's VERIFY (f8f38eb): 181.36 s, on a nearly idle machine, and 105.24 s in CI run 939) — 4231 from its Task 5 on (it added one S-5 test in `test/self/s5-output-adapters.test.ts`, `parseJsonStdout`'s marker walk; 154.87 s at Task 5) — 4230 from the fifth plan's FIX_PLAN Task 11 on (the plan written at 1e2972e: its Task 11 added one S-7 test, `test/self/s7-red-green-sweep.test.ts`'s sweep of the product-facing bodies outside the registry — the E-6 fixture, the four single-casing probes, and T11.6-1's drive-mismatch arm, synthetic entries T99.7-2 through T99.7-7; 134 s at Task 11, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; 142 s at its Task 12, its confirmation run at 7f59049's trees, alone in CI's whole inner stage, all passing, 0 skipped; CI's harness-self job ran it in 126 s at 7f59049, run 915; unchanged through the sixth plan, written at 849b69d, whose Tasks 1–5 added none: 159.90 s at its VERIFY (68f0718), with another agent's Vitest beside it, and 126.63 s in CI run 917 there; 147 s at its Task 6, its confirmation run at 715dff7's trees, alone in CI's whole inner stage, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before; CI's harness-self job ran it in 99 s at 715dff7, run 923; unchanged at the seventh plan's VERIFY (b00e7cd) — 176.08 s, with another agent's Vitest beside it, and 83.30 s in CI run 924 — and through that plan's Tasks 1–4, which added none: 149.58 s at Task 4) — 4229 from its Task 9 on (its Task 9 added two S-9 TypeScript records, T11.6-3's order-workspace `xspec.config.ts` and `lib/deux.ts`; 132 s at Task 9, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before) — 4227 from its Task 2 on (its Task 1 added S-4's three skeleton vectors, 4223 tests, and its Task 2 four vectors of the shared fresh-identifier reader in `test/self/added-import-identifiers.test.ts`; 191 s at Task 2, all passing, 0 skipped, the certification runner's lines 154 PASS / 38 FAIL as before) — 4220 from the fourth plan's FIX_PLAN Task 10 on (the plan written at 6a4a280: its Task 10 added S-3's three vectors for a crash of T6.5-22(a)'s own MDX parse, and its Task 11 only rows to CONF-ORPHAN's grammar-guard table, still one test; 177 s at that plan's Task 12, its confirmation run at 8bebeba's trees, alone in CI's whole inner stage, all passing, 0 skipped; CI's harness-self job ran it in 124 s at 8bebeba, run 902, and in 129 s at 4117ede, run 903, where the fifth plan's VERIFY ran it in 192.75 s in CI's whole inner stage) — 4217 from the third plan's FIX_PLAN Task 9 on (179 s at the fourth plan's VERIFY, 72d5126, and 107 s in CI there; the plan written at ad9eb42; its Tasks 5 through 9 each added one table to the grammar guard, one test per table — CONF-AVAIL's at Task 5, 4213 tests, 151 s alone; CONF-DISC's at Task 6, 4214; CONF-VALID's at Task 7, 4215; CONF-MD's at Task 8, 4216; CONF-CORE's at Task 9, 4217 — and its Tasks 10 and 10a only added rows to CONF-CORE's table; 137 s at that plan's Task 11, its confirmation run at fdc3c49, alone in CI's whole inner stage (network off, uid 1000, no capabilities), all passing, 0 skipped; CI's harness-self job ran it in 97 s at fdc3c49, run 888) — 4212 from that plan's Task 4 on (it added the 27th file, `test/self/certification-fixture-grammar.test.ts`, with one test; 137 s alone, all passing, 0 skipped) — 26 files and 4211 tests from that plan's Task 3 on (it added S-3's four in-run-evaluation vectors and S-8's item-6 test; 136 s alone, all passing, 0 skipped) — 4206 from the re-descent's second plan's FIX_PLAN Task 13 on (it added that file's sixth test, pinning every command's run under JSON output and the mutating commands' performed, preview, and section forms; 172 s alone at that plan's Task 14, its confirmation run, all passing, 0 skipped; CI's harness-self job ran it in 133 s at 79d2013) (4205 at that plan's Task 12, which added the fifth, pinning `armSteps`; 4204 at its Task 11, which added the fourth, the JSON-output reading guard; ~181 s) (4203 at that plan's Task 10, which added the 26th file, `test/self/p8-fixed-seed-draws.test.ts`, with three tests; ~177 s) (25 files and 4200 tests at that plan's Task 9, which added S-5's three correction-judge tests), 4197 tests from that plan's Task 7 on (iteration 82; it added one staged-source ledger record, T4.5-3's `SPEC?.a;` arm, one more test of `test/self/s9-staged-sources.test.ts`, 1570 there; ~184 s; unchanged at that plan's Task 8, which restaged two records in place, ~181 s) (4196 at that plan's Tasks 4 through 6, Task 4 adding two staged-source ledger records, each one more test of that file, 1569 there; 4194 at that plan's Task 3, which added five S-9 builder vectors for spec-group files not named `.mdx` — four in `test/self/s9-fixture-well-formedness.test.ts`, one in `test/self/s9-undeclared-staging.test.ts`; 4189 at that plan's Task 2b, which added S-3's two capture-limit vectors and S-8's helper-conversion vector; 4186 at its Task 2, which added S-8's capture-limit vector; 4185 from the first plan's Task 64 through Task 66, its last, 4158 at Task 63, 4094 at Task 62, 3983 at Task 61, 3955 at Task 60, 3950 at Tasks 58 and 59, 3947 at Task 57, 3940 at Tasks 52 through 56, 3935 at Task 51, 3933 at Task 50, 3929 at Task 49, 3925 at Task 48, 3921 at Task 47, 3911 at Task 46, 3905 at Task 45, 3895 at Task 44, 3881 at Task 43, 3862 at Task 42, 3857 at Task 41, 3844 at Task 40, 3840 at Task 39, 3833 at Task 38, 3826 at Task 37, 3823 at Task 36, 3821 at Task 35, 3796 at Task 34, 3784 at Tasks 32 and 33, 3770 at Task 31, 3767 at Tasks 29 and 30, 3762 at Task 28, 3761 at Task 27, 3759 at Task 26, 3757 at Task 25, 3744 at Task 24, 3743 at Task 23, 3740 at Task 21, 3731 at Task 19, 24 files and 3693 tests at Task 18, 3621 at Task 17, 3550 at Task 16o, 3542 at Task 16n, 3534 at Task 16m, 3494 at Task 16l, 3452 at Task 16k, 3424 at Task 16j, 3401 at Task 16i, 3338 at Task 16h, 3289 at Task 16g, 3242 at Task 16f, 3221 at Task 16e, 3199 at Task 16d, 3128 at Task 16c, 3078 at Task 16b, 3061 at Task 16, 3023 at Task 15, 3017 at Task 14, 22 files and 2961 tests at Task 13, 2960 at Task 12, 2959 before it: S-9's staged-sources self-test runs one test per staged-source record, so each new record adds one; Task 13 added one S-5 test, Task 14 the new file `test/self/s9-typescript-well-formedness.test.ts`, 56 tests, Task 15 six S-2 tests, and Task 16 the TypeScript records' tests — 17 fixed ones plus one per TypeScript judgement, 21 at Task 16, 38 at Task 16b, 88 at Task 16c, 159 at Task 16d, 181 at Task 16e, 202 at Task 16f, 249 at Task 16g, 298 at Task 16h, 361 at Task 16i, 384 at Task 16j, 412 at Task 16k, 454 at Task 16l, 494 at Task 16m, 502 at Task 16n, and 503 from Task 16o; Task 16o also added five `test/self/s9-undeclared-staging.test.ts` tests, one fixed TypeScript-records test, and one MDX record's judgement — the Windows leg's drive-mismatch fixture's two records; Task 17 added the 71 tests of S-9's Unicode 15.1 block in `test/self/s9-fixture-well-formedness.test.ts`, Task 18 the new file `test/self/s6-name-analysis.test.ts`, 72 tests, Task 19 the new file `test/self/added-import-identifiers.test.ts`, 38 tests, Task 21 nine S-9 staged-source tests, one per T1.4-5 record, Task 23 three, one per record of T2.4-5's escaped-root workspace, Task 25 thirteen, one per record of T4-2's eleven new arm rows, its no-other-construct `src/c.ts`, and its `specs/NAME.mdx`, Task 26 two, one per record of T4.3-2's template-literal arm's `src/app.ts` and T4.5-3's `login-v2` spec source, Task 28 one, the record of T5.7-2's U+3000/U+202F arm's `specs/MAIN.mdx`, Task 34 twelve, one per record of T6.5-7's CRLF and lone-CR re-runs — three MDX and three TypeScript records per kind, Task 35 twenty-five — five `test/self/import-insertion.test.ts` tests and one per record of T6.5-8's restaged arms and their CRLF and lone-CR re-runs, thirteen MDX net and seven TypeScript, Task 36 two — two `test/self/import-insertion.test.ts` tests of the `pinnedOffsets` set, T6.5-9's code-arm origin record replaced one for one, Task 38 seven, one per record of T6.5-18's configuration, origin, target, and four `src/c.ts` stagings, Task 39 seven, one per record of T6.5-20's three configurations and four spec sources, Task 40 four, one per record of T6.5-20 (c)'s two configurations, its code source, and `specs/B.md/C.mdx`, Task 41 thirteen, one per record of T6.5-20 (d)'s two configurations and nine `src/c.ts` stagings and of (e)'s configuration and `specs/A.mdx`, Task 42 five, one per record of T6.5-21's three configurations, its `specs/A.mdx`, and (b)'s `specs/A.md`, Task 43 nineteen, one per record of T6.5-22's configuration, `specs/A.mdx`, and fourteen receivers, and three `test/self/added-import-identifiers.test.ts` tests of `judgeAddedImportsOfFile`, Task 44 fourteen, one per record of T6.5-23's configuration, `specs/origin.mdx`, `specs/target.mdx`, `specs/c.mdx`, and ten `src/c.ts` stagings, Task 45 ten, one per record of T6.5-23 (f)'s `specs/A.mdx`, `specs/B.mdx`, and seven `src/c.ts` stagings and (g)'s `specs/target.mdx`, Task 46 six, one per record of T6.5-23 (h)–(k)'s six `src/c.ts` stagings, Task 47 ten, one per record of T6.5-23 (l)–(p)'s eight `src/c.ts` stagings, (l)/(m)'s `specs/A.mdx`, and (o)'s `specs/third.mdx`, Task 48 four, one per record of T7-2's four import-modifier arms, Task 49 four, one per record of T7.1-1's path-character configuration and spec source and its code-source control's configuration and code source, Task 50 four, one per record of T7.3-1's graph-data-area and look-alike outDir configurations, Task 51 two, one per record of T11.6-2's invalid-path `.mdx` sources, Task 52 five, one per record of T12.0-5's positive side of the backslash — two MDX (`specs/a`, backslash, `b.mdx` and the code side's `specs/A.mdx`) and three TypeScript (the code side's configuration, `src/a`, backslash, `b.ts`, and `src/ab.ts`), Task 60 five, one per record of T14-11 (x)'s five code sources, Task 61 twenty-eight — eleven, one per record of T14-12's new arms (four MDX: (ae)–(ag)'s and (aa)'s `specs/S.mdx`; seven TypeScript: the five new code arms', (ab)'s configuration, and (ac)'s code source), four S-9 MDX form vectors, and thirteen S-9 TypeScript tests — the ten `T14_12_CODE_FORM_VECTORS`, their count, and (ac)'s judgement and offset pin), Task 62 one hundred eleven — S-9 P-2/P-3 form vectors over P-2's full brace-side whitespace set (fifteen new own-line `{X}` vectors, nineteen own-line block-comment sequences with X in every gap, and seventy-six inline ones, both forms per code point with and without a tail) and one test pinning that set and its vectors' coverage, Task 63 sixty-four — one S-9 P-5 import-header form vector per drawn spec basename, Task 64 twenty-seven — three property-runner self-tests of the TypeScript per-draw check (`test/self/property-infrastructure.test.ts`, 18 tests) and twenty-four S-9 TypeScript tests of the §16 generators' forms in `test/self/s9-typescript-well-formedness.test.ts` (twenty-two vectors and two coverage tests), all passing (~137–172 s, 146 s at Task 17, 144 s at Task 18, 144 s at Task 19, 147 s at Task 21, 138 s at Task 23, 131 s at Task 25, 136 s at Task 26, 143 s at Task 28, 134 s at Task 34, 132 s at Task 35, 130 s at Task 36, 152 s at Task 38, 155 s at Task 39, 159 s at Task 40, 156 s at Task 41, 157 s at Task 42, 155 s at Task 43, 155 s at Task 44, 153 s at Task 45, 153 s at Task 46, 153 s at Task 47, 154 s at Task 48, 154 s at Task 49, 149 s at Task 50, 148 s at Task 51, 152 s at Task 52, 152 s at Task 55 (3940 tests, unchanged), 154 s at Task 56 (3940 tests, unchanged), 157 s at Task 58 (3950 tests), 161 s at Task 59 (3950 tests, unchanged), 159 s at Task 60 (3955 tests), 159 s at Task 61 (3983 tests), 155 s at Task 62 (4094 tests), 156 s at Task 64 (4185 tests), 164 s at Task 66 (4185 tests, unchanged), 171 s at the second plan's Task 2 (4186 tests), 171 s at its Task 2b (4189 tests), 170 s at its Task 3 (4194 tests), 176 s at its Task 4 (4196 tests); CI's harness-self job ~108 s), and certification summed — before the 13.5 re-descent's new fixtures; Current totals above give today's 171 PASS / 48 FAIL / 0 error / 0 hang over 39 lines, the 9 conformers' 40 (test, fixture) pairs all PASS and the 30 violators' 179 pairs 131 PASS and 48 FAIL (186 PASS / 50 FAIL, 42 and 194 pairs, before the plan written at 2a2b94e's FIX_PLAN Task 1) — to 154 PASS / 38 FAIL / 0 error / 0 hang over 27 `certification run against` lines, every FAIL a violator's expected outcome: the 6 conformers' 39 (test, fixture) pairs all PASS, and the 21 violators' 153 pairs are 115 PASS and 38 FAIL, unchanged at Task 66, at the re-descent's second plan's Task 14, at the third plan's Task 11 (fdc3c49, locally and in CI run 888's harness-self job), at the fourth plan's Task 12 (8bebeba's trees, locally and in CI run 902's harness-self and suite-linux jobs), at the fifth plan's Task 12 (7f59049's trees, locally and in CI run 915's harness-self and suite-linux jobs), and at the sixth plan's Task 6 (715dff7's trees, locally and in CI run 923's harness-self and suite-linux jobs), at the seventh plan's VERIFY (b00e7cd, locally and in CI run 924), at its Task 6 (107f624's trees, locally and in CI run 933's harness-self and suite-linux jobs), at the eighth plan's VERIFY (34032b5, locally and in CI run 934), at its Task 4 (97c7c24's trees, locally and in CI run 938's harness-self and suite-linux jobs), at the ninth plan's VERIFY (f8f38eb, locally and in CI run 939), at its Task 10 (8b20530's trees, locally and in CI run 952's harness-self and suite-linux jobs), at the tenth plan's VERIFY (7ef10b6, locally and in CI run 953), at its Task 10 (0ad39cd's trees, locally and in CI run 963's harness-self and suite-linux jobs), at the eleventh plan's VERIFY (7e232fb, locally and in CI run 964), at its Task 15 (c88ab04's trees, locally and in CI run 979's harness-self and suite-linux jobs), at the twelfth plan's VERIFY (e6b7cb0, locally and in CI run 980), and at its Task 12 (bb37aab's trees, locally and in CI run 992's harness-self and suite-linux jobs) (`grep 'certification run against' <log> | grep -oE '[0-9]+ pass, [0-9]+ fail, [0-9]+ error, [0-9]+ hang' | awk '{p+=$1; f+=$3; e+=$5; h+=$7} END {print p, f, e, h}'`; for one kind's sum, insert `| grep ' conformer:'` or `| grep ' violator:'` after the first `grep`). - The self project — and, once the Linux-leg tests (T13.5-7, T14-9, T14-10, T13.5-8 since its acquisition-after arms' unlistable `specs/sub`, T13.5-10 since its permission removals, T13.4-12 since its unreadable leftovers' `--x` lock directory and `-w-------` entry, T13.5-11 since its `-wx` and `r-x` stagings during holds and its T13.5-7 write refusals, T13.5-12 since its `--x` `specs/sub` during holds, T11.2-6 since its emit directory `out` staged mode 000 around each run of its unreadable-emit-directory fixture, and P-15 since its leftover plain files with every permission removed, each verified refused on the harness itself) are registered, the suite project — must run as an unprivileged identity. The permission-based stagings of environment refusals (`test/helpers/permissions.ts`; TEST-SPEC E-1) verify themselves on the harness's own process before any product is invoked and throw `HarnessStagingError` — a harness error, never a diagnosed product failure — when the runner is privileged: root, or any identity holding CAP_DAC_OVERRIDE, writes into a read-only directory and reads a mode-0o200 file, so `test/self/permission-staging.test.ts` fails as root by design, as do the six tests of `test/self/lock-path.test.ts` that stage a mode refusing this process's own read or write (H-4's grant-and-restore under `.xspec/lock`) and verify it first, and the one test of `test/self/lock-staging.test.ts` that stages leftover plain files with every permission removed, whose staging verifies the removal on this process and throws `HarnessStagingError` when its own read succeeds, the two tests of `test/self/lock-state.test.ts` that first verify on this process the refused read of a mode-0o000 entry and the refused listing of a mode-0o300 (`-wx`) directory in the lock directory, and the one test of `test/self/s3-subprocess-driver.test.ts` that runs a stand-in from a working directory staged mode 000 once entered (`runProductInEnteredDirectory`, whose staging verifies itself through `stageDirectoryMode`) (never skip or work around it). CI runs both projects through `.github/scripts/run-without-network.sh`, which refuses root and a runner without passwordless sudo: it enters fresh network and mount namespaces as root through sudo and drops back to the caller's own uid, gid, and groups with every capability cleared, staying in the machine's user and process-identifier namespaces, so the command has no network, mode bits bite, and sudo still works there (the administrative access 13.5's machine-wide stagings need: T13.5-9's second user and second mount, T13.5-10(e)-(g)'s fresh process-identifier namespaces; TEST-SPEC E-1, H-2). It also restores the caller's environment and resource limits (sudo resets both), maps the host's name to loopback in a private `/etc/hosts` where the real one lacks it (sudo, built with fqdn, otherwise warns on stderr inside the network namespace), verifies all of it, and prints one `run-without-network.sh: uid ...` verification line, naming the temporary directory's filesystem type, before the command's output. In a root sandbox, reproduce its unprivileged identity alone with `unshare --map-user=1000 --map-group=1000 -- npm run test:self` (util-linux 2.38+: the command runs as uid 1000 with every capability cleared, while the repository's root-owned files stay owner-accessible, so git, npm, and Vitest's cache work unchanged — the whole self project takes the same ~2.5 min there). A plain non-root user needs no wrapper for that. sudo cannot work under these `unshare --map-user` recipes (no real root is mapped, so its set-user-ID bit is ignored), so tests needing administrative access fail there as harness errors. To reproduce CI's whole inner stage, administrative access included, run the wrapper itself as a non-root user with passwordless sudo from a copy of the checkout that user owns; in this sandbox that is `claude` (uid 999, gid 1001, NOPASSWD sudo): copy with `mkdir <copy> && tar --exclude=./.git -cf - . | tar -xf - -C <copy> && chown -R claude:claude <copy>`, then `sudo -n -u claude -H bash -c 'export PATH=/opt/node22/bin:$PATH && cd <copy> && git init -q && bash .github/scripts/run-without-network.sh env -u NODE_OPTIONS <command>'` (a `<copy>` under `/home/claude`), with `/opt/node22/bin` first because the `PATH` sudo gives `claude` (`/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin`) finds `/usr/local/bin/node`, Node v20.20.2, where this repository and CI need Node 22: the wrapper hands the command the caller's environment, so `node --version` as the command prints v22.22.2 with the export and v20.20.2 without it. At 34df333 the whole self project took ~2 min this way and gave CI's result; at 4994dab, on Node 22, 124 s, with the same 2 failed / 4313 passed as the `unshare --map-user` recipe's 127 s run. This sandbox has no `ip`, so the wrapper's loopback bring-up is a no-op here, where CI's runner brings `lo` up. sudo also drops the sandbox's agent variables (`CLAUDECODE`, `AI_AGENT`), under which Vitest 4 (std-env's `isAgent`) prints plain text through its `agent` reporter, so this recipe's log is the default reporter's, with ANSI color escapes even when redirected to a file: strip them (`sed 's/\x1b\[[0-9;]*m//g'`) before grepping it for `×` or the `Tests` summary. Self-test files that need administrative access are named `*.admin.test.ts` (the first, from the 772854b plan's FIX_PLAN Task 11: `test/self/machine-staging.admin.test.ts`): CI runs them with the rest, and under the `unshare --map-user` recipes, where sudo cannot work, they fail as harness errors (`HarnessStagingError`, mode `administrative-access`), never skips. Where harness runs get no administrative access — this sandbox, whose permission system refuses sudo-related commands as credential exploration, so no recipe here, this one included, may run a test, staging, or script that needs it, nor inspect sudo, accounts, or credentials — run the self project with `--exclude 'test/self/**/*.admin.test.ts'` on the command line (never skip them in code) and verify those files in CI: push, then read that push's harness-self job before relying on the result (its check run's annotations, `gh api repos/<owner>/<repo>/check-runs/<job-id>/annotations`, list every failing test up to GitHub's cap of ten error annotations per step — run 1176's full-suite job, 22 tests failing, showed ten — so a job failing more is read from its log; its log comes through the GitHub MCP `get_job_logs` tool, `return_content` with `tail_lines` about 200 reaching the summary, though not on every log (a whole log comes through `return_content: false`, as the bullet beginning "Reading a CI run from this sandbox" describes) — the built-in `gh api` refuses the log's redirect). The same holds for registered product tests needing it (T13.5-9, T13.5-10(e)-(g)), which S-7's sweep also runs. The older nested recipe still reproduces the network-denied unprivileged stage, without sudo: nest the `unshare --map-user` wrapper in a fresh network namespace whose loopback is up: `unshare --map-root-user --net -- bash -c 'python3 <lo-up.py> && cd /home/user/xspec && unshare --map-user=1000 --map-group=1000 -- <command>'`. This sandbox has neither `ip` nor `ifconfig`, so `<lo-up.py>` is a five-line Python helper that ORs IFF_UP (1) into `lo`'s flags through `fcntl.ioctl` on an `AF_INET` datagram socket: `SIOCGIFFLAGS` (0x8913) reads them and `SIOCSIFFLAGS` (0x8914) writes them, each request `struct.pack('16sH14s', b'lo', flags, bytes(14))`. Inside, the command runs as uid 1000 with `CapEff` 0, loopback binds, names do not resolve, and the agent proxy is unreachable. CI's runners set no `NODE_OPTIONS` (neither `.github/workflows/ci.yml` nor `.github/scripts/run-without-network.sh` sets it, the hosted `ubuntu-24.04` image's README in `actions/runner-images` lists no such variable, and run 963's harness-self log never names it), so Node there runs with its default heap limit, about 2 GB, whereas this sandbox's own `NODE_OPTIONS`, which reaches every command it starts, the namespaced ones included, varies by session: `--max-old-space-size=8192` (an 8 GB heap) in earlier sessions, `--use-openssl-ca` (Node's default heap, V8's `heap_size_limit` 2096 MB with or without it) in the session of 2026-10-25 (seen by the 86d4836 determination's VERIFY, confirmed by its plan spawn): to reproduce CI's environment whatever it holds, the heap limit included, unset it inside the inner namespace — `unshare --map-user=1000 --map-group=1000 -- env -u NODE_OPTIONS <command>` (V8's `heap_size_limit` then reads 2096 MB, against 8240 MB under the 8 GB setting; the tenth plan's VERIFY at 7ef10b6 and its FIX_PLAN Task 10 ran this way). Hand-staging a permission refusal in a scratch workspace as root works only when the staging and the product run share one namespace invocation — `unshare --map-user=1000 --map-group=1000 -- bash -c 'cd <workspace> && chmod -R a-w .xspec && node /abs/path/to/dist/cli/bin.js build --json'` (or `chmod 0100 specs/sub` for an unlistable directory): inside it the mapped identity owns the root-created files and the cleared capabilities make the mode bits bite, whereas outside it root ignores them. - Hang guards (TEST-SPEC S-3, with H-10, E-5, and §16's preamble; `test/helpers/hang-guards.ts`, since FIX_PLAN Task 18 of the plan written at 2a2b94e): the harness follows S-3's conservative design — a span carries no guard of its own. Every product invocation carries its own guard, the subprocess driver's hang guard (`RunOptions.timeoutMs`, default `DEFAULT_TIMEOUT_MS`, 30 s, overridden per call site), whose expiry kills the run and rejects it with `ProductRunTimeoutError`. No test, trial loop, property, shrink phase, certification verification, or sweep carries a time limit: every Vitest project's `testTimeout` is 0 (`test/vitest.config.ts`; Vitest 4.1.10 arms no timer for a timeout of 0 or less, `withTimeout` in `node_modules/@vitest/runner/dist/chunk-artifact.js`, and resolves a test's `timeout` with `??`, so an explicit 0 holds); registry entries name no `timeoutMs` (the field, its validation, and `DEFAULT_PRODUCT_TEST_TIMEOUT_MS` are gone); `declareProductTests`, the certification verifications, the S-7 sweeps, the E-6 writer, and the Windows leg's tests are declared with `NO_SPAN_GUARD` (0); no self-test passes a Vitest timeout (Vitest's 10 s `hookTimeout` still bounds `onTestFinished` cleanups); and the certification runner has no watchdog and no `testTimeoutMs` option — a temporary runner's own `{ timeout: … }` (the scratch patterns pass 7 200 000) bounds nothing but itself. A tripped guard ends its test: a body may convert the kill into a diagnosed failure (H-8; `runBounded`, `exitOf`, P-8's and P-11's command runners, unshrunk); the certification runner classifies a body ending with the kill unconverted — itself or as a `cause` in what it threw (`isHangGuardKill`, name fallback included) — as `hang` (it was `error`, `hang` having been the removed watchdog's), and `checkProperty` reports such a kill as a hang ("a product invocation did not terminate within its own hang guard while running trial N of M" or "while shrinking (on a shrunk input)", with the seed and the input, unshrunk, the kill its `cause`). A held run's guard covers its own work: once the harness finds the run's own hold standing — `RunningProduct.waitForFile` or `holdFileStands` on the `--test-hold` path its argv names (`holdPathArgument`, `test/helpers/invocation-grammar.ts`), resolved against its working directory and unoccupied as the run started — the guard is suspended until `releaseHoldFile` lifts that hold, then armed again for what is left of it (a held run's timeout then reads "timed out after N ms of its own hang guard, suspended while the harness kept its hold standing (TEST-SPEC S-3), and was killed"); so held runs take their module's ordinary per-run guard (`HELD_RUN_TIMEOUT_MS` in `section-13.5-iii.ts`, `-vi.ts`, and `-vii.ts`, `HELD_RESOLVE_TIMEOUT_MS` and `INTERFERENCE_HOLD_TIMEOUT_MS` in `section-13.5-ii.ts`, `HOLDER_TIMEOUT_MS` in `section-13.5-v.ts`, `E6_HELD_RUN_TIMEOUT_MS`, and `WINDOWS_HELD_RUN_TIMEOUT_MS` are gone; T13.5-13's held runs take its `RUN_TIMEOUT_MS`, 60 s), a hold observed by a harness's own `pathExists` polling suspends nothing (poll `holdFileStands`, as P-10's `holdsOrExits` and T13.5-13's `awaitExitedOrHolding` do), a lift must go through `releaseHoldFile`, and a hold path staged occupied keeps the run's guard running throughout (VIOL-CORE-HOLDLINK's dangling-link arm still fails T13.5-1 at `runBounded`'s 15 s). Counts bounding work — a property's shrink-execution cap, P-14's and P-15's shrink budgets, trial counts, P-10's `EXTRA_PRE_START_READS` — are no guards. Per-invocation guard sizing (since FIX_PLAN Task 19 of that plan): every per-invocation guard is at least ten times the longest the invocations it covers take, measured unloaded against the built product at the largest input their staging admits (H-11's scales: P-8's nesting floor, S-8's answer scale, P-11's fuzz), so `DEFAULT_TIMEOUT_MS` (30 s) covers every invocation but those whose call sites size their own — P-8's `FUZZ_COMMAND_TIMEOUT_MS` 60 s (its largest admitted answer, `view specs/B.mdx --text` over B with two balanced 4096-deep towers appended, 25.0 MB in 2.7–3.2 s at that Task, 3.8–5.0 s at the re-descent's second plan's Task 11), P-11's 300 s (raised at that Task from 120 s, which was 4.7× its largest admitted answer: `view --text specs/A.mdx` over A with two towers appended under the LF → U+2028 rewrite, 125.8 MB in 16.0–16.4 s at that Task and 25.4 s at that Task 11), T13.5-13's and P-14's `RUN_TIMEOUT_MS` 60 s, `runBounded`'s 15 s (`test/suite/registry/section-13.5.ts`), E-6's refused `move` 15 s (`E6_BUSY_TIMEOUT_MS`; the Windows leg's whole E-6 subset runs in ~45 s), the second user's probe 120 s. Measured at that Task against the scratch build (`<scratchpad>/p9j_2a2/build`): the suite project but its two admin files, under the namespace, in a scratch copy of the checkout whose `test/helpers/subprocess.ts` appended each run's guarded time and command line to a file named by an environment variable (and `test/suite/declare.ts` the running test's ID) — 86 files, 351 tests (T10.1-6 and T10.7-9 failing diagnosed, Phase 10's), 1421 s at a load average of 5–7 on 4 cores, 12,921 invocations: the longest under the default guard T1.3-7's `view specs/A.mdx` over its 2048-deep chained-id tower (2.79 s there; alone and unloaded 2.35 s, its `build` 2.11 s and `query subtree` 2.07 s), every other under 1 s (P-8's longest 0.98 s and P-11's 0.96 s at the pinned seeds, `runBounded`'s 0.74 s, a T13.5-13 or P-14 run under 0.8 s); the two answer-scale maxima through a temporary self-test staging `FUZZ_BASE_FILES` with `sectionTowerSource(4096, true)` appended twice (`mdx: { unchecked: [the file] }`) and timing `runProduct` with a 900 s guard. Re-measure the same way whenever a generator bound, S-2's staged maxima, or the product's speed at scale moves. Harness-step guards (since that Task; `test/helpers/step-guards.ts`, S-3 with H-11): every step of the harness's own work between invocations carries a guard of its own, a tripped one the harness error `HarnessStepTimeoutError` — `rethrowHarnessError` lets it through, `checkProperty` reports it as a harness error with its seed, and the certification runner records the test's `error` — through `guardStep` (a timer racing the step, which is also measured as it settles) on `TestWorkspace.create`, `file`, `edit`, `copyFrom`, and `readBytes`, `copyTreeBytes`, `snapshotDirectory`, `PathPoller.stop`, and T6.5-22(a)'s check in the driver; `execFile`'s own `timeout` on git scripting (`runGit`, 60 s), `mkfifo` (60 s), and the premise `git rev-parse` of `test/suite/registry/section-6.3.ts` (60 s; it had read a kill as the premise holding), each kill mapped through `execFileGuardTrip`; and `guardSyncStep` — bounded construction, checked: no timer interrupts a synchronous step, so it runs to completion and raises the error once it returns past its guard, what it threw the error's `cause` — on `parseJsonStdout`, the driver's T12.7-1 walk, the entry points of `test/helpers/oracles/`, P-2/P-3's `specSubtreeTexts`, the TypeScript tooling's answers (`ConsumerProject`), and `checkProperty`'s draws, per-draw S-9 checks, and shrink replays. One guard, `DEFAULT_STEP_GUARD_MS` 120 s, serves every step, sized by the same rule: measured at that Task (the guards logging each step's duration through a scratch-backed copy of the module, over the oracle, tooling, property, staging, and S-8 self-tests and 41 oracle-heavy product tests — section 4, P-2, P-3, P-5, P-6, P-9, P-12, P-13, T1.3-7, T6.5-13, T6.5-15, T6.5-16, T6.5-18 — against the scratch build), the longest steps T1.3-7's staging of its tower 1.3–1.7 s, S-8's blowup's 204 MB decode 0.66 s and T12.7-1 walk 1.2–1.5 s, a `ConsumerProject` answer at most 1.26 s, every oracle call under 20 ms. A synchronous step that never returns is the one harness hang no guard ends: bounded construction rules it out, and CI's job limits (E-1: harness-self 20 min, full suite 90 min, Windows leg 30 min) bound it outside S-3's rule — a job cut at its limit, not a failed test — and locally nothing does: interrupt a run that stops progressing. Waits beside invocations carry no bounds of their own (since that Task): `waitForFile` (its `timeoutMs` option and `DEFAULT_WAIT_FOR_FILE_TIMEOUT_MS` gone) ends at the latest once its run has exited — a live run that never creates the file is killed at its own guard and the wait then rejects with the premature-exit error, the kill its `cause` (`isHangGuardKill` sees it) — and a wait for another path while its run stands held rejects at once, a plain `Error` (a held run creates nothing until lifted); P-10's `holdsOrExits` (its 10 s gone) and T13.5-13's `awaitExitedOrHolding` (`SETTLE_TIMEOUT_MS` gone) end once each run has held or exited, a run doing neither killed at its own guard and its exit failed diagnosed (`settleMutatingRun`, `exitOf`); E-6's hold waits (`E6_HOLD_WAIT_MS`, `WINDOWS_HOLD_WAIT_MS` gone), its held run's cleanup (`stopHeldRun`, `E6_STOP_TIMEOUT_MS` gone: the run's own guard, resumed as the hold is lifted, bounds it), and the second user's probe's wait for its report likewise; P-10's reader confirmation (one look per read), the polling reader of T13.5-5 and P-10 (stopped by its caller once the runs end), and P-14's flips (stopped once its reads settle) carried none. Kill confirmations after a SIGKILL or `taskkill` (`DEFAULT_GROUP_GONE_TIMEOUT_MS` 30 s, `PROCESS_LIST_TIMEOUT_MS`) are harness steps under bounds of their own. Timing records elsewhere in this file citing a test's "N s `timeoutMs`", a runner's watchdog, or a `waitForFile` bound record bounds since removed. Pre-product checks (S-3's closing clause; since FIX_PLAN Task 20 of that plan): `test/self/s3-hang-guards.test.ts` (10 tests, ~26 s alone; 11 tests, ~34–40 s alone, since its Task 111) runs stand-in spans, their delays together past one invocation's shrunk own guard, through each machinery a span runs through — the framework options `declareProductTests` gives every entry (its second parameter, a declarer defaulting to Vitest's `test`, takes a recorder, so every registered entry's declaration is read with no body run), `runProductTestBody`, the certification runner, `checkProperty` at the fixed seeds and in its shrink phase (each phase required to reach the very counterexample and execution count an invocation-free twin's shrink reaches), `runVoidableTrial`, `readRecordedCompanionPaths` over stand-in `recorded` sets, T13.3-5(a)'s `readTamperingTrials` (`test/suite/registry/section-13.3.ts`) over the stand-in graph-data file sets of one and two files the stand-in's `build` writes under `.xspec/` (`XSPEC_S3_GRAPH_FILES` files, each `s3-source.txt`'s bytes and its index; 24 and 26 trials, one 100 ms stand-in invocation each, the test ~7 s alone), and a held run's hold — walks every entry's declaration and each Vitest project's `testTimeout` (all 0), and scans every `.ts` file under `test/` but `test/fixtures/` with `typescript-5.9.3`: no framework timeout but `NO_SPAN_GUARD` or 0 anywhere; and in the span machinery (`test/suite/`, `test/windows/`, `test/local/`, `test/helpers/`, the certification runner, its fixture manifest, `certification.test.ts`, the S-7 file) no `Promise.race`, `AbortSignal.timeout`, global `setTimeout` or `setInterval`, clock comparison that can end work, or name holding the word "deadline" outside the functions its `OWN_GUARD_SITES` lists (the per-invocation guard, the step guards, kill confirmations and exit collections after a kill, harness subprocess bounds, the PID-namespace control protocol), each listed site still found, and no hold-named path deleted but by `releaseHoldFile` or probed in a sleeping loop but by `waitForFile` or `holdFileStands`. So a new bounded harness step in any other function fails the scan until it is listed there with its reason; delays in the span machinery use `node:timers/promises`' `setTimeout` imported as `sleep`; and hold paths keep the word "hold" in their names. - 13.5's machine-wide stagings, I (`test/helpers/machine-staging.ts`; TEST-SPEC H-2, E-1, E-3, T13.5-9), made with the job's administrative access outside every product run, every one failing as `HarnessStagingError`, never a skip: `requireAdministrativeAccess()` (`sudo -n true`, exit 0 and silent; mode `administrative-access`; a self-test stages access withheld through its `sudo` option, naming a stand-in command, never `sudo`); `ensureSecondUser()` (memoized per process: the account `xspec-second`, no home, its primary group the harness's own primary group, never removed, made by `sudo -n flock --wait 60 /run/lock/xspec-second-user.lock /bin/sh -c 'getent passwd "$1" > /dev/null || exec useradd …' sh xspec-second <gid>` — `useradd` checks the name before it locks the account files, so unserialized makers running at once both add it, the later overwriting the earlier's uid: CI run 1126 saw makers read uids 1003 and 1004; mode `second-user`); `stageGroupAccess(root)` (plain files g+rw, directories g+rwx, every harness-owned directory above the root g+x — a workspace's `mkdtemp` directory is 0700 — `restore()` reinstating each mode; what is made later keeps its maker's modes, so `.xspec` and the like must exist before the staging; mode `group-access`); `stageSecondMount(root, workspace.tempRoot)` (`sudo -n mount --bind` at `<tempRoot>/second-mount-<hex>`, verified through `/proc/self/mountinfo` — a bind mount shares its source's `st_dev` — and a probe file through either path; `remove()` unmounts with retries and removes the directory, and must run before the workspace's disposal; mode `second-mount`); `secondUserLauncher(user)`, a `RunLauncher` for `startProduct`'s `launcher` run option (`sudo -n -- /bin/sh -c 'umask "$1" && shift && exec "$@"' sh <umask> prlimit <every limit of the harness's process> -- setpriv --reuid=<uid> --regid=<gid> --init-groups --inh-caps=-all --bounding-set=-all -- env -i -- <the driver's environment> <command> <args>`; the command must be absolute and hold no `=`); `verifySecondUserReach(user, { root, createIn, binding })` (T13.5-9's verification: a probe run as the second user through the launcher, from a 0770 scratch directory under the temporary folder, lists every directory and reads every file under the root, creates and removes a file in each `createIn` directory, checks the binding's command executable and required files readable, and lists the harness's process while the harness lists the probe's) and `secondUserCreatesIn(user, dir)` (the same create check, unjudged); `reclaimForHarness(root)` (`sudo -n chown -R -h <uid> -- <root>`: every entry under the root, the root included, given to the harness's uid, no link followed, modes and groups untouched; T13.5-9 runs it after each run as the second user and before the workspace's disposal, so a product writing as the second user where it must be refused leaves nothing the harness cannot read or remove and still fails diagnosed; mode `second-user`). Hosted-runner facts (CI runs 1126 and 1127): sudo, with no terminal, forks the command directly into the process group it leads, so a launched run — always its own group — is killed whole by `sudo -n kill -s KILL -- -<group>`, which the driver's guards and `killGroup` use (the harness's own signal to those processes is `EPERM`, so `RunningProduct.kill` refuses a launched run); `killGroup` on a launched run also waits for every descendant its started process had (`descendantsOf` in `test/helpers/kill-discipline.ts`), so one that left the group fails as `ProcessGroupLingerError`; a launched run gets exactly the driver's environment (no `SUDO_*`), working directory, argv, umask, and limits, as the second user's uid and the shared gid (1001 there) with every capability set empty; Node, and the built product and the empty stub (`test/fixtures/empty-stub/bin.mjs`) in the checkout under `/home/runner/work`, are reachable by the second user (the verification's reach check passes there: the built product's in runs 1126 and 1127, the stub's in run 1216, Node executable and the stub readable). `test/self/machine-staging.admin.test.ts` checks the second user's reach against the harness-owned empty stub (`test/fixtures/empty-stub/bin.mjs`: Node executable, the stub readable, the stub never started), never the built product, so it needs no product build (H-8), while T13.5-9's own check reaches the built product it runs. H-6's run notes key a mutating run's lock path by the root path it was started under, so a run started through the second mount notes `<mount>/.xspec/lock`, not `<root>/.xspec/lock`. - 13.5's machine-wide stagings, II (`test/helpers/machine-staging.ts`; TEST-SPEC H-2, E-1, E-3, T13.5-3, T13.5-10(e)-(g)): fresh process-identifier namespaces, made through sudo like stagings I, every failure `HarnessStagingError` of mode `pid-namespace` (or `administrative-access` first), never a skip. Each run started in one drops back to the harness's own uid, gid, and supplementary groups (`setpriv --reuid=<uid> --regid=<gid> --groups=<process.getgroups()>`, `--clear-groups` when there are none, `--inh-caps=-all --bounding-set=-all`, so every capability set is empty), with the harness's umask and resource limits and exactly the driver's environment (stagings I's root and `env -i` stages, shared). `freshNamespaceLauncher()` (launcher A; (f), (g)): `sudo -n -- /bin/sh -c 'umask "$1" && shift && exec "$@"' sh <umask> prlimit <limits> -- unshare --pid --fork --mount-proc -- setpriv ... -- env -i -- <env> <command> <args>`, so the run is identifier 1 of a namespace whose own `/proc` lists it alone (the working directory kept); verified once per process and sudo command by a probe run through it (a success remembered, a failure asked again). `openHarnessNamespace()` (launcher B; (e)'s run on another machine): the same `unshare` stage starting `/bin/bash --norc -c <NAMESPACE_FIRST_PROCESS_SCRIPT>` as the namespace's first process, verified fresh at open (`observe()` reads `{ listed: [1], lastAllocated: 1 }`); the script uses builtins alone, answering `observe` on its stdin with `observed <ns_last_pid> <listed>...` without forking, and bash's SIGCHLD handler reaps the orphans a namespace's first process adopts (a Node first process would not: libuv waits only for its own children). `--norc` is required: Node's stdio pipes are socketpairs, and a non-interactive bash whose stdin is a socket takes itself for a remote shell and sources `~/.bashrc` (here, under `unshare --map-user`, `/home/ubuntu/.bashrc: Permission denied` on stderr). Its `launcher` enters runs with `nsenter --target=<first process> --pid --mount --wdns=<cwd>` (entering a mount namespace resets the working directory to `/`; util-linux 2.39's `--wdns` resolves the directory inside, where `--wd` would keep one from the old mount namespace; mounts made after the namespace opened are not visible there); `close()` kills the first process's group through sudo and confirms it gone, the kernel ending every process in the namespace. Observations: `inNamespaceIdentifiers(run)` (the started process's and its descendants' `/proc/<pid>/status` NSpid lines, the field one level below the harness's own; a run with none is the staging error), `hasAllocated(observation, id)` for (e)'s reuse check, and the verifications `verifyNamespaceListsNone(namespace, ids, what)` ((e)) and `verifyListedByHarness(ids, what)` ((g)). Threads draw from the same identifiers as processes, so a namespace's `ns_last_pid` runs past its processes' identifiers (CI run 1130: a Node stand-in entered into a fresh harness namespace and its grandchild bore 9 at most, the last allocated 15), and a child process's in-namespace identifier comes after its parent's threads'. Hosted-runner facts (CI runs 1130 and 1131): every staging above works through the wrapper; two launcher-A runs of one stand-in bear the same in-namespace identifiers; the group kill through sudo reaches a namespace's first process from outside and empties the namespace, the hang guard's too. None of it runs in this sandbox (the directive above): `test/self/pid-namespace-staging.test.ts` pins locally the command lines, NSpid and answer parsing, `hasAllocated`, the first process's script run as a plain child, the (g) check, and the failure paths through stand-in sudo commands, one granting access but starting every command in the harness's own namespace among them; `test/self/pid-namespace-staging.admin.test.ts` runs in CI only. - Runs from a working directory entered before its staging (TEST-SPEC T14-10(k), (l)(iii); H-2; since the plan written at 2a2b94e's FIX_PLAN Task 22): `runProductInEnteredDirectory(binding, options, stage)` (`test/helpers/subprocess.ts`) spawns the harness's wrapper `test/helpers/entered-directory-wrapper.mjs` (plain Node ESM, harness code; `test/tsconfig.json` includes `.ts` files alone, so Prettier formats it but nothing typechecks it) in `options.cwd` with an empty environment and a control channel on file descriptor 3; once the wrapper reports itself ready, `stage()` stages the directory — for T14-10, `stageDirectoryMode(dir, 0o000, [{ attempt: "list", refused: true }, { attempt: "examine", name: "xspec.config.ts", refused: true }])` (`test/helpers/permissions.ts`), and for T6.3-6(e) its `read` probe, a plain file below the directory, a nested path allowed (an object file under `objects/`) — and the wrapper then replaces itself with the product through `process.execve` (Node.js 22.15 and later: this sandbox's v22.22.0 and CI's `node-version: 22` have it; without it the run is refused as a plain `Error` before anything spawns). So the product is the spawned process itself — its `process.ppid` the harness, only descriptors 0–2 open (`process.execve` discards every other descriptor itself), its environment exactly `productEnvironment(binding, options.env)` (no shell in between: `/bin/sh`, dash here, would add `PWD` and drop variables whose names are no shell identifiers) — with its own hang guard armed only as it starts (the wrapper's start, the staging, and the exec each a `guardStep`), and the staging is undone after the run, before T12.7-1's walk. The command must be an absolute path to an executable regular file (the exec searches no `PATH`; every binding uses `process.execPath`). A staging error surfaces as itself (`HarnessStagingError` on a privileged runner); anything else ending the run before the product starts — the wrapper's `{"failed":…}` report, or an exec the kernel refuses, which aborts Node with "process.execve failed with error code …" on stderr — is a harness error, never the product's outcome. Against the built product from a mode-000 `R/tools` (hand-probed at that Task through a temporary self-test, `R` a built specs-only workspace): `build --json`, `ids --json`, `inventory`, and `coverage nope --json` each exit 2 with `read-failure` at `.`, `ids extra --json` exits 2 code-less, and `version` exits 0. Its self-tests are the six vectors of `test/self/s3-subprocess-driver.test.ts` whose titles contain "entered-directory" (~0.35 s together but for the guard vector's 3.0 s, its staging sleeping 2.5 s) and the two of `test/self/permission-staging.test.ts` whose titles contain "mode 000": run them with `-t 'entered-directory|mode 000'` on those two files under the unprivileged namespace. Start each run a self-test awaits only when it awaits it: runs started together and awaited in turn let a later one reject — after the I/O each makes before its pre-flight — while an earlier one is still awaited, and Vitest then fails the whole run on that unhandled rejection though every test passes (`Errors 1 error`, exit 1; CI run 1421, the pre-flight refusals vector, whose table now starts each refused run inside its loop, from the plan written at 2a2b94e's FIX_PLAN Task 49). Reordering the eager table so the executable-file refusal, the one making extra `stat` and `access` calls, came first reproduced it in 3 of 3 runs of `-t 'pre-flight refusals'`; the loop-started table, reordered alike, passed 3 of 3. -- Certification fixture products (CERTIFICATIONS.md, e.g. `test/fixtures/conf-core/`) are plain Node ESM programs with no build step and no dependencies but one: the CONF-DISC conformer (`test/fixtures/conf-disc/product.mjs`, its violators with it) judges discovered code sources' well-formedness (SPEC 14.20) with the harness's own `typescript-5.9.3`, loaded lazily through `createRequire` by the first invocation that discovers a code source (~0.25 s), never `typescript` — so `npm ci` must have run, as for the tooling driver. The certification runner (and manual debugging) invokes `node test/fixtures/<fixture>/bin.mjs <command> …` with a staged workspace as the working directory. Violator executables sit beside the conformer's entry as `bin-<deviation>.mjs` (e.g. `bin-nolock.mjs`) and run the same way. Every fixture exits 70 — outside SPEC 12.0's exit partition — for a fixture-internal crash (the stack on stderr), and the CONF-DISC, CONF-CORE, CONF-VALID, CONF-MD, CONF-AVAIL, and CONF-ORPHAN fixtures also for an invocation outside their certified scope (`xspec: fixture scope error: …` on stderr, e.g. CONF-AVAIL's every product command but `view` and `occurrences` (`at` included) or an `occurrences --file` glob admitting a code source, CONF-DISC's every product command but `build`, `check`, `ids`, `inventory`, and `query edges`, `query`'s other subcommands (`query nodes`, …), the flags its served synopses name but it does not serve (`ids --tree`, `--file`, `--unreferenced`; `query edges --to`, `--kinds`), or a `check` on a workspace passing `build`'s validations (the scope serves `check` over T7-6's validation-failing invalid-source workspaces alone) — each refused only once every SPEC 12.0 syntax-class check it can decide has passed, so `query nodes extra` or `query edges --kinds contains,,x` is the usage error (exit 2), not the scope error, CONF-CORE's every product command but `build`, `check`, `ids`, `show`, `query`, `coverage`, `impact`, `rename`, `move`, and `review` (each `query` and `review` subcommand served), `ids`' `--tree`, `--file`, and `--unreferenced`, any `query nodes` or `query edges` filter (each refused only once its value spelling has passed, as CONF-MD's below), `move --preview` (refused only once each operand holds at most one `#` and the two spell one form — a mixed-form `move` is the syntax-class usage error, exit 2), a section-form `move` its argument checks and precondition admit (the section form is served to its argument checks alone: a nonexistent origin ID is the usage error after acquisition and the hold), a `rename --preview` of a performable operation, a configuration's `markdown`, `coverage`, or `policy` key (an unknown top-level key is the configuration error, exit 2), or, over discovered code sources (code groups are parsed and discovered, edgeless and never read), `query nodes` or a read's `<node>`/`<graph-node>` naming a code source — CONF-CORE judging every syntax-class error, a review subcommand's session-name form included, before configuration is loaded and before any acquisition or hold, and each gated read's argument checks — a `<node>` or `<graph-node>` identity parse-local over the named file (an unparseable named file masking it), a session name against the session directory, and `rename --preview`'s the real rename's — after loading configuration and before the gate of 13.3, a `review show` item ID past it (so on its failing workspace `show specs/A.mdx#zz` or `review status nope` exits 2, not the gate's 1), CONF-VALID's every product command but `build` and `query node`/`query nodes`, `query`'s other subcommands, or `query nodes`' `--group`, `--file`, and `--coverage` filters (refused only once `--coverage`'s vocabulary and `--file`'s outside-root rule have passed; `--tag` is served, a spelling no tag can have under 1.4 a usage error, 11.1), CONF-MD's every product command but `build`, `check`, and `query node`/`query nodes`/`query edges`, `query`'s other subcommands, any `query nodes` or `query edges` filter (each refused only once its value spelling has passed: `--tag` well-formed under 1.4's exact classes, `--coverage`'s vocabulary, `--file`'s outside-root rule, `--from`/`--to` with at most one `#`, `--kinds`' vocabulary), or a configuration key SPEC 7 defines but its scope excludes (`code`, `coverage`, `policy`, `markdown.outDir`; an unknown key stays a configuration error, exit 2), CONF-ORPHAN's every command but `build` and `check`, a `coverage` or `policy` rule, a spec source other than one `<S id="…">` section of plain Markdown lines, or a code source other than `export const NAME = DIGITS` lines — `--test-hold` on its `build` or `check` being no scope error but SPEC 12.0's unknown-flag usage error, exit 2, neither command mutating (13.5); CONF-ORPHAN keeps its graph data, record included, in `.xspec/graph.json`): such an exit is a fixture-side condition, never a product verdict, so a test hitting it needs a fixture (or staging) fix, not a product diagnosis. `test/fixtures/` is excluded from the harness typecheck; Prettier still formats it. A fixture judging a byte-order mark must inspect the raw bytes (EF BB BF): a UTF-8 `TextDecoder` strips a leading BOM from its output unless constructed with `ignoreBOM: true`, so a check on the decoded text never sees one (the CONF-AVAIL conformer, `test/fixtures/conf-avail/product.mjs`, decodes with `ignoreBOM: true` after that byte check). The CONF-AVAIL conformer's cycle pass (the last pass of `loadWorkspace`; SPEC 5.3, 14.9) runs Tarjan's SCC over each parsed file's positional tree as `contains` edges (parent to child, the root to its top-level sections) beside the recorded `depends` and `embeds` occurrences: one condition-9 finding per SCC holding a cycle (a self-loop, or two or more nodes), located at every participating reference spelling alone, a `contains` edge spelling nothing, so a section depending on or embedding its own ancestor (T11.2-4's `p.c` holding `{text("p")}`) reports one 14.9 at that spelling (the embedding's whole braced container), exit 1 — before FIX_PLAN Task 15 of the plan written at 2a2b94e the pass ran over reference edges alone and answered such a file finding-free, its texts already poisoned by the text engine's own re-entry check; the violators inherit it. Scratchpad `t9j2a2_15/probe.mjs` (`node probe.mjs <root holding test/fixtures/conf-avail/> <absolute scratch dir>`, ~7 s; rebuild it from this description if it is gone) stages eight shapes beside a one-spec-group configuration — T11.2-4's two `p`/`p.c` arms, a child's `d` on its parent, a grandchild embedding its grandparent, a parent's `d` on its child, a self-embedding, a sibling's `d` chain through an ancestor embedding, an acyclic cross-file embedding — and prints, for each of the four fixtures and each of `view --text --json`, `view --text`, `view`, and `occurrences`, the exit, each finding's code, `path` (or its omission), and located bytes, the texts, and the occurrence records. -- The certification fixtures' invocation-grammar guard (CERTIFICATIONS.md preamble, third paragraph; SPEC 12.0, 12.7): `test/self/certification-fixture-grammar.test.ts` registers one test per conformer table in `GRAMMAR_TABLES`, each running its argv rows against the conformer's binding from `CERTIFICATION_FIXTURES` — every row in a fresh workspace staged from the table's declaration or the row's own `staging` (CONF-VALID's gated-read rows stage a workspace failing `build`'s validations, 13.3; CONF-MD's anchored configuration-error rows one lacking `specs`) and, where the row names a `prepare` step, prepared by it on the row's workspace and its twin's alike before the invocation (CONF-CORE's failing workspace: `build`, then T13.5-8's staged-source record `T13_5_8_BOM`, exported from `test/suite/registry/section-13.5.ts`, at `specs/B.mdx` — a source staged after an invocation in a workspace must be a record; an existing audit session `s`: `build`, then `review create --strategy audit --name s`), a `like` row's canonical spelling in a twin whose after-state must be byte-identical, an exit-2 row's workspace compared unchanged, a `--test-hold` row's hold choreographed by `runInvocation` (a held row, `hold.created`, started with `startProduct`, its hold file awaited with `waitForFile`, deleted with `releaseHoldFile`, and only then its exit awaited — a `like` row's twin likewise when its `canonicalHold` names a path; a refused one watched while it runs, so a fixture creating the hold file fails the row at once instead of hanging until the driver's 30 s guard), and a row's `after` check run on its workspace last — and failing once with every failing row listed. Run it alone under the namespace: `unshare --map-user=1000 --map-group=1000 -- npx vitest run --config test/vitest.config.ts --project self test/self/certification-fixture-grammar.test.ts` (~20 s with Vitest's start-up; CONF-DISC's 43 rows take ~3.3–3.6 s, CONF-AVAIL's 30 ~2.6 s, CONF-ORPHAN's 43 ~3.5 s, CONF-VALID's 58 ~4.8–5.3 s, CONF-MD's 68 ~5.3 s, CONF-CORE's 61 ~8.3 s; `-t CONF-DISC` runs one table). Liveness of a row that passes against the conformer: back up the fixture's `product.mjs` to the scratchpad, apply a one-point mutation of its reader with a small Node script (each anchor asserted to match exactly once), run the guard, and copy the backup back in the same command, comparing the sha256 afterwards — e.g. `--` not ending flag reading fails exactly the three `--` rows, and a `--json` counted wherever it stands fails `build --test-hold --json` and `build -- --json`. +- Certification fixture products (CERTIFICATIONS.md, e.g. `test/fixtures/conf-core/`) are plain Node ESM programs with no build step and no dependencies but one: the CONF-DISC conformer (`test/fixtures/conf-disc/product.mjs`, its violators with it) judges discovered code sources' well-formedness (SPEC 14.20) with the harness's own `typescript-5.9.3`, loaded lazily through `createRequire` by the first invocation that discovers a code source (~0.25 s), never `typescript` — so `npm ci` must have run, as for the tooling driver. The certification runner (and manual debugging) invokes `node test/fixtures/<fixture>/bin.mjs <command> …` with a staged workspace as the working directory. Violator executables sit beside the conformer's entry as `bin-<deviation>.mjs` (e.g. `bin-nolock.mjs`) and run the same way. Every fixture exits 70 — outside SPEC 12.0's exit partition — for a fixture-internal crash (the stack on stderr), and the CONF-DISC, CONF-CORE, CONF-VALID, CONF-MD, CONF-AVAIL, CONF-ORPHAN, and CONF-IMPORT fixtures also for an invocation outside their certified scope (`xspec: fixture scope error: …` on stderr, e.g. CONF-AVAIL's every product command but `view` and `occurrences` (`at` included) or an `occurrences --file` glob admitting a code source, CONF-DISC's every product command but `build`, `check`, `ids`, `inventory`, and `query edges`, `query`'s other subcommands (`query nodes`, …), the flags its served synopses name but it does not serve (`ids --tree`, `--file`, `--unreferenced`; `query edges --to`, `--kinds`), or a `check` on a workspace passing `build`'s validations (the scope serves `check` over T7-6's validation-failing invalid-source workspaces alone) — each refused only once every SPEC 12.0 syntax-class check it can decide has passed, so `query nodes extra` or `query edges --kinds contains,,x` is the usage error (exit 2), not the scope error, CONF-CORE's every product command but `build`, `check`, `ids`, `show`, `query`, `coverage`, `impact`, `rename`, `move`, and `review` (each `query` and `review` subcommand served), `ids`' `--tree`, `--file`, and `--unreferenced`, any `query nodes` or `query edges` filter (each refused only once its value spelling has passed, as CONF-MD's below), `move --preview` (refused only once each operand holds at most one `#` and the two spell one form — a mixed-form `move` is the syntax-class usage error, exit 2), a section-form `move` its argument checks and precondition admit (the section form is served to its argument checks alone: a nonexistent origin ID is the usage error after acquisition and the hold), a `rename --preview` of a performable operation, a configuration's `markdown`, `coverage`, or `policy` key (an unknown top-level key is the configuration error, exit 2), or, over discovered code sources (code groups are parsed and discovered, edgeless and never read), `query nodes` or a read's `<node>`/`<graph-node>` naming a code source — CONF-CORE judging every syntax-class error, a review subcommand's session-name form included, before configuration is loaded and before any acquisition or hold, and each gated read's argument checks — a `<node>` or `<graph-node>` identity parse-local over the named file (an unparseable named file masking it), a session name against the session directory, and `rename --preview`'s the real rename's — after loading configuration and before the gate of 13.3, a `review show` item ID past it (so on its failing workspace `show specs/A.mdx#zz` or `review status nope` exits 2, not the gate's 1), CONF-VALID's every product command but `build` and `query node`/`query nodes`, `query`'s other subcommands, or `query nodes`' `--group`, `--file`, and `--coverage` filters (refused only once `--coverage`'s vocabulary and `--file`'s outside-root rule have passed; `--tag` is served, a spelling no tag can have under 1.4 a usage error, 11.1), CONF-MD's every product command but `build`, `check`, and `query node`/`query nodes`/`query edges`, `query`'s other subcommands, any `query nodes` or `query edges` filter (each refused only once its value spelling has passed: `--tag` well-formed under 1.4's exact classes, `--coverage`'s vocabulary, `--file`'s outside-root rule, `--from`/`--to` with at most one `#`, `--kinds`' vocabulary), or a configuration key SPEC 7 defines but its scope excludes (`code`, `coverage`, `policy`, `markdown.outDir`; an unknown key stays a configuration error, exit 2), CONF-ORPHAN's every command but `build` and `check`, a `coverage` or `policy` rule, a spec source other than one `<S id="…">` section of plain Markdown lines, or a code source other than `export const NAME = DIGITS` lines — `--test-hold` on its `build` or `check` being no scope error but SPEC 12.0's unknown-flag usage error, exit 2, neither command mutating (13.5); CONF-ORPHAN keeps its graph data, record included, in `.xspec/graph.json`; CONF-IMPORT's (`test/fixtures/conf-import/`, FIX_PLAN Task 6 of the plan written at e57210b) every command but `build`, `check`, `ids`, and `inventory` — none mutating, so `--test-hold` is each one's unknown-flag usage error — a `query` subcommand once its synopsis and its flags' value spellings pass, `ids`' `--tree`, `--file` (once its outside-root rule passes), and `--unreferenced`, a non-empty `code` map, a `coverage` or `policy` rule, a journal (`build`, `check`, `ids`) or a session directory (`check`, `inventory`), a spec-group file without `.mdx` wherever sources are analyzed, a source other than one line holding `<S id="…">` (or `<Spec id="…">`), plain text, and the closing tag, or a directory at a derived path; CONF-IMPORT keeps its graph in `.xspec/graph.json`, which `ids`' refresh (13.3) rewrites, and its record in `.xspec/record.json`, which `build` alone writes, and its source holds no backslash, every special character built from its code point; its violators, from FIX_PLAN Task 7 of that plan, `bin-braced.mjs` (VIOL-IMPORT-BRACED, the switch `refuseBracedEscapes`) and `bin-single.mjs` (VIOL-IMPORT-SINGLE, `refuseSingleQuotes`), each consumed at `specifierRefusal`, the one hook `loadConfig` calls with the specifier as `parseConfigText` read it, its refusal the configuration error (14.14) concerning the anchoring path; `test/self/certification.test.ts -t IMPORT` certifies the family, ~38 s with Vitest's start-up: the conformer passes all 48 fixed-seed draws of P-19 in 17.1 s, VIOL-IMPORT-BRACED fails P-19 in 7.6 s and VIOL-IMPORT-SINGLE in 2.9 s, each at seed 271828183's first trial, `build --json` exiting 2 with the configuration-error document where the twin exits 0): such an exit is a fixture-side condition, never a product verdict, so a test hitting it needs a fixture (or staging) fix, not a product diagnosis. `test/fixtures/` is excluded from the harness typecheck; Prettier still formats it. A fixture judging a byte-order mark must inspect the raw bytes (EF BB BF): a UTF-8 `TextDecoder` strips a leading BOM from its output unless constructed with `ignoreBOM: true`, so a check on the decoded text never sees one (the CONF-AVAIL conformer, `test/fixtures/conf-avail/product.mjs`, decodes with `ignoreBOM: true` after that byte check). The CONF-AVAIL conformer's cycle pass (the last pass of `loadWorkspace`; SPEC 5.3, 14.9) runs Tarjan's SCC over each parsed file's positional tree as `contains` edges (parent to child, the root to its top-level sections) beside the recorded `depends` and `embeds` occurrences: one condition-9 finding per SCC holding a cycle (a self-loop, or two or more nodes), located at every participating reference spelling alone, a `contains` edge spelling nothing, so a section depending on or embedding its own ancestor (T11.2-4's `p.c` holding `{text("p")}`) reports one 14.9 at that spelling (the embedding's whole braced container), exit 1 — before FIX_PLAN Task 15 of the plan written at 2a2b94e the pass ran over reference edges alone and answered such a file finding-free, its texts already poisoned by the text engine's own re-entry check; the violators inherit it. Scratchpad `t9j2a2_15/probe.mjs` (`node probe.mjs <root holding test/fixtures/conf-avail/> <absolute scratch dir>`, ~7 s; rebuild it from this description if it is gone) stages eight shapes beside a one-spec-group configuration — T11.2-4's two `p`/`p.c` arms, a child's `d` on its parent, a grandchild embedding its grandparent, a parent's `d` on its child, a self-embedding, a sibling's `d` chain through an ancestor embedding, an acyclic cross-file embedding — and prints, for each of the four fixtures and each of `view --text --json`, `view --text`, `view`, and `occurrences`, the exit, each finding's code, `path` (or its omission), and located bytes, the texts, and the occurrence records. Every conformer's reader takes as the configuration import's module specifier any static string literal (SPEC 7, 2.4; CERTIFICATIONS.md preamble), in either quote style, escapes and line continuations included, matched as spelled and never decoded, interpreted, resolved, or loaded (CONF-ORPHAN's and CONF-IMPORT's `parseConfigText` take any string token, CONF-IMPORT's returning the specifier's quote and spelled characters, given no meaning, to `loadConfig`, which hands them to its violators' hook `specifierRefusal` (null in the conformer); the five regex readers' `parseConfigSource` an alternation of the two quote styles, a backslash taking the character after it, CRLF whole, its regular expression written by a script building each backslash from code point 92), and none takes the configuration file up as a source but through its configured globs. `test/self/certification-fixture-import.test.ts` pins it: one test per conformer reader in `ROWS` (CONF-CORE's covering CONF-RACE, CONF-READERS, CONF-LEFTOVER, and every violator, which run their conformer's `product.mjs`; a new conformer with a reader of its own gets a row, as CONF-IMPORT's did at the e57210b plan's FIX_PLAN Task 7, its `build`, `check`, `ids`, and `inventory` over T7-9's workspace taking ~5 s), each staging its grammar table's valid declaration (exported from `test/self/certification-fixture-stagings.ts`, shared by the two guards) once importing from `"xspec"` and once per entry of `SPELLINGS` (13 spellings, each spliced in by concatenation, every backslash, line terminator, and U+FFFD built from its code point), running the row's commands in order, each under `--json`, the twin's exiting as SPEC fixes them, and requiring each spelling's run to equal the twin's: exit code, stdout bytes, and the workspace after it but for the configuration file (which must keep its staged bytes) and graph data (`isGraphDataKey`). Run alone under the namespace (`npx vitest run --config test/vitest.config.ts --project self test/self/certification-fixture-import.test.ts`): ~40 s with Vitest's start-up (CONF-CORE's ten commands ~15 s, each other row 2.6–5.6 s); every row failed against the readers as they stood before FIX_PLAN Task 4 of the plan written at e57210b, each refusing every specifier but `"xspec"` (exit 2). +- The certification fixtures' invocation-grammar guard (CERTIFICATIONS.md preamble, third paragraph; SPEC 12.0, 12.7): `test/self/certification-fixture-grammar.test.ts` registers one test per conformer table in `GRAMMAR_TABLES`, each running its argv rows against the conformer's binding from `CERTIFICATION_FIXTURES` — every row in a fresh workspace staged from the table's declaration (the seven valid declarations exported from `test/self/certification-fixture-stagings.ts`, shared with the configuration-import guard) or the row's own `staging` (CONF-VALID's gated-read rows stage a workspace failing `build`'s validations, 13.3; CONF-MD's anchored configuration-error rows one lacking `specs`) and, where the row names a `prepare` step, prepared by it on the row's workspace and its twin's alike before the invocation (CONF-CORE's failing workspace: `build`, then T13.5-8's staged-source record `T13_5_8_BOM`, exported from `test/suite/registry/section-13.5.ts`, at `specs/B.mdx` — a source staged after an invocation in a workspace must be a record; an existing audit session `s`: `build`, then `review create --strategy audit --name s`), a `like` row's canonical spelling in a twin whose after-state must be byte-identical, an exit-2 row's workspace compared unchanged, a `--test-hold` row's hold choreographed by `runInvocation` (a held row, `hold.created`, started with `startProduct`, its hold file awaited with `waitForFile`, deleted with `releaseHoldFile`, and only then its exit awaited — a `like` row's twin likewise when its `canonicalHold` names a path; a refused one watched while it runs, so a fixture creating the hold file fails the row at once instead of hanging until the driver's 30 s guard), and a row's `after` check run on its workspace last — and failing once with every failing row listed. Run it alone under the namespace: `unshare --map-user=1000 --map-group=1000 -- npx vitest run --config test/vitest.config.ts --project self test/self/certification-fixture-grammar.test.ts` (~20 s with Vitest's start-up; CONF-DISC's 43 rows take ~3.3–3.6 s, CONF-AVAIL's 30 ~2.6 s, CONF-ORPHAN's 43 ~3.5 s, CONF-VALID's 58 ~4.8–5.3 s, CONF-MD's 68 ~5.3 s, CONF-CORE's 61 ~8.3 s, CONF-IMPORT's 48 ~5.5–6 s from the e57210b plan's FIX_PLAN Task 7 on, its `check` rows built first by `IMPORT_BUILT` and its clauses' code spans the constant `TICK`, so the section spells no backslash; `-t CONF-DISC` runs one table). Liveness of a row that passes against the conformer: back up the fixture's `product.mjs` to the scratchpad, apply a one-point mutation of its reader with a small Node script (each anchor asserted to match exactly once), run the guard, and copy the backup back in the same command, comparing the sha256 afterwards — e.g. `--` not ending flag reading fails exactly the three `--` rows, and a `--json` counted wherever it stands fails `build --test-hold --json` and `build -- --json`. - To run a selection of product tests against one fixture executable that the certification manifest does not (yet) list — e.g. a violator before its manifest entry lands — put a temporary `*.test.ts` under `test/self/` (the self project's include pattern is `test/self/**/*.test.ts`; files elsewhere never run) that calls `runProductTests` from `test/self/certification-runner.ts` with a `ProductBinding` of the fixture (`command: process.execPath`, `prefixArgs: [<abs bin path>]`) and `productTestSuite.select([...ids])` from `test/suite/registry/index.ts`, run it as `npx vitest run --config test/vitest.config.ts --project self test/self/<file>.test.ts`, and delete the file before committing. The same pattern over `CERTIFICATION_FIXTURES` (`test/self/certification-fixtures.ts`: each violator's `binding()` and `certifies`), writing every result's full `diagnosis` to a scratch JSON file named by an environment variable, compares a harness change's effect on certified falsifications, which the certification lines show only by each diagnosis's first line: the fourteenth plan's FIX_PLAN Task 3 ran P-1 against the three CONF-VALID violators and P-2 against the two CONF-MD violators under the namespace, once with HEAD's `test/helpers/property.ts` stashed and once with the task's (~50 s each), every full diagnosis identical. The same runner red-checks that a certification rests on the assertion its violator's entry names rather than on an incidental one (the a71eb0c plan's FIX_PLAN Task 10; T13.4-5 by VIOL-CORE-CHATTYREADS, whose Expected failures then left T13.4-5's never-regenerated arm untouched — a certification CERTIFICATIONS.md dropped at 7226090, T13.4-5 out of the manifest from the 2a2b94e plan's FIX_PLAN Task 1 on; the recipe stands for any certified test): on a scratch-backed copy of `test/suite/registry/section-13.4.ts`, skip the byte-compare loop — its one `for (const probe of probes) {` replaced by `for (const probe of probes.slice(0, 0)) {` through a script asserting the target occurs exactly once, the module copied back and `cmp`-checked afterwards — and run T13.4-5 alone against the CONF-CORE conformer and VIOL-CORE-CHATTYREADS under the namespace (~1 s each): the never-regenerated arm journal-neutral since that Task, both pass with the loop skipped, and with the loop the conformer passes and CHATTYREADS fails at the loop's first probe (``T13.4-5 `build` (SPEC 12.1): the journal and session files after the command — …``); before it, with the loop skipped, CHATTYREADS still failed at the arm's journal compare (`T13.4-5: the journal across the session-deletion arm — still byte-identical …`), the certification resting there instead. - Hand-probing the CONF-CORE conformer's 13.5 exclusivity (`test/fixtures/conf-core/product.mjs`, `acquireExclusivity`; since FIX_PLAN Task 13 of the plan written at 772854b): exclusivity lives in `.xspec/lock`, each run's entry an empty plain file named `<pid>-<16 random hex digits>`, an entry live when `/proc`'s listing shows its identifier; the NOLOCK and STALELOCK switches act in `judgeLockDirectory`, the HOLDLINK switch (`holdThroughLink`, `bin-holdlink.mjs`) in `holdAtSeam` (a dangling link at the hold path read as nothing there, the hold file created at the link's target and held while the path, judged through the link, holds it; a link to an existing file or directory refused exit 2 as the conformer refuses it). The EARLYRELEASE switch (`releaseAtHold`, `bin-earlyrelease.mjs`, since FIX_PLAN Task 16) acts in `runMutating`: past the hold — or straight after acquiring, without the seam — the run releases (its entry, the emptied lock directory, an emptied area directory its acquisition created), sleeps `EARLY_RELEASE_DWELL_MS` (1000 ms), and finishes outside exclusivity; scratchpad `t9j2_16/span.mjs` (`node span.mjs <bin.mjs> <absolute empty scratch dir> [rounds]`, ~3 s a round; rebuild it from this description if it is gone) stages a built CONF-CORE workspace with the audit session `s` per command and prints each of the five mutating commands' start-to-hold and lift-to-exit times and exit (the conformer ~25–45 ms lift-to-exit, EARLYRELEASE ~1030–1045 ms). The READERENTRY switch (`readersAddEntries`, `bin-readerentry.mjs`, since FIX_PLAN Task 17) acts in `loadConfig` through `addReaderEntry`: `build` and the read commands (`isBuildOrReadInvocation`, the set VIOL-READERS-CLAIM's switch uses too) add one entry in the conformer's form once their configuration is loaded, where `lstat` finds directories at `.xspec` and `.xspec/lock`, and leave it. Scratchpad `t9j2_17/make_standins.py` (`python3 -I make_standins.py <out dir>`; rebuild it from this description if it is gone) writes T13.5-4's liveness stand-ins over the conformer, each a `standinDispatch` hook around `dispatchCommand` in `runXspec` acting while a lock directory stands: a neutral passthrough, the `workspace-busy` token printed on a read's stdout, `check --json` reporting a finding at `.xspec/lock` (exit 1), `check --json` reporting another finding with exit 0, every entry-form file appended to, and every entry-form file renamed. The CHATTYREADS switch (`chattyReads`, `bin-chattyreads.mjs`) acts in `runXspec` on `check` alone since the 2a2b94e plan's FIX_PLAN Task 10 (`checkInvocation`; before it, on `isBuildOrReadInvocation`'s whole set): once `dispatchCommand` returns exit 0 or 1 from a `check`, it appends `CHATTY_READ_ENTRY`'s one fixed line to `.xspec/journal` through `appendJournal`, creating the file (and `.xspec`) where absent; exit 2 or 70 appends nothing. Scratchpad `t9j2a2_10/probe.mjs` (`node probe.mjs <bin> <absolute empty scratch dir>`, ~2 s; rebuild it from this description if it is gone) stages the CORE workspace shape and runs `build`, `ids`, `show`, `query nodes`, `coverage`, `impact --base x` (exit 2), the review reads, `review create`, `check` exiting 0 and exiting 2 (`--bogus`, an extra operand, `--test-hold`), a `rename`, and, beside a BOM-led `specs/B.mdx`, `build --json`, `check --json`, and `ids --json` (exit 1), printing each command's exit and whether `.xspec/journal` changed: the conformer changes it at the `rename` alone, CHATTYREADS there and at each `check` exiting 0 or 1, one line each. Journal validation (since the 2a2b94e plan's FIX_PLAN Task 12): `journalFindings` — 14.13 over `readJournal`, a journal path holding anything but a plain file one finding and each line that is no `rename` or `move` JSON entry one naming its line, every finding `path` `.xspec/journal` with `locations` `[]`, `CHATTY_READ_ENTRY` an entry and never reported — is one of `loadGraph`'s validations, so `build`, every gated read, the mutating `review` subcommands' gate, and `rename`/`move`'s precondition (`rename --preview`'s too) report it beside any source finding, exit 1, writing nothing; `check` makes it itself (`loadGraph`'s `judgeJournal: false`), beside its staleness and session findings and beside the source findings where those fail; and `resolveBaseline` reads it first for `review create --base` (in `judgeArguments`, past acquisition and the hold, LATEHOLD's before its hold) and `impact --base` (past discovery), a journal error there the exit-2 error document's `code` `journal-error`, `path` `.xspec/journal`, otherwise the code-less unreadable baseline. Scratchpad `t9j2a2_12/probe.mjs` (`node probe.mjs <fixture dir> <absolute empty scratch dir> [<bin name>...]`, ~7 s a bin, `bin.mjs` by default; rebuild it from this description if it is gone) stages the CORE workspace shape built with the audit session `s` and, on a fresh copy per command, prints each command's exit, its JSON document's findings or error (code, path, locations, message), and every change outside `.xspec/lock`: with a garbage line appended to the journal (line 1; line 2 after a `rename`'s entry; lines 2 and 3), beside a BOM-led `specs/B.mdx`, and with the journal path a directory or a link to a plain file, it runs `build`, `check`, the gated reads, the mutating `review` subcommands, `rename`, `move`, `rename --preview`, the two `--base` commands with and without `--json`, and the usage errors that precede the gate (an unknown profile, old ID, or item); then, on the garbage workspace, the seam-ordering runs under `--test-hold` (hold created first, the workspace unchanged while held, `.xspec/lock` gone after) and the acquisition-first runs (beside a held `review resolve`, and with `.xspec/lock` a link to an outside directory); then the valid-journal controls and a journal `bin-chattyreads.mjs check` appended to. The 13.3 refresh's place (since the 2a2b94e plan's FIX_PLAN Task 13): `runMutating`'s `proceed` hands `operate` a fourth argument, a closure over `refreshBeforeSessionWrite(judged.graph)` (`refreshStaleGraphData` where `refreshesGraphData` is set, the mutating `review` subcommands alone), which `review create`, `resolve`, and `split` call just before `writeSession`, once every outcome 10.7 orders past the gate has passed — the session read (`requireSession`, a corrupt session's 14.21), `create`'s existing-name refusal, the item check (`requireItem`), `resolve`'s blocked refusal, and `split`'s other-kind and childless refusal — so on a stale, valid workspace a run one of them turns back leaves `.xspec/graph.json` byte-identical (before it, the refresh ran ahead of `operate` and every such run rewrote it); EARLYWRITE and LATEHOLD share the path, and EARLYREFRESH's refresh before acquisition, where it runs, makes the closure a no-op. Scratchpad `t9j2a2_13/probe.mjs` (`node probe.mjs <fixture dir> <absolute empty scratch dir> [<bin name>...]`, ~5.5 s a bin, `bin.mjs` by default; rebuild it from this description if it is gone) stages the CORE workspace shape built with the audit sessions `s` and `c` (`c` then made unparseable) and a copy whose `s` has had its `a` item split (a `parent-consistency` item for `a`), applies T13.5-1's staleness edit (`Kid text.` to `Kid text, edited.`) to both, and, on a fresh copy per command, unheld and then under `--test-hold`, prints each command's exit, its document, every change outside `.xspec/lock`, and whether `.xspec/graph.json` kept its stale bytes or holds those `build` writes on a twin (while held too): an unknown item for `resolve` and `split`, `create` of `s` and of `S`, a blocked `resolve`, a childless and an other-kind `split`, and the corrupt `c` named by `resolve` and `split` (each refused past the gate, exit 2 or 1); `--base`, `--coverage`, and an unknown session (refused ahead of the gate); and the performed `create`, `resolve` (`skipped`; `updated` with `--note`), and `split` — the conformer, EARLYWRITE, and LATEHOLD keep graph data stale on every refused run and refresh it to `build`'s bytes on every performed one (EARLYWRITE before its hold, the others after the lift), while EARLYREFRESH's early refresh, judging nothing past `build`'s validations, rewrote it before acquisition on every run, the ahead-of-the-gate refusals included, until the 2a2b94e plan's FIX_PLAN Task 14. The EARLYREFRESH switch (`refreshBeforeExclusivity`, `bin-earlyrefresh.mjs`; its foresight since that Task 14) acts in `runMutating` before acquisition, for the mutating `review` subcommands alone, through `foreseeSessionWrite`: reading alone, on the workspace as it stands, it judges acquisition (`acquisitionForeseenRefused`: `.xspec` holding anything but a directory, `.xspec/lock` anything but a directory or a plain file, or a live run's entry by `judgeListing`), anything at the `--test-hold` path, `judge` (the argument checks, baseline resolution, the gate) over the first discovery, and then the operation itself, handed a refresh closure that throws `SessionWriteReached`, so it stops just before `writeSession` having written and emitted nothing; a run reaching that point refreshes there, over the foreseen gate's graph, the late closure then a no-op, and a run any outcome turns back (a usage error, findings, a refusal, a scope or system error) refreshes nothing early and keeps the conformer's late refresh; a write the environment would refuse is never foreseen. Scratchpad `t9j2a2_14/probe.mjs` (`node probe.mjs <fixture dir> <absolute empty scratch dir> [<bin name>...]`, ~9 s a bin, `bin.mjs` by default; rebuild it from this description if it is gone) stages `t9j2a2_13/probe.mjs`'s stale workspaces and runs its commands unheld and held, the ahead-of-the-gate refusals held too (`review create --base x --name n` with and without `--json`, `--coverage nope`, an unknown session for `resolve` and `split`), then the runs turned back at the hold or acquisition: the hold path a plain file, `.xspec/lock` a symbolic link to an outside directory, `create`, `resolve`, and `split` beside a held `rename specs/A.mdx g g2` (`workspace-busy`), and `.xspec` a dangling link on an unbuilt copy; the conformer and EARLYREFRESH print the same exits, documents, and final trees, graph data kept stale on every refused run, the four performed held runs' while-held verdicts alone differing (EARLYREFRESH's graph data already holding `build`'s bytes while held). The audit review engine (since the 2a2b94e plan's FIX_PLAN Tasks 16 and 17): one derivation, `rederive` over `auditDerivation` (each node's `subtree-coherence` item, or a decomposed node's `parent-consistency` item in its place; each item's `blockedBy` its child sections' items, a decomposed child's replaced by all items of its decomposition, `standInOf`), places every item a session gains — `review create` derives the empty session, an `updated` resolve re-derives it, and `review split` records `{ journalAt, kind, scope }` in the session's `decompositions` (the original's kind and current scope identity), removes the original, and ends by re-deriving, then points every item still blocked by the original at all items of its decomposition; every item a derivation matches keeps its `id`, status, note, and recorded state and takes the generated scope, context, origin, and `reason` (`adoptGenerated`; until Task 17 only a split's decomposition items, passed as `adopt`); item and decomposition scopes match as identities mapped forward through the journal; and `baseline` and `current` are each `{ context, journalAt, nodes }` (`recordState`: the recorded context set and the journal position of its spellings beside the recorded nodes' hashes and presence), so an item taking newer spellings keeps its recorded state's meaning (`isStale` compares each recorded hash by name and the current context set with the recorded one). `review resolve` (since Task 17) sets the status and the note — an earlier note removed when `--note` is not given (reviewer D's G11) — re-derives first where the status is `updated`, and then assigns the item its current context set as `context` (`assignCurrentContext` over `currentContextSet`: the generator's context, or the context last assigned to an item no longer generated, every spelling moved to the current journal position) and records `current`, so a resolve leaves its item reading its resolved status on the same workspace (before it, a `parent-consistency` item whose node had gained a child read `invalidated` straight after its resolve). Reads present `currentContextSet` as each item's `context`; `baseline`, `current`, and `export`'s `decompositions` with every recorded node under its current identity (`presentedState`, the stored `journalAt`s left out); and an absent scope or context node with the text the item's `provenance` archive holds (`archiveTexts`, `archivedTextOf`: `{ journalAt, texts }`, each node's text as its role presents it — own text for a `subtree-coherence` item's ancestors — written as the item enters, at each derivation producing it, and at each resolve, a node absent now keeping the text archived when last present: 10.7's provenance rule; before Task 17, `recordedTextOf` read `current` then `baseline`, which held an ancestor's subtree text and nothing a later derivation saw). Scratchpad `t9j2a2_16/probe.mjs` (`node probe.mjs <fixture dir> <absolute empty scratch dir> [<bin name>]`, ~5 s, `bin.mjs` by default; rebuild it from this description if it is gone) prints `review export s --json`'s items (id, kind, scope node, status, blocked state, `blockedBy`) and decompositions around reviewer D's three repros — G8: `a` > `a.b`, `a.c` added after `create`, `a`'s item split; G9: `a` > `a.b` > `a.b.c`, `a.b`'s item split, then `a`'s; G10: a top-level `z` added after `create`, `a`'s item split — and around an `updated` resolve once decomposed nodes have gained children, a split before and after a `rename` and a file-form `move`, a `next`-driven walk to full resolution, and the two split refusals; `t9j2a2_16/probe3.mjs` (`node probe3.mjs <fixture dir> <absolute empty scratch dir>`, under 1 s) drives TEST-SPEC T10.7-9's audit fixture and prints what its arms (a), (c), (d), and (e) assert (blocking, entries, the reused `N.b` item's stored status, note, `current`, and scope); `t9j2a2_16/probe2.mjs` (same usage) follows an item a split adopts after a `rename` and a `move` through an edit, a re-resolve, and its scope's deletion (status, invalidation, and absent-scope text as at the 2a2b94e plan's Task 15). Scratchpad `t9j2a2_17/probe.mjs` (`node probe.mjs <fixture dir> <absolute empty scratch dir> [<bin name>]`, ~8 s, `bin.mjs` by default; rebuild it from this description if it is gone) prints `review show s <id> --json`'s status, note, `blockedBy`, scope and context nodes (presence, text), and its `current` and `baseline` node keys and context, beside `review status` and `export`'s note and decompositions, across: G11's repro (a resolve with `--note`, then one without, after which `show` and `export` carry no note); a `parent-consistency` item whose node gains a child after its split, read before its resolve (the child in its context) and after an `updated` and, on a twin, a `no-change` resolve (each reading its resolved status, the child in `current`; Task 16's fixture read `invalidated`); a `subtree-coherence` item whose scope gains a child at a re-derivation, resolved after it (`current` holding the child); a scope node whose text changed before a re-derivation and was then deleted (presented with the re-derivation's text), a `parent-consistency` item's deleted subtree (its context as last assigned, each absent child with its text), and an absent ancestor (its own text); reads after a `rename` (every recorded node and decomposition under its current identity); and TEST-SPEC T10.4-6(b)'s audit twin (the context a re-derivation assigns reads `invalidated` and, once the item is no longer generated, is still presented, never the recorded set). The BUILDWAIT switch (`buildWaitsForHolders`, `bin-buildwait.mjs`, since FIX_PLAN Task 18) acts in `commandBuild` through `loadGraph`'s `afterDiscovery` hook, `awaitNoLiveHolder`: once the sources are discovered, `build` looks every 50 ms (`BUILD_WAIT_POLL_MS`) while `lstat` finds directories at `.xspec` and `.xspec/lock` and the listing holds an entry-form plain file recording an identifier other than its own that `/proc` lists (`liveHolderStands`, judged as `judgeLockDirectory` judges), proceeding otherwise — a refused listing or examination included — and writing nothing there. Scratchpad `t9j2_18/probe.mjs` (`node probe.mjs <fixture dir> <absolute empty scratch dir> <bin>...`, ~15 s; run it under `unshare --map-user=1000 --map-group=1000` so its `-wx` staging bites; rebuild it from this description if it is gone) prints, per fixture bin, `build --json`'s exit and time while a `rename` holds (a 4 s bound), with nothing at the lock path, beside a dead entry and a non-entry file, beside an entry recording the probe's own live identifier, beside an unlistable lock directory, and with a symbolic link at the lock path (the conformer exits 0 at once in every case; BUILDWAIT waits exactly in the held and live-entry cases). Scratchpad `t9j2_18/make_standins.py` (`python3 -I make_standins.py <out dir>`; rebuild it from this description if it is gone) writes T13.5-4's `build`-arm liveness stand-ins over the conformer, each a `standinDispatch` hook acting on `build` alone while a lock directory stands: a neutral passthrough, `build --json` refused with the busy error document (exit 2), `build` exiting 1 with a finding, `build` terminating every live holder first, `build` appending to the journal, `build` appending to the derived module `specs/A.xspec.ts`, `build` adding an entry of its own, `build` appending to or renaming every entry-form file, and a marker left outside the workspace (`<root>/../zz-concurrent-build`) on which a later `rename` prints an extra stdout line or writes `specs/zz-concurrent.txt`. Scratchpad `t9j2_14/probe.mjs` (`node probe.mjs <fixture dir> <absolute empty scratch dir>`, ~10 s; rebuild it from this description if it is gone) prints, for the conformer and HOLDLINK, the exit, the link target's state, and the lock directory after a `rename --test-hold` on a hold path holding a file, a directory, a link to a file, and a dangling link. Scratchpad `t9j2_13/probe.mjs` (`node probe.mjs <fixture dir> <empty scratch dir>`, ~10 s; run it under `unshare --map-user=1000 --map-group=1000` so its permission stagings bite; rebuild it from this description if it is gone) stages CONF-CORE-shaped workspaces (the CORE_DECL configuration and `specs/A.mdx`) and prints one line per observation: the held `rename`'s one entry while held and after a SIGKILL; a second `rename --json`'s exit and error document while held, the holder's entry unaltered; a dead entry's takeover; leftovers removed by a successful `rename` (a plain file at the lock path; a tree with a dead identifier's entry; links to outside targets, a dangling link, a FIFO, dot-named and non-UTF-8-named directories, a mode-000 file, every outside target untouched); `.xspec/lock` a symbolic link and `.xspec` a plain file or a symbolic link (exit, error document, nothing written); a refused `rename` on an unbuilt workspace, held and unheld (no `.xspec` afterwards); the NOLOCK and STALELOCK deviations; `-wx` and `r-x` empty lock directories and a read-only unbuilt root (T13.5-10(d)); and eight overlapping held `review create`s on an unbuilt workspace. To compare with an earlier fixture, extract it with `git archive <rev> test/fixtures/conf-core | tar -x -C <dir>` and pass `<dir>/test/fixtures/conf-core`. Scratchpad `t9j2_24/make_standins.py` (`python3 -I make_standins.py <out dir>`, printing the bins comma-separated; rebuild it from this description if it is gone) writes T13.5-10(d)'s liveness stand-ins over the conformer, each one deviation in `acquireExclusivity` or what it calls: no release after acquisition's read or write failure (the busy refusal still releasing), or after a failure met removing a leftover; a leftover's refused listing reported at the nested path; a refused examination of the lock path crashing; a refused read at establishment proceeding without exclusivity; the refused listing's diagnostic naming the run's entry, and the refused entry addition's naming the absolute lock path; the argument checks run before acquisition where no `.xspec` stands; a refused removal of the plain file at the lock path ignored, the lock directory's creation then attempted over it; release listing the lock directory before its deletions; a leftover directory renamed within the lock directory before its removal (conforming) or moved out of it into the area; and a neutral copy. A scratch `test/self/zz-*.test.ts` running T13.5-10 against them (the bullet above) takes ~45–60 s a bin under the namespace. Scratchpad `t9j2_25/make_standins.py` (same usage; rebuild it from this description if it is gone) writes T13.5-10(e)'s one-machine liveness stand-ins over the conformer: liveness judged by an entry-form name alone, whatever the occupant's kind (fails each replacement staging); an entry-form name's kind learned through a link, `stat` for `lstat` (fails the link staging alone); an entry-form occupant that is no plain file opened (blocks at the FIFO staging, diagnosed at the 10 s hold-file wait); release, finding its entry gone, sweeping the lock directory whole (fails the deleted-entry staging once the `rename` completes) or bringing it back by `mkdir`; release erring where the lock directory is gone (the last two fail the lock-directory-deleted runs alone); and a neutral copy. `t9j2_25/only_e.py` (`python3 -I only_e.py apply <pristine copy of section-13.5-ii.ts> [all|<indexes into INTERFERENCES>|none] [nolockdir]`, then `restore <pristine copy>`) makes T13.5-10's body run (e) alone, optionally some interferences only; (e) alone takes ~14 s a bin. `t9j2_13/race.mjs` (`node race.mjs <fixture dir> <empty scratch dir> [rounds] [n]`, ~9 s for 20 rounds of 8) starts rounds of overlapping unheld `review create`s on built and unbuilt workspaces and prints the exit tally, any exit but 0 or a `workspace-busy` 2, or a lock directory left behind, counted bad. Configuration and discovery (since FIX_PLAN Task 19 of the plan written at 772854b): `loadConfig` refuses an unknown top-level key (`configuration-error` at the configuration file) and parses `code` groups; `discover` lists only directories some glob can reach into, never `.xspec`, a refused listing `read-failure` at that directory, a file both groups match `configuration-error` at the configuration file; `runMutating` discovers before acquiring and again past the hold, the second discovery's `{ spec, code }` passed to `judgeArguments`, `judgeWorkspace`, and `operate` (the finishing regeneration reads it, a file-form `move`'s relocation applied), EARLYWRITE judging it before its writes and VIOL-CORE-LATEHOLD (`lateHold`, which replaced VIOL-CORE-LATELOCK's `lateAcquisition` in the 772854b plan's FIX_PLAN Task 21: acquire, the second discovery, `judgeArguments`, then the hold) judging the argument checks on it before its hold. Scratchpad `t9j2_19/probe19.mjs` (`node probe19.mjs <fixture dir> <absolute empty scratch dir> <bin>...`, a few seconds a bin; run it under `unshare --map-user=1000 --map-group=1000` so its `--x` stagings bite; rebuild it from this description if it is gone) prints per bin: `rename` under an unknown top-level key, under a file both groups match, and with `specs/sub` unlistable (then `build`, `check`, `ids`, `coverage nope`, `impact --base x`, `review list` there), each exit and error document; `move specs/A.mdx#nope specs/B.mdx#x` and the wrong-kind `rename`/`move` of a code source under `--test-hold` (hold created, nothing changed while held, exit after the lift); a code-group workspace's `build`, `check`, `review create`, `rename`, and a `move` into a code glob; the second discovery meeting a both-groups file and an unlistable directory created during the hold; `.xspec` `-wx`; and a mixed-form `move` under an invalid configuration. The acquirer's own identifier and the gap (T13.5-10(f), (g); CI run 1154): an entry recording `process.pid` is judged a leftover, never a live run's, so a run that is a fresh namespace's first process (identifier 1) takes over the entry `1-…` a killed first process left; met in the harness's own namespace such an entry reads live wherever identifier 1 is listed — always: a namespace's first process — so there the conformer refuses it `workspace-busy`, leaving it in place, and proceeds once `.xspec/lock` is deleted by hand ((g)'s refused outcome). The stand-ins of FIX_PLAN Task 26's CI probe, each one deviation the probe wrote into a copy of `product.mjs`: `name-by-identifier` (`newEntryName` returning `String(process.pid)`, `ENTRY_NAME` `^([1-9][0-9]*)$`, the entry opened `w` rather than `wx`) fails (f)'s name inequality (both entries named `.xspec/lock/1`); `refuses-own-identifier` (`identifier !== process.pid` replaced by `identifier !== null`) fails (f), refused `workspace-busy`; `every-entry-live` (`listed(identifier)` replaced by `listed !== null`) fails (e) on another machine, refused though the namespace had allocated nothing near the holder's identifier (its last allocated 12); and `refusal-sweeps` (a busy refusal's release removing the lock directory whole) fails (g) at the refused run's entry check (nothing at `.xspec/lock`). Full diagnoses of the CORE family (the certification lines carry outcomes only): a temporary `test/self/zz-*.test.ts` per the bullet above, calling `runProductTests` for the conformer's and each violator's `binding()` over `inScope` and writing each result's `diagnosis` to a JSON file (~27 s under the namespace). The LISTFIRST switch (`listBeforeEntry`, `test/fixtures/conf-race/bin-listfirst.mjs`, since FIX_PLAN Task 32 of the plan written at 772854b) acts in `acquireExclusivity` through `acquireListingFirst`: the lock path examined without following a link and, a directory, listed (a missing area or lock directory, or anything else there, holding nothing; a refused examination or listing the read failure as the conformer's), the listing judged by `judgeListing` (the judgment half of `judgeLockDirectory`, which `removeLeftovers` completes), `LIST_FIRST_INTERVAL_MS` (3000) slept, then the entry established by `establishEntry` and the listing's leftovers removed, never listing again; the CONF-RACE conformer, `test/fixtures/conf-race/bin.mjs`, runs this product deviation-free. Four held runs started together on the CONF-RACE conformer spread their acquisition points over 14–38 ms unloaded and 75–140 ms with six busy loops on four cores; under LISTFIRST all four hold, at ~3.1 s. - Confirming that a CONF-ORPHAN violator fails T13.4-11 on its one expected arm alone: the registered body (`T13_4_11` in `test/suite/registry/section-13.4.ts`) walks its arms in sequence and stops at the first failing one, so in a normal `-t ORPHAN` run the arms after it never meet the violator. Drop the expected arm's `walkOrphanArm(...)` line from the body with a one-line `sed`, run `-t ORPHAN`, and restore the file with `git checkout --` in the same command so the restore cannot be skipped: the violator's runner line then reads `PASS` (its certification test showing `×`, expected under the edit), proving every other arm passes against it (~9 s per run). VIOL-ORPHAN-THROUGHLINK (`test/fixtures/conf-orphan/bin-throughlink.mjs`, switch `componentLinksInsideRoot`, consumed in `recordedOccupant` alone, so the removal and 14.10's recorded-file form move together) fails at (e)'s inside staging's first `check` and passes with that staging's line dropped. VIOL-ORPHAN-LINKTARGET (`bin-linktarget.mjs`, switch `removeLinkTarget`, consumed in `removeRecorded` alone, so 14.10's recorded-file form is unchanged) fails at (c) after `build`, the link at `specs/A.md` still standing and its outside target deleted, and passes with (c)'s `walkOrphanArm(product, ORPHAN_ARM_LINK)` line dropped. The scratch probe pattern for a fixture's arm by hand: stage `xspec.config.ts` and `specs/A.mdx` in a directory, spawn `node test/fixtures/conf-orphan/<bin> build --json` there, restage, and re-run `check --json` / `build --json`. Without editing the working tree (the tenth plan's Task 7, after compliance reviewer D's probe at 7ef10b6): in a scratch harness copy (made as the graph-data-name stand-in's `setup.sh` makes one), `sed` an `export` onto `walkOrphanArm`, `walkOrphanOrderIndependence`, `orphanArmLinkComponent`, and each `ORPHAN_ARM_*` constant of the copy's `test/suite/registry/section-13.4.ts`, and run there, alone under the namespace, a temporary `test/self/zz-*.test.ts` that walks each arm by itself — `walkOrphanArm(binding, arm)` for (a)–(d) and (f), `orphanArmLinkComponent("inside")` and `("outside")` for (e), then `walkOrphanOrderIndependence(binding)` — against each ORPHAN fixture's binding (`CERTIFICATION_FIXTURES` in `test/self/certification-fixtures.ts`: the conformer's `binding()`, each of its `violators`' `binding()`), catching each arm's error and writing one line per arm to a file (~9 s for all three fixtures): at 92b61a1 and after that task, CONF-ORPHAN passes every arm, VIOL-ORPHAN-THROUGHLINK fails (e)'s inside staging alone, and VIOL-ORPHAN-LINKTARGET (c) alone. T13.4-11 (c)'s rebuild-instruction assertion (`walkOrphanArm`'s recorded-file branch, support.ts `assertFindingInstructsRebuilding`, the `/build/i` judge of SPEC 14.10's instruction to rebuild) red-checks through the red-checking bullet's wrapper pattern around CONF-ORPHAN's conformer rather than the built product, since the conformer passes every arm while the built product stops T13.4-11 at (a): a temporary `test/self/zz-*.test.ts` binds `{ command: process.execPath, prefixArgs: [wrapper, mode, <conformer bin>] }` (the bin taken from the CONF-ORPHAN entry's `binding().prefixArgs[0]` in `CERTIFICATION_FIXTURES`) and runs `runProductTests(binding, productTestSuite.select(["T13.4-11"]))`; the wrapper acts only on an exit-1 `check --json` while the cwd holds `specs/A.md` as a symbolic link (`lstat`, judged before the spawn: (c)'s first `check` alone, so the rewrite fires once per run), replacing the message of the `stale-output` finding concerning `specs/A.md` with one naming no build in any case, its path and citation kept (`specs/A.md is a recorded derived file the current sources and configuration no longer generate (SPEC 14.10, 13.4)`): the whole test is caught at (c)'s assertion in ~1 s, while the unmodified answer passes it in ~4 s (~11–14 s for both modes with Vitest's start-up, under the unprivileged namespace). The same wrapper around `dist/cli/bin.js`, walked through the scratch copy's `walkOrphanArm(binding, ORPHAN_ARM_LINK)`, is caught there too, while the built product passes arm (c) alone unmodified (its recorded-file message ends "run `xspec build` to remove it (SPEC 14.10)"). @@ -78,14 +95,20 @@ Build, test, and run instructions for this repository (nothing else belongs in t - Measuring what the fixed CI seeds actually stage through a section-16 module's private generators (e.g. P-1's `segmentCandidate`/`tagsValueCandidate` in `test/suite/registry/section-16-p1.ts`): copy the module minus its registered test (`sed '/^const P_1 = defineProductTest/,$d'`) to a `*.tmp.ts` twin beside it, append an `export { … }` of the generators and oracle functions, and drive `drawFixedSeedTrials(generator, 25)` (`test/helpers/property.ts`; 25 = the default runs per seed) from a temporary self-test (pattern above) that classifies the draws and prints counts through `console.info` under `--disable-console-intercept` — the way to confirm a generator change still reaches every certified flip class and every staging shape before running the certification; delete both files before committing (nothing imports the twin, but `tsc -p test` and Prettier would see it). P-1 itself runs ~35 s against the built product on the default seed set (150 `build` invocations) and ~15 s under `XSPEC_PROPERTY_SEED=random` (one seed per property). To count a violator's flip class in that temporary self-test, re-judge each draw with the twin's own `segmentsVerdict`/`tagsVerdict` after replacing the violator's deviating code points by `a` (no forbidden name contains `a`, and `a` neither splits a segment nor a tag): a draw is in VIOL-VALID-SEP's class when the oracle rejects it and accepts it with U+2028 and U+2029 replaced, in VIOL-VALID-CTRL's likewise for U+0000-U+0008, U+000E-U+001F, and U+007F, and in VIOL-VALID-WIDE's when the oracle accepts it and it holds U+00A0 or U+0085. The fixed seeds' P-1 counts since the re-descent's FIX_PLAN Task 3 (U+2028 and U+2029 moved into the invalid quote-and-escape group at weight 10 each, U+00A0 and U+0085 staying the valid boundaries at weight 5 each), 75 draws per property: segment draws: 11 hold U+2028 and 10 hold U+2029; SEP's class 5 (3 holding U+2028, 2 holding U+2029), WIDE's 6 (4 holding U+00A0, 3 holding U+0085), CTRL's 4; 19 accepted. Tag draws: 11 hold U+2028 and 9 hold U+2029; SEP's class 7 (4 and 4), WIDE's 3 (2 and 1), CTRL's 8; 33 accepted. Equal weights 3 to 8 left U+2029 at most one SEP-class segment draw (none at 3), and 3 to 5 none among the tag draws. The segment property falsifies first at seed 271828183: CTRL at trial 22 (shrunk to a lone U+0000), WIDE at trial 2 (shrunk to `aaa`, U+00A0, `.a`), and SEP's class first at trial 11 (`a`, U+2028, `0b`), where the built product, which predates 1.4's bar on the two code points, fails P-1 diagnosed (shrunk to a lone U+2028; ~14 s). - P-5's fixed-seed section moves and their draw guard (the eleventh plan's FIX_PLAN Task 14; TEST-SPEC §16 P-5, E-5): `test/self/p5-fixed-seed-draws.test.ts` replays `drawFixedSeedTrials(genSectionMoveTrial, P5_SECTION_MOVE_RUNS)` — P-5's arm-2 generator and its registered 8 runs per seed, both exported by `test/suite/registry/section-16-p5-p6.ts` — and requires every `TEXT_POSITION_SHAPES` member drawn at least once (a single-line section holding prose moved into a text-position target parent of that shape). At the fixed seeds 6 of the 24 trials route there: `laterLine` 3 (seed 271828183, trials 5, 7, and 8), `selfClosing` 2 (seed 271828183 trial 6, seed 161803399 trial 1), and `sameLine` 1 (seed 161803399 trial 8); seed 314159265 routes none (most of its trials draw an import-adding move first). Unbiased, none of the 24 could take the routing (7 of the 24 models held no section whose collapse holds prose, none held one beside a valid target admitting a paired shape, and the trials over the 3 holding one beside a valid empty target each drew another move), hence the module's `TEXT_POSITION_BIAS` (0.4 of the trials drawing no import-adding move) and `TEXT_POSITION_ROUTING` (0.9); the module header's "the target side" paragraph says how a bound trial is drawn. A trial that draws no new choice keeps its draws, but every later trial of its seed shifts once one does: P-5's falsifying trial (seed 271828183, trial 1, an import-adding move) is unchanged, its counterexample identical but for the rendered `textPositionTarget` field. All six passed `runSectionMoveTrial` against the built product, run from a temporary self-test over the twin (~10 s, with an S-9 `deriveMdx` and oracle pass over all 24 draws). To re-measure, use the twin recipe above; the twin must not re-export `genSectionMoveTrial`, `TextPositionShape`, `stagedSectionMoveSources`, `P5_WOULD_BE_LABEL_PREFIX`, `FLOW_LAYOUT`, or the decoration constants `LEAD_OUTSIDE`, `LEAD_INSIDE`, `TAIL_INSIDE`, `TAIL_OUTSIDE`, `WS_RESIDUE`, and `TAB_RESIDUE`, which the module exports, and a twin and the module itself cannot load in one Vitest process (the staged-source ledger, `test/helpers/staged-ts.ts`, refuses the second load's duplicate record name), so compare the two in separate runs. Should the guard fail after a generator change (P-5's, or PROP-03's `genWorkspaceModel`, which shifts every stream), re-weight the bias or routing and re-measure; never weaken the guard. Since the twelfth plan's FIX_PLAN Task 10 the file holds a second test, S-9's per-draw replay: P-5's arm 2 run through `checkProperty` as registered — `genSectionMoveTrial`, the fixed seeds (no `seeds`, `env: {}`), `P5_SECTION_MOVE_RUNS`, and `drawSources: stagedSectionMoveSources` — with a body that only counts, so every fixed-seed draw's staged files and would-be texts derive before any product exists (P-5 itself stops at its first falsified trial), each of the 24 draws yielding at least one would-be text (~0.2 s of test time, ~2 s with Vitest's start-up). At the fixed seeds the 24 draws yield 43 would-be texts, every one deriving: 13 origins as the deletion leaves them, 2 origins with the created module's import added at offset 0, 4 existing targets, 9 coincident files, 6 created targets needing no declaration, 5 created targets with their declarations (one each), and 4 other files referencing into the moved subtree with the created module's import — the 11 created-target trials' 11 added imports. Red check: drop the moved text's final `>` in the composer (`movedTextOf`'s `return render(section);` in test/helpers/oracles/section-move.ts, `.slice(0, -1)` appended): the replay fails at seed 271828183's trial 1 (`specs/Iterator.mdx (would-be: …)`) while the shape guard passes; restore with `cp` and `cmp`. Since the twelfth plan's FIX_PLAN Task 11 the file also holds four refused-shape tests (TEST-SPEC §16 preamble and P-5, §17 S-9: a refused shape drawn is a harness error carrying its seed, never a falsified property, never a draw to skip): each hands `checkProperty` one trial (generator `() => refused`, `runs: 1`, `seeds: [<the base draw's seed>]`, `env: {}`, `drawSources: stagedSectionMoveSources`, a body counting its calls) built from a fixed-seed arm-2 draw with its layout replaced, the base draw the first in replay order that qualifies (none qualifying throws a harness-defect `Error`: choose another base, never weaken the test). Three one-sided inline spellings, each with `LEAD_OUTSIDE` and `TAIL_OUTSIDE` (T6.5-16's origin), over the first draw moving a section with body lines in the `inline` form — seed 271828183's trial 4 (index 3: `specs/exports.mdx`'s top-level `s0`, one prose line, moved to the created `specs/require.mdx`): `WS_RESIDUE` remainder with `TAIL_INSIDE` lead, `LEAD_INSIDE` remainder with `TAB_RESIDUE` lead, and `TAB_RESIDUE` remainder with the closing tag joined (`closeJoined`). Each test asserts by `deriveMdx` that every staged file derives, then that the run rejects `while checking trial 1 of 1 (S-9: …) with seed 271828183` naming `XSPEC_PROPERTY_SEED=271828183`, no `HarnessAssertionError`, its cause the `mdx-derivability` `HarnessStagingError` of the destination's would-be text (`specs/require.mdx (would-be: the created target …)`, end-tag-mismatch), the body never running. The fourth sets `FLOW_LAYOUT` on the first draw routed into a text-position target parent (seed 271828183's trial 5, `laterLine`): rejected the same way by `buildSectionMove`'s guard before any file is judged, its cause a plain `Error` (`P-5 harness defect: a flow moved text into a laterLine text-position target parent …`). Red checks, the module restored with `cp` and `cmp` after each: with `...wouldBeSectionMoveSources(trial, built),` dropped from `stagedSectionMoveSources` the three inline tests fail (`expected the checkProperty call to reject, but it resolved`: the body ran once on each refused draw) and the replay test fails (no would-be text), the other two passing; with the guard's `trial.layout.form !== "collapse" ||` disabled, the text-position test alone fails — the would-be target text then catches the shape (`HarnessStagingError` cause). The file's six tests take ~0.3 s of test time (~2.5 s with Vitest's start-up). - P-16, path-blocks generation (TEST-SPEC §16 P-16, with S-6, S-8, and S-9; the plan written at 2a2b94e, FIX_PLAN Task 138; `test/suite/registry/section-16-p16.ts`, wrapper `test/suite/section-16-p16.test.ts`): each trial stages PROP-03's spec model (`section-16-p4.ts`, whose model-space `FILE_NAMES` run to 16 for the files P-16 appends, an index past them a harness defect) deepened by up to three nested sections (`deepened`), beside code sources `src/c<k>.ts` importing every spec module (`import S<j>, { text as t<j> } from "../specs/<name>.xspec";`) and holding markers and `text(...)` calls at top level and in function units, commits it, applies one to six steps (`applyP16Step`: spec edits through P-4's `applyEdit`, `deleteSection`, code edits, a spec file added or the last one deleted, `rename`, and file- and section-form `move`, the section move's candidates — every root, every section outside the moved subtree, a created target — each admitted by `moveProblem` and its would-be texts judged per draw through P-5's `stagedSectionMoveSources`), re-stages every source from its model after each journaled operation, builds, and compares `review export p16 --json` with the oracle's prediction (`predictP16Trial`, `assertP16Export`). Its journal maps are recorded per operation in workspace identities over the nodes present when the operation runs: a node deleted before a later file move keeps its pre-move path, as the product presents it, never the moved file's final path. Against the built product, alone under the namespace, P-16 (18 trials, `P16_RUNS` 6 per seed) fails diagnosed at seed 271828183's trial 1, shrunk over 60 executions to a lone root-prose edit, at the first subtree-coherence item's scope-node read — the product emits no `scopeNodes`, T10.5-5's and T10.5-9's contract — in ~132 s; since the plan written at 891fbc0's FIX_PLAN Task 65, which made the product present `scopeNodes`, P-16 passes all 18 trials against the built product, unmodified (39.5 s alone in that task's run). To reach its own assertions past that and past T10.7-13's missing metadata pair (missing until FIX_PLAN Task 15 of the plan written at b17cba9; the built product carries it since, at that tree P-16 still failing as above, 127.3 s), run the trials one by one from a temporary self-test (`drawFixedSeedTrials(genP16Trial, P16_RUNS)`, each through `runP16Trial` exported from a scratch-backed copy of the module that reads a subtree-coherence item lacking the list as the oracle's scope set), binding the stand-in `<scratchpad>/t9j2a2_138/standin.mjs` (`prefixArgs: [standin, mode, bin]`; mode `conform` supplies the metadata pair on `review export` and nothing else): 15 of the 18 trials pass, ~2–4 s each, ~45 s in all, and 3 fail diagnosed at a parent-consistency origin lacking the changed nodes below its branch head — the origin drawn from visited nodes alone, T10.5-1's both-edited twin's deviation, a node deleted under its journal-mapped baseline parent among them (the product's rule 2 origin until FIX_PLAN Task 20 of the plan written at b17cba9; this one-by-one run has not been repeated since). Simpler since that plan's FIX_PLAN Task 26: the whole P-16 test, unmodified, passes all 18 trials (~33 s) through the launcher stand-in of the bullet beginning "Hand-probing path-blocks' node links", which supplies `scopeNodes` from the product's own recorded states, while the product before Task 26 fails it there at seed 271828183's trial 1, at a subtree-coherence scope set holding a section moved out to a created file. The stand-in's twelve other modes (`swap`, `dropitem`, `dupitem`, `dropctx`, `addctx`, `droporigin`, `extraorigin`, `duporigin`, `blockedby`, `unknownblocker`, `presence`, `scoperoot`) each fail, at the intended assertion, every passing trial their deviation reaches. `test/self/p16-fixed-seed-draws.test.ts` (2 tests, ~0.4 s of test time) replays the fixed-seed draws, requiring every step kind and every shape P-16's entry lists — a created target, a present node under a new parent, every item kind, a root present at the baseline visited, skipping, a parent-consistency chain, a deleted node in a scope under its journal-mapped identity, absent requirement and code-impact scopes, a root sourcing an embedding, baseline markers and calls — and replays S-9's per-draw check through `checkProperty`. At the fixed seeds the 18 draws take 51 steps (specEdit 15, codeEdit 10, rename 7, moveFile 7, deleteSection 5, moveSection 3, addSpecFile 3, deleteSpecFile 1) and predict 80 items (code-impact 46, subtree-coherence 21, parent-consistency 5, dependency-consistency 5, metadata-consistency 3), the chain, the created target, the journal-mapped deletion, and the deleted scope node once each: any change to P-16's weights, to PROP-03's model generator, or to P-5's basename draw moves every stream, so re-measure with a temporary self-test printing the guard's per-shape counts (copy its first test, logging `reached` instead of asserting) and re-weight where one goes missing; never weaken the guard. S-8's P-16 test (`test/self/s8-answer-scale-capacity.test.ts`) derives each fixed-seed answer's scale from the model (`p16AnswerScale` over 25 runs per seed: the largest bound 134,876 bytes, 8 items, its largest text 111 bytes, under `LARGEST_GENERATED_INPUT_BYTES`) and decodes a synthetic export at that scale through `decodeExportReport` and `assertP16Export`. +- P-19, configuration import spellings (TEST-SPEC §16 P-19, T7-9, S-9, E-5; FIX_PLAN Task 5 of the plan written at e57210b): `test/suite/registry/section-16-p19.ts` (wrapper `test/suite/section-16-p19.test.ts`, manifest spread after `section16P16Tests`, H-7 row `["2.4", "7"]`) draws the import's specifier per trial — quote style, a shape text (`P19_SHAPE_TEXTS`), each character raw or escape-spelled, and inserted pieces: continuations after LF, CR, CR LF, U+2028, and U+2029; the nine single-character escapes; the NUL escape, never before a digit; escapes of other code points; escaped non-escape characters; raw U+FFFD and other raw non-ASCII, raw U+2028 and U+2029 among them (TypeScript 5.9.3 accepts both inside a string literal and ends one only at a raw LF or CR); the other quote; an escaped backslash before `u{41}`. Every backslash is built from U+005C (`BACKSLASH` in `test/helpers/config-import.ts`), and the literal is joined into the configuration by that module's `configImportText` (`CONFIG_IMPORT_HEAD` + literal + `CONFIG_IMPORT_TAIL`: one spec group `main` over `specs/*.mdx`, `markdown: { emit: true }`), the one staging path it shares with every configuration of T7-9's (a) and (b) (`test/suite/registry/section-7-import.ts`, below); it also holds the twin's record `CONFIG_IMPORT_TWIN_CONFIG` and the records of `specs/A.mdx` and `specs/B.mdx` (`<S id="a">A</S>`, `<S id="b">B</S>`, each with a final LF). 16 runs per seed (48 draws); the twin runs once before the property, then each draw runs `build`, `check`, `ids`, and `inventory`, each under `--json`, against it (exit outcome and stdout equal; after the four, every file outside `.xspec/` but the configuration byte-identical). The guard `test/self/p19-fixed-seed-draws.test.ts` (~3.5 s, no namespace needed) classifies each fixed-seed literal with a scanner of its own: single-quoted 27 of 48, a braced escape at or below U+FFFF 30, with leading zeros 26, of a surrogate 5, and every shape, escape form, terminator, and single-character escape reached (the rarest twice); it also reads each draw's staged configuration back and replays S-9's per-draw check. Against the built product P-19 passes all 48 draws since FIX_PLAN Task 167 of the Phase 10 plan written at b63b527, whose `checkImport` (`src/core/config.ts`) reads no specifier value: 46.8 s of test, run beside `section-7-import` (69.7 s wall for the two files). Before it, P-19 failed diagnosed at seed 271828183 trial 1, shrunk to the double-quoted `@acme/config` (the product then took the double-quoted `xspec` alone): ~20 s test, ~34 s wall. Green- and red-checked through a scratch stand-in wrapping `dist/cli/bin.js` that rewrote the specifier to the double-quoted `xspec` for each run and restored the file afterwards: it passed all 48 draws in ~81 s; leaving single-quoted specifiers alone, or those holding a braced escape at or below U+FFFF, it failed at seed 271828183 trial 1 (~25 s and ~36 s with shrinking). S-9's TypeScript vectors gained `P19_TS_FORM_VECTORS`: the twin and, per quote style, every shape text raw, every escape of their characters, and every inserted piece (38 generated vectors). +- T7-9, configuration import, arms (a) to (d) (TEST-SPEC T7-9, T7-8, T14-10, H-8, S-3, S-9, E-1; FIX_PLAN Tasks 31, 32, and 33 of the plan written at e57210b): `test/suite/registry/section-7-import.ts` (wrapper `test/suite/section-7-import.test.ts`, manifest spread after `section7DiscoveryTests`, H-7 row `["7", "2.4", "7.6", "12.0", "12.7", "14"]`) stages every configuration through `configImportText` (`test/helpers/config-import.ts`, shared with P-19, whose twin and source records are named `T7-9/P-19 ...`), each a record made at module load: (a)'s eleven spellings (`T7_9_A_ARMS`) declared well-formed, (b)'s four scanner-rejected escapes (`T7_9_B_ARMS`) unparseable, (c)'s seven designations (`T7_9_C_ARMS`) well-formed beside their two `.js` module records. A module-load self-check (`assertStagedAsSpelled`) pins each record's bytes (the builder's head, the literal, its tail; the quote; the counts of backslashes, LFs, and U+FFFD; each escape's code-unit index); every backslash comes from `BACKSLASH` and every LF from its code point, so the module holds no backslash byte. The twin (`"xspec"`) runs first in a workspace of its own, held to H-5; each (a) arm then runs `build`, `check`, `ids`, and `inventory`, each under `--json`, against it (exit outcome and stdout byte-equal; after the four, every file outside `.xspec/` but the configuration byte-identical), each (b) arm holds the four commands to `expectConfigurationError`, the finding pinned to `code` `configuration-error`, `path` `xspec.config.ts`, `locations` `[]`, and each (c) arm compares as (a) does, its own staged entry pruned from the file compare. (c)'s literals are also pinned at load against the path each arm stages at (`assertDesignates`); `./locked.js`'s file is staged mode 0o200 (`stageReadRefusalOfFile`, its kind then re-examined), `./sealed/define.js`'s `sealed/` mode 000 (`stageDirectoryMode` with T14-10(l)'s three probes), and `./fifo` a FIFO (`stageFifo`, `assertFifosIntact` after each command), each verified on the harness itself, so local runs need the `unshare --map-user` recipe (as root they are a `HarnessStagingError`). Arm failures are collected and the body fails once naming each; a hang propagates at once, a (c) command's renamed for its arm with the driver's kill as its cause (the certification runner still records a hang). The harness denies no network itself (CI's Linux jobs run network-denied, E-1). (d) (`runInstalls`, after (c)) stages, at `node_modules/N` beside a configuration importing from `"N"`, a trap package (`trapManifest` giving `N` and `index.js` as `main` and `exports`; the entry `TRAP_ENTRY`, a CommonJS record, writes `t7-9-trap-marker` at the parent of its nearest `node_modules`, prints `T7-9(d) trap entry ran: ...` on both streams, and exits 113) and, separately, a `package.json` FIFO (`stageFifo`), each under `trap`, `xspec`, and the name the package directory's manifest gives (`thirdInstallName`: `modulePackageDirectory`, then `moduleNameGrammarProblem`, deduplicated against the first two; its configuration composed at run time, judged by `judgeTypeScript` under `guardSyncStep`, and staged under `ts.perDraw`, the one non-section-16 user of that declaration); each name's twin (no `node_modules`) runs `build`, `check`, `ids`, `view specs/A.mdx`, `inventory`, `review list`, and `rename specs/A.mdx a b`, each `--json`, first, and each arm then asserts per command: no marker and no tell on either stream, the FIFO intact, exit and stdout the twin's, written files the twin's (`assertWriteDeltasEqual` over snapshots taken with `EXCLUDE_LOCK_PATH`, graph data included), and T7-8's outcome (H-5). So (d)'s third name needs the package directory: with `XSPEC_PACKAGE_DIR` set it is `@modularcloud/xspec`, beside S-7's stub package `xspec-empty-stub`, and with none given (or the built binding's missing one) its two arms fail diagnosed, naming the missing directory. Against the built product it passes all 28 arms with `XSPEC_PACKAGE_DIR` set since FIX_PLAN Task 167 of the Phase 10 plan written at b63b527, whose `checkImport` (`src/core/config.ts`) reads no specifier value and refuses only a specifier that is no string literal (an identifier, a template literal, or a parenthesized string, each of which TypeScript 5.9.3 parses with no syntax diagnostic), the four (b) arms exiting 2 through the parse's syntax diagnostics: 36.9 s of test, run beside `section-16-p19` (69.7 s wall for the two files). Before it, it failed diagnosed 21 of 28 arms (every (a) arm but the single-quoted `'xspec'`, all seven (c) arms, and (d)'s `trap` and `@modularcloud/xspec` arms, each refused with exit 2 and a configuration error requiring the specifier `"xspec"`): 17.4 s of test, 26 s wall at Task 33 of the plan written at e57210b (15.3 s with no package directory, the third name's two arms then diagnosed as missing; 7.7 s of test for (a) to (c) alone at Task 32). Green- and red-checked through a temporary `test/self/zz-*.test.ts` (`runProductTests` over `productTestSuite.select(["T7-9"])`, ~9 s for the three CONF-IMPORT fixtures): the conformer passes every (a) and (c) arm and fails (b)'s four (it accepts them, exit 0), VIOL-IMPORT-BRACED fails the same four, VIOL-IMPORT-SINGLE also the single-quoted arm; a scratch stand-in wrapping `dist/cli/bin.js` that rewrote the configuration-error document's `path` to `.` failed each (b) arm at the finding pin. Task 32's scratch stand-ins wrapping the conformer red-check (c)'s stagings: one examining the designated path's kind (`lstat`, refusing all but a plain file) fails the `./nowhere.js`, `./sealed/define.js`, `./fifo`, `./specs`, and `./xspec.config` arms and passes `./locked.js` (its kind examinable); one reading its content but skipping FIFOs fails `./locked.js` too; one reading it blindly hangs at the FIFO arm, ending the test as a hang naming that arm (~42 s, one 30 s guard). Task 33's scratch stand-in (a `.mjs` wrapping `dist/cli/bin.js`, bound with `packageDir` from a fresh pack) green-checks (d): rewriting a plain quoted specifier to `"xspec"` around the real run and restoring it after, it passes all six (d) arms (and every (a), (b), (c) arm but the two escape-spelled (a) arms it leaves unrewritten); red-checks: loading the specifier through `createRequire` from the configuration first, where `node_modules/N/package.json` is a plain file, fails the three trap-package arms at the marker (the `xspec` one included, which the built product passes); reading that manifest whatever it is hangs at `trap`'s FIFO arm, the test ending as a hang naming it (59 s of test, one 30 s guard); answering as S-7's stub (exit 87, silent) for the specifier `"trap"` fails that name's two arms at T7-8's outcome though their runs equal their twin's. Find the configuration's specifier in a stand-in by slicing after `import { defineConfig } from ` (no regular expression, so no backslash). +- T7-10, the configuration file as a source, arms (a), (b), (c), (d), and (e) (TEST-SPEC T7-10, T7-3, T6.3-4, T7.1-1, S-9; FIX_PLAN Tasks 34, 35, 36, and 37 of the plan written at e57210b): registered beside T7-9 in `test/suite/registry/section-7-import.ts` (same wrapper and manifest line; H-7 row `["7", "1.7", "2.1", "2.7", "4", "4.5", "5.6", "6.3", "6.4", "6.5", "6.6", "7.1", "7.2", "7.3", "9.3", "10.7", "11.1", "11.4", "11.6", "12.0", "12.1", "12.7", "13.1", "13.3", "13.4", "14"]`). Every configuration is a record made at module load: `CONFIG_IMPORT_HEAD`, one of five plain double-quoted specifiers (`T7_10_SPECIFIERS`, no escape), and a tail, (a)'s T7-9's own (`configImportText`, no code group) and (b)'s `discoveredTail(glob)`, which adds the code group `app` globbing `*.ts` or, separately, `xspec.config.ts`; each workspace stages T7-9's `specs/A.mdx` record alone. `sourceConfig` pins (b)'s two ranges from the record's parts and checks them at load: the import declaration `[0, head + literal)`, no terminator, and `defineConfig` at its call (TypeScript 5.9.3's parser gives the same spans, `[0, 46)` and `[63, 75)` for `"./specs/A.xspec"`). (a) holds `build` and `check --json` to exit 0 finding-free. Each (b) group's control (`"xspec"`) runs first: `build` and `check` finding-free, and `query edges --from xspec.config.ts` exit 0. Each (b) arm's `build` and `check --json` must then exit 1 with at least one 14.15 (`invalid-import`, its one location the import range, `path` null) and, in the two `.xspec` arms, at least one 14.18 (`unsupported-node-usage` at the call), nothing else (TEST-SPEC pins no count), and `inventory --json` exit 0 with no finding, listing `xspec.config.ts` once, in group `app` alone. (c) (`T7_10_C_ARMS`, 12 arms) runs each consequence once on the undiscovered twin (`T7_10_C_TWINS`: T7-9's twin configuration, (a)'s `"./missing.xspec"` and `"./specs/A.xspec"` records, and an undiscovered `"./specs/B.md"` record) and once per (b) group (`T7_10_C_STAGINGS`: that group's control and (b) records, and a discovered `"./specs/B.md"` record): the gate (a premise `build --json` under `"xspec"`, the configuration restaged through `file()`, then `build --json`, `ids --json`, and `query nodes`, each inside `assertLeavesUnchanged`, the reads' findings compared with the build's through `gateComparable`, every member but the message, in order); the designation (`move specs/A.mdx specs/B.mdx --json` before any build, its one `refused-invalid-destination` finding pinned through `pinnedFinding`, `path` `specs/B.mdx`, `locations` `[]`; the twin's applied mapping `specs/A.mdx` and `specs/A.mdx#a` to `specs/B.mdx` and `specs/B.mdx#a`, `specs/B.mdx` holding the moved bytes, the origin gone); the baseline (`gitInit` and `gitCommitAll` over c1's configuration, the working tree restaged and built; `impact --base c1 --json` and `review create --base c1 --name n --json` each exit 2 with `code` and `path` null and standard error holding `xspec.config.ts`, `review create` inside the compare; the twin's both exit 0, its impact report decoded); and the converse (the undiscovered `"./specs/A.xspec"`: `move --preview --json` decoded form-exact with no edit in `xspec.config.ts`, the move as the twin's, the configuration's bytes then equal to the record's, `build` and `check --json` finding-free; each discovered twin's `move --json` refused inside the compare with (b)'s findings alone, `assertSourceFindings`). (d) (`T7_10_D_ARMS`, the twin `runBaselineReadTwin`, and `T7_10_D_ESCAPE`; 7 arms) creates each repository from `baselineReadDecl` (c1's configuration beside `T7_10_D_C1_SOURCE`, `<S id="a">Old A</S>`), commits `c1`, restages T7-9's twin configuration and T7-10's source, runs the premise `build --json`, and only then stages the FIFO (`stageFifo`) or the trap package (`trapManifest`, `TRAP_ENTRY`) in the working tree alone (`stageBaselineDesignation`); every command runs through `runGuardedCommand` and is followed by `assertFifosIntact` or `assertTrapNeverRan` (now taking its rule). `impact --base c1 --json` is decoded, the edited section `specs/A.mdx#a` required `changed`, and its `requirements` and `code` compared with the twin's (the echoed `baseline` dropped); the FIFO and trap arms also run `review create --base c1 --name n --json` and `review status n --json`, the items compared as `{kind, scope, status, blocked}` in item order. The twin (`"xspec"`, no FIFO or trap) runs first; its diagnosed failure is collected (`collectTwinFailure`), each comparison then failing through `twinOf`. The escape arm's `c1` spells T7-9(b)'s first escape (its record declared unparseable and pinned by `assertStagedAsSpelled(arm, "T7-10(d)")`), its `impact --base c1 --json` held to `expectFailingBaseline` (now taking its reason). (e) (`T7_10_E_FAMILIES`, 5 arms) stages each configuration from `CONFIG_IMPORT_HEAD`, `"xspec"`, and `specDiscoveredTail(glob)` (T7-9's tail, the spec group `main` globbing `specs/*.mdx` and `glob`, no blank line inside the default export) as an MDX record carrying `ts: "well-formed"` (`stagedMdx(name, text, "well-formed", "well-formed")`: the file is read both as a configuration and as a spec source, and S-9 judges it under both): (i) `xspec.config.ts` over the globs `xspec.config.ts` and `*.ts`; (ii) `xspec.config.mdx` over `*.mdx`, every invocation carrying `--config xspec.config.mdx` after the command's own argv. Each family's twin (the spec group globbing `specs/*.mdx` alone: (i) T7-9's twin record, (ii) an MDX record of those bytes at `xspec.config.mdx`) runs first, `build` and `check --json` finding-free. Each arm's `build` and `check --json` must exit 1 with at least one 14.19 (`invalid-source-path`, `path` the file, `locations` `[]`; (i) alone), 14.15 (`invalid-import` at `[0, 36)`), and 14.16 (`invalid-construct` at the export statement whole, `[38, length - 1)`, the final line feed excluded), every finding of each so pinned and no other examined (TEST-SPEC names none); then `inventory --json` exits 0, the file listed once in `sources`, in `main` alone, its `derived` entry `{module: null, markdown: null}` ((i)) or its `module` `xspec.config.xspec.ts` ((ii)). `specDiscoveredArm` self-checks each text at load (one blank line after the import, none inside the export statement); a scratch probe (a temporary self-test calling `readMdxTree` on the four records from `stagedMdxLedger()`) confirmed the MDX parse S-9 judges by yields exactly two ESM blocks per record, `ImportDeclaration` `[0, 36)` and `ExportDefaultDeclaration` `[38, length - 1)`, TypeScript 5.9.3 giving the same spans (`ExportAssignment` for the second). The 41 arms' failures are collected. Against the built product since FIX_PLAN Task 168 of the Phase 10 plan written at b63b527 (a spec module import's value-level binding of no permitted form is tracked, each use 14.18 at its identifier; bullet beginning "Hand-probing SPEC 14.18 for spec-module bindings of no permitted form") it passes all 41 arms: 30.6 s of test, beside T7-9 (36.3 s) in `section-7-import` (75.3 s wall, the module channel's inputs set). From FIX_PLAN Task 167 (`checkImport` reads no specifier value) to Task 168 it failed diagnosed 8 of 41 arms, each at its 14.18 assertion (no `unsupported-node-usage` at `defineConfig`'s call, the report holding the import's 14.15 alone): the four (b) `.xspec` arms (`"./specs/A.xspec"` and `"./missing.xspec"` under each code group), (c)'s two gate arms, and the converse's two discovered twins; every other arm passed: 25.0 s of test, run beside `section-16-p19` (69.7 s wall for the two files). Before Task 167, it failed diagnosed 30 of 41 arms (18.6 s of test, 27.0 s wall at Task 37 of the plan written at e57210b; 30 of 36 in 13.9 s of test, 21.3 s wall at Task 36; 25 of 29 in 9.97 s at Task 35): every (a) and (b) arm, every (c) arm but the two discovered baselines, and (d)'s five resolving baselines refused with exit 2 at their first command by the configuration error requiring `"xspec"` (for a baseline, `impact` refusing it code-less); both (b) controls, both discovered baseline arms, (d)'s twin, (d)'s escape baseline, and (e)'s five arms passed. Green- and red-checked through a scratch `.mjs` stand-in wrapping `dist/cli/bin.js`, bound through a temporary `test/self/zz-*.test.ts` (`runProductTests` over `productTestSuite.select(["T7-10"])`, about 15 s per mode). It rewrites a specifier other than `"xspec"` to `"xspec"` around the real run and restores it after; where the configuration's text holds `code: {` and its import is one (b) refuses, it answers `build`, `check`, `ids`, `query`, and `move` itself with (b)'s findings (exit 1, writing nothing); it refuses a discovered `"./specs/B.md"` configuration's move; it answers a `--base` whose tree holds such a discovered configuration with the code-less error (exit 2), and runs one whose tree holds an undiscovered configuration importing from another specifier against a fresh commit with that specifier rewritten (`git hash-object -w`, `git mktree`, `git commit-tree`, no ref moved) substituted for the `--base` value. So it passes all 29 arms. Task 34's stand-in (the 17 arms of (a) and (b), about 9 s per mode, answering `build` and `check --json` alone) still passed when it reported a `.xspec` declaration twice under 14.15; dropping 14.18 failed the four `.xspec` (b) arms at the 14.18 assertion; answering the findings with no code group failed the five (a) arms; never answering them, with `query edges --from xspec.config.ts` refused (exit 2), failed the ten (b) arms and both controls; a 14.15 range one byte long failed the ten (b) arms at the range pin. Answering `build`'s findings with no code group now fails the gate twin and the converse as well, beside the five (a) arms. Each of Task 35's perturbations fails its arms at the assertion under check: a write by the failing build (the compare), an `ids` dropping 14.18 (the gate's equality), a `query nodes` answering (exit), the designation's move performed or the twin's refused (exit), a second refusal finding (the pin), a baseline read leniently (exit), a session written (the compare), a coded error (`code` and `path`), a standard error not naming `xspec.config.ts`, the twin's baseline refused (exit), a preview listing a configuration edit, a move rewriting the configuration (its bytes), and the converse twin's move performed (exit) or refused with an extra refusal reason (no other finding). A stand-in that injects a finding must keep 12.7's order (a second `refused-invalid-destination` concerning `specs/B.md` goes before the one concerning `specs/B.mdx`), or the form-exact decode rejects the report before the assertion under check. Task 36's copy of that stand-in (scratch only) keeps a `--base` whose tree's configuration spells a backslash on the real run and substitutes every other undiscovered baseline not importing from `"xspec"` as above, so it passes all 36 arms (21.4 s of test, about 30 s per mode); each of its perturbations fails its arms at the assertion under check: a resolving arm's impact report losing its first requirement entry (the five resolving arms, at the equality), an arm's `review status` with its first item's `blocked` flipped (the FIFO and trap arms, at the items' equality), the trap loaded through `createRequire` from the configuration (the trap arm, at the marker), every impact report's `requirements` emptied (the twin and the five, at the edited section), the escape baseline substituted leniently (the escape arm, at exit 2), the twin's baseline refused (the twin, then each comparison through `twinOf`), and the FIFO read through (the test ending as a hang naming the FIFO arm, 47 s of test, one 30 s guard). Task 37's stand-in (scratch only, bound through a temporary `test/self/zz-*.test.ts` reading its modes from an environment variable; its identity mode answers as the built product, 30 of 41) perturbs one (e) answer per mode where the configuration's spec group globs a second pattern beside `specs/*.mdx`, each caught at the assertion under check (about 20 s of test per mode): the 14.14 error document (exit 2), and the configuration never taken for a spec source (the second glob removed around the real run), fail all three arms at the exit-1 assertion; 14.19 dropped fails the two (i) arms at the 14.19 assertion; the 14.16 range one byte late, and the 14.15 range one byte early, fail all three at their pins; the `derived` entry's `module` flipped, and the `sources` entry dropped, fail all three at the inventory assertions; and a 14.15 injected into the twins' `build` fails both twins at the finding-free check. +- T7-11, configured names (TEST-SPEC T7-11; FIX_PLAN Task 38 of the plan written at e57210b): registered in `test/suite/registry/section-7-names.ts` (wrapper `test/suite/section-7-names.test.ts`, its manifest line after `section7ImportTests`; H-7 row `["7", "7.4", "7.5", "8.2", "11.6", "12.0", "12.7", "14"]`), 23 arms whose diagnosed failures are collected as T7-10's are, the body failing once at the end: (a) eight group arms (`T7_11_A_ARMS`: a spec group over `specs/A.mdx`, and a code group over `src/a.ts` beside `specs: {}`, named `__proto__` as an identifier key and as a string-literal key, `constructor`, and `hasOwnProperty`), each `build --json` and `check --json` finding-free and `inventory --json`'s `specs`, `code`, and `sources` compared whole; (b) a profile and a forbidden rule both named `toString` over the one edge `tests/T.mdx#t` to `specs/A.mdx#a` (`inventory`'s resolved profile and rule views, `coverage toString --json`, `check --json`'s one 14.12 finding); (c) six arms (`T7_11_C_ARMS`: a profile's target, its boundary, and a rule's `from` group, each naming `__proto__` and `constructor`), each run on a workspace configuring a spec group of that name (`coverage --json` or `check --json`) and on its twin keying that group `product` or `tests` (`build` refused per 14.14, nothing written); (d) `coverage constructor --json` and `coverage __proto__ --json` after the premise `coverage p --json`, each the plain usage error. Every file is a record made at module load, and the module spells no backslash. Alone against the built product it passes in 12.6 s of test (20.7 s wall). Red-checked through the scratch-wrapper pattern (bullet beginning "Red-checking a strengthened product test"), the wrapper reading `xspec.config.ts` from its working directory to choose what it perturbs, seven modes in about 90 s of test: a simulated plain-object product (a `constructor` group and a `toString` name refused as duplicates, a `hasOwnProperty` group a crash, `__proto__` groups dropped from `inventory`, unknown inherited references accepted, `coverage <inherited>` answering) fails 20 of the 23 arms, each at its first diverging assertion; reporting an identifier-keyed `__proto__` as `___proto__` (TypeScript's escaped identifier text) fails (a)'s two identifier-key `__proto__` arms; renaming the `toString` profile in `coverage toString`, or the rule in `check`'s finding, fails (b); refusing a configured `__proto__` or `constructor` boundary or selector group as ambiguous fails (c)'s four such arms; giving (d)'s usage errors a configuration error's code and path fails both (d) arms; the unperturbed wrapper passes. - Format code (Prettier, default config, `src/` and `test/` only): `npm run format`; verify: `npm run format:check`. -- CI: `.github/workflows/ci.yml` — harness-self (Linux), full suite (Linux; both Linux jobs run through `.github/scripts/run-without-network.sh`: network disabled after setup, the runner's own unprivileged identity, the job's passwordless sudo kept), and the Windows E-6 leg on every pull request. The harness-self job installs no product: it does not build, and a step confirms `dist/` absent before the self project and certification run (TEST-SPEC H-8), so a self-test or certification that needs the built product fails there; the full-suite and Windows jobs build it first. Each Linux job's wrapped step opens with the wrapper's verification line; on the hosted `ubuntu-24.04` runner (run of 8d20bdb) it read `uid 1001, gid 1001, groups 1001,4,100,118,999; no capabilities; the caller's resource limits; network: lo alone; administrative access: sudo; temporary directory /tmp on ext2/ext3` (`ext2/ext3` is `stat -f`'s name for ext4's magic), and no sudo warning followed. The `e6-linux-outputs` upload step of the full-suite job runs under `if: ${{ !cancelled() }}` (with `if-no-files-found: ignore`), so the exchange the E-6 writer test wrote is uploaded even when other Linux tests fail — only a cancelled job, or one that died before its suite step, ends with no artifact: the Windows byte-identity verdict is meaningful whenever the Linux writer test completed, not only on a fully green Linux run, and that test fails loudly on the missing manifest exactly when no exchange was written. Job time limits (`timeout-minutes`): harness-self 20, full suite 90, Windows 30 — limits of the CI service, not harness guards (TEST-SPEC S-3). The full-suite job took up to 34 minutes on the slower hosted-runner class (green runs 1286–1332), with the twenty new tests, P-16, and new arms of TEST-SPEC's Phase 6 HALT at 80b83aa not yet implemented. Re-measure once a job passes ~75% of its limit. +- CI: `.github/workflows/ci.yml` — harness-self (Linux), full suite (Linux; both Linux jobs run through `.github/scripts/run-without-network.sh`: network disabled after setup, the runner's own unprivileged identity, the job's passwordless sudo kept), and the Windows E-6 leg on every pull request. Both Linux jobs provision E-1's Node.js releases at setup (`provision-node-releases.sh` into `$RUNNER_TEMP/node-releases`, exported as `XSPEC_NODE_RELEASES_DIR`), and the full-suite job packs the built product (`pack-package.sh` into `$RUNNER_TEMP/xspec-package`, its package directory exported as `XSPEC_PACKAGE_DIR`); the wrapper restores the caller's environment exactly, so both reach the wrapped run. The harness-self job installs no product: it does not build, and a step confirms `dist/` absent and `XSPEC_PACKAGE_DIR` unset before the self project and certification run (TEST-SPEC H-8), so a self-test or certification that needs the built product fails there; the full-suite and Windows jobs build it first. Each Linux job's wrapped step opens with the wrapper's verification line; on the hosted `ubuntu-24.04` runner (run of 8d20bdb) it read `uid 1001, gid 1001, groups 1001,4,100,118,999; no capabilities; the caller's resource limits; network: lo alone; administrative access: sudo; temporary directory /tmp on ext2/ext3` (`ext2/ext3` is `stat -f`'s name for ext4's magic), and no sudo warning followed. The `e6-linux-outputs` upload step of the full-suite job runs under `if: ${{ !cancelled() }}` (with `if-no-files-found: ignore`), so the exchange the E-6 writer test wrote is uploaded even when other Linux tests fail — only a cancelled job, or one that died before its suite step, ends with no artifact: the Windows byte-identity verdict is meaningful whenever the Linux writer test completed, not only on a fully green Linux run, and that test fails loudly on the missing manifest exactly when no exchange was written. Job time limits (`timeout-minutes`): harness-self 30, full suite 360 (GitHub's own per-job limit for hosted runners, 6 hours), Windows 30 — limits of the CI service, not harness guards (TEST-SPEC S-3). The full-suite job took up to 34 minutes on the slower hosted-runner class (green runs 1286–1332) and 46.5 minutes at 3d8e7ad (main's run 40718517942, where harness-self took 6.5), before IP 0002's tests of SPEC 7.6 (173 covered setups per type-checking arm, six Node.js releases per runtime arm), S-4's checks of 7.6's setups, and S-10 were implemented. At 7e7119b (run 40863439587), the first with the module channel's setup steps, harness-self took 7.2 minutes and the full suite 50 (its Vitest run 2957.9 s), packing taking under 1 s, and both Linux jobs were red on the same five self-test gates alone, the ones reading SPEC.md's H-7 keys and CERTIFICATIONS.md's fixtures: `test/self/s1-traceability.test.ts` (the new key 7.6, unmapped) and `test/self/certification-document.test.ts` (CONF-IMPORT and its violators, certifying P-19, not yet wired), which IP 0002's specification changes leave to Phase 9; every product-facing test passed, and the Windows leg was green. At d0ccc8f (run 1892, id 41158514177), IP 0002's Phase 9 end, with every test of SPEC 7.6, P-17, P-18, P-19, S-4's checks of 7.6's setups, and S-10 implemented: harness-self took 9.4 minutes (562 s, 31% of its limit; its self project 54 files and 7295 tests, all passing, in 515.23 s, `certification.test.ts` 307.4 s of it and `s10-node-release-driver.test.ts` 104.2 s); the full suite 51.4 (3083 s, 14%; `npm test` 154 files and 7688 tests — the 392 registered product tests, the E-6 writer test, and the self project's 7295 — in 3049.79 s, 8340.7 s of test time summed over its files, the slowest `section-12.0-iv.test.ts` 650.9 s, `section-16-p12.test.ts` 509.2 s, `section-13.5-ii.test.ts` 445.5 s, and `certification.test.ts` 400.4 s), its 12 failures all diagnosed product failures (P-17, P-18, P-19, T7-9, T7-10, and T7.6-1 to T7.6-7: the built product predates IP 0002's product changes); and the Windows leg 1 minute (3 files and 10 tests, all passing, in 29.39 s; `e6-linux-outputs` 30642 bytes). At 21af7d9 (run 1893, id 41162798634), whose changes from d0ccc8f are comments and records alone, harness-self took 9.1 minutes (its self project in 502.03 s), the full suite 39.7 (`npm test` in 2353.63 s, the same 154 files and 7688 tests, the same 12 failures each at the same first assertion), and the Windows leg 1.4 (its Vitest run 50.85 s): the hosted runners' spread between runs of one harness and product. Each job's per-file test counts equal those of `npx vitest list --config test/vitest.config.ts --project <project> --json=<file>` on the same tree (a listing collects every test and runs none), so every registered test ran. Against that product, 7.6's tests, P-17, and P-18 stop at their first failing setup, run, or draw (`section-7.6.test.ts` 20.8 s, `section-7.6-ii.test.ts` 6.4 s, P-17 14.5 s, P-18 3.4 s); against a conforming scratch stand-in package their bodies took about 560 s locally (T7.6-3 390 s, T7.6-4 75 s, T7.6-5 29 s, P-17 23 s, T7.6-2 17 s, P-18 11 s, T7.6-1 10 s, T7.6-7 4 s, T7.6-6 2 s), T7-9's and T7-10's refused arms some seconds more, so a conforming product adds about 9 minutes of test time and the full suite stays near an hour of its six. Measured with the conforming product (IP 0002's Phase 10 plan, written at b63b527, its Task 170 landing at 809a932): at cfc142e (run 1903, id 41194590465), the first run with every test passing, harness-self took 8.9 minutes, the full suite 40.4 (`npm test` 154 files and 7688 tests, all passing, in 2391.72 s; `section-7.6.test.ts` 265.6 s, `section-7.6-ii.test.ts` 121.9 s, P-19 47.7 s, P-17 45.1 s, and P-18 26.8 s), and the Windows leg 1.1; at 6acaf6e (run 1904, id 41197546944), the same product and harness trees, harness-self took 9.25 minutes (555 s, 31% of its limit; its self project 54 files and 7295 tests in 514.14 s, `certification.test.ts` 305.0 s and `s10-node-release-driver.test.ts` 104.1 s), the full suite 53.0 (3181 s, 15%; `npm test` in 3147.07 s, the slowest files `section-12.0-iv.test.ts` 610.2 s, `section-16-p12.test.ts` 501.1 s, `section-13.5-ii.test.ts` 415.5 s, `certification.test.ts` 394.1 s, and `section-7.6.test.ts` 366.2 s, with `section-7.6-ii.test.ts` 163.5 s, P-19 62.2 s, P-17 55.9 s, and P-18 35.4 s), and the Windows leg 1.5 (its Vitest run 49.97 s), the whole run 54.6 — the hosted runners' spread again, 40 to 53 minutes for one tree. Neither Linux job comes within a third of its limit, so the suite stays one job and no limit was raised (FIX_PLAN Task 47 of the plan written at e57210b). Where the full suite outgrows the service's limit, TEST-SPEC E-1 splits it across parallel jobs whose union is the whole suite, every verdict reported, never trimming it. Re-measure once a job passes ~75% of its limit. - Reading a CI run from this sandbox: `gh` here is Claude Code's built-in GitHub client, not the GitHub CLI, and `gh api <REST endpoint>` reaches api.github.com through the session's GitHub proxy (confirmed at the third plan's FIX_PLAN Task 11). `gh api 'repos/{owner}/{repo}/actions/runs?branch=claude/xspec-ui-apis-4df8fa&per_page=5' --jq '.workflow_runs[] | [.id, .run_number, .head_sha[0:7], .status, .conclusion] | @tsv'` lists the branch's runs, `gh api repos/{owner}/{repo}/actions/runs/<run-id>/jobs` gives each job's and step's status and conclusion, and `gh api repos/{owner}/{repo}/check-runs/<job-id>/annotations` a job's annotations (a job's ID is its check run's); the pulls and branches endpoints answer too. It refuses the log download's redirect (to a `*.blob.core.windows.net` host), so `gh api repos/{owner}/{repo}/actions/jobs/<job-id>/logs` fails by design. The GitHub MCP tools fetch logs: `get_job_logs` (`job_id`, `return_content: false`) returns one job's signed `logs_url` on `productionresultssa<N>.blob.core.windows.net` (valid ~10 min; the plain-text log, 172 KB for a green harness-self job), and `actions_get`'s `get_workflow_run_logs_url` (the run's ID) a signed URL on `results-receiver.actions.githubusercontent.com` for a zip holding one `<n>_<job name>.txt` log per job (0.3 MB for a green run). Read a whole log that way, through `return_content: false`: the content route (`return_content: true`) cut run 1684's `suite-linux` log off before Vitest's closing summary (seen by VERIFY at 891fbc0, opening the re-descent's Phase 10 plan), so fetch the `logs_url` with `curl -o` into a fresh `mktemp -d` directory and read the file there (run 1700's green logs at 1eaee27 came so: `harness-self` 336 KB, `suite-linux` 878 KB, `suite-windows` 24 KB). Each URL arrives JSON-escaped, every ampersand spelled as the six-character JSON escape of U+0026: turn each into `&` (build the escape from character codes, e.g. Python's `chr(92) + 'u0026'`, since the tool-parameter layer may decode that spelling), and `curl -sS -o <file> '<url>'` fetches it through the proxy. Spelling each ampersand as a placeholder in the shell command and restoring it there works too, through `sed 's/<placeholder>/\&/g'` — never through bash's `${U//<placeholder>/&}`: under bash 5.2's default `patsub_replacement` that `&` stands for the matched text, so the placeholder survives and the storage host answers `PublicAccessNotPermitted` (seen at FIX_PLAN Task 15 of the plan written at b17cba9). A job no hosted runner acquires ends `cancelled` after ~15 min with no steps and the annotation "The job was not acquired by Runner of type hosted even after multiple attempts" (run 887's `suite-linux` at 008d1e1), and the Windows leg then fails on the missing `e6-linux-outputs` artifact, by design: an infrastructure event, not a harness result, so read a cancelled job's annotations before reading it as a verdict. A push to the branch cancels the branch's run in progress (`concurrency` with `cancel-in-progress`), so a run completes only when no later push lands within ~13–29 min (run 642 at 8f5660d: `harness-self` 2 min; `suite-linux` 11 min, its `npm test` running the suite and self projects together — 99 files, 3287 tests — in 673 s; `suite-windows` 1 min after it, since it waits on the Linux leg's E-6 exchange; run 643 at c62f451, the same product and harness trees: `suite-linux` 19 min, `npm test` in 1126 s; run 853 at f8e031e, the Phase 9 re-descent's end: `harness-self` 2 min, its self project in 77 s; `suite-linux` 19 min, `npm test` (104 files, 4530 tests) in 1147 s, the suite's 28 diagnosed product failures its only failures; `suite-windows` 1.5 min after it, 3 files, 9 tests; run 871 at 79d2013, the re-descent's second plan's last harness change: `harness-self` 3 min, its self project (26 files, 4206 tests) in 133 s; `suite-linux` 19 min, `npm test` (105 files, 4551 tests) in 1106 s, the same 28 diagnosed product failures its only failures; `suite-windows` 1 min after it, 3 files, 9 tests; run 888 at fdc3c49, the third plan's last harness change: `harness-self` 2 min, its self project (27 files, 4217 tests) in 97 s; `suite-linux` 20 min, `npm test` (106 files, 4562 tests) in 1153 s, the same 28 diagnosed product failures its only failures; `suite-windows` queued 5 min for a runner, then 1.5 min, 3 files, 9 tests; run 902 at 8bebeba, the fourth plan's last harness change: `harness-self` 2.5 min, its self project (27 files, 4220 tests) in 124 s; `suite-linux` 20 min, `npm test` (106 files, 4565 tests) in 1161 s, the same 28 diagnosed product failures its only failures; `suite-windows` 1 min after it, 3 files, 9 tests; run 915 at 7f59049, the fifth plan's last harness change: `harness-self` 2.5 min, its self project (27 files, 4230 tests) in 126 s; `suite-linux` 20 min, `npm test` (106 files, 4575 tests) in 1195 s, the same 28 diagnosed product failures its only failures, the E-6 writer test passing and `e6-linux-outputs` uploaded (30153 bytes); `suite-windows` 1.5 min after it, 3 files, 9 tests, the drive-mismatch test included; run 923 at 715dff7, the sixth plan's last harness change: `harness-self` 2 min, its self project (27 files, 4230 tests) in 99 s; `suite-linux` 15 min, `npm test` (106 files, 4575 tests) in 880 s, the same 28 diagnosed product failures its only failures, the E-6 writer test passing and `e6-linux-outputs` uploaded (30153 bytes); `suite-windows` 1 min after it, 3 files, 9 tests in 40 s, the drive-mismatch test included; run 933 at 107f624, carrying 7bf3664's trees, the seventh plan's last harness change: `harness-self` 2.5 min, its self project (27 files, 4234 tests) in 128 s; `suite-linux` 15 min, `npm test` (106 files, 4579 tests) in 883 s, the 31 diagnosed product failures (the same 28 plus T11-1, T11-2, and T11-3) its only failures, the E-6 writer test passing and `e6-linux-outputs` uploaded (30153 bytes); `suite-windows` 1 min after it, 3 files, 9 tests in 21 s, the drive-mismatch test included; run 938 at 97c7c24, the eighth plan's last harness change: `harness-self` 2.5 min, its self project (27 files, 4234 tests) in 131 s; `suite-linux` 15.5 min, `npm test` (106 files, 4579 tests) in 906 s, the same 31 diagnosed product failures its only failures, the E-6 writer test passing and `e6-linux-outputs` uploaded (75 files, 30153 bytes); `suite-windows` 1.5 min after it, 3 files, 9 tests in 38 s, the drive-mismatch test included; run 952 at 8b20530, whose harness and product trees are e041cea's, the ninth plan's last harness change: `harness-self` 2.5 min, its self project (27 files, 4236 tests) in 131 s; `suite-linux` 20.5 min, `npm test` (106 files, 4581 tests) in 1220 s, the same 31 diagnosed product failures its only failures, the E-6 writer test passing and `e6-linux-outputs` uploaded (75 files, 30153 bytes); `suite-windows` 1.5 min after it, 3 files, 9 tests in 41 s, the drive-mismatch test included; run 963 at 0ad39cd, whose harness and product trees are b923478's, the tenth plan's last harness change: `harness-self` 2.5 min, its self project (27 files, 4236 tests) in 133 s; `suite-linux` 16.5 min, `npm test` (106 files, 4581 tests) in 987 s, the same 31 diagnosed product failures its only failures, the E-6 writer test passing and `e6-linux-outputs` uploaded (75 files, 30153 bytes); `suite-windows` 1 min after it, 3 files, 9 tests in 24 s, the drive-mismatch test included; run 979 at c88ab04, the eleventh plan's last harness change: `harness-self` 2.5 min, its self project (28 files, 4306 tests) in 114 s; `suite-linux` 12.5 min, `npm test` (107 files, 4651 tests) in 730 s, the same 31 diagnosed product failures its only failures, the E-6 writer test passing and `e6-linux-outputs` uploaded (75 files, 30153 bytes); `suite-windows` 1 min after it, 3 files, 9 tests in 23 s, the drive-mismatch test included; run 992 at bb37aab, the twelfth plan's last harness change: `harness-self` 2.5 min, its self project (28 files, 4311 tests) in 129 s; `suite-linux` 12.5 min, `npm test` (107 files, 4656 tests) in 732 s, the same 31 diagnosed product failures its only failures, the E-6 writer test passing and `e6-linux-outputs` uploaded (75 files, 30153 bytes); `suite-windows` 1 min after it, 3 files, 9 tests in 39 s, the drive-mismatch test included; run 996 at 87d419b, the thirteenth plan's last harness change: `harness-self` 2.5 min, its self project (28 files, 4313 tests) in 130 s; `suite-linux` 19 min, `npm test` (107 files, 4658 tests) in 1129 s, the same 31 diagnosed product failures its only failures, the E-6 writer test passing and `e6-linux-outputs` uploaded (75 files, 30153 bytes); `suite-windows` 1 min after it, 3 files, 9 tests in 30 s, the drive-mismatch test included; run 1001 at 31bae80, the fourteenth plan's last harness change: `harness-self` 2.5 min, its self project (28 files, 4315 tests) in 123 s; `suite-linux` 20.5 min, `npm test` (107 files, 4660 tests) in 1224 s, the same 31 diagnosed product failures its only failures, the E-6 writer test passing and `e6-linux-outputs` uploaded (75 files, 30153 bytes); `suite-windows` 1.5 min after it, 3 files, 9 tests in 39 s, the drive-mismatch test included; run 1203 at 33e7d0b, the 13.5 re-descent plan's (772854b) last harness change: `harness-self` 6 min, its self project (39 files, 4444 tests) in 324 s; `suite-linux` 18.5 min, `npm test` (127 files, 4797 tests) in 1099 s, its 29 diagnosed failures — 28 registered product tests and the E-6 writer test, the built product predating 13.5's revision — its only failures, and no `e6-linux-outputs` artifact (the writer fails before writing one); `suite-windows` 1 min after it, 3 files, 9 tests in 29 s, its 2 diagnosed failures the byte-identity test and the drive-mismatch test's premise; run 1207 at b9eb318, the 092db72 plan's last harness change: `harness-self` 5.5 min, its self project (39 files, 4444 tests) in 316 s; `suite-linux` 25 min, `npm test` (127 files, 4797 tests) in 1474 s, the same 29 diagnosed failures its only failures, and no `e6-linux-outputs` artifact; `suite-windows` 1.5 min after it, 3 files, 9 tests in 42 s, the same 2 diagnosed failures; run 1212 at 6ada37b, the acfff0b plan's last harness change: `harness-self` 6 min, its self project (39 files, 4444 tests) in 325 s; `suite-linux` 25.5 min, `npm test` (127 files, 4797 tests) in 1519 s, the same 29 diagnosed failures its only failures, and no `e6-linux-outputs` artifact; `suite-windows` 1.5 min after it, 3 files, 9 tests in 46 s, the same 2 diagnosed failures; run 1219 at e55a7a1, the 2d9cdf6 plan's last harness change: `harness-self` 4.5 min, with no product installed (no build step), its self project (39 files, 4444 tests) in 246 s; `suite-linux` 25 min, `npm test` (127 files, 4797 tests) in 1476 s, the same 29 diagnosed failures its only failures, and no `e6-linux-outputs` artifact; `suite-windows` 1 min after it, 3 files, 9 tests in 36 s, the same 2 diagnosed failures; the whole run 27 min; run 1224 at a1e6ae5, the f50cf9f plan's last harness change: `harness-self` 4.5 min, with no product installed (no build step), its self project (39 files, 4444 tests) in 243 s; `suite-linux` 25.5 min, `npm test` (127 files, 4797 tests) in 1523 s, the same 29 diagnosed failures its only failures, and no `e6-linux-outputs` artifact; `suite-windows` 1.5 min after it, 3 files, 9 tests in 45 s, the same 2 diagnosed failures; the whole run 27 min; run 1236 at e9a530a, the d0c8039 plan's last harness change: `harness-self` 6 min, with no product installed (no build step), its self project (39 files, 4452 tests) in 330 s; `suite-linux` 24.5 min, `npm test` (127 files, 4805 tests) in 1461 s, the same 29 diagnosed failures its only failures, and no `e6-linux-outputs` artifact; `suite-windows` 1.5 min after it, 3 files, 9 tests in 47 s, the same 2 diagnosed failures; the whole run 26 min; run 1245 at f5f7ab2, the 93e22f1 plan's last harness change: `harness-self` 6 min, with no product installed (no build step), its self project (39 files, 4456 tests) in 326 s; `suite-linux` 27.5 min, `npm test` (127 files, 4809 tests) in 1623 s, the same 29 diagnosed failures its only failures, and no `e6-linux-outputs` artifact; `suite-windows` 1.5 min after it, 3 files, 9 tests in 35 s, the same 2 diagnosed failures; the whole run 29 min; run 1253 at 0c927d8, the affd85f plan's last harness change: `harness-self` 5.5 min, with no product installed (no build step), its self project (39 files, 4460 tests) in 322 s; `suite-linux` 16.5 min, `npm test` (127 files, 4813 tests) in 964 s, the same 29 diagnosed failures its only failures, and no `e6-linux-outputs` artifact; `suite-windows` 1.5 min after it, 3 files, 9 tests in 47 s, the same 2 diagnosed failures; the whole run 18 min; run 1266 at 58361cb, the a71eb0c plan's last harness change: `harness-self` 5.5 min, with no product installed (no build step), its self project (39 files, 4465 tests) in 316 s; `suite-linux` 16 min, `npm test` (127 files, 4818 tests) in 935 s, the same 29 diagnosed failures its only failures, and no `e6-linux-outputs` artifact; `suite-windows` 1 min after it, 3 files, 9 tests in 39 s, the same 2 diagnosed failures; the whole run 17 min; run 1272 at b5ac9a8, the 9bdb418 plan's last harness change: `harness-self` 5.5 min, with no product installed (no build step), its self project (39 files, 4465 tests) in 322 s; `suite-linux` 26 min, `npm test` (127 files, 4818 tests) in 1537 s, the same 29 diagnosed failures its only failures, and no `e6-linux-outputs` artifact; `suite-windows` 1.5 min after it, 3 files, 9 tests in 44 s, the same 2 diagnosed failures; the whole run 27.5 min). A CI log's lines carry a timestamp prefix and ANSI colour codes (Vitest colours its output under `CI`), and its `×` lines carry the bare test title with no `file > ` path, so the failed-ID recipe of the fourth-plan Task 24 bullet (which greps the `×` lines of a local `--reporter=verbose` log for `> ID`) finds nothing on it. On a CI log, strip the colour codes and take the IDs from Vitest's ` FAIL ` summary lines instead: `sed -E 's/\x1b\[[0-9;]*m//g' <log> | grep -E ' FAIL +suite ' | grep -oE '> (T[0-9.]+-[0-9]+|P-[0-9]+) ' | sed -E 's/^> //; s/ $//' | sort -u`. The `suite` project badge keeps out the self project's failures (` FAIL self `, read the same way) and the certification runner's per-pair ` FAIL T…` lines (a violator's expected outcomes, which carry no `> `). Checked on run 33275585205's `suite-linux` log (98 failed): 98 ` FAIL suite ` lines and 97 IDs, the one line without an ID being the E-6 writer test's (`test/suite/e6-exchange-writer.test.ts > E-6 Linux leg: …`); run 642's green log holds no ` FAIL ` summary line at all. In a CI log Vitest's closing summary (`Test Files`, `Tests`, `Start at`, `Duration`) need not follow the last failure block: in run 1253's full-suite log it landed after the 15th of the `Failed Tests` section's 29 blocks (run 1246's came after the last), so a reader of that section takes every ` FAIL ` block through the end of the log rather than stopping at the summary. To confirm that two runs' `suite-linux` logs fail each test at the same first assertion (the plan index's "each at the same first assertion as at …"), strip the colour codes and the timestamp prefix (`^\d{4}-\d\d-\d\dT[0-9:.]+Z ?`) from every line, then for each ` FAIL +suite … > <ID> ` line take the first later line containing `Error:` (its `HarnessAssertionError: …` head) and compare the two logs' heads ID by ID: a short `python3 -I` script under the scratchpad does it in under a second on two ~1 MB logs (runs 1574 and 1576, all 20 shared IDs identical with no masking needed). +- GitHub through this sandbox's proxy (recorded at IP 0002's release): numeric-ID repository paths (`repositories/{id}/...`) get an HTTP 403 that names `repos/{owner}/{repo}/...` instead, and `gh api --paginate` follows next-page links of that numeric-ID form, so fetch each page yourself through the `repos/{owner}/{repo}/...` path with a `page=N` query parameter (with `per_page`), stopping at the first short page. That 403 names a route to the same data, so it is not a refusal. The proxy refuses two things outright, and both are refusals, never worked around: deleting a branch ("Write access to this GitHub API path is not permitted through this proxy.", HTTP 403) and the GitHub Actions secrets API ("Access to this GitHub Actions path is not permitted through this proxy.", HTTP 403). Branch deletion and repository secrets are manual Developer steps (`specs/DEVOPS.md`, Release-phase guidance). +- Escape spellings in tool input (recorded at IP 0002's release): a backslash followed by `u` and four hex digits, or by `u` and a braced code point, typed literally into tool input (Edit, Write, a Bash command, a heredoc, or an inline script) can arrive decoded. During IP 0002's test-plan refinement, an Edit and a committed review silently lost such escapes, and a probe or test whose input lost its escapes checks the wrong text and can pass for the wrong reason. So never type such a sequence literally. Where a file must hold one (a spec, a review, a test, a fixture, or a probe), write those lines with a script that builds the backslash from its code point (Python's `chr(92)`, JavaScript's `String.fromCharCode(92)`), then count the escapes in the written bytes with a pattern built the same way. Treat any other backslash sequence that must reach a file unchanged the same way, and in a report or review name an escaped spelling by file and line, or in words. - Answer-document scale (TEST-SPEC H-11): the suite stages section towers 4096 deep (`NESTING_DEPTHS` in `test/suite/registry/section-16-p8.ts`), past V8's limits in this Node — a plain recursive function gets ~9.9k frames, and `JSON.stringify`/`structuredClone` throw `RangeError` at that nesting while `JSON.parse` is iterative. Harness walks over answer documents therefore use explicit stacks (`decodeViewNodeForm`, `assertUnavailabilityMarkerForms`, `describeJsonValue`'s fallback, and `query.ts`'s `walkForRangeData` and `decodeIdsTreeNode` — `ids --tree` nests one node per section level — in `test/helpers/adapters/`, and the registry modules' own generic JSON walkers, `canonicalJson`, `collectStringLeaves` and `canonicalizeJson` in `test/suite/registry/section-10.*.ts` and `section-12.0-i.ts`); a property reporting `RangeError: Maximum call stack size exceeded` as a harness error names a walk still recursing per level — its `Caused by` frames locate it. To drive a decoder at depth by hand, a temporary self-test (see above) building the document in a loop is enough: 200k-deep `ids --tree` and edge documents decode in well under a second. A walker its module does not export can be exercised the same way as a scratch `.ts` twin of it run under `node --experimental-strip-types` (Node 22); `deriveMdx(source)` answers `{ derives: true }` or `{ derives: false, reason, position? }`. - Staged-scale gates (TEST-SPEC S-2, S-8): `test/self/staged-scale.ts` derives the suite's staged input maxima from what the suite stages, per kind. The generator maximum `LARGEST_GENERATED_INPUT_BYTES` (196,830 bytes: `specs/A.mdx` plus the whole mutation budget of appended depth-4096 towers, built by `largestGeneratedDocument()`) comes from the generators themselves — `NESTING_DEPTHS`, `MAX_MUTATIONS_PER_TRIAL`, `TERMINATOR_SEQUENCES`, `FUZZ_BASE_FILES`, and the byte-exact tower builder `sectionTowerSource(depth, balanced)` exported by `test/suite/registry/section-16-p8.ts` — through `DEEPEST_STAGED_TOWER` (4096) and `TOWER_BYTES` (65,542); a generator bound moves it. The deterministic maximum `LARGEST_DETERMINISTIC_INPUT_BYTES` (4,225,030 bytes: T1.3-7's chained-id tower, `depthTower(DEPTH_FLOOR)` exported by `test/suite/registry/section-1.3.ts`, built by `largestDeterministicDocument()`) is quadratic in `DEPTH_FLOOR` (2048), which alone moves it. `LARGEST_STAGED_INPUT_BYTES` and `largestStagedDocument()` are the larger of the two — today the deterministic one. `test/self/s2-workspace-builder.test.ts` stages the tower, the generator maximum, and the deterministic maximum (the largest document the suite stages, staged as T1.3-7 stages it — `specs/A.mdx` through the declarative `files` path) through the workspace builder and reads each back byte-complete with its structural counts (the input side; its exact-size pins move only when a bound does — update them deliberately), and `test/self/s8-answer-scale-capacity.test.ts` (the answer side, with P-2/P-3's `specSubtreeTexts` oracle) pins each quantity to its closed form, binds every pin to the kind it sizes (the fixed-seed replay bounds and the 500× blowup pin to the generator maximum; the 8× blowup pin to the staged maximum — T1.3-7's largest answer, ~13 MB of `view`, is ~3× its input), replays the fixed CI seed set through `drawFixedSeedTrials(generator, runs)` (`test/helpers/property.ts`; the same per-seed PRNG stream `checkProperty` uses, no property body) to confirm the staged draws stay inside the generator maxima, and drives every H-3/12.7 decoder and answer-document walk on synthetic documents at that scale: a `view` nested 8192 deep (two depth-4096 towers nested by a shuffle mutation) and the `view --text` blowup — two depth-4096 towers whose LF → U+2028 rewrite leaves every level's separators as content, ~204 MB in the `\u2028` spelling. The blowup document is written to a workspace file and streamed to stdout by a stand-in script through `runProduct`, so the test costs ~10 s and holds roughly 0.6–0.8 GB in the Vitest worker (the captured bytes, their UTF-8 string, and the parsed document coexist); run it alone with `npx vitest run --config test/vitest.config.ts --project self test/self/s8-answer-scale-capacity.test.ts`. `DEFAULT_MAX_OUTPUT_BYTES` in `test/helpers/subprocess.ts` (512 MiB) is gated by that test at no less than twice the blowup document — lower it, grow a generator's scale, or grow T1.3-7's `DEPTH_FLOOR` past the 8× pin, and S-8 fails, by design; memory for the cap is committed only as output arrives. S-2's deterministic-maximum vector ("the largest document the suite stages — T1.3-7's 2048-deep chained-id tower") is the slowest builder vector; since 8fc5d11 no Vitest timeout applies to it — every project in `test/vitest.config.ts` sets `testTimeout: 0` (S-3) — where before it ran under Vitest's 5000 ms default: 1.7–1.9 s with its file run alone (`npx vitest run --config test/vitest.config.ts --project self test/self/s2-workspace-builder.test.ts`, under the namespace, at the third plan's FIX_PLAN Task 11; 2.3–2.5 s at the re-descent's second plan's Task 14, 2.3–2.9 s at 44c5dad), 2.4 s inside the full self project at that Task 11 (3.3 s at the second plan's Task 14), and 1.4–1.7 s in CI's harness-self job (runs 873 and 888). Before 8fc5d11 it timed out only under concurrent load (load average ~11 on 4 cores, another run beside it; 3.6 s beside another agent's certification run at cc21726; 5408.9 ms, past the 5000 ms default, inside `npm test` at the twelfth plan's VERIFY (e6b7cb0), three harness runs sharing the machine at a load average of about 14, against 1657–2075 ms with its file run alone, 2038 ms and 1010 ms in CI run 980's harness-self and full-suite jobs, and 2039 ms and 921 ms in run 992's); since 8fc5d11 no Vitest timeout can recur, so a slow run under load is no failure. - Answer-scale timings (TEST-SPEC H-11; `test/suite/registry/section-16-p11.ts`): P-11's per-invocation hang guard (`FUZZ_COMMAND_TIMEOUT_MS`, 300 s since the plan written at 2a2b94e's FIX_PLAN Task 19, 120 s before) is derived in its comment from the largest answer a P-11 draw admits (its body carries no budget since the plan written at 2a2b94e's FIX_PLAN Task 18, the "Hang guards (TEST-SPEC S-3)" bullet below; it had a 20 min `timeoutMs`), measured through `runProduct` against the built product at 20ee9fd on a 4-core machine: `view --text specs/A.mdx` over `FUZZ_BASE_FILES` with `sectionTowerSource(4096, true)` appended twice to `specs/A.mdx` and every LF rewritten to U+2028 emits 58.6 MB and exits in 17.0 s (bare `view --text`: 16.5 s; the same input with LF → U+0020: 9.3 s; `view`, `occurrences`, and `at` at that scale: 1.0–1.5 s; any arm over an unmutated-scale draw: ~0.3 s), and the pinned seed set's 36 trials draw 5 tower trials (sections at most 2048 deep, no terminator rewrite) and 18 `view --text` answer arms, 2 of them over towers — a conforming P-11 sweep runs in ~35 s here. Re-measure with a temporary self-test (pattern above) that stages that input through `TestWorkspace.create`, times `runProduct(builtProductBinding(), { cwd, argv, timeoutMs: 900_000 })`, and prints through `console.info` under `--disable-console-intercept`; count what the pinned seeds stage with `drawFixedSeedTrials(genAvailabilityTrial, 12)` (`test/helpers/property.ts`). Revisit the guard whenever a generator bound (`NESTING_DEPTHS`, `MAX_MUTATIONS_PER_TRIAL`) or the product's answer time at that scale moves. P-8's per-invocation hang guard (`FUZZ_COMMAND_TIMEOUT_MS` in `test/suite/registry/section-16-p8.ts`; 60 s since the re-descent's second plan's FIX_PLAN Task 11, which added `view`, `view --text`, `occurrences`, `at`, `inventory`, `version`, and `query reachable` to P-8's menu — 10 s before) is derived the same way over P-8's own menu forms, and its kill is likewise reported unshrunk (`shrinkable: false`). Measured at that task against the built product (Phase 10's, c62f451) alone under the namespace, each case staging `FUZZ_BASE_FILES` through `TestWorkspace.create`, a staging `build`, then the case's file written `unchecked`, every menu form timed through `runProduct(builtProductBinding(), { cwd, argv, timeoutMs: 900_000 })` (~2.5 min for four cases): P-8's largest answer is `view specs/B.mdx --text` over `specs/B.mdx` with `sectionTowerSource(4096, true)` appended twice, 25.0 MB in 3.8–5.0 s — B's maximum, since the LF → U+2028 rewrite leaves B unparseable (its import line swallows the file; `view specs/B.mdx --text` then answers 478 bytes); every other menu form over either file at that scale, with or without the rewrite, at most 2.4 s (`view specs/A.mdx` 23.7 MB), `inventory` and `version` under 0.4 s; over the unmutated base, ~0.5 s. The same run re-measured P-11's maximum against today's product: `view --text specs/A.mdx` over the two towers with every LF rewritten to U+2028 now emits 125.8 MB in 25.4 s (58.6 MB in 17.0 s at 20ee9fd), so P-11's 120 s guard was then 4.7× its maximum, not the 7× its comment derived (raised to 300 s, at least ten times it, at the plan written at 2a2b94e's FIX_PLAN Task 19, which re-measured 125.8 MB in 16.0–16.4 s; the "Hang guards (TEST-SPEC S-3)" bullet above). The re-descent's second plan's FIX_PLAN Task 13 measured P-8's added forms the same way (a fresh staged workspace per form): the `rename` and file-form `move` previews, the section-form moves performed and previewed (both targets), and `show specs/A.mdx#a --json`, over `specs/A.mdx` or `specs/B.mdx` carrying the two appended balanced 4096-deep towers (A also under the U+2028 rewrite), each exit 1 with the 13.3 gate's report — 4.7 MB as JSON, 1.8 MB human — in at most 2.0 s, and over one or three appended 4096-deep parenthesis towers in `src/app.ts` exit 1 (the workspace fails) in under 0.6 s; `view specs/B.mdx --text` stays P-8's largest answer and the 60 s guard stands. - Checking whether a staged MDX shape is well-formed (SPEC 14.20) before pinning it in a fixture: the harness declares the stock MDX 3 parser as its own devDependencies (`micromark` with `micromark-extension-mdxjs`, `mdast-util-from-markdown` with `mdast-util-mdx` — TEST-SPEC S-9 needs a means independent of the product's `remark-mdx`), so from the repository root `node --input-type=module -e 'import { fromMarkdown } from "mdast-util-from-markdown"; import { mdxjs } from "micromark-extension-mdxjs"; import { mdxFromMarkdown } from "mdast-util-mdx"; fromMarkdown(TEXT, { extensions: [mdxjs()], mdastExtensions: [mdxFromMarkdown()] })'` throws where the stock grammar rejects the shape (bare specifiers resolve from the working directory for `-e`; a script under the scratchpad cannot resolve them) — the product's 14.20 verdict up to its documented widenings of that grammar (`src/core/mdx.ts`). The product's own verdict needs no workspace: a scratch `.mjs` importing `parseSpecSource` (or `specSourceParseFailure`, the verdict alone) from `/home/user/xspec/dist/core/mdx.js` by absolute path prints a text's 14.20 finding or its document model — every section's `range`, `openingTagRange`, and `closingTagRange`, and the findings — in milliseconds (a 4096-deep tower parses in ~0.3 s). JSX tag matching lives in the mdast layer: the tokenizer alone (`postprocess(parse({ extensions: [mdxjs()] }).document().write(preprocess()(TEXT, "utf8", true)))` from `micromark`) accepts an unclosed or mismatched tag that the full parse, and the product, reject. Beware CommonMark's block structure, which the CONF-MD conformer's hand-rolled lexer does not model: a paragraph-continuation line whose first non-whitespace character is `>` interrupts as a block quote whatever its indentation (MDX disables indented code), so a text-context multi-line JSX tag cannot close on a bare `>` line, while a tag opening at line start can (the concrete JSX flow attempt). An ESM block interrupts no paragraph and runs to a blank line: an import line following text without a blank line between is paragraph text, one directly followed by a non-blank line fails acorn, and two imports on one physical line separated by U+2028 or U+2029 derive as one block with a blank line on each side (acorn reads the ECMAScript LineTerminator; automatic semicolon insertion applies). The harness's own entry for that check is `deriveMdx` in `test/helpers/mdx-derivability.ts` (bytes or a string; `{ allowances: [...] }` names the S-9 early-error allowances of `MDX_ALLOWANCES` a source relies on, applied inside the parse so a later rejection still surfaces; the verdict is `{ derives: true }` or `{ derives: false, reason, position? }`); its self-test runs alone, no namespace needed, with `npx vitest run --config test/vitest.config.ts --project self test/self/s9-fixture-well-formedness.test.ts` (~0.5 s); it judges T3-1's and T6.2-3's staged sources verbatim, imported from their registry modules (`REMOVALS_SOURCE` in `test/suite/registry/section-3.ts`; `I3_ROOM_SOURCE` and the two post-move files in `section-6.2.ts`), so a restaging of either fixture is checked by that single file before any product runs (the self project can import registry modules: `defineProductTest` only builds a frozen entry). The workspace builder (`test/helpers/workspace.ts`) applies that same check to every staged file whose path ends in `.mdx`, at staging time (`TestWorkspace.create` and `file()` alike, before the bytes are written): well-formed is the default, and a staging declares the exceptions by workspace-relative path in `mdx: { unparseable: [...], unchecked: [...], allowances: { "<path>": [...] } }` on the `create` declaration (it also governs later `file()` calls on those paths) or per call as `file(path, contents, { mdx: "well-formed" | "unparseable" | "unchecked" | { allowances: [...] } })`; a source contradicting its declaration throws `HarnessStagingError` (mode `mdx-derivability`, the message naming the path and the parser's reason and position) — a harness error the S-7 sweep, the certification runner, and the suite report as such, never a diagnosed product failure and never a skip — so every 14.20 fixture (invalid UTF-8, a byte-order mark, a syntax rejection) needs its `unparseable` entry, every early-error form its allowance, and `unchecked` is only for fuzz mutations and noise files whose derivability TEST-SPEC does not declare (never a way to hide an ill-formed fixture; S-9). The parse is in-process and cheap at the suite's scale (the 4096-deep tower ~0.3 s, the 4.2 MB deterministic maximum ~1.4 s), so no staging is exempted for size; a staging refused inside `create` leaves no temporary directory behind. Its identifier characters — expressions', ESM blocks', JSX element and attribute names', private names', and RegExp group names' — and its whitespace are Unicode 15.1's, judged code point by code point (FIX_PLAN Task 17; S-9, SPEC 14.20): TypeScript 5.9.3's ESNext tables (`ts.isIdentifierStart`/`isIdentifierPart` of `typescript-5.9.3`, equal to Unicode 15.1's ID_Start/ID_Continue), never acorn 8.17's (Unicode 17) nor the runtime's (Unicode 17 on Node 22.22.2) — so an identifier or JSX name holding U+1C89 (a Unicode 16 letter) does not derive, its staging needing an `unparseable` entry, while U+2EBF0 (a 15.1 letter, astral) derives in a JSX element or attribute name as in an expression. acorn's name, private-name, and JSX-name tokens are held to 15.1 as they finish (`Unicode151Parser`), and the MDX tag tokenizer sees each non-ASCII code point inside an open tag through a stand-in of its 15.1 class (`withUnicode151Jsx`, an astral code point read whole from the text at micromark's offset), its rejection messages naming the actual character `(U+XXXX, judged by Unicode 15.1)`; `deriveMdx` throws a plain `Error` — a harness error, never a verdict — on a runtime whose `\s` class is not Unicode 15.1's, since the stock empty-expression judgement reads it. That block of the self-test runs alone with `-t 'Unicode 15.1'` on the file (71 tests, ~1 s, half of it the scan confirming acorn admits every 15.1 identifier character); stashing the helper alone (the red-check recipe above) fails 27 of them. -- Checking whether a staged TypeScript shape — a code source or a configuration file — is well-formed (SPEC 14.20) before pinning it in a fixture (FIX_PLAN Task 14; TEST-SPEC S-9's TypeScript clause): the harness's judge is `judgeTypeScript(source, name)` in `test/helpers/ts-derivability.ts` (bytes or a decoded string, and the file name), which uses `typescript-5.9.3`'s parser at ESNext. A name ending `.tsx` parses as TSX and every other name as plain TypeScript; the parser is given a neutral name of that kind, so a `.d.ts` name is plain TypeScript too, never TypeScript's ambient declaration-file parse. Each text is read twice, as module code and as script code, by forcing the module indicator on and off through `createSourceFile`'s `setExternalModuleIndicator`. Only the parse's own diagnostics count (scanner and parser): no program, binder, or checker is created. Bytes that are not valid UTF-8, or that begin with a byte-order mark, are unparseable (SPEC 1.6). The verdict is `{ verdict: "well-formed" }`, `{ verdict: "unparseable", reason, errors }`, or `{ verdict: "one-way", accepts, reason, errors }`; `errors` lists each reading's diagnostics, each located by UTF-16 index, byte offset, and 1-based line and column. `tsDeclarationProblem(verdict, "well-formed" | "unparseable")` returns the harness error's text, or undefined when the verdict agrees with the declaration. A one-way text is a problem under either declaration; the top-level `await` forms are the cases (`await /re/;` is accepted as module code only, `let a = await / 2 / 1;` as script code only). Quick probe with no build: a scratch `.mts` that imports `judgeTypeScript` from `/home/user/xspec/test/helpers/ts-derivability.ts` by absolute path runs under `node --experimental-strip-types --no-warnings <file>.mts` and prints a verdict in milliseconds. The self-test runs alone, no namespace needed: `npx vitest run --config test/vitest.config.ts --project self test/self/s9-typescript-well-formedness.test.ts` (56 tests, ~2 s with start-up). TypeScript 5.9.3 facts the vectors rely on: it parses `await x` as an await expression outside an await context too, so that text is accepted both ways and left to the checker. It scans U+200B, U+0085, and a non-leading U+FEFF as whitespace. At ESNext it admits U+2EBF0 in identifiers (ES5 does not), but never U+1C89 (TS1127 at its first byte). Its scanner rejects `010` (TS1121) and `09` (TS1489) at the literal's first digit. An invalid `/// <reference …/>` directive (TS1084) is one of the parse's own diagnostics. It accepts `using` and `await using` declarations both ways wherever they stand — at a file's top level too (`using f = () => {};`, `await using h = () => {};`), and inside an async function — so a staging of either form needs no `ts` declaration (FIX_PLAN Task 22's T1.7-2 `src/using.ts` and T4.6-1 arms). The workspace builder (`test/helpers/workspace.ts`) applies this check at staging time (FIX_PLAN Task 15), through the same four stagings as the `.mdx` check (`TestWorkspace.create`'s initial files, `file()`, `edit()`, `copyFrom()`), before the bytes are written: every file whose name ends in one of `TS_DEFAULT_SUFFIXES` (`.ts`, `.tsx`, `.mts`, `.cts`, `.js`, `.jsx`, `.mjs`, `.cjs` — so `.d.ts` names, `xspec.config.ts`, and every `--config` target the suite stages, all named `.ts`) is declared well-formed by default, and a staging declares the exceptions by workspace-relative path (keyed and normalized as the `mdx` declaration's keys) in `ts: { unparseable: [...], unchecked: [...], wellFormed: [...], perDraw: [...] }` on the `create` declaration (it also governs later `file()`, `edit()`, and `copyFrom()` stagings of those paths) or per call as `file(path, contents, { ts: "well-formed" | "unparseable" | "unchecked" | "per-draw" })` (`perDraw` and `"per-draw"` since FIX_PLAN Task 16o: a property draw's composed configuration or code source, judged well-formed at staging and exempt from the undeclared-staging guard's TypeScript arm, section-16 modules only); a path in two lists is refused at creation. `unparseable` is for a file TEST-SPEC declares unparseable or malformed (T1.6-5's encodings, T7-2's syntax-error and encoding configurations, T11.6-4's, T12.6-2's, and T12.7-3's malformed configurations, T14-3's and T14-5's TSX-only constructs, T14-11's (m) and (v) code sources, every code-source arm of T14-12 wherever it is staged — `unparseableDecl` and T14-11's `reassertedCase` derive it from the arm's `kind`), `unchecked` for one whose well-formedness the document does not declare (P-8's and P-11's mutated code sources and configuration, T13.4-2's truncated and garbage-overwritten derived files, T13.4-4's noise at the generated module's path, and since FIX_PLAN Task 16i T7.5-6's tampered generated module — product-written bytes plus a harness comment, staged by `file()` with `{ ts: "unchecked" }`, and since FIX_PLAN Task 16l T12.2-2's and T12.2-4 (a)'s likewise), and `wellFormed` for a code source whose name the default does not reach (a code group globs any name: §11.4's `docs/impl.mdx` — T2.1-2's `docs/EXTRA.mdx` carries its declaration in its MDX record's `ts` since FIX_PLAN Task 16b, T7.3-1's `specs/A.md` (well-formed) and T7-6's `specs/a'b.md` holding `)` (`unparseable`) are `StagedTs` records carrying theirs since FIX_PLAN Task 16h, and T7.5-5's `src/end$` and `src/end` share one well-formed `StagedTs` record (`CODE_MARKER_TO_P`) since FIX_PLAN Task 16i, and T13.4-11(b)'s `specs/A.md` is a well-formed `StagedTs` record since FIX_PLAN Task 16l, a record making its path judged). A contradiction — and a text accepted read one way only, under any declaration but `unchecked` — throws `HarnessStagingError` (mode `ts-derivability`, naming the path, the verdict's first TypeScript error, and the remedy), a harness error the S-7 sweep, the certification runner, and the suite report as such; `tsDeclarationOf(path)` reads back the declaration in effect (undefined for a path nothing judges), and `judgeTsDeclaration(key, bytes, declaration)` is the one code path. The S-2 self-test (`test/self/s2-workspace-builder.test.ts`, 21 tests) carries the builder's TypeScript vectors. Finding every staging a builder check judges in one pass, instead of one harness error per run: temporarily make the private `checkTs` (or `checkMdx`) append one JSON line per judged staging — path, declaration, the judge's verdict, `this.invocationMark.invoked`, and the running body's ID (`product-invocations.ts` keeps it in an `AsyncLocalStorage`; export a getter for the run) — to a scratch file and return instead of throwing, run the self project (S-7's sweep reaches every body's pre-invocation stagings) and the suite once each, and revert the edit. The staged-source ledger covers TypeScript through its TypeScript records (the bullet on them below; FIX_PLAN Task 16), the undeclared-staging guard through its TypeScript arm (Task 16o), and the property runner's per-draw check judges each draw's generated code sources and configurations before the body runs (Task 64; the per-draw bullet below) — P-7's capture sources among them, whose names the default does not reach: the capture arm's `drawSources` marks each `"code-source"`, and its body lists them in `ts.perDraw`, so the builder judges them at staging too. +- Checking whether a staged TypeScript shape — a code source or a configuration file — is well-formed (SPEC 14.20) before pinning it in a fixture (FIX_PLAN Task 14; TEST-SPEC S-9's TypeScript clause): the harness's judge is `judgeTypeScript(source, name)` in `test/helpers/ts-derivability.ts` (bytes or a decoded string, and the file name), which uses `typescript-5.9.3`'s parser at ESNext. A name ending `.tsx` parses as TSX and every other name as plain TypeScript; the parser is given a neutral name of that kind, so a `.d.ts` name is plain TypeScript too, never TypeScript's ambient declaration-file parse. Each text is read twice, as module code and as script code, by forcing the module indicator on and off through `createSourceFile`'s `setExternalModuleIndicator`. Only the parse's own diagnostics count (scanner and parser): no program, binder, or checker is created. Bytes that are not valid UTF-8, or that begin with a byte-order mark, are unparseable (SPEC 1.6). The verdict is `{ verdict: "well-formed" }`, `{ verdict: "unparseable", reason, errors }`, or `{ verdict: "one-way", accepts, reason, errors }`; `errors` lists each reading's diagnostics, each located by UTF-16 index, byte offset, and 1-based line and column. `tsDeclarationProblem(verdict, "well-formed" | "unparseable")` returns the harness error's text, or undefined when the verdict agrees with the declaration. A one-way text is a problem under either declaration; the top-level `await` forms are the cases (`await /re/;` is accepted as module code only, `let a = await / 2 / 1;` as script code only). Quick probe with no build: a scratch `.mts` that imports `judgeTypeScript` from `/home/user/xspec/test/helpers/ts-derivability.ts` by absolute path runs under `node --experimental-strip-types --no-warnings <file>.mts` and prints a verdict in milliseconds. The self-test runs alone, no namespace needed: `npx vitest run --config test/vitest.config.ts --project self test/self/s9-typescript-well-formedness.test.ts` (121 tests since FIX_PLAN Task 5 of the plan written at e57210b, P-19 adding seven generated vectors, ~12 s with start-up, most of it importing the registry). TypeScript 5.9.3 facts the vectors rely on: it parses `await x` as an await expression outside an await context too, so that text is accepted both ways and left to the checker. It scans U+200B, U+0085, and a non-leading U+FEFF as whitespace. At ESNext it admits U+2EBF0 in identifiers (ES5 does not), but never U+1C89 (TS1127 at its first byte). Its scanner rejects `010` (TS1121) and `09` (TS1489) at the literal's first digit. It accepts both ways T7-2's string-literal import names (`import { "defineConfig" as d } from "xspec"`, and its twin with the name's `C` written as a hexadecimal escape), an export assignment (`export = defineConfig({…})`), and an import assignment (`import defineConfig = require("xspec")`). It rejects both ways, each with exactly one scanning error, T7-9(b)'s four specifiers: a hexadecimal escape with one digit (TS1125, three code units past the backslash, where the second digit is due), a braced Unicode escape of the code point 110000 hexadecimal (TS1198, at the value's first digit), an octal escape of backslash, `0`, `1` (TS1487), and a backslash before `8` (TS1488), the last two at the backslash. The self-test's `T7_9_B_SPECIFIERS` table holds these four, each backslash built from U+005C, so the file's source spells none. An invalid `/// <reference …/>` directive (TS1084) is one of the parse's own diagnostics. It accepts `using` and `await using` declarations both ways wherever they stand — at a file's top level too (`using f = () => {};`, `await using h = () => {};`), and inside an async function — so a staging of either form needs no `ts` declaration (FIX_PLAN Task 22's T1.7-2 `src/using.ts` and T4.6-1 arms). The workspace builder (`test/helpers/workspace.ts`) applies this check at staging time (FIX_PLAN Task 15), through the same four stagings as the `.mdx` check (`TestWorkspace.create`'s initial files, `file()`, `edit()`, `copyFrom()`), before the bytes are written: every file whose name ends in one of `TS_DEFAULT_SUFFIXES` (`.ts`, `.tsx`, `.mts`, `.cts`, `.js`, `.jsx`, `.mjs`, `.cjs` — so `.d.ts` names, `xspec.config.ts`, and every `--config` target the suite stages, all named `.ts`, but T7-10(e)'s `xspec.config.mdx`, an MDX record carrying its TypeScript declaration) is declared well-formed by default, and a staging declares the exceptions by workspace-relative path (keyed and normalized as the `mdx` declaration's keys) in `ts: { unparseable: [...], unchecked: [...], wellFormed: [...], perDraw: [...] }` on the `create` declaration (it also governs later `file()`, `edit()`, and `copyFrom()` stagings of those paths) or per call as `file(path, contents, { ts: "well-formed" | "unparseable" | "unchecked" | "per-draw" })` (`perDraw` and `"per-draw"` since FIX_PLAN Task 16o: a property draw's composed configuration or code source, judged well-formed at staging and exempt from the undeclared-staging guard's TypeScript arm, section-16 modules only); a path in two lists is refused at creation. `unparseable` is for a file TEST-SPEC declares unparseable or malformed (T1.6-5's encodings, T7-2's syntax-error and encoding configurations, T11.6-4's, T12.6-2's, and T12.7-3's malformed configurations, T14-3's and T14-5's TSX-only constructs, T14-11's (m) and (v) code sources, every code-source arm of T14-12 wherever it is staged — `unparseableDecl` and T14-11's `reassertedCase` derive it from the arm's `kind`), `unchecked` for one whose well-formedness the document does not declare (P-8's and P-11's mutated code sources and configuration, T13.4-2's truncated and garbage-overwritten derived files, T13.4-4's noise at the generated module's path, and since FIX_PLAN Task 16i T7.5-6's tampered generated module — product-written bytes plus a harness comment, staged by `file()` with `{ ts: "unchecked" }`, and since FIX_PLAN Task 16l T12.2-2's and T12.2-4 (a)'s likewise), and `wellFormed` for a code source whose name the default does not reach (a code group globs any name: §11.4's `docs/impl.mdx` — T2.1-2's `docs/EXTRA.mdx` carries its declaration in its MDX record's `ts` since FIX_PLAN Task 16b, T7.3-1's `specs/A.md` (well-formed) and T7-6's `specs/a'b.md` holding `)` (`unparseable`) are `StagedTs` records carrying theirs since FIX_PLAN Task 16h, and T7.5-5's `src/end$` and `src/end` share one well-formed `StagedTs` record (`CODE_MARKER_TO_P`) since FIX_PLAN Task 16i, and T13.4-11(b)'s `specs/A.md` is a well-formed `StagedTs` record since FIX_PLAN Task 16l, a record making its path judged). A contradiction — and a text accepted read one way only, under any declaration but `unchecked` — throws `HarnessStagingError` (mode `ts-derivability`, naming the path, the verdict's first TypeScript error, and the remedy), a harness error the S-7 sweep, the certification runner, and the suite report as such; `tsDeclarationOf(path)` reads back the declaration in effect (undefined for a path nothing judges), and `judgeTsDeclaration(key, bytes, declaration)` is the one code path. The S-2 self-test (`test/self/s2-workspace-builder.test.ts`, 21 tests) carries the builder's TypeScript vectors. Finding every staging a builder check judges in one pass, instead of one harness error per run: temporarily make the private `checkTs` (or `checkMdx`) append one JSON line per judged staging — path, declaration, the judge's verdict, `this.invocationMark.invoked`, and the running body's ID (`product-invocations.ts` keeps it in an `AsyncLocalStorage`; export a getter for the run) — to a scratch file and return instead of throwing, run the self project (S-7's sweep reaches every body's pre-invocation stagings) and the suite once each, and revert the edit. The staged-source ledger covers TypeScript through its TypeScript records (the bullet on them below; FIX_PLAN Task 16), the undeclared-staging guard through its TypeScript arm (Task 16o), and the property runner's per-draw check judges each draw's generated code sources and configurations before the body runs (Task 64; the per-draw bullet below) — P-7's capture sources among them, whose names the default does not reach: the capture arm's `drawSources` marks each `"code-source"`, and its body lists them in `ts.perDraw`, so the builder judges them at staging too. - Task 46's malformed-value arms (T12.0-5's U+FFFD table and normalization negatives in `test/suite/registry/section-12.0-i.ts`, T6.5-5's destination arms in `test/suite/registry/section-6.5.ts`) red/green-check through the same scratch wrapper with three interventions on the argv before the spawn — `accept` strips U+FFFD from every argument (caught at the first malformed arm's exit code: the stripped invocation succeeds, or on `move` refuses with exit 1), `loadconf` prints a `configuration-error` document and exits 2 whenever the working directory's `xspec.config.ts` is the unknown-key twin and an argument holds U+FFFD (caught at the invalid twin's `code`-null pin inside `expectSyntaxClassUsageError`), and `normalize` rewrites a `./specs/A.mdx` or `specs//A.mdx` `show`/`view` operand to `specs/A.mdx` (caught at the `./` arm) — ~30 s per test as root (no permission staging is involved), `raw` passing both tests whole. A wrapper receives non-UTF-8 argv bytes already decoded to U+FFFD by Node's `process.argv`, so it can delegate the Linux byte arms but never forward them byte-exact: hand-drive those directly against `dist/cli/bin.js` with `$'a.m\377d'` quoting (and `$'\357\277\275'` for U+FFFD), which the built product answers with `argument N is not valid UTF-8`, `code` null, identically with the configuration invalid. - Task 47's syntax-class rows (T12.0-10's `T12_0_10_SYNTAX_ROWS` in `test/suite/registry/section-12.0-ii.ts`) green-check through the same scratch wrapper with a rule rather than a rewrite: a `conform` mode that answers six argv shapes with the plain usage error document (`code` and `path` null, one stderr line) without spawning the product — `--preview` beside `--test-hold`, a `review … --name` value beginning with `.`, an `occurrences --to` value holding whitespace (the row's value since the plan written at 2a2b94e, FIX_PLAN Task 103, is `a.mdx#x\y`, its id segment carrying the escape character), a `--tag` value holding the escape character, a `--file` value beginning with `../`, and an `at` third operand that is not decimal digits — and spawns the product for everything else; driven through `runProductTests(binding, productTestSuite.select(["T12.0-10"]), { concurrency: 1 })` from a temporary self-test (deleted before committing) it passes the whole test in ~13 s as root (no permission staging is involved), while `raw` fails diagnosed at the `--test-hold` row within ~10 s — from the plan written at 2a2b94e's FIX_PLAN Task 104 until the e049255 plan's FIX_PLAN Task 10 the body's last arm, past the gate, failed the built product at T10.1-4's decomposed-item state, so a green check of the syntax rows read that one failure there (every syntax row runs before it); since that task the built product passes T12.0-10 whole (51.7 s beside `section-10.1`). Against the built product those six shapes are the diagnosed failures: the first five load configuration before the syntax check (14.14 on both configuration-state twins), and `at`'s offset spelling is judged after the configuration search but before the parse — the plain `+7` error under an invalid configuration, 14.14 with `path` `"."` under none — while its argument count precedes the search; every other row of the table, `view <file> --file` and the `query nodes --group <code-group>` precedence arm included, passes as pinned. Since Phase 10 FIX_PLAN Task 44 all six pass against the built product: the parser judges them before the configuration is located. - Task 49's T12.2-4 (`test/suite/registry/section-12.1-12.2.ts`) green/red-checks through the same scratch-wrapper pattern (a temporary `test/self/*.test.ts` binding `{ command: process.execPath, prefixArgs: [wrapper, mode, binJs] }` through `runProductTests`, deleted before committing): the wrapper spawns the product and rewrites only `check --json` on a workspace failing build's validations (a finding whose code is not `stale-output`, `policy-violation`, or `corrupt-session` present) — `conform` drops the `policy-violation` the product reports there, adds the unit-form `stale-output` (path `.xspec`, locations []) when `.xspec/graph.json` is present but unparseable, and adds one `stale-output` per `extra/E.xspec.*` file when `xspec.config.ts` lacks the `extra:` group (arm (b)'s orphans), re-sorting the array by condition ordinal (12.7); the whole test then passes in ~5 s, while `keep-policy` (the product's real answer), `no-orphans`, `no-unit`, `mismatch-beside` (a per-file 14.10 for `hi/H.xspec.ts`), and `unit-located` (the unit form naming `.xspec/graph.json`) are each caught at their own arm's assertion. @@ -169,11 +192,19 @@ Build, test, and run instructions for this repository (nothing else belongs in t - T6.6-4's tie-break stagings (FIX_PLAN Task 41; `test/suite/registry/section-6.6.ts`, arm (e) over section-6.5-iii.ts's exported `A13_TIE_BREAK_ARMS` — T6.5-13's (b), (d), (d, terminated), and (g) under `R16_CONFIG`, the exported `a13ReadAddedIdentifiers` reading the fresh identifiers): run alone with `-t 'T6.6-4 '` on `test/suite/section-6.6.test.ts` (~4 s to its diagnosed failure against the built product, arms (a) through (d) passing first). Observed against the built product: every tie-break arm fails at `assertTieBreakEntry` — the preview reports the `import-addition` at [0, 0) (the offset-0 placement) where the pins are the tag's end, [12, 12), for (b) and (g) and the file's end, [4, 4) and [5, 5), for (d) and (d, terminated), and for (g) one `import-addition` entry for the two added declarations; with that call commented out, (b) fails at the byte contract (the product's `specs/b.mdx` reads `import x from "./x.xspec"`, U+000A, the paired form, `</S>` with no final terminator). Each arm is reached through the table-driven filter variant (`A13_TIE_BREAK_ARMS.filter((arm) => arm.key === "(g)")` on the `for` line, the file restored from a scratch `.bak` copy and `cmp`-checked after each run). The stand-in red/green check (a scratch `task41-standin.mjs`, mode first on its argv, driven by a temporary `test/self/zz-task41-standin.test.ts` calling `runProductTests` over the one entry per mode under `--disable-console-intercept`, deleted before committing): the temporary test dumps the table to a scratch `task41-arms.json` (each arm's files, argv, receiving, added, the composed forms for the fixed identifiers `x1`/`y1`, others, receivingEdits, origin, movedConstruct, movedIdAttribute, embeddings), and the wrapper, on a `move` whose operands and every staged file match a dumped arm, answers `--preview --json` with the product's document whose `files` are replaced by the plan it composes itself from the dumped bytes (ASCII fixtures, so char index = byte offset) and, on the real `move`, lets the product perform it, then writes the receiving file's composed form and the other files' bytes and re-runs the real `build`; `conform` passes the whole T6.6-4 in ~10 s (as root; no permission staging is involved), while `swap` (`target-insertion` before `import-addition` at one offset) is caught at the form-exact preview decode's order check, `one` ((g)'s two additions reported as one) at (g)'s tie-break entry, `offset0` (the addition at [0, 0)) at (b)'s, `noref` (the origin's `reference-rewrite` dropped) at the whole-plan compare on `specs/a.mdx`, and `bytes` (the product's real bytes kept) at (b)'s byte contract; `raw` fails diagnosed as the product does. The five red modes take ~30 s together. - T6.6-4(a)'s twice-spelled `d` array (the plan written at 2a2b94e, FIX_PLAN Task 53; `test/suite/registry/section-6.6.ts`): arm (a)'s `specs/Core.mdx` (`A4_CORE_SOURCE`, a plain string — the body's first workspace, staged before any invocation, so no staged-source record) holds `<S id="core.twice" d={["core.mid", "core.mid"]}>` between `core.sib` and `core.plain`, and `armAPlan` expects a `reference-rewrite` at each of its two entries, located by `spansWithin(source, container, fragment, count, where)` (every occurrence of a fragment inside a unique container, its count a staging premise: another count or an overlap throws a plain staging error, never a product failure). Against the built product T6.6-4 passes alone through the scratch runner of the bullet beginning "Red-checking a strengthened product test" (10.4 s; 9.7 s before the arm), the preview reporting the two entries at `specs/Core.mdx` [264, 274) and [276, 286), its human form listing them as `264-274 reference-rewrite` and `276-286 reference-rewrite`. Red checks through a stand-in passing the product's streams and exit code through and rewriting only `rename specs/Core.mdx core.mid core.hub --preview --json`'s `specs/Core.mdx` edits inside the array (keyed on the operands and the staged `d={["core.mid", "core.mid"]}`): the second entry's edit dropped (one per edge), moved onto the first entry, or the pair replaced by one edit spanning the array literal or the whole prop each fail at arm (a)'s `specs/Core.mdx` exact edit-list compare (~1 s); the `--json` document kept and the human report's `276-286` line dropped fails at the human-report check (`Missing: number 276, number 286`); the unperturbed stand-in passes (11.0 s). - T7-2's import-modifier arms (re-descent FIX_PLAN Task 48; the last four rows of `FORM_VIOLATIONS` in `test/suite/registry/section-7-basics.ts`, their records named `T7-2 xspec.config.ts (a type-only import clause: …)`, `(a type-only import specifier: …)`, `(a deferred import: …)`, and `(import attributes: …)`, each declared well-formed): against the built product T7-2 fails diagnosed at the `import defer { defineConfig } from "xspec"` arm alone — the product loads that configuration and builds (exit 0, `{"findings": []}`) — while it refuses the type-clause, type-specifier, and attributes arms with `configuration-error`, exit 2 (`-t 'T7-2 '` on `test/suite/section-7-basics.test.ts`, ~12 s under the namespace; the whole file, three tests, ~42 s, T7-1 and T7-3 passing). To see that the `defer` arm is the only failure, drop its row from a scratch-backed copy of the module and rerun `-t 'T7-2 '`: the rest of T7-2 then passes whole; restore the module from the copy and `cmp` it. Since the re-descent's Phase 10 FIX_PLAN Task 11 (plan written at 0614030) the product refuses the `defer` arm too (exit 2, `configuration-error`), and T7-2 passes whole. +- T7-2's wrapped forms and call variants (TEST-SPEC T7-2, S-9; FIX_PLAN Task 39 of the plan written at e57210b): nine rows of `FORM_VIOLATIONS` in `test/suite/registry/section-7-basics.ts`, between the numeric-literal key's row and the four import-modifier rows, their records named `T7-2 xspec.config.ts (the call wrapped: …)` (`satisfies object`, parenthesized, a non-null assertion), `(the argument wrapped: …)` (`as const`, parenthesized), `(a value inside the argument wrapped: …)` (`markdown: { emit: true as boolean }`, `specs: ({…})`), and `(the call spelled outside 7's list: …)` (`defineConfig<object>({…})`, `defineConfig?.({…})`), each the canonical configuration with one deviation (the `as boolean` arm's valid twin has `markdown: { emit: true }`) and declared well-formed (`judgeTypeScript` accepts all nine both ways). Alone against the built product T7-2 passes whole (`-t 'T7-2 '` on `test/suite/section-7-basics.test.ts`, 10.7 s of test, 18.4 s wall): it refuses all nine with `configuration-error`, exit 2. Red-checked through the scratch-wrapper pattern (bullet beginning "Red-checking a strengthened product test"), one mode per arm: the wrapper rewrites `xspec.config.ts` in its working directory to the selected arm's unwrapped twin before spawning `dist/cli/bin.js` (restoring the bytes after), as a product skipping outer expressions would load it; ten modes in 52.9 s of test, each perturbing mode failing T7-2 diagnosed at its own arm's exit-code assertion (exit 0 where 2 is due), the passthrough mode passing. +- T7-2's binding forms (TEST-SPEC T7-2, S-9; FIX_PLAN Task 40 of the plan written at e57210b): five rows of `FORM_VIOLATIONS` in `test/suite/registry/section-7-basics.ts`, between the wrapped forms' rows and the four import-modifier rows, their records named `T7-2 xspec.config.ts (an escape-spelled string-literal import name: …)`, `(a default import: …)`, `(a namespace import: …)`, `(an extra default binding: …)`, and `(an extra named binding: …)`, each declared well-formed; and one loading arm, run after the aliased-import arm, over `STRING_IMPORT_NAME_CONFIG` (`import { "defineConfig" as d } from "xspec"`) and its identifier-named twin `IDENTIFIER_IMPORT_NAME_CONFIG`. `bindingFormConfig(importName)` composes those two and the escape-spelled row, so the three files differ in the import name alone. The two views are compared through the module-level `configurationViewOf(product, config, label)` (`build` exit 0, then the `configuration` member of `inventory --json`) and `assertConfigurationViewsIdentical` (as values and as serializations), which the comments arm now shares. `BACKSLASH` now stands at the head of the T7-2 section, before `FORM_VIOLATIONS`: defined at its old place, after the table, it would be in its temporal dead zone when the table is built at module load. A module-load self-check pins the escape-spelled name: one backslash, then `x43`, right after the quote and `define`, decoding to the string literal `"defineConfig"`; the staged record's first line holds exactly one 0x5C byte (checked by a scratch probe of `stagedTsLedger()`). `s9-staged-sources` passes 4076 of 4076, the seven new records judged well-formed both ways. Alone against the built product T7-2 passes whole (`-t 'T7-2 '` on `test/suite/section-7-basics.test.ts`, 12.1 s of test, 20.0 s wall): it refuses the five rows with `configuration-error`, exit 2, and loads the string-literal import name with a view identical to its twin's. Red-checked through the scratch-wrapper pattern (bullet beginning "Red-checking a strengthened product test"), eight modes in 57.6 s of test. Five modes each rewrite `xspec.config.ts` from one refused row's bytes to its valid twin before spawning `dist/cli/bin.js`, restoring the bytes after: the escape-spelled name to the string-literal one, the other four to the canonical file. Each fails T7-2 diagnosed at its own row's exit-code assertion (exit 0 where 2 is due). One mode rewrites the string-literal name's file to the escape-spelled one, which the product refuses: `build` exits 2 where 0 is due. One changes the glob in the string-literal name's `inventory` view and fails the byte-identical comparison. The passthrough mode passes. The wrapper builds its backslash and line feeds from their code points. +- T7-2's statement forms and statement order (TEST-SPEC T7-2, S-9; FIX_PLAN Task 41 of the plan written at e57210b): two rows of `FORM_VIOLATIONS` in `test/suite/registry/section-7-basics.ts`, after the four import-modifier rows (TEST-SPEC's order), their records named `T7-2 xspec.config.ts (a statement form: an export assignment, …)` (`export = defineConfig({…})` beside `import { defineConfig } from "xspec"`) and `(a statement form: an import assignment, …)` (`import defineConfig = require("xspec")` beside `export default defineConfig({…})`), each the canonical configuration with one deviation and declared well-formed (`judgeTypeScript` accepts both both ways); and one loading arm, run after the binding forms' loading arm, over `STATEMENT_ORDER_CONFIG` (`export default defineConfig({…})`, then `import { defineConfig } from "xspec"`) against its import-first twin, the canonical `SPECS_ONLY_CONFIG` itself (its record now named `T7-1/T7-2/T7-3 xspec.config.ts (the canonical configuration: …)`). `twoStatementConfig(first, second)` composes a file from `CANONICAL_IMPORT_STATEMENT` and `CANONICAL_EXPORT_STATEMENT` in the order given, and a module-load self-check pins the import-first composition to the canonical text, so the pair differs in the statements' order alone. `configurationViewOf(product, config, label, { check: true })` runs `check` after `build`, both held to exit 0, before reading `inventory`'s `configuration`; among T7-2's arms the statement-order arm alone asks for it (T7-1's configuration-name arms and their twin ask for it too, beside a `configPath`; bullet beginning "T7-1's configuration file names"). `s9-staged-sources` passes 4079 of 4079. Alone against the built product T7-2 passes whole (`-t 'T7-2 '` on `test/suite/section-7-basics.test.ts`, 14.6 s of test, 23.0 s wall): it refuses both statement forms with `configuration-error`, exit 2, and loads the export-first file (`build` and `check` exit 0) with a view identical to its twin's. Red-checked through the scratch-wrapper pattern (bullet beginning "Red-checking a strengthened product test"), seven modes in 67.5 s of test. Two modes each rewrite one statement form's bytes to the canonical file before spawning `dist/cli/bin.js`, restoring the bytes after; each fails T7-2 diagnosed at its own row's exit-code assertion (exit 0 where 2 is due). Two rewrite the export-first file to the export-assignment file, which the product refuses: for every command (`build` exits 2 where 0 is due), and for `check` alone (`check` exits 2 where 0 is due). Two perturb the export-first file's `inventory` view, one changing its glob and one reversing its members' order; each fails the byte-identical comparison. The passthrough mode passes. The wrapper builds its line feeds from their code point. +- T7-2's keys and enumerated values read as spelled (TEST-SPEC T7-2, S-9; FIX_PLAN Task 42 of the plan written at e57210b): in `test/suite/registry/section-7-basics.ts`, run after the verbatim group name's arms and before the encoding arms, two refused tables made by `refusedConfigArms` — `SPELLED_KEY_VIOLATIONS` (the string-literal top-level key `specs` with its `s` written as the hexadecimal escape of U+0073; a profile's `mode` `direct` with its `d` written as that of U+0064) and `SPELLED_IDENTIFIER_KEY_VIOLATIONS` (the identifier key `specs` with its `s` written as the Unicode escape of U+0073; the verbatim group name keyed as an identifier under `target: "product"`), their records named `T7-2 xspec.config.ts (keys read as spelled: …)`, `(enumerated values read as spelled: …)`, and `(identifier keys read as spelled: …)` — and three loading arms: `expectTwoSpelledGroups` over `STRING_KEYS_TWO_GROUPS_CONFIG` and `IDENTIFIER_KEYS_TWO_GROUPS_CONFIG` (`ab` beside `ab` with its `b` escaped, globbing `a/*.mdx` and `b/*.mdx` over `SECTION_A_SOURCE` at `a/A.mdx` and `SECTION_B_SOURCE` at `b/B.mdx`, both records renamed to list those paths; `build` exit 0, then `inventory`'s `configuration.specs` and `sources` compared exactly), and `expectVerbatimGroupNameResolves` over `IDENTIFIER_NAME_CONFIG` (the string-literal group-name arm now runs through the same helper). `verbatimNameConfig(groupKey, target)` takes the key's spelling (`VERBATIM_GROUP_STRING_KEY` for the string-literal records, whose bytes are unchanged), and `canonicalWithSpecsKey(key)` composes the canonical file with its top-level key spelled `key`. Every escape is built from `BACKSLASH` through `checkedEscapeSpelling(spelled, escapeText, character, decoded)`, which throws at module load unless the spelling holds one backslash followed by the escape's text, the escape designates the character, and the spelling decodes to the given twin; a second module-load check pins `canonicalWithSpecsKey("specs")` to the canonical text and the new files' backslash counts (1, 1, 1, 2, 3, 1, 1). `s9-staged-sources` passes 4086 of 4086, the seven new records judged well-formed both ways, and a ledger probe (a temporary self-test filtering `stagedTsLedger()` after importing the registry) showed each escape in the staged bytes exactly as TEST-SPEC line 330 spells it. Alone against the built product T7-2 passes whole (`-t 'T7-2 '` on `test/suite/section-7-basics.test.ts`, 24.1 s of test, 37.7 s wall; 28.4 s and 42.1 s in the first run after a container restart): it refuses the four new rows with `configuration-error`, exit 2, loads both two-group files with both groups reported as spelled, and resolves the identifier-keyed group. Red-checked through the scratch-wrapper pattern (bullet beginning "Red-checking a strengthened product test"), eleven modes in 91.3 s of test, three at a time (`Promise.all` over three workers in the temporary self-test). Seven modes rewrite `xspec.config.ts` before spawning `dist/cli/bin.js`, restoring the bytes after. Decoding a refused row's one escape fails T7-2 diagnosed at that row's exit-code assertion (exit 0 where 2 is due), for each of the four rows (the identifier-keyed group's row with every escape in its file decoded). Decoding a two-group file's escaped `b` makes the product refuse a repeated key (`build` exits 2 where 0 is due), for both files. Decoding the identifier key alone in the identifier-keyed group's files leaves its refusal standing (the boundary, still escape-spelled, names no group) and makes its resolving twin's `build` exit 2 where 0 is due. Three modes perturb an `inventory` answer — the string-literal two-group file's second group renamed `ab`, the identifier two-group file's sources swapped between its groups, the identifier-keyed group renamed `product` — and each fails the assertion it targets. The passthrough mode passes. The wrapper builds its backslash and line feeds from their code points. +- T7-2's comments inside the import declaration (TEST-SPEC T7-2, S-9; FIX_PLAN Task 43 of the plan written at e57210b): `COMMENTED_CONFIG` in `test/suite/registry/section-7-basics.ts` (its record still `T7-2 xspec.config.ts (comments)`, declared well-formed) spells its import declaration as TEST-SPEC line 330 does — `/* c */` between `import` and `{`, `{` and `defineConfig`, `defineConfig` and `}`, and `}` and `from`; `// c` after `from`, its line feed putting `"xspec"` on the next line; `/* c */` after the specifier — and the one comments arm still compares its `inventory` `configuration` view with the unchanged `COMMENT_FREE_CONFIG`'s. `s9-staged-sources` passes 4086 of 4086. Alone against the built product T7-2 passes whole (`-t 'T7-2 '` on `test/suite/section-7-basics.test.ts`, 23.2 s of test, 34.7 s wall): the product loads the commented file, its view identical to the twin's. Red-checked through the scratch-wrapper pattern (bullet beginning "Red-checking a strengthened product test"), three modes in 79.3 s of test, each acting only where the working directory's `xspec.config.ts` holds `/*` or `//` between `import` at a line's start and `"xspec"`: making that file unparseable before spawning `dist/cli/bin.js` (a closing parenthesis appended on a line of its own, the bytes restored after) fails T7-2 diagnosed at the comments arm's `build` (exit 2 where 0 is due), and keeping only the first glob in its `inventory` view fails the byte-identical comparison; the passthrough mode passes. Before the change both perturbing modes passed T7-2 (57.8 s of test). The wrapper builds its line feeds from their code point. +- T7-1's configuration file names (TEST-SPEC T7-1, S-9; FIX_PLAN Task 44 of the plan written at e57210b): `runConfigurationNameArms` in `test/suite/registry/section-7-basics.ts`, which T7-1's body runs after the occupancy arms and before the name-casing probe (still last), drives `CONFIG_NAME_ARMS` in TEST-SPEC's order — `xspec.config.mts`, `xspec.config.cts`, `xspec.config.tsx` — each through `configurationViewOf(product, record, label, { check: true, configPath: name })`: the record staged at that root path alone beside `specs/A.mdx` (no `xspec.config.ts`), and `build`, `check`, and `inventory --json` each given `--config <name>` and held to exit 0. The twin follows, `SPECS_ONLY_CONFIG` driven the same way with `configPath: "xspec.config.ts"`, and each arm's `configuration` view is then compared with the twin's (`assertConfigurationViewsIdentical`). Without `configPath`, `configurationViewOf` stages `xspec.config.ts` and passes no `--config`, as before. The `.mts` and `.cts` arms stage `SPECS_ONLY_CONFIG` itself (its record name now ends `; T7-1's xspec.config.mts and xspec.config.cts)`); the `.tsx` arm stages `TSX_SPECS_ONLY_CONFIG`, the canonical text as a record of grammar `"tsx"` (the builder refuses a `"ts"` record at a `.tsx` path), and a module-load self-check pins each arm's bytes to the canonical text under the grammar `tsGrammarOf` gives its name. T7-1's H-7 row is now `["7", "11.6", "12.0", "12.6", "14"]`. `s9-staged-sources` passes 4087 of 4087. Alone against the built product T7-1 passes whole (`-t 'T7-1 '` on `test/suite/section-7-basics.test.ts`, 14.99 s of test, 27.2 s wall): it loads every name, parsing each as plain TypeScript, a choice no declarative file observes. Red-checked through the scratch-wrapper pattern (bullet beginning "Red-checking a strengthened product test"), seven modes in 120.7 s of test, each acting only on invocations whose `--config` names its arm's file: refusing every command there (exit 2) fails T7-1 diagnosed at that arm's `build` for each of `.mts`, `.cts`, and `.tsx`; refusing `check` alone for `.cts` fails it at that arm's `check`; replacing the `.tsx` arm's `inventory` glob, or reversing the order of the `.mts` arm's `configuration` members, fails the byte-identical comparison (`assertSameJson` renders member order, so the reordering fails there already); the passthrough mode passes. The wrapper builds its line feeds from their code point. +- T7-3's empty glob lists (TEST-SPEC T7-3, S-9; FIX_PLAN Task 45 of the plan written at e57210b): T7-3's body (`test/suite/registry/section-7-basics.ts`) ends with arm (g), `EMPTY_GLOB_LIST_ARMS` in TEST-SPEC's order, each through `expectEmptyGlobListLoads`: the spec group `product: []` alone (`EMPTY_SPEC_GLOBS_CONFIG`, its workspace holding the configuration alone), then the code group `app: []` beside the spec group `main` over `specs/*.mdx` (`EMPTY_CODE_GLOBS_CONFIG`, over `specs/A.mdx`). Each holds `build` and `check` to exit 0, then compares `inventory --json`'s list of the empty group's kind exactly (`[{ name, globs: [] }]`) and its `sources` exactly (`[]`; `specs/A.mdx` a member of `main` alone). T7-3's H-7 row is now `["7", "7.1", "7.2", "11.6", "12.7", "14"]`. `s9-staged-sources` passes 4089 of 4089. Alone against the built product T7-3 passes whole (`-t 'T7-3 '` on `test/suite/section-7-basics.test.ts`, 11.25 s of test, 23.1 s wall): it accepts both empty lists. Red-checked through the scratch-wrapper pattern (bullet beginning "Red-checking a strengthened product test"), eleven modes in 131.6 s of test, each acting only in a workspace whose configuration holds its arm's empty list: for each arm, refusing every command (exit 2) fails T7-3 at that arm's `build`, failing `check` (exit 1) at its `check`, dropping the group or reporting its globs as `["**/*"]` at the inventory's view, and putting a file in the group (`xspec.config.ts` in `product`; `specs/A.mdx` also in `app`) at its `sources`; the passthrough mode passes. Labels holding a backtick are spelled as a template prefix plus a double-quoted string (`` `${label}: ` + "`build` …" ``), never an escaped backtick, so no line holds a backslash. - T7-7 (the plan written at 2a2b94e, FIX_PLAN Task 57; `test/suite/registry/section-7-basics.ts`, the `T7_7_*` section after T7-3 — `runT77UnstagedTwin` first, then `runT77Arm` over `T7_7_ARMS`): four workspaces of one declaration, `T7_7_WORKSPACE`, its records `T7_7_CONFIG` (staged again at the inside link target `config/linked.config.ts`, and its text written beyond the root as the outside target `../outside/linked.config.ts`), `T7_7_CODE_SOURCE`, and the shared `SECTION_A_SOURCE`, arm (b)'s `src/x.mdx` an MDX record alone. Alone against the built product through the scratch-wrapper pattern (bullet beginning "Red-checking a strengthened product test") it passes in ~4.5 s of test. A stand-in simulating a product that reads the configuration through the link, or one reusing its recorded parse while the recorded sources' hashes match (it never sees `src/x.mdx`), runs the real `bin.js` in a mirror of the root and reports that run's streams and exit code as its own: `fs.cpSync(root, mirror, { recursive: true, dereference: true, filter })` into `fs.mkdtempSync(path.join(path.dirname(root), "mirror-"))` — the workspace's own temporary directory beside the root, so the harness's disposal removes the mirror, the stand-in removes nothing, and neither the root's nor the outside directory's compare sees it (`filter` leaves `src/x.mdx` out for the reuse simulation); applied to one command alone, each is caught at that command's exit-code assertion (~2–5 s a mode). Refusing as the product does but then writing `.xspec/stray`, leaving an empty `.xspec/lock` after `ids` (a read: the lock path compared), appending to the outside target, or replacing the link by a plain file is caught at that command's compare; the same `.xspec/lock` after the `rename` (a mutating command's run: the lock path left out of the compare, H-6) at `assertLockPathAbsent`; the link's stored target as the error document's `path`, at the finding pin; `version` exiting 2, at its exit code. - T7-8 (the plan written at 2a2b94e, FIX_PLAN Task 58; `test/suite/registry/section-7-discovery.ts`, the `T7_8_*` section after T7-6 — `runT78TwinPair` over `T7_8_UNLISTABLE_PAIR` and the two `T7_8_KIND_PAIRS`, then `runT78CarveOut`): eight workspaces, four staged/twin pairs from one declaration builder, `t78Decl`, over its records `T7_8_CONFIG`, `T7_8_DOCS_CONFIG`, `T7_8_AREA_GLOB_CONFIG`, `T7_8_A_SOURCE`, `T7_8_B_SOURCE`, and `T7_8_CODE_SOURCE` (the staged directories' plain files stay strings). Its written-file compare is `assertWriteDeltasEqual`, exported from `test/helpers/determinism.ts` from that Task with optional run labels (the two-directory form's default text unchanged): each command's delta across its run, every snapshot taken with `EXCLUDE_LOCK_PATH` and outside the staging window — a staged directory admits no snapshot (`--x` refuses the walk's listing, `r--` its `lstat` of the entry) — so the staging is applied after the snapshot before the run and restored before the one after, re-applied and verified anew for every command. Alone against the built product through the scratch-wrapper pattern (bullet beginning "Red-checking a strengthened product test") it passes in ~18 s (58 product invocations); run as the sandbox's root, it ends a harness error at its first staging (`HarnessStagingError: read-refusal-of-directory staging of …/data: listing … was not refused`), the E-1 verification that braces the test (CERTIFICATIONS.md's exclusion entry naming T7-8). A stand-in that, before running the real `bin.js`, reads the tree as a failing product does and on `EACCES` prints a 12.7 error document (`code` `read-failure`, the refused path, `locations` and `identities` `[]`) and exits 2 is caught at `assertNeverReadFailure` in the half naming that product, each half passing the others: walking every non-dot directory from the root, at (a)'s `data`; walking `specs` and `src` into dot-directories, at (a)'s `specs/.cache`; `lstat`ing every entry of every directory it lists, at (b)'s `specs/sub/.keep` (restricted to `docs`, at `docs/notes.txt`); listing `.xspec` when the configuration names `".xspec/`, at (c)'s `build`. A twin-equal stub — each working directory's first `build` passed through, the command under check exiting 7 with no output, its state kept outside the workspace — is caught at that command's H-5 outcome assertion, for each of the seven commands; a trailing space on the staged run's stdout at the stdout compare, (c)'s `check` included; and a staged-only write (`stray.txt` at the root, or a byte appended to the rename's rewritten `specs/B.mdx`) at the written-file compare. Such a write must happen only while the staging is in effect (an `EACCES` probe of the staged directory): a stand-in that also writes during the unstaged initial `build` rewrites the same bytes on every later run, which no per-run delta sees. - T7.1-1's path-character arms and code-source control (re-descent FIX_PLAN Task 49; `PATH_CHARACTER_ARMS`, `runPathCharacterArm`, and the `CODE_PATH_CONTROL_*` constants in `test/suite/registry/section-7.1-7.3.ts`, their records named `T7.1-1 xspec.config.ts (the path-character arms: …)`, `T7.1-1 the path-character arms' spec source (…)`, `T7.1-1 xspec.config.ts (the code-source path control: …)`, and `T7.1-1 the code-source path control's code source (…)`): against the built product T7.1-1 fails diagnosed at its first path-character arm — `specs/a"b.mdx` builds with exit 0 and `{"findings": []}`; a hand probe shows the product applies no 7.1 bar to any of the eight paths, while the control passes (`-t 'T7\.1-1 '` on `test/suite/section-7.1-7.3.test.ts`, ~9 s under the namespace). The arms green-check through the stand-in wrapper pattern (above): a scratch `.mjs` that runs `dist/cli/bin.js` and, when `specs/` under the cwd holds an `.mdx` file whose relative path contains one of the seven barred characters (built from their code points), appends one `invalid-source-path` finding per such file (`identities` and `locations` `[]`, `path` the file) to a `build --json` or `check --json` answer and exits 1, and in a `view` answer replaces every node identity of such a file's view with `{"unavailable": true}`, appends the same finding, and exits 1. Through it T7.1-1 passes (~10 s, 24 product invocations: 5 for the two-group and non-`.mdx` workspaces, two per path-character arm, three for the control), while leaving the identities defined, dropping the view's finding, missing the directory-component arm, flagging the control's code source, or a wrong concerned path each fail at the matching assertion. On Linux the `"`, backslash, LF, and CR arms and the control (its name holds a backslash) run; elsewhere the body skips them. The wrong-case extension arm (the plan written at 2a2b94e, FIX_PLAN Task 59; `runWrongCaseExtensionArm` and the `WRONG_CASE_EXTENSION_*` constants, its records named `T7.1-1 xspec.config.ts (the wrong-case extension arm: …)` and `T7.1-1 specs/A.MDX (…)`), run after the non-`.mdx` arm on every leg, passes against the built product (T7.1-1 alone ~7.6 s under the namespace, 27 product invocations); it red-checks through the same wrapper pattern: a scratch `.mjs` that, when the cwd's `xspec.config.ts` holds `"specs/*.MDX"`, answers `build --json` or `check --json` with `{"findings": []}` and exit 0, or rewrites `inventory --json`'s `derived` entry for `specs/A.MDX` to `module` `specs/A.xspec.ts` and `markdown` `specs/A.md`, fails at the matching command's exit code or at the derived compare; the module before the arm passed all three. - T7.3-1's graph-data-area `outDir` arms (re-descent FIX_PLAN Task 50; `GRAPH_DATA_AREA_OUTDIRS` and `LOOKALIKE_OUTDIRS` in `test/suite/registry/section-7.1-7.3.ts`, the body's arms (d'') and (d'''), their records named `T7.3-1 xspec.config.ts (outDir ".xspec" …)`, `… (outDir ".xspec/md" …)`, and `… (outDir ".xspec2", a look-alike of the graph-data area)`, `… (outDir ".xspecs/md", …)`): against the built product T7.3-1 fails diagnosed at its `".xspec"` arm — `build --json` exits 0 with `{"findings": []}`; a hand probe shows the product accepts `.xspec` and `.xspec/md` and emits `specs/A.md` into the graph-data area (`.xspec/specs/A.md`, `.xspec/md/specs/A.md`), while the look-alikes emit under `.xspec2/` and `.xspecs/md/` as asserted (`-t 'T7\.3-1 '` on `test/suite/section-7.1-7.3.test.ts`, ~6 s under the namespace). The arms green-check through the stand-in wrapper pattern (above): a scratch `.mjs` that reads the `outDir: "…"` literal from the cwd's `xspec.config.ts` and, when it is `.xspec` or begins `.xspec/`, prints a `configuration error` line on stderr and, under `--json`, the 12.7 error document (`code` `"configuration-error"`, `path` `"xspec.config.ts"`, `identities` and `locations` `[]`) and exits 2 without running the product, else runs `dist/cli/bin.js` unchanged. Through it T7.3-1 passes (~9 s, 26 product invocations, every arm after the new ones included), while refusing `.xspec` alone, refusing every spelling whose bytes begin `.xspec`, creating `.xspec/` before refusing, or replacing a look-alike's created `outDir` by a symlink each fail at the matching assertion. The wrong-type arms (b') and the Linux-leg single-casing `outDir` arms (the plan written at 2a2b94e, FIX_PLAN Task 59; `WRONG_TYPE_VIOLATIONS`, and `LOOKALIKE_OUTDIRS`' rows `".XSPEC"` and `".XSPEC/md"`, skipped off Linux through their `linuxLeg` flag; records `T7.3-1 xspec.config.ts (markdown: { emit: "true" } …)`, `… (markdown: { emit: true, outDir: true } …)`, `… (outDir ".XSPEC", a single-casing spelling of the graph-data area, Linux leg)`, and `… (outDir ".XSPEC/md", …)`) pass against the built product, which refuses both literals with exit 2 and emits under `.XSPEC/` and `.XSPEC/md/` beside its graph data in `.xspec/` (T7.3-1 alone ~6.7 s under the namespace, 30 product invocations). They red-check through the same wrapper pattern: accepting `emit: "true"` or `outDir: true` (`build` exit 0, `{"findings": []}`) fails at that arm's exit code; refusing every `outDir` whose ASCII-lowercased spelling is `.xspec` or begins `.xspec/` fails at the `".XSPEC"` arm's `build`, and folding case in the `.xspec/` prefix test alone at the `".XSPEC/md"` arm's; the module before these arms passed all four. -- T7.5-1's selector-glob arms, T7.5-2's twice-spelled edge, and T7.5-4's inside-root selector spelling (the plan written at 2a2b94e, FIX_PLAN Task 60; `test/suite/registry/section-7.4-7.5.ts` — T7.5-1's last three `RULE_MATRIX` rows (`../x/*.ts` and the capture pattern `a/../../$1.ts` in `from`, `/src/*.ts` in `to`), each row's record named `T7.5-1 xspec.config.ts (<label>)` as every row's is; T7.5-2's third workspace, `FORBIDDEN_TWICE_FILES`, its records `T7.5-2 twice-spelled edge xspec.config.ts` and `… hi/H.mdx` beside `lo/BASE.mdx`, the shared `SECTION_A_SOURCE`; T7.5-4's arm (b'), `insideRootSelectorFiles` over `./src/*.ts` and its `src/*.ts` twin, each workspace built under its own configuration, its records `T7.5-4 inside-root selector spelling xspec.config.ts (from { files: "…" })` beside the shared `CODE_MARKER_TO_P` at `src/a.ts` and `SECTION_P_SOURCE` at `tgt/P.mdx` — `CODE_MARKER_TO_P` defined in the module's shared fixture material, since T7.5-4's fixtures are built at module load before T7.5-5's section): alone against the built product through the scratch-wrapper pattern (bullet beginning "Red-checking a strengthened product test") T7.5-1 passes in ~5.4 s (29 product invocations), T7.5-2 in ~1.7 s (6), and T7.5-4 in ~3.5 s (11; the `./src/*.ts` workspace runs `build`, `query edges --kinds references`, and `check --json`). They red-check through a scratch stand-in wrapping `dist/cli/bin.js`, each mode recognizing its workspace by a literal of its `xspec.config.ts` or `hi/H.mdx`: accepting one outside-root selector glob at `build` (exit 0, `{"findings": []}`) fails at that arm's exit-code assertion; doubling the twice-spelled workspace's `policy-violation` finding in its `check --json` answer fails at the findings decoder when the copy is identical (12.7's collapse) and at the `14.12 x1` count when the copy's message differs; adding the twin's finding to the `./src/*.ts` workspace's `check --json` (exit 1) fails at that `check`'s exit code, and refusing `./src/*.ts` as a configuration error at its `build`'s; the module before these arms passed all seven modes. +- T7.5-1's selector-glob arms, T7.5-2's twice-spelled edge, and T7.5-4's inside-root selector spelling (the plan written at 2a2b94e, FIX_PLAN Task 60; `test/suite/registry/section-7.4-7.5.ts` — T7.5-1's last three `RULE_MATRIX` rows (`../x/*.ts` and the capture pattern `a/../../$1.ts` in `from`, `/src/*.ts` in `to`), each row's record named `T7.5-1 xspec.config.ts (<label>)` as every row's is; T7.5-2's third workspace, `FORBIDDEN_TWICE_FILES`, its records `T7.5-2 twice-spelled edge xspec.config.ts` and `… hi/H.mdx` beside `lo/BASE.mdx`, the shared `SECTION_A_SOURCE`; T7.5-4's arm (b'), `insideRootSelectorFiles` over `./src/*.ts` and its `src/*.ts` twin, each workspace built under its own configuration, its records `T7.5-4 inside-root selector spelling xspec.config.ts (from { files: "…" })` beside the shared `CODE_MARKER_TO_P` at `src/a.ts` and `SECTION_P_SOURCE` at `tgt/P.mdx` — `CODE_MARKER_TO_P` defined in the module's shared fixture material, since T7.5-4's fixtures are built at module load before T7.5-5's section): alone against the built product through the scratch-wrapper pattern (bullet beginning "Red-checking a strengthened product test") T7.5-1 passed in ~5.4 s (29 product invocations; its current time: the bullet beginning "T7.5-1's kind-without-group arms"), T7.5-2 in ~1.7 s (6), and T7.5-4 in ~3.5 s (11; the `./src/*.ts` workspace runs `build`, `query edges --kinds references`, and `check --json`). They red-check through a scratch stand-in wrapping `dist/cli/bin.js`, each mode recognizing its workspace by a literal of its `xspec.config.ts` or `hi/H.mdx`: accepting one outside-root selector glob at `build` (exit 0, `{"findings": []}`) fails at that arm's exit-code assertion; doubling the twice-spelled workspace's `policy-violation` finding in its `check --json` answer fails at the findings decoder when the copy is identical (12.7's collapse) and at the `14.12 x1` count when the copy's message differs; adding the twin's finding to the `./src/*.ts` workspace's `check --json` (exit 1) fails at that `check`'s exit code, and refusing `./src/*.ts` as a configuration error at its `build`'s; the module before these arms passed all seven modes. +- T7.5-1's kind-without-group arms (TEST-SPEC T7.5-1, S-9; FIX_PLAN Task 46 of the plan written at e57210b): three `RULE_MATRIX` rows in `test/suite/registry/section-7.4-7.5.ts`, after the two-forms row and before the unknown-group row (TEST-SPEC's order), each selector in `from` beside `to: { group: "aux" }` — `{ files: "src/*.ts", kind: "code" }`, `{ tags: ["a"], kind: "spec" }`, and `{ kind: "spec" }` — each through `expectConfigRefused` (one `build --json`), its record named `T7.5-1 xspec.config.ts (<label>)` as every row's is. T7.5-1's H-7 row stays `["7.5", "7", "14"]`: the body asserts 7.5's 14.14 refusal, never 7.6's type contract. `s9-staged-sources` passes 4092 of 4092. Alone against the built product T7.5-1 passes whole (`-t 'T7.5-1 '` on `test/suite/section-7.4-7.5.test.ts`, 32 product invocations, 8.43 s of test, 19.6 s wall): it refuses all three selectors. Red-checked through the scratch-wrapper pattern (bullet beginning "Red-checking a strengthened product test"), four modes in 24.1 s of test: each perturbing mode acts only in a workspace whose `xspec.config.ts` holds its arm's selector, rewrites that selector as a product vetting `kind` only beside `group` reads it (the `kind` dropped; the bare `{ kind: "spec" }` read as `{ files: "**/*.mdx" }`), runs the real product over it, and restores the original bytes, and each fails T7.5-1 diagnosed at its own arm's exit-code assertion (the real `build --json` exiting 0); the passthrough passes. - Review-operation refusals in TEST-SPEC T10.7-14's finding form (the plan written at 2a2b94e, FIX_PLAN Task 62): `expectReviewRefusal(product, workspace, argv, sessionRel, context, { nothingModified })` in `test/suite/registry/support.ts` is the one check every refusal site runs — T10.1-2's case-fold `create`, T10.1-6's stale twin holding a valid `s`, T10.3-2, T10.7-1's existing valid session and its both-valid case pair (`--name Foo` beside `foo.json` and `FOO.json`), T10.7-9's five `split` refusals (its path-blocks fixture's two, its audit fixture's two — N's parent-consistency item and the leaf s's item — and Q's item in an audit session of its own once Q's only child is deleted by manual edit), T10.7-10's blocked `resolve`, T10.7-14's seven (`test/suite/registry/section-10.7-iii.ts`, wrapper `test/suite/section-10.7-iii.test.ts`, the module for the new §10.7 tests T10.7-13 and T10.7-15 too), and T10.7-15's three on stale graph data (since FIX_PLAN Task 87: in (a) run directly, in (b) held at the seam under T14-9's graph-data staging through the check's `run` option — `run: (argv) => Promise<RunResult>`, `--json` already appended, by default `runCli` — its answer judged like any other) and its two on hand-edited twins of (A) (since FIX_PLAN Task 88: (c)(i)'s `resolve` and (c)(ii)'s `split`, run directly inside the arm's whole-root compare), T12.7-1's arm D (since FIX_PLAN Task 109: `review create --strategy audit --name s` naming the session its first run created, `.xspec/reviews/s.json`, no `nothingModified`), and T14-6's code-null refusal arm (since FIX_PLAN Task 121: the same staging, the same session file, no `nothingModified`): exit 1, standard output exactly one code-less finding through the form-exact decode, `code` and `path` `null`, `locations` `[]`, `identities` unasserted. It takes the command without `--json` (appended; given, a plain error), the session file the refusal names (for a case-fold `create`, the existing session's), required a plain file before and after the run and byte-identical, and `nothingModified: true` where the site's entry states nothing modified or created (the whole-root compare, H-6's lock-path exclusion applied; T10.7-14 itself compares the session file alone). T10.7-1's, T10.7-9's, and T10.7-10's sites hand it to their staging's refusal visitor as the refusal's `home` (support.ts `visitReviewRefusal`, since the plan written at 2a2b94e's FIX_PLAN Task 133's third part; the bullet beginning "T12.0-15's `review` family, third part"). The built product passes it wherever it is reached (T10.7-14 alone ~4.4 s); in T10.7-9's own run (T12.0-15's run of its staging, the visitor's `home` false, reaches all five on the built product) its path-blocks refusals (N's parent-consistency item and N.a's leaf item, past (b) and (c)) are reached only through scratchpad `t9j2a2_82/standin.mjs fixbc` or a later level — as `t9j2a2_62/standin.mjs`'s inner stand-in, `<mode> <…>/t9j2a2_82/standin.mjs fixbc` (`path#1` and `stray#2` caught at their sites) — its audit fixture's two past (c) only through `t9j2a2_83/standin.mjs conform` with the earlier arms skipped (T10.7-9's bullet; `path#1`, `path#2`, `stray#1`, and `stray#2` caught at their sites), and its Q refusal, which the built product reaches with the earlier arms skipped (`path#1` and `stray#1` caught), T10.1-6's valid-`s` twin only through `t9j2a2_3/standin.mjs restore`. Red-checking a refusal site: scratchpad `t9j2a2_62/standin.mjs <mode>[#<k>] [<inner stand-in> <inner mode>] <bin> <argv…>` rewrites the k-th (bare: every) refused `review create|resolve|split --json` answer holding a code-less finding — `path` (the session file as its `path`), `locate`, `code`, `extra` (a sixth member), `twice` (a second finding in 12.7 order), `wrap` (a second top-level member), `touch` (a newline appended to the session file), `stray` (a file at the root, caught only under `nothingModified`), `pass` — each caught at its own assertion; its `#k` counter lives in `t9j2a2_62/state/`, keyed by the workspace path, so each fresh workspace counts from 1 (rebuild the stand-in from this description if it is gone). - The metadata pair (TEST-SPEC T10.7-13; the plan written at 2a2b94e, FIX_PLAN Task 63): `decodeReviewItemValue` (`test/helpers/adapters/review.ts`) requires on every `metadata-consistency` item that `review next --json`, `show`, or `export` presents the member `"metadata"` — `{"before", "after"}`, each side `{"present": false}` or `{"present": true, "d": [identity…], "coverage", "tags"}` (the adapter's assumed layout; `coverage` the 12.7 token `"required"`/`"none"` and `tags` a 12.7 tag set, both decoded literally, `decodeTagSet`; `d` in any order; an absent side carrying none of the three) — failing loudly when absent, and reads no pair on another kind (`ReviewItem.metadata`; `MetadataPair` and `MetadataSide` in `model.ts`; S-5's entry `review show (metadata-consistency item: the metadata pair)`). The built product carries no pair, so against it every test decoding such an item through those surfaces fails diagnosed at that decode (``… adapter: at $.items[3].metadata: expected the scope node's metadata pair …``): at this Task T10.2-1, T10.4-2, T10.5-2, T10.5-3, T10.5-4, T10.7-12, and T10.7-13, every other test of the §10, §12.0, §12.7, §15, §6.1, §6.3, and §1.6–1.7 modules and P-8 and P-9 keeping its verdict (T1.6-3, T6.3-6, T10.1-6, and T10.7-9 failing at their earlier arms as before; one run of those 76 tests through the scratch runner at concurrency 3, ~275 s). T10.7-13 (`test/suite/registry/section-10.7-iii.ts`: three path-blocks workspaces — specs/M.mdx for (a) and then (d), specs/GH.mdx for (b), specs/K.mdx for (c) with its journaled `rename specs/K.mdx t4 t9`; each arm's item set asserted from `export` as a premise, each item's context, where the entry states it, and pair then asserted through `export`, `show`, and a `next` walk resolving `no-change` between items, `d` compared as a set) fails the built product at (a)'s first `export` (~1.1 s) and passes whole under scratchpad `t9j2a2_63/standin.mjs conform <bin> <argv…>` (~22 s), as do the six others (~53 s together at concurrency 3). The stand-in injects the pair computed from the product's own `query node <scope> --json` answers — in the workspace (an unknown node the absent side) and in the session's recorded baseline commit (`creationParameters.base` in the session file), its tree archived into the stand-in's own `tmp/` (never removed) and built there — each baseline `d` target mapped forward through the current journal's lines that the baseline tree's journal lacks (the product's compact-JSON entries, their `map` pairs); rebuild it from this description if it is gone. Its modes red-check T10.7-13: `unmapped` (baseline identities) fails (c)'s before-side `d` set, `ctxold` (the context mapped back) (c)'s context, `bothcurrent` and `swapped` (a)'s before-side `d` set, `afterkept` (d)'s after-side presence, `nextwrong` (`next`'s after-side tags emptied) (a)'s `next` read, `onlyexport` and `shownone` (a)'s `show` decode, and `spelled`, `coverbool`, and `coverupper` the adapter's tag-set and coverage decodes at (a)'s `export`; `reversed` and `dup` pass, `d` being a set; `omit=<scope prefix>` (e.g. `omit=specs/GH.mdx`) and `omitabsent` leave one arm's items to the product's own answer, the rest injected, so that arm alone meets the missing pair (each arm of the built product fails at its own first `export` decode). - Item IDs as well-formed argument values (TEST-SPEC T10.2-1; SPEC 10.2, 12.0; the plan written at 2a2b94e, FIX_PLAN Task 66): `decodeItemId` in `test/helpers/adapters/review.ts` decodes every item ID the review adapter meets — each `review status` row's `id`, each item's `id` at `next --json`, `show`, and `export` (`decodeReviewItemValue`), and each `blockedBy` entry — as a non-empty string free of U+FFFD and of unpaired surrogates (12.0's two bars: valid UTF-8, no U+FFFD), failing loudly (``… adapter: at $.items[0].id: expected an item ID that is a well-formed argument value (SPEC 10.2, 12.0 … not one holding U+FFFD at UTF-16 index 6 …``), so every test observing an item ID checks it, P-9's draws included. S-5's test "every review decode of an item ID …" stages six malformed and three well-formed IDs at all seven sites (a throwaway decoding each document showed all 42 malformed documents decoding under the adapter before this Task and rejected with it). T10.2-1 names each representative item by its own `id` through `showRepresentativeItem` (`test/suite/registry/section-10.2-10.3.ts`: `review show <name> <id> --json`, exit 0, the shown item's id, kind, and scope node those of its `status` row). The built product's IDs (`item-<n>` at that Task; since FIX_PLAN Task 157 of the plan written at abb7839, `r` and 16 lowercase hex digits derived from the item's kind and scope node, extended by further digits on a clash — well-formed argument values either way, and T10.2-1 reads them from the product, never spelling one) pass: T10.2-1 still fails it at Task 63's metadata pair (`review show pb` of the metadata-consistency item, ~2.6 s) and passes whole under scratchpad `t9j2a2_63/standin.mjs conform` (copied as `t9j2a2_66/standin63.mjs`, ~8 s), and the 76 review-decoding tests of the bullet above keep their verdicts (64 pass, 12 fail diagnosed at the same first lines; two runs of 40 and 36 tests at concurrency 3, ~125 s and ~160 s). Red-checking an item-ID arm: scratchpad `t9j2a2_66/standin66.mjs <mode> <n> <inner_1> … <inner_n> <argv…>` runs `node <inner_1> … <inner_n> <argv…>` — chained before the conforming stand-in with n = 3 (`standin63.mjs conform <bin>`) — and rewrites the item IDs of `review status|show|next|export` answers, mapping a rewritten ID back on input: `fffd` (a trailing U+FFFD) and `lone` (a trailing lone surrogate, which reaches the stand-in's argv as U+FFFD) fail T10.2-1 at `review status pb`'s decode and pass under the adapter before this Task; `covshowid` (`show cov`'s `id` rewritten) fails at the coverage arm's `show`, which the body before this Task caught only at the export compare; `pbshowid` fails at the first `show pb`; `pass` passes (rebuild the stand-in from this description if it is gone). @@ -286,7 +317,7 @@ Build, test, and run instructions for this repository (nothing else belongs in t - FIX_PLAN (fourth plan) Task 22 (the T14-11 exchange — the §2 `UnparseableStaging` exports, T14-12's arm stagings, and their consumer — plus `section-14-iii.ts`'s other post-invocation initial files, as staged-source records; `test/suite/registry/support.ts`, `section-14.ts`, `section-2.2-2.3.ts`, `section-2.4.ts`, `section-2.7.ts`, `section-14-iii.ts`; 53331cd): the records are staged by T14-4's and T14-6's sweeps (`T14_12_REPORTER_STAGINGS`) and T14-11's (w) arms too, so the checks ran six suite files together — `P4_SITES=<log> P3_TASK12_CAPTURE=<log> unshare --map-user=1000 --map-group=1000 -- npx vitest run --config test/vitest.config.ts --project suite section-2.2-2.3.test section-2.4.test section-2.7.test section-14.test section-14-iii.test section-15.test --reporter=verbose` (~42 s; 28 tests, 11 diagnosed failures — T2.3-3, T2.4-2, T2.4-5, T2.7-3, T2.7-4, T14-2, T14-4, T14-6, T14-7, T14-11, T14-12; 335 writes in the capture log, compared sorted; the script is `p4-task22-run.sh <tag>` in the scratchpad, `p4-task22-diag.py <log>` extracting each failure's message block up to its first stack frame with temporary paths and `.xspec.tmp-<pid>-` names normalized). Most re-staged sites lie behind diagnosed failures, so a per-arm diagnostic variant reached them, before and after the conversion alike: `p4-task22-variant.py apply|restore` (scratch copies, restored and `cmp`-checked) renames each arm runner `runX` to `runX__inner` and appends a hoisted `async function runX(...args)` wrapper that try/catches and appends `<label> PASS` or `<label> FAIL [<error constructor>] <first three message lines>` to `$P4_T22_VARIANT_LOG` — anchored on the runners' names alone, so one patch applies to both sides of a conversion that rewrites their bodies (`runUnparseableFormArm`, `runCommentForms`, `runEnclosedConstructArm`, `runUnparseableCommentArm`, `runRangeRuleArm`, and T14-12's five runners) — while T2.3-3's two form loops iterate `.slice(0, 0)` (its unparseable arm then runs as the body's first) and T14-4's and T14-6's bodies get a prepended loop over `SWEEP_ENTRIES` filtered to the `T14-12` labels, each entry's `build --json` findings logged as `[condition, code, locations]` JSON, then `return` (~29 s; 107 log lines and 478 writes, both compared sorted). A red check on an `unparseable` record cannot splice an unclosed tag (the source stays unparseable and the judge passes it): make the source derive or flip the declaration to `"well-formed"` (`p4-task22-red.py apply|restore`: 19 records fail as `mdx-derivability` in the S-9 self-test). The builder self-test's `someUnparseableRecord()` (`test/self/s9-staged-sources.test.ts`) borrows the ledger's first `unparseable` record — T2.3-3's since this task — so a red check making that record derive fails that self-test as well. Duplicate-bytes probe (`p4-task22-dupes.json`): 730 records in 33 groups (the new one: the code arms' spec source with `"T4.5-9 specs/A.mdx"`). Run facts: the S-9 self-test alone 756 tests over 730 records (723 `T…`, 4 `E-6`, 3 `P-…`; ~5 s, no namespace); self project 22 files, 2896 passed, 0 skipped under the namespace (~90 s; 2867 + the 29 record tests); certification 144 PASS / 33 FAIL / 0 error / 0 hang over the 23 `certification run against` lines. - FIX_PLAN (fourth plan) Task 23 (the §14 modules' post-invocation initial files as staged-source records; `test/suite/registry/section-14.ts`, `section-14-ii.ts`, with records reused from `section-12.1-12.2.ts`, `section-5.1-5.3.ts`, `section-6.5.ts`, and `section-6.5-iii.ts`; c782148): the plain before/after pair ran seven suite files together — `p4-task23-run.sh <tag> [file-substrings…]` in the scratchpad (default: the four converted-or-reused modules' suite files), with `section-6.5.test section-6.5-iii.test section-6.6.test` added for the exported and renamed records (~74 s; 44 tests, 21 diagnosed failures; 514 writes in the capture logs, compared sorted). A suite file added after the before run gets its own before run from HEAD's copies of its modules (`git show HEAD:<path> > <path>`, the converted copies back from the scratchpad afterwards and `cmp`-checked), the two before logs concatenated and sorted against the one after log. One diagnostic variant reaches every arm behind `section-14.ts`'s diagnosed failures: the module-local `withWorkspace` swallows its body's failure and logs `<n> <files keys> PASS|FAIL …`, so every later arm and sweep entry runs (T14-4, T14-6, T14-7, T14-11); `section-14-ii.ts`'s T14-9/T14-10 arm functions take Task 22's rename-and-wrap form, and arm (g)'s first block an inner try/catch so its invalid-configuration workspace is reached (`p4-task23-variant.py apply|restore`; ~105 s for the two files; 205 log lines and 609 writes, both compared sorted). The conversion scripts (`p4-task23-convert-14.py`, `-14b.py`, `-14c.py`, `p4-task23-convert-others.py`) move each expression with a string-, template-, and comment-aware scanner (`p4_task23_lib.py`: `find_close`, `expr_end`, `call_args`, `wrap_after`) instead of re-typing it; Python's `json.dumps` writes a non-ASCII character of a generated record name as a backslash-u escape, so keep generated names ASCII (or pass `ensure_ascii=False`) and grep the diff's added lines for backslash-u escapes before committing. The duplicate-bytes probe (`p4-task23-dupes2.json`): 796 records in 36 groups; a new entry whose bytes equal a record the same test already stages elsewhere (T14-7's two) is that record, exported and renamed. The ledger self-test alone runs in ~5 s (no namespace); red check (`p4-task23-red.py apply|restore`): an unclosed tag spliced into four new records and the sweep's 14.20 source made to derive fail exactly those five as `mdx-derivability` (5 failed, 817 passed). Run facts: the S-9 self-test alone 822 tests over 796 records (789 `T…`, 4 `E-6`, 3 `P-…`); self project 22 files, 2962 passed, 0 skipped under the namespace (~91 s; 2896 + the 66 record tests); certification 144 PASS / 33 FAIL / 0 error / 0 hang over the 23 `certification run against` lines. - The undeclared-staging guard covers initial files (fourth-plan FIX_PLAN Task 24, the plan's last task; TEST-SPEC S-9's timing clause for the initial `.mdx` files of a workspace created after a body's first product invocation, S-7, H-8): `TestWorkspace.stageInitial` (`test/helpers/workspace.ts`) calls `guardUndeclaredStaging(rel, <the workspace declaration's entry> ?? "well-formed", "initial entry")` for a plain `.mdx` entry before the S-9 judge — the same guard `file()` and `copyFrom()` call (site `"write"`), one code path. At creation only the per-body mark can be set (the root was registered an instant before and nothing has run in it), so a creation is refused only inside a registered body — the suite wrapper, the certification runner and S-7's sweep, a property runner's later trials — after the body's first invocation; outside a body context (a self-test, the E-6 fixture) creation never refuses. Exempt: a record entry and a path the workspace declaration lists `unchecked` or `perDraw` (the latter still judged at creation; the per-draw unparseable list went in the fifth-plan Task 3); refused whatever the plain entry's declaration (well-formed, `unparseable`, allowances — those ride a record). `create()`'s catch disposes the half-built workspace, entries staged before the refused one included. The diagnosis: ``undeclared-staging staging of <path>: an initial `files` entry of a workspace created after a product invocation in the running body of <ID> (in another workspace: S-7's sweep stops at the body's first invocation wherever it happens), staged with plain contents (declared "…") — …``, then the remedies (a staged-source record as the entry's value, the path dropped from the workspace's `mdx` declaration; `mdx.perDraw` for a property draw's initial file; `mdx.unchecked` for a P-8 mutation or noise file); `file()`'s message is unchanged. A future unconverted post-invocation entry surfaces as that harness error at the first run reaching its site (behind a diagnosed product failure: when the product gets there). Self-test: `test/self/s9-undeclared-staging.test.ts` 16 tests (14 since the fifth-plan Task 3 removed the per-draw unparseable declaration's two tests; the new one inside `runProductTestBody("T0-9", …)`: before the body's first invocation a plain creation passes; after it the refusals, each leaving nothing behind, and the exemptions; outside any body after an invocation elsewhere a creation passes). Observing "nothing left behind" without racing the other self-test files' concurrent `xspec-harness-*` directories: its `createInPrivateTemp` points `TMPDIR`, `TMP`, and `TEMP` at a fresh private directory for the one `create()` call (`os.tmpdir()` reads them at each call; Vitest 4's default `forks` pool gives each test file its own process environment), restores them, and lists that directory — a success leaves exactly one `xspec-harness-*` entry, a refusal none. Red checks: `git stash push -q test/helpers/workspace.ts && (unshare --map-user=1000 --map-group=1000 -- npx vitest run --config test/vitest.config.ts --project self test/self/s9-undeclared-staging.test.ts 2>&1 | grep -E '×|Tests '); git stash pop -q` fails exactly the new test (1 failed, 15 passed); the guard on a converted module — on a scratch-backed copy of `test/suite/registry/section-2.1.ts`, make the shared record `"T2.1-2/T2.1-3 specs/BASE.mdx"` plain (`).source,` closing its `stagedMdx(…)` in `VALID_BASE_FILES`) and run `unshare --map-user=1000 --map-group=1000 -- npx vitest run --config test/vitest.config.ts --project suite test/suite/section-2.1.test.ts -t 'T2.1-3 '` (~5 s): T2.1-3 fails as ``HarnessStagingError: undeclared-staging staging of specs/BASE.mdx: an initial `files` entry of a workspace created after a product invocation in the running body of T2.1-3 …`` (a later arm's workspace; its first workspace's plain entry passes) — restore with `cp` and verify with `cmp`. Run facts at 3d0f424: self project 22 files, 2967 passed, 0 skipped under the namespace (~90 s); certification 144 PASS / 33 FAIL / 0 error / 0 hang over the 23 `certification run against` lines; the full suite against the built product (`unshare --map-user=1000 --map-group=1000 -- npx vitest run --config test/vitest.config.ts --project suite --reporter=verbose > <log> 2>&1`, 704 s on 4 workers — the first full run since the conversions of Tasks 3–23b): 77 files (47 failed, 30 passed), 337 tests, 82 failed, 255 passed; the failed-ID set (`grep -E '^\s+×' <log> | grep -oE '> (T[0-9.]+-[0-9]+|P-[0-9]+) ' | sed -E 's/^> //; s/ $//' | sort -u`) `comm -3`-empty against the known 82-ID list; `grep -oE '^[A-Za-z]*Error' <log> | sort | uniq -c` gives 82 `HarnessAssertionError` and nothing else; `grep -c 'undeclared-staging' <log>` 0; the E-6 exchange test passes; P-6 through P-13 pass (P-12 under the guard). No site needed converting. -- The staged-source ledger's TypeScript records (FIX_PLAN Task 16 and its split tasks; TEST-SPEC S-9's TypeScript and timing clauses, H-8): `test/helpers/staged-ts.ts` — `stagedTs(name, source, ts = "well-formed", grammar = "ts")` registers a `StagedTs` at module load (bytes; declaration `"well-formed"` or `"unparseable"`, never `unchecked`; grammar `"ts"`, or `"tsx"` for a `.tsx` path — SPEC 14.20 selects TSX by the `.tsx` suffix alone), named as MDX records are (`"<TEST-ID>[/<TEST-ID>…] <what it stages>"`, the lead IDs registered tests or `E-6`), sealed by the manifest beside the MDX ledger (`sealStagedTsLedger()` in `test/suite/registry/index.ts`). The builder (`test/helpers/workspace.ts`) takes a record in `file(rel, record)` and as an initial `files` entry (`InitialFileContents = FileContents | StagedMdx | StagedTs`) and stages its bytes under the record's declaration whatever the name (a record makes its path judged, as `ts.wellFormed` does); it throws `HarnessStagingError` mode `ts-derivability`, nothing written, for a `ts` option beside a record, a workspace `ts` entry naming an initial record's path, an `.mdx` path, and a path selecting the other grammar. An `.mdx` path a code group discovers is an MDX source and a code source at once: its MDX record carries the TypeScript declaration too (`stagedMdx(name, source, mdx, ts)`, e.g. T2.1-2's `docs/EXTRA.mdx`), staged under both, a `ts` option or workspace `ts` entry beside it a contradiction. `test/self/s9-staged-sources.test.ts` judges every TypeScript record with `judgeTsDeclaration(record.name, bytes, record.ts, tsGrammarFileName(record.grammar))` (the optional fourth argument names the grammar's neutral file) and every MDX record carrying `ts` as plain TypeScript, one test each: `npx vitest list --config test/vitest.config.ts --project self test/self/s9-staged-sources.test.ts | grep 'every staged TypeScript source'` lists them (503 from Task 16o: E-6's two — the self-test pins that count — the Windows leg's drive-mismatch configuration (`ANCHOR_CONFIG` of `test/helpers/e6-drive-mismatch.ts`, Task 16o), nineteen of the §1 modules, seventeen of §2 and §3, T2.1-2's `docs/EXTRA.mdx` MDX record carrying `ts` among them, fifty of `section-4.ts`, T4-2's and T4-5's arm tables laid out at module load one record per row, and seventy-one of §4.3–§4.6 — fifteen of `section-4.3-4.4.ts`, fifty of `section-4.5.ts`, six of `section-4.6.ts` — their arm tables likewise one record per row, and twenty-two of Task 16e — seven of `section-5.7.ts`, eight of `section-6.4.ts`, one each of the other §5 and §6.1–§6.3 modules but `section-5.6.ts`, and `support.ts`'s `UNKNOWN_KEY_CONFIG`, and twenty-one of Task 16f — ten of `section-6.5.ts`, five of `section-6.5-ii.ts`, two each of `section-6.5-iii.ts` and `section-6.6.ts`, one of `section-6.7.ts`, and `section-13.5.ts`'s configuration — and forty-seven of Task 16g, all of `section-7-basics.ts`, thirty-three of them its refused-configuration tables' rows, and forty-nine of Task 16h — twenty-six of `section-7-discovery.ts` (T7-4's outside-root and inside-root arms one record per row) and twenty-three of `section-7.1-7.3.ts` (T7.3-1's emission-matrix, emit-required, and invalid-outDir tables one record per row), and sixty-three of Task 16i, all of `section-7.4-7.5.ts` (T7.4-1's and T7.5-1's matrix tables one record per row; its byte-identical code sources one record each, `OK_CODE_SOURCE` for `src/impl.ts` and `dualcode/d.ts`, `CODE_MARKER_TO_P` for T7.5-5's five paths), and twenty-three of Task 16j — two of `section-8.ts`, one of `section-9.3.ts`, two each of `section-10.1.ts` and `section-10.2-10.3.ts`, four of `section-10.4.ts`, one each of `section-10.5.ts` and `section-10.6.ts`, four of `section-10.7-i.ts`, and six of `section-10.7-ii.ts` (the §10 modules' configuration constants the records themselves, staged in every workspace that names them; `section-8.ts`'s two wrapped in place in their `files` maps; `section-9.3.ts`'s a record wrapping `section-5.6.ts`'s constant), and twenty-eight of Task 16k — two of `section-11.ts`, three of `section-11.2.ts` (its exported `SPECS_ONLY_CONFIG` the record itself, staged by import in the §11.3, §11.4, and P-12 bodies), five of `section-11.3.ts` (wrappers of other modules' plain constants), eight of `section-11.6.ts` (T11.6-4's broken configuration an `unparseable` record), three of `section-12.0-i.ts`, six of `section-12.0-ii.ts` (its two byte-identical inline unknown-key configurations one record), and one of `section-12.0-iii.ts`, and forty-two of Task 16l — eight of `section-12.1-12.2.ts` (`markdownConfig(true)` and `markdownConfig(false)` one module-level record each, staged at every site), two each of `section-12.3-12.5.ts` and `section-12.6.ts` (T12.6-2's malformed `--config` target an `unparseable` record), nine of `section-12.7.ts` (T12.7-3's malformed configuration one `unparseable` record staged at `cfg/xspec.config.ts` and `a/xspec.config.ts`), one of `section-13.1-13.2.ts`, two of `section-13.3.ts`, thirteen of `section-13.4.ts` (T13.4-11's `OrphanArm` typing its configuration fields `StagedTs`), three of `write-refusal-staging.ts`, and two of `section-14-ii.ts` (T14-9's precedence fixture, staged through `write-refusal-staging.ts`'s `prepareRefusalWorkspace`), and forty of Task 16m — thirty-one of `section-14.ts` (its `SPECS_ONLY_CONFIG` and `SPEC_AND_CODE_CONFIG` the records themselves, staged at every site; `BOGUS_KEY_CONFIG` one record for the byte-identical inline configurations of T14-3's configuration-error arm and `BOGUS_KEY_DECL`; `markdownConfig(true)`'s record; the sweep's 14.22 configuration and code-source entries wrapped in place, `codeArm` taking a record; T14-5's `.mts` arm's configuration and `src/view.mts`, an `unparseable` record wrapping `T14_5_UNIT_SOURCE` — the `.tsx` arm, the body's first workspace, stages the constant plain, and one record carries one grammar and one declaration; T14-11's code sources, (m)'s and (v)'s `unparseable`, (u)'s one record per table row, `RangeRuleCase.config` typed `StagedTs` and its `ts` field gone, and `reassertedCase` throwing at load unless each (w) staging's failing file is a record declared unparseable), one of `section-14-ii.ts` (T14-10 (g)'s invalid configuration), and eight of `section-14-iii.ts` (its two configurations the records themselves, T14-12's code-form arms (l)–(o) one record per row, and the negative code arms (p) and (q) `unparseable` records, `unparseableDecl` declaring nothing beside them), and eight of Task 16n — one configuration each of `section-16-p1.ts`, `section-16-p2-p3.ts`, `section-16-p4.ts`, `section-16-p9.ts`, and `section-16-p10.ts` (each module's constant the record itself; P-2/P-3's `stagedSources` hands the runner the draw's composed files only), `section-16-p5-p6.ts`'s `P5_P6_SPECS_ONLY_CONFIG` (a wrapper of `section-5.6.ts`'s plain `SPECS_ONLY_CONFIG`, staged by `drawWorkspace`), and `section-16-p8.ts`'s two, the fuzz base configuration and `src/app.ts` in `FUZZ_BASE_RECORDS` beside its two MDX records (P-12 needs none: its trials stage `section-11.2.ts`'s record by import); 502 at Task 16n, 494 at Task 16m, 454 at Task 16l, 412 at Task 16k, 384 at Task 16j, 361 at Task 16i, 298 at Task 16h, 249 at Task 16g, 202 at Task 16f, 181 at Task 16e, 159 at Task 16d, 88 at Task 16c, 38 at Task 16b, 21 at Task 16; the self-test alone runs 1350 tests from Task 16o, 1347 at Task 16n, 1339 at Task 16m, 1299 at Task 16l, 1257 at Task 16k, 1229 at Task 16j, 1206 at Task 16i, 1143 at Task 16h, ~8 s). Red check: break one record's bytes on a scratch-backed copy (T1.5-2's `CODE_ARM_SOURCE` in `section-1.5.ts`, `export const ok` to `export const`), run the self-test alone with `-t '<record name>'`, read `HarnessStagingError: ts-derivability staging of <record name>: declared well-formed, but it is not well-formed TypeScript …`, restore with `cp` and verify with `cmp`. Conversion rule: every code source or configuration file (any path the TypeScript check judges — a `TS_DEFAULT_SUFFIXES` name, or one declared in `ts.wellFormed` or `ts.unparseable`) a body stages after its first product invocation — a `file()` call after an invocation in that workspace or anywhere in the running body, or an initial `files` entry of a workspace the body creates after its first invocation — is a `StagedTs` created at module level from the SAME expression (moved, never re-spelled; staged bytes identical; verify escape-spelled literals byte-wise), carrying the declaration in effect for that write (the former `ts` option, else the workspace declaration's entry — then dropped from the workspace declaration, the record carrying it — else well-formed) and the grammar its path selects. A module constant serving pre- and post-invocation stagings becomes the record itself (named after the tests staging it after an invocation; other uses pass the record too, a string use takes `.source`); a template function called with body-local state is enumerated, in order, into a module-level record table, and one called with fixed arguments gives one module-level record per distinct call (`section-7-discovery.ts`'s `invalidSourceConfig`, since Task 16l `section-12.1-12.2.ts`'s `markdownConfig` and `section-13.1-13.2.ts`'s `emissionConfig`); an arm or variant table types its field `StagedTs`. An imported constant whose owner's bodies stage it only before an invocation stays plain in its owner, and the consuming module wraps it in a record of its own, passed at its post-invocation sites only (`section-9.3.ts`'s `T9_3_3_ARM_2_CONFIG` until the plan written at 2a2b94e's FIX_PLAN Task 132, which made the owners' own impact stagings post-invocation stagings of T12.0-15 and so gave the owners the wrappers, beside the plain exports other modules import: `section-5.6.ts`'s `IMPACT_SPECS_ONLY_CONFIG`, staged by T9.3-3's arm 2 too, and `section-9.ts`'s `IMPACT_SPEC_AND_CODE_CONFIG`; since Task 16k `section-11.3.ts`'s `T11_3_1_*`, `section-12.0-ii.ts`'s, and `section-12.0-iii.ts`'s wrappers); an inline literal is hoisted into a module-level record, byte-identical inline literals of one module sharing one. Not records: `unchecked` stagings (P-8's and P-11's mutations, T13.4-2's damaged derived files, T13.4-4's noise, and a tampered generated module — product-written bytes plus a harness suffix, staged by `file()` with `{ ts: "unchecked" }`, since judging them would make a product's malformed module a harness error: T7.5-6's `hi/H.xspec.ts` since Task 16i, and `section-12.1-12.2.ts`'s `${original}// tampered` stagings — T12.2-2's `specs/A.xspec.ts` and T12.2-4 (a)'s `hi/H.xspec.ts` — since Task 16l), `edit()` of product-written bytes, `copyFrom()` of product output, and draw-composed files (P-7's configurations; P-13's configuration, `c0/U.ts`, and `c1/V.ts`), declared per draw since FIX_PLAN Task 16o (`ts.perDraw`; the runner's own per-draw TypeScript check is FIX_PLAN Task 64's). Finding a module's remaining plain post-invocation TypeScript stagings (the detector, temporary; since FIX_PLAN Task 16o the guard's TypeScript arm refuses each such staging at the first run reaching it, so the detector serves only to list every site in one pass): save `test/helpers/workspace.ts`, add a module-level function that appends one JSON line (path key, declaration, site, the workspace mark, `productInvokedInBody()`, the first stack frames under `test/suite/` or `test/helpers/`) to the file `$XSPEC_TS_PLAIN` names when the declaration is defined and not `unchecked` and either mark is set, and call it from the plain-contents branch of `file()` (declaration `options.ts ?? this.tsDeclarationOf(rel)`, mark `this.invocationMark.invoked`), of `stageInitial()` (`this.tsDeclarationOf(rel)`, mark false — only the per-body mark applies at creation), of `copyFrom()` when `!source.productInvoked`, and from the `StagedMdx` branches when the record carries no `ts`; run the module's suite files under the namespace with the variable set (and `test/self/certification.test.ts`, whose conformer runs reach arms past the built product's diagnosed failures), then restore with `cp` and verify with `cmp`. No line means no plain post-invocation staging was reached; a site behind a diagnosed product failure that no conformer reaches shows only by reading the module. The first survey (an instrument in `checkTs` logging every judged staging with both marks, at 3f43daa, over the whole suite and `certification.test.ts`) found 1902 post-invocation TypeScript stagings, about 600 distinct (path, bytes) pairs, across about 70 modules; certification added arms of T7-6 and T13.4-11 the suite's diagnosed failures hide. After the §1 conversion and E-6 (Task 16 itself): the §1 suite files and the E-6 writer keep their verdicts against the built product (26 of 28 pass; T1.4-1 and T1.4-4 fail diagnosed at their U+2028 arms), and the detector finds no plain post-invocation staging in them. After §2 and §3 (Task 16b): the six suite files keep their verdicts against the built product (36 of 36 pass, ~40 s under the namespace), and the detector finds no plain post-invocation staging in them; run over `certification.test.ts` (~2.2 min) it still logs the bodies of later split tasks and of the property runner — P-1, P-2, P-3, T7-4, T7-6, T13.4-11, T13.5-1, T13.5-4, T13.5-8, T11.2-4, and T11.4-3. After `section-4.ts` (Task 16c): the two §4-preamble suite files (`section-4.test.ts`, `section-4.1-4.2.test.ts`) keep their verdicts against the built product (12 of 12 pass, ~35 s under the namespace), and the detector finds no plain post-invocation staging in them (92 before); `section-4.1-4.2.ts` stages nothing after an invocation (one workspace per body, no `file()`), and no §4 test is certified, so `certification.test.ts` reaches none of them. After §4.3–§4.6 (Task 16d): `section-4.3-4.4.test.ts`, `section-4.5.test.ts`, and `section-4.6.test.ts` keep their verdicts against the built product (17 of 17 pass; ~17 s, ~60 s, and ~11 s under the namespace), and the detector finds no plain post-invocation staging in them (135 before); `stageOffendingStatement`, `stageSameScopeArm`, and `stageCollidingTextCall` in `section-4.5.ts` run at module load, so a broken arm table there fails the registry's load with its harness error. After §5 and §6.1–§6.4 (Task 16e): the nine suite files `section-5.1-5.3.test.ts` through `section-6.4.test.ts` keep their verdicts against the built product (40 of 40 pass; ~190–200 s run one file at a time under the namespace), and the detector finds no plain post-invocation staging in them (65 before); `section-5.6.ts` stages only `.mdx` records after an invocation, and T6.4-7's `copyFrom()` seeding of product output stays plain. Shared constants that later modules' bodies also stage after an invocation are records since Task 16e, so the detector no longer logs those sites: `support.ts`'s `UNKNOWN_KEY_CONFIG` (the configuration-state twins' invalid configuration; T6.4-3, T6.5-5, T10.7-1, T11-2, T11-4, and T12.0-5 stage the twins after an invocation, T11.3-3 before any), `section-5.7.ts`'s exported `SPEC_AND_CODE_CONFIG` (T11.3-1), and `section-6.4.ts`'s exported `RENAME_REFUSAL_CONFIG`, `RENAME_USAGE_CONFIG`, and `RENAME_USAGE_ORDERING_FILES`'s `src/app.ts` (T6.6-3); the twins' `missing` workspace still stages the callers' own plain `src/app.ts` maps (T11-2, T11-4; T6.5-5's passes a record since Task 16f). The consumer suite files `section-6.5`, `6.6`, `11`, `11.3`, `12.0-i`, and `14` keep their verdicts with those records (41 of 41 pass, ~190 s together under the namespace). After §6.5–§6.7 (Task 16f): the five suite files `section-6.5.test.ts`, `section-6.5-ii.test.ts`, `section-6.5-iii.test.ts`, `section-6.6.test.ts`, and `section-6.7.test.ts` keep their verdicts against the built product (25 of 25 pass; ~325 s together under the namespace with `--no-file-parallelism`), and the detector finds no plain post-invocation staging in them (183 before); T6.5-1's consumer `src/app.ts` records are made in `fileMoveArm` at module load, one per specifier, and the code sources and configurations only a body's first workspace stages, before any invocation (T6.5-7's, T6.5-8's TS arm's, T6.5-9's, T6.5-18's, and T6.6-4(a)'s), stay plain. Shared constants made records by Task 16f for other modules' bodies: `section-6.5.ts`'s exported `MOVE_REFUSAL_CONFIG` and `MOVE_DERIVED_PATH_CONFIG` and `section-6.5-iii.ts`'s exported `R16_CONFIG` (T14-7's later workspaces), and `section-13.5.ts`'s one configuration (`CORE_DECL`'s and `ISO_TWO_DECL`'s; T6.6-3, T13.5-1, T13.5-4, T13.5-6, and T13.5-8 stage it after an invocation), so the detector logs no site of `section-13.5.ts`'s own (T13.5-7's are `write-refusal-staging.ts`'s); over `certification.test.ts` (27 of 27 pass, ~133 s) it now logs only P-1, P-2, P-3, T7-4, T7-6, T11.2-4, T11.4-3, and T13.4-11. The consumer suite files `section-13.5` and `section-14` keep their verdicts with those records (17 of 17 pass, ~260 s together under the namespace). After `section-7-basics.ts` (Task 16g): `section-7-basics.test.ts` keeps its verdicts against the built product (3 of 3 pass, ~51 s under the namespace), and the detector finds no plain post-invocation staging in it (48 before); `refusedConfigArms` makes the five refused-configuration tables' records at module load, one per row, `expectConfigRefused` takes a record (its declaration the record's), and `SPECS_ONLY_CONFIG` is one record serving T7-1 and T7-3; no T7-1–T7-3 body is certified per fixture, so over `certification.test.ts` (~146 s with the detector) it still logs only P-1, P-2, P-3, T7-4, T7-6, T11.2-4, T11.4-3, and T13.4-11. After `section-7-discovery.ts` and `section-7.1-7.3.ts` (Task 16h): the two suite files keep their verdicts against the built product (5 of 6 pass, T7-6 failing diagnosed at its invalid-source arm; ~31 s together under the namespace with `--no-file-parallelism`), and the detector finds no plain post-invocation staging in them (45 before); `runT74SingleCasingGlobProbe` stages its configuration record on the Windows leg too (E-6), T7-6's `specs/a'b.md` record is made from the string constant its condition-20 window still spells, and `expectConfigRefused` of `section-7.1-7.3.ts` takes a record; over `certification.test.ts` (~141 s with the detector; the CONF-DISC conformer reaches T7-6's arms past the built product's diagnosed failure) it now logs only P-1, P-2, P-3, T11.2-4, T11.4-3, and T13.4-11. After `section-7.4-7.5.ts` (Task 16i): `section-7.4-7.5.test.ts` keeps its verdicts against the built product (8 of 8 pass, ~45 s under the namespace), and the detector finds no plain post-invocation staging in it (106 before); no T7.4 or T7.5 test is certified, so over `certification.test.ts` (~132 s with the detector) it still logs only P-1, P-2, P-3, T11.2-4, T11.4-3, and T13.4-11. After §8–§10 (Task 16j): the ten suite files `section-8.test.ts`, `section-9.test.ts`, `section-9.3.test.ts`, and the seven §10 files keep their verdicts against the built product (54 of 54 pass, ~435 s together under the namespace with `--no-file-parallelism`), and the detector finds no plain post-invocation staging in them (53 before); `section-9.ts` stages no TypeScript after an invocation (each body's one workspace, its code-source edits before the first `build`); `section-5.6.ts`'s exported `SPECS_ONLY_CONFIG` stays a plain string, and a consumer staging it after an invocation wraps it in a record of its own (T9.3-3's arm 2: `T9_3_3_ARM_2_CONFIG` in `section-9.3.ts`, since the plan written at 2a2b94e's FIX_PLAN Task 132 `section-5.6.ts`'s own `IMPACT_SPECS_ONLY_CONFIG`); no §8–§10 test is certified, so over `certification.test.ts` (~123 s with the detector) it still logs only P-1, P-2, P-3, T11.2-4, T11.4-3, and T13.4-11. After §11 and §12.0 (Task 16k): the nine suite files `section-11.test.ts`, `section-11.2.test.ts` through `section-11.6.test.ts`, and the three `section-12.0` files keep their verdicts against the built product (44 of 44 pass; ~351 s before and ~332 s after, together under the namespace with `--no-file-parallelism`), and the detector finds no plain post-invocation staging in them (51 before); `section-11.4.ts` needed no edit (its later workspaces stage `section-11.2.ts`'s record) and `section-11.5.ts` stages no TypeScript after an invocation; P-12's trials stage that record by import, so `section-16-p12.test.ts` under the detector (passing, ~274 s) logs nothing; over `certification.test.ts` (~133 s with the detector) it now logs only P-1, P-2, P-3, and T13.4-11. After §12.1–§13 (Task 16l): the nine suite files `section-12.1-12.2.test.ts`, `section-12.3-12.5.test.ts`, `section-12.6.test.ts`, `section-12.7.test.ts`, `section-13.1-13.2.test.ts`, `section-13.3.test.ts`, `section-13.4.test.ts`, `section-13.5.test.ts`, and `section-14-ii.test.ts` keep their verdicts against the built product (40 of 41 pass, T13.4-11 failing diagnosed at arm (a); ~334 s before and ~314 s after, together under the namespace with `--no-file-parallelism`), and the detector finds no plain post-invocation staging in them but T14-10's invalid configuration in `section-14-ii.ts` (Task 16m's; 102 before); T14-9's precedence fixture in `section-14-ii.ts` is staged through `write-refusal-staging.ts`'s `prepareRefusalWorkspace`, so its two records came with that module's; over `certification.test.ts` (~122 s with the detector; the CONF-ORPHAN conformer reaches T13.4-11's later arms) it now logs only P-1, P-2, and P-3. After §14 (Task 16m): the three suite files `section-14.test.ts`, `section-14-ii.test.ts`, and `section-14-iii.test.ts` keep their verdicts against the built product (12 of 12 pass; ~259 s before and ~252 s after, together under the namespace with `--no-file-parallelism`), and the detector finds no plain post-invocation staging in them (194 before); over `certification.test.ts` (~123 s with the detector; 27 of 27 pass, 154 PASS / 38 FAIL lines) it still logs only P-1, P-2, and P-3, the property runner's fixed files (Task 16n). After the §16 properties' fixed files (Task 16n): the eleven `section-16-*.test.ts` suite files keep their verdicts against the built product (12 of 13 pass, P-1 failing diagnosed at seed 271828183's trial 11, shrunk to a lone U+2028, as before; 351 s before and 363 s after, together under the namespace on 4 workers with the detector and the write log on), and the detector over them logs only the draw-composed files Task 16o declares per draw — P-7's configurations (38) and P-13's configuration, `c0/U.ts`, and `c1/V.ts` (49) — of 422 before (P-1 39, P-2 70, P-3 17, P-4 34, P-5 32, P-6 11, P-8 70, P-9 8, P-10 8, P-11 46, and those 87; P-12 none); over `certification.test.ts` (27 of 27 pass, 154 PASS / 38 FAIL lines, ~134 s with the detector) it logs nothing. A byte-identity check for a conversion: temporarily make the builder's private `write()` append `{rel, length, sha256}` per write to a scratch file, run the module's suite file once with the HEAD module and once with the converted one, and compare the two ordered sequences (Task 16c: 162 writes, equal); over several suite files in one run, log `process.pid` too and compare per process — each test file runs in its own forked worker, and Vitest may order the files differently from one run to the next (Task 16e: 371 writes over the nine §5/§6.1–§6.4 files, run with `--no-file-parallelism`, equal; Task 16f: 739 over the five §6.5–§6.7 files and 655 over `section-13.5` and `section-14`, equal; Task 16g: 106 over `section-7-basics.test.ts`, equal; Task 16h: 162 over `section-7-discovery.test.ts` and `section-7.1-7.3.test.ts`, 99 and 63 per process, equal; Task 16i: 261 over `section-7.4-7.5.test.ts`, equal; Task 16j: 393 over the ten §8–§10 suite files, run with `--no-file-parallelism`, equal per process; Task 16k: 312 over the nine §11 and §12.0 suite files, run with `--no-file-parallelism`, equal per process; Task 16l: 513 over the nine §12.1–§13 suite files, `section-13.5` and `section-14-ii` among them, run with `--no-file-parallelism`, equal per process; Task 16m: 669 over the three §14 suite files, run with `--no-file-parallelism`, equal per process; Task 16n: 1540 over the eleven property suite files, run on 4 workers, 11 processes, equal per process). +- The staged-source ledger's TypeScript records (FIX_PLAN Task 16 and its split tasks; TEST-SPEC S-9's TypeScript and timing clauses, H-8): `test/helpers/staged-ts.ts` — `stagedTs(name, source, ts = "well-formed", grammar = "ts")` registers a `StagedTs` at module load (bytes; declaration `"well-formed"` or `"unparseable"`, never `unchecked`; grammar `"ts"`, or `"tsx"` for a `.tsx` path — SPEC 14.20 selects TSX by the `.tsx` suffix alone), named as MDX records are (`"<TEST-ID>[/<TEST-ID>…] <what it stages>"`, the lead IDs registered tests or `E-6`), sealed by the manifest beside the MDX ledger (`sealStagedTsLedger()` in `test/suite/registry/index.ts`). The builder (`test/helpers/workspace.ts`) takes a record in `file(rel, record)` and as an initial `files` entry (`InitialFileContents = FileContents | StagedMdx | StagedTs`) and stages its bytes under the record's declaration whatever the name (a record makes its path judged, as `ts.wellFormed` does); it throws `HarnessStagingError` mode `ts-derivability`, nothing written, for a `ts` option beside a record, a workspace `ts` entry naming an initial record's path, an `.mdx` path, and a path selecting the other grammar. An `.mdx` path a code group discovers is an MDX source and a code source at once: its MDX record carries the TypeScript declaration too (`stagedMdx(name, source, mdx, ts)`, e.g. T2.1-2's `docs/EXTRA.mdx`; and a configuration file read as a spec source, T7-10(e)'s `xspec.config.ts` a spec group discovers and `xspec.config.mdx` named by `--config`), staged under both, a `ts` option or workspace `ts` entry beside it a contradiction. `test/self/s9-staged-sources.test.ts` judges every TypeScript record with `judgeTsDeclaration(record.name, bytes, record.ts, tsGrammarFileName(record.grammar))` (the optional fourth argument names the grammar's neutral file) and every MDX record carrying `ts` as plain TypeScript, one test each: `npx vitest list --config test/vitest.config.ts --project self test/self/s9-staged-sources.test.ts | grep 'every staged TypeScript source'` lists them (503 from Task 16o: E-6's two — the self-test pins that count — the Windows leg's drive-mismatch configuration (`ANCHOR_CONFIG` of `test/helpers/e6-drive-mismatch.ts`, Task 16o), nineteen of the §1 modules, seventeen of §2 and §3, T2.1-2's `docs/EXTRA.mdx` MDX record carrying `ts` among them, fifty of `section-4.ts`, T4-2's and T4-5's arm tables laid out at module load one record per row, and seventy-one of §4.3–§4.6 — fifteen of `section-4.3-4.4.ts`, fifty of `section-4.5.ts`, six of `section-4.6.ts` — their arm tables likewise one record per row, and twenty-two of Task 16e — seven of `section-5.7.ts`, eight of `section-6.4.ts`, one each of the other §5 and §6.1–§6.3 modules but `section-5.6.ts`, and `support.ts`'s `UNKNOWN_KEY_CONFIG`, and twenty-one of Task 16f — ten of `section-6.5.ts`, five of `section-6.5-ii.ts`, two each of `section-6.5-iii.ts` and `section-6.6.ts`, one of `section-6.7.ts`, and `section-13.5.ts`'s configuration — and forty-seven of Task 16g, all of `section-7-basics.ts`, thirty-three of them its refused-configuration tables' rows, and forty-nine of Task 16h — twenty-six of `section-7-discovery.ts` (T7-4's outside-root and inside-root arms one record per row) and twenty-three of `section-7.1-7.3.ts` (T7.3-1's emission-matrix, emit-required, and invalid-outDir tables one record per row), and sixty-three of Task 16i, all of `section-7.4-7.5.ts` (T7.4-1's and T7.5-1's matrix tables one record per row; its byte-identical code sources one record each, `OK_CODE_SOURCE` for `src/impl.ts` and `dualcode/d.ts`, `CODE_MARKER_TO_P` for T7.5-5's five paths), and twenty-three of Task 16j — two of `section-8.ts`, one of `section-9.3.ts`, two each of `section-10.1.ts` and `section-10.2-10.3.ts`, four of `section-10.4.ts`, one each of `section-10.5.ts` and `section-10.6.ts`, four of `section-10.7-i.ts`, and six of `section-10.7-ii.ts` (the §10 modules' configuration constants the records themselves, staged in every workspace that names them; `section-8.ts`'s two wrapped in place in their `files` maps; `section-9.3.ts`'s a record wrapping `section-5.6.ts`'s constant), and twenty-eight of Task 16k — two of `section-11.ts`, three of `section-11.2.ts` (its exported `SPECS_ONLY_CONFIG` the record itself, staged by import in the §11.3, §11.4, and P-12 bodies), five of `section-11.3.ts` (wrappers of other modules' plain constants), eight of `section-11.6.ts` (T11.6-4's broken configuration an `unparseable` record), three of `section-12.0-i.ts`, six of `section-12.0-ii.ts` (its two byte-identical inline unknown-key configurations one record), and one of `section-12.0-iii.ts`, and forty-two of Task 16l — eight of `section-12.1-12.2.ts` (`markdownConfig(true)` and `markdownConfig(false)` one module-level record each, staged at every site), two each of `section-12.3-12.5.ts` and `section-12.6.ts` (T12.6-2's malformed `--config` target an `unparseable` record), nine of `section-12.7.ts` (T12.7-3's malformed configuration one `unparseable` record staged at `cfg/xspec.config.ts` and `a/xspec.config.ts`), one of `section-13.1-13.2.ts`, two of `section-13.3.ts`, thirteen of `section-13.4.ts` (T13.4-11's `OrphanArm` typing its configuration fields `StagedTs`), three of `write-refusal-staging.ts`, and two of `section-14-ii.ts` (T14-9's precedence fixture, staged through `write-refusal-staging.ts`'s `prepareRefusalWorkspace`), and forty of Task 16m — thirty-one of `section-14.ts` (its `SPECS_ONLY_CONFIG` and `SPEC_AND_CODE_CONFIG` the records themselves, staged at every site; `BOGUS_KEY_CONFIG` one record for the byte-identical inline configurations of T14-3's configuration-error arm and `BOGUS_KEY_DECL`; `markdownConfig(true)`'s record; the sweep's 14.22 configuration and code-source entries wrapped in place, `codeArm` taking a record; T14-5's `.mts` arm's configuration and `src/view.mts`, an `unparseable` record wrapping `T14_5_UNIT_SOURCE` — the `.tsx` arm, the body's first workspace, stages the constant plain, and one record carries one grammar and one declaration; T14-11's code sources, (m)'s and (v)'s `unparseable`, (u)'s one record per table row, `RangeRuleCase.config` typed `StagedTs` and its `ts` field gone, and `reassertedCase` throwing at load unless each (w) staging's failing file is a record declared unparseable), one of `section-14-ii.ts` (T14-10 (g)'s invalid configuration), and eight of `section-14-iii.ts` (its two configurations the records themselves, T14-12's code-form arms (l)–(o) one record per row, and the negative code arms (p) and (q) `unparseable` records, `unparseableDecl` declaring nothing beside them), and eight of Task 16n — one configuration each of `section-16-p1.ts`, `section-16-p2-p3.ts`, `section-16-p4.ts`, `section-16-p9.ts`, and `section-16-p10.ts` (each module's constant the record itself; P-2/P-3's `stagedSources` hands the runner the draw's composed files only), `section-16-p5-p6.ts`'s `P5_P6_SPECS_ONLY_CONFIG` (a wrapper of `section-5.6.ts`'s plain `SPECS_ONLY_CONFIG`, staged by `drawWorkspace`), and `section-16-p8.ts`'s two, the fuzz base configuration and `src/app.ts` in `FUZZ_BASE_RECORDS` beside its two MDX records (P-12 needs none: its trials stage `section-11.2.ts`'s record by import); 502 at Task 16n, 494 at Task 16m, 454 at Task 16l, 412 at Task 16k, 384 at Task 16j, 361 at Task 16i, 298 at Task 16h, 249 at Task 16g, 202 at Task 16f, 181 at Task 16e, 159 at Task 16d, 88 at Task 16c, 38 at Task 16b, 21 at Task 16; the self-test alone runs 1350 tests from Task 16o, 1347 at Task 16n, 1339 at Task 16m, 1299 at Task 16l, 1257 at Task 16k, 1229 at Task 16j, 1206 at Task 16i, 1143 at Task 16h, ~8 s). Red check: break one record's bytes on a scratch-backed copy (T1.5-2's `CODE_ARM_SOURCE` in `section-1.5.ts`, `export const ok` to `export const`), run the self-test alone with `-t '<record name>'`, read `HarnessStagingError: ts-derivability staging of <record name>: declared well-formed, but it is not well-formed TypeScript …`, restore with `cp` and verify with `cmp`. Conversion rule: every code source or configuration file (any path the TypeScript check judges — a `TS_DEFAULT_SUFFIXES` name, or one declared in `ts.wellFormed` or `ts.unparseable`) a body stages after its first product invocation — a `file()` call after an invocation in that workspace or anywhere in the running body, or an initial `files` entry of a workspace the body creates after its first invocation — is a `StagedTs` created at module level from the SAME expression (moved, never re-spelled; staged bytes identical; verify escape-spelled literals byte-wise), carrying the declaration in effect for that write (the former `ts` option, else the workspace declaration's entry — then dropped from the workspace declaration, the record carrying it — else well-formed) and the grammar its path selects. A module constant serving pre- and post-invocation stagings becomes the record itself (named after the tests staging it after an invocation; other uses pass the record too, a string use takes `.source`); a template function called with body-local state is enumerated, in order, into a module-level record table, and one called with fixed arguments gives one module-level record per distinct call (`section-7-discovery.ts`'s `invalidSourceConfig`, since Task 16l `section-12.1-12.2.ts`'s `markdownConfig` and `section-13.1-13.2.ts`'s `emissionConfig`); an arm or variant table types its field `StagedTs`. An imported constant whose owner's bodies stage it only before an invocation stays plain in its owner, and the consuming module wraps it in a record of its own, passed at its post-invocation sites only (`section-9.3.ts`'s `T9_3_3_ARM_2_CONFIG` until the plan written at 2a2b94e's FIX_PLAN Task 132, which made the owners' own impact stagings post-invocation stagings of T12.0-15 and so gave the owners the wrappers, beside the plain exports other modules import: `section-5.6.ts`'s `IMPACT_SPECS_ONLY_CONFIG`, staged by T9.3-3's arm 2 too, and `section-9.ts`'s `IMPACT_SPEC_AND_CODE_CONFIG`; since Task 16k `section-11.3.ts`'s `T11_3_1_*`, `section-12.0-ii.ts`'s, and `section-12.0-iii.ts`'s wrappers); an inline literal is hoisted into a module-level record, byte-identical inline literals of one module sharing one. Not records: `unchecked` stagings (P-8's and P-11's mutations, T13.4-2's damaged derived files, T13.4-4's noise, and a tampered generated module — product-written bytes plus a harness suffix, staged by `file()` with `{ ts: "unchecked" }`, since judging them would make a product's malformed module a harness error: T7.5-6's `hi/H.xspec.ts` since Task 16i, and `section-12.1-12.2.ts`'s `${original}// tampered` stagings — T12.2-2's `specs/A.xspec.ts` and T12.2-4 (a)'s `hi/H.xspec.ts` — since Task 16l), `edit()` of product-written bytes, `copyFrom()` of product output, and draw-composed files (P-7's configurations; P-13's configuration, `c0/U.ts`, and `c1/V.ts`), declared per draw since FIX_PLAN Task 16o (`ts.perDraw`; the runner's own per-draw TypeScript check is FIX_PLAN Task 64's). Finding a module's remaining plain post-invocation TypeScript stagings (the detector, temporary; since FIX_PLAN Task 16o the guard's TypeScript arm refuses each such staging at the first run reaching it, so the detector serves only to list every site in one pass): save `test/helpers/workspace.ts`, add a module-level function that appends one JSON line (path key, declaration, site, the workspace mark, `productInvokedInBody()`, the first stack frames under `test/suite/` or `test/helpers/`) to the file `$XSPEC_TS_PLAIN` names when the declaration is defined and not `unchecked` and either mark is set, and call it from the plain-contents branch of `file()` (declaration `options.ts ?? this.tsDeclarationOf(rel)`, mark `this.invocationMark.invoked`), of `stageInitial()` (`this.tsDeclarationOf(rel)`, mark false — only the per-body mark applies at creation), of `copyFrom()` when `!source.productInvoked`, and from the `StagedMdx` branches when the record carries no `ts`; run the module's suite files under the namespace with the variable set (and `test/self/certification.test.ts`, whose conformer runs reach arms past the built product's diagnosed failures), then restore with `cp` and verify with `cmp`. No line means no plain post-invocation staging was reached; a site behind a diagnosed product failure that no conformer reaches shows only by reading the module. The first survey (an instrument in `checkTs` logging every judged staging with both marks, at 3f43daa, over the whole suite and `certification.test.ts`) found 1902 post-invocation TypeScript stagings, about 600 distinct (path, bytes) pairs, across about 70 modules; certification added arms of T7-6 and T13.4-11 the suite's diagnosed failures hide. After the §1 conversion and E-6 (Task 16 itself): the §1 suite files and the E-6 writer keep their verdicts against the built product (26 of 28 pass; T1.4-1 and T1.4-4 fail diagnosed at their U+2028 arms), and the detector finds no plain post-invocation staging in them. After §2 and §3 (Task 16b): the six suite files keep their verdicts against the built product (36 of 36 pass, ~40 s under the namespace), and the detector finds no plain post-invocation staging in them; run over `certification.test.ts` (~2.2 min) it still logs the bodies of later split tasks and of the property runner — P-1, P-2, P-3, T7-4, T7-6, T13.4-11, T13.5-1, T13.5-4, T13.5-8, T11.2-4, and T11.4-3. After `section-4.ts` (Task 16c): the two §4-preamble suite files (`section-4.test.ts`, `section-4.1-4.2.test.ts`) keep their verdicts against the built product (12 of 12 pass, ~35 s under the namespace), and the detector finds no plain post-invocation staging in them (92 before); `section-4.1-4.2.ts` stages nothing after an invocation (one workspace per body, no `file()`), and no §4 test is certified, so `certification.test.ts` reaches none of them. After §4.3–§4.6 (Task 16d): `section-4.3-4.4.test.ts`, `section-4.5.test.ts`, and `section-4.6.test.ts` keep their verdicts against the built product (17 of 17 pass; ~17 s, ~60 s, and ~11 s under the namespace), and the detector finds no plain post-invocation staging in them (135 before); `stageOffendingStatement`, `stageSameScopeArm`, and `stageCollidingTextCall` in `section-4.5.ts` run at module load, so a broken arm table there fails the registry's load with its harness error. After §5 and §6.1–§6.4 (Task 16e): the nine suite files `section-5.1-5.3.test.ts` through `section-6.4.test.ts` keep their verdicts against the built product (40 of 40 pass; ~190–200 s run one file at a time under the namespace), and the detector finds no plain post-invocation staging in them (65 before); `section-5.6.ts` stages only `.mdx` records after an invocation, and T6.4-7's `copyFrom()` seeding of product output stays plain. Shared constants that later modules' bodies also stage after an invocation are records since Task 16e, so the detector no longer logs those sites: `support.ts`'s `UNKNOWN_KEY_CONFIG` (the configuration-state twins' invalid configuration; T6.4-3, T6.5-5, T10.7-1, T11-2, T11-4, and T12.0-5 stage the twins after an invocation, T11.3-3 before any), `section-5.7.ts`'s exported `SPEC_AND_CODE_CONFIG` (T11.3-1), and `section-6.4.ts`'s exported `RENAME_REFUSAL_CONFIG`, `RENAME_USAGE_CONFIG`, and `RENAME_USAGE_ORDERING_FILES`'s `src/app.ts` (T6.6-3); the twins' `missing` workspace still stages the callers' own plain `src/app.ts` maps (T11-2, T11-4; T6.5-5's passes a record since Task 16f). The consumer suite files `section-6.5`, `6.6`, `11`, `11.3`, `12.0-i`, and `14` keep their verdicts with those records (41 of 41 pass, ~190 s together under the namespace). After §6.5–§6.7 (Task 16f): the five suite files `section-6.5.test.ts`, `section-6.5-ii.test.ts`, `section-6.5-iii.test.ts`, `section-6.6.test.ts`, and `section-6.7.test.ts` keep their verdicts against the built product (25 of 25 pass; ~325 s together under the namespace with `--no-file-parallelism`), and the detector finds no plain post-invocation staging in them (183 before); T6.5-1's consumer `src/app.ts` records are made in `fileMoveArm` at module load, one per specifier, and the code sources and configurations only a body's first workspace stages, before any invocation (T6.5-7's, T6.5-8's TS arm's, T6.5-9's, T6.5-18's, and T6.6-4(a)'s), stay plain. Shared constants made records by Task 16f for other modules' bodies: `section-6.5.ts`'s exported `MOVE_REFUSAL_CONFIG` and `MOVE_DERIVED_PATH_CONFIG` and `section-6.5-iii.ts`'s exported `R16_CONFIG` (T14-7's later workspaces), and `section-13.5.ts`'s one configuration (`CORE_DECL`'s and `ISO_TWO_DECL`'s; T6.6-3, T13.5-1, T13.5-4, T13.5-6, and T13.5-8 stage it after an invocation), so the detector logs no site of `section-13.5.ts`'s own (T13.5-7's are `write-refusal-staging.ts`'s); over `certification.test.ts` (27 of 27 pass, ~133 s) it now logs only P-1, P-2, P-3, T7-4, T7-6, T11.2-4, T11.4-3, and T13.4-11. The consumer suite files `section-13.5` and `section-14` keep their verdicts with those records (17 of 17 pass, ~260 s together under the namespace). After `section-7-basics.ts` (Task 16g): `section-7-basics.test.ts` keeps its verdicts against the built product (3 of 3 pass, ~51 s under the namespace), and the detector finds no plain post-invocation staging in it (48 before); `refusedConfigArms` makes the five refused-configuration tables' records at module load, one per row, `expectConfigRefused` takes a record (its declaration the record's), and `SPECS_ONLY_CONFIG` is one record serving T7-1 and T7-3; no T7-1–T7-3 body is certified per fixture, so over `certification.test.ts` (~146 s with the detector) it still logs only P-1, P-2, P-3, T7-4, T7-6, T11.2-4, T11.4-3, and T13.4-11. After `section-7-discovery.ts` and `section-7.1-7.3.ts` (Task 16h): the two suite files keep their verdicts against the built product (5 of 6 pass, T7-6 failing diagnosed at its invalid-source arm; ~31 s together under the namespace with `--no-file-parallelism`), and the detector finds no plain post-invocation staging in them (45 before); `runT74SingleCasingGlobProbe` stages its configuration record on the Windows leg too (E-6), T7-6's `specs/a'b.md` record is made from the string constant its condition-20 window still spells, and `expectConfigRefused` of `section-7.1-7.3.ts` takes a record; over `certification.test.ts` (~141 s with the detector; the CONF-DISC conformer reaches T7-6's arms past the built product's diagnosed failure) it now logs only P-1, P-2, P-3, T11.2-4, T11.4-3, and T13.4-11. After `section-7.4-7.5.ts` (Task 16i): `section-7.4-7.5.test.ts` keeps its verdicts against the built product (8 of 8 pass, ~45 s under the namespace), and the detector finds no plain post-invocation staging in it (106 before); no T7.4 or T7.5 test is certified, so over `certification.test.ts` (~132 s with the detector) it still logs only P-1, P-2, P-3, T11.2-4, T11.4-3, and T13.4-11. After §8–§10 (Task 16j): the ten suite files `section-8.test.ts`, `section-9.test.ts`, `section-9.3.test.ts`, and the seven §10 files keep their verdicts against the built product (54 of 54 pass, ~435 s together under the namespace with `--no-file-parallelism`), and the detector finds no plain post-invocation staging in them (53 before); `section-9.ts` stages no TypeScript after an invocation (each body's one workspace, its code-source edits before the first `build`); `section-5.6.ts`'s exported `SPECS_ONLY_CONFIG` stays a plain string, and a consumer staging it after an invocation wraps it in a record of its own (T9.3-3's arm 2: `T9_3_3_ARM_2_CONFIG` in `section-9.3.ts`, since the plan written at 2a2b94e's FIX_PLAN Task 132 `section-5.6.ts`'s own `IMPACT_SPECS_ONLY_CONFIG`); no §8–§10 test is certified, so over `certification.test.ts` (~123 s with the detector) it still logs only P-1, P-2, P-3, T11.2-4, T11.4-3, and T13.4-11. After §11 and §12.0 (Task 16k): the nine suite files `section-11.test.ts`, `section-11.2.test.ts` through `section-11.6.test.ts`, and the three `section-12.0` files keep their verdicts against the built product (44 of 44 pass; ~351 s before and ~332 s after, together under the namespace with `--no-file-parallelism`), and the detector finds no plain post-invocation staging in them (51 before); `section-11.4.ts` needed no edit (its later workspaces stage `section-11.2.ts`'s record) and `section-11.5.ts` stages no TypeScript after an invocation; P-12's trials stage that record by import, so `section-16-p12.test.ts` under the detector (passing, ~274 s) logs nothing; over `certification.test.ts` (~133 s with the detector) it now logs only P-1, P-2, P-3, and T13.4-11. After §12.1–§13 (Task 16l): the nine suite files `section-12.1-12.2.test.ts`, `section-12.3-12.5.test.ts`, `section-12.6.test.ts`, `section-12.7.test.ts`, `section-13.1-13.2.test.ts`, `section-13.3.test.ts`, `section-13.4.test.ts`, `section-13.5.test.ts`, and `section-14-ii.test.ts` keep their verdicts against the built product (40 of 41 pass, T13.4-11 failing diagnosed at arm (a); ~334 s before and ~314 s after, together under the namespace with `--no-file-parallelism`), and the detector finds no plain post-invocation staging in them but T14-10's invalid configuration in `section-14-ii.ts` (Task 16m's; 102 before); T14-9's precedence fixture in `section-14-ii.ts` is staged through `write-refusal-staging.ts`'s `prepareRefusalWorkspace`, so its two records came with that module's; over `certification.test.ts` (~122 s with the detector; the CONF-ORPHAN conformer reaches T13.4-11's later arms) it now logs only P-1, P-2, and P-3. After §14 (Task 16m): the three suite files `section-14.test.ts`, `section-14-ii.test.ts`, and `section-14-iii.test.ts` keep their verdicts against the built product (12 of 12 pass; ~259 s before and ~252 s after, together under the namespace with `--no-file-parallelism`), and the detector finds no plain post-invocation staging in them (194 before); over `certification.test.ts` (~123 s with the detector; 27 of 27 pass, 154 PASS / 38 FAIL lines) it still logs only P-1, P-2, and P-3, the property runner's fixed files (Task 16n). After the §16 properties' fixed files (Task 16n): the eleven `section-16-*.test.ts` suite files keep their verdicts against the built product (12 of 13 pass, P-1 failing diagnosed at seed 271828183's trial 11, shrunk to a lone U+2028, as before; 351 s before and 363 s after, together under the namespace on 4 workers with the detector and the write log on), and the detector over them logs only the draw-composed files Task 16o declares per draw — P-7's configurations (38) and P-13's configuration, `c0/U.ts`, and `c1/V.ts` (49) — of 422 before (P-1 39, P-2 70, P-3 17, P-4 34, P-5 32, P-6 11, P-8 70, P-9 8, P-10 8, P-11 46, and those 87; P-12 none); over `certification.test.ts` (27 of 27 pass, 154 PASS / 38 FAIL lines, ~134 s with the detector) it logs nothing. A byte-identity check for a conversion: temporarily make the builder's private `write()` append `{rel, length, sha256}` per write to a scratch file, run the module's suite file once with the HEAD module and once with the converted one, and compare the two ordered sequences (Task 16c: 162 writes, equal); over several suite files in one run, log `process.pid` too and compare per process — each test file runs in its own forked worker, and Vitest may order the files differently from one run to the next (Task 16e: 371 writes over the nine §5/§6.1–§6.4 files, run with `--no-file-parallelism`, equal; Task 16f: 739 over the five §6.5–§6.7 files and 655 over `section-13.5` and `section-14`, equal; Task 16g: 106 over `section-7-basics.test.ts`, equal; Task 16h: 162 over `section-7-discovery.test.ts` and `section-7.1-7.3.test.ts`, 99 and 63 per process, equal; Task 16i: 261 over `section-7.4-7.5.test.ts`, equal; Task 16j: 393 over the ten §8–§10 suite files, run with `--no-file-parallelism`, equal per process; Task 16k: 312 over the nine §11 and §12.0 suite files, run with `--no-file-parallelism`, equal per process; Task 16l: 513 over the nine §12.1–§13 suite files, `section-13.5` and `section-14-ii` among them, run with `--no-file-parallelism`, equal per process; Task 16m: 669 over the three §14 suite files, run with `--no-file-parallelism`, equal per process; Task 16n: 1540 over the eleven property suite files, run on 4 workers, 11 processes, equal per process). - P-12 valid by construction (fifth-plan FIX_PLAN Task 1; TEST-SPEC §16 preamble, S-9; `test/suite/registry/section-16-p12.ts`): `embedArgumentMenu(hasImport, s1Closed)` and `dPropMenu(hasImport, s1Closed)` offer the anchor `"t"`/`'t'` always, `M0.t` with the import, and the `"s1"` forms (the embedding and `d={["t", "s1"]}`) only once `genFileLines` has passed `s1`'s closing tag (`s1` is always the first, top-level section); the twists, the `"zz"` spellings, and `P12_UNPARSEABLE_VECTORS` are gone, `stagedP12Sources` returns every file unmarked, and `runP12Trial` declares `mdx: { perDraw: mdxPathsOf(files) }`. `P12_FORM_VECTORS` holds 44 vectors, pinned `toBe(44)` in `test/self/s9-fixture-well-formedness.test.ts` (1728 tests): the two every-form files (`s1` first, spelling the omitted prop and the opening menus alone inside it; the `"s1"` embeddings right after its closing tag; the later sections from the full menus) and 19 + 23 minimal contexts, where a `"s1"` form follows a closed `<S id="s1">`/`mot.`/`</S>` and the `d` array's bearer is `s2`. Draw facts: the CI set (`drawFixedSeedTrials(genP12Trial, 3)`, 9 trials) has 20 files, 8 imports, one `M0.t`, 4 embeddings and 6 single `d` props (10 occurrences), one depth-2 section, multi-byte prose in 14 files, and 1339 `at` invocations; neither it nor the 75-trial set (`…, 25`) draws a `"s1"` reference or a `d` array, which a 1000-trial sample on 40 other seeds (`1000 + 7919·i`, 25 runs each, passed as `drawFixedSeedTrials`'s third argument) draws 39 times (21 embeddings, 18 arrays) in 38 trials. Validity cross-check recipe (implementation-time, uncommitted): dump the draws and `P12_FORM_VECTORS` as JSON to the scratchpad from a temporary self-test (`writeFileSync(…, JSON.stringify(drawFixedSeedTrials(genP12Trial, 25)))`, deleted afterwards), then a Python script stages each trial in a fresh scratch directory with `SPECS_ONLY_CONFIG` (`test/suite/registry/section-11.2.ts`) as `xspec.config.ts` and runs `node /home/user/xspec/dist/cli/bin.js build --json` there — every trial of both sets, the sample's 38 `"s1"`-spelling trials, and all 44 vectors (a with-import vector staged as `specs/B.mdx` beside an anchor-only `specs/A.mdx`, `<S id="t">\nmot.\n</S>\n`) exit 0 with `{"findings": []}` (~1 min in all); before the change the reviewer's replay found only 3 of the 9 CI trials building. Red check: on a scratch-backed copy, `stagedP12Sources` returning `contents.replace("</S>", "")` fails P-12 in ~4.6 s at trial 1 of 3 of seed 271828183 with the runner's S-9 harness error (`HarnessStagingError: mdx-derivability staging of specs/A.mdx: composed by the generator as well-formed … end-tag-mismatch`) before any product invocation; restore with `cp` and `cmp`. Run facts at the fifth-plan Task 1: P-12 alone against the built product (`unshare --map-user=1000 --map-group=1000 -- npx vitest run --config test/vitest.config.ts --project suite test/suite/section-16-p12.test.ts --reporter=verbose`) passes at the fixed seeds in 158 s; self project 22 files, 2954 passed, 0 skipped under the namespace (~91 s); certification 144 PASS / 33 FAIL / 0 error / 0 hang over the 23 `certification run against` lines. - P-12 requires every staged file's view entry (fifth-plan FIX_PLAN Task 2; TEST-SPEC §16 P-12, H-8; SPEC 11.4, 11.2; `test/suite/registry/section-16-p12.ts`): right after the bare `view` answer's entries are collected into `viewByPath` (after the unknown-path and duplicate-view checks) and before the two `occurrences` invocations, `runP12Trial` maps `trial.files`, in order, to `[path, content, entry]` triples — a staged file with no entry fails (`fail`, context "P-12 `xspec view`": ``the answer carries no view for "<path>" — a staged spec source, parseable (valid by construction and judged derivable by S-9 before the product ran) and discovered under the configuration's `specs/**/*.mdx` …``) — and the at sweep iterates those triples; the masked-case arm (no entry answered by `{ unavailable: true }` at every offset) and the `UNAVAILABLE` constant are gone, the masked case being T11.5-3's deterministic arm, outside P-12's valid draws. Red check (the stand-in wrapper recipe above): a scratch wrapper whose `drop-view` mode pops the last element of every `view` answer's `views` array and re-serializes the document (exit code kept), driven from a temporary `test/self/zz-p5-task2-standin.test.ts` (`runProductTests(binding, productTestSuite.select(["P-12"]), { concurrency: 1 })`, run alone under the namespace with `--disable-console-intercept`, deleted before committing), fails P-12 as a diagnosed `PropertyFalsifiedError` (a `HarnessAssertionError`: outcome `fail`) in ~7 s at trial 1 of 3 of seed 271828183 — the drawn trial stages `specs/A.mdx`, `specs/B.mdx`, and `specs/C.mdx` (C's view the one dropped), and after 4 accepted shrink steps (4 property executions) the counterexample is `specs/A.mdx` alone holding the anchor (`<S id="t">`, `mot.`, `</S>`, each on its own line), its assertion the new message naming `specs/A.mdx`: the runner reports the shrunk counterexample's assertion, so the named file is the shrunk trial's last, not the drawn trial's. Run facts at the fifth-plan Task 2: P-12 alone against the built product (Task 1's command) passes at the fixed seeds (155 s test time, ~160 s wall); self project 22 files, 2954 passed, 0 skipped under the namespace (~90 s); certification 144 PASS / 33 FAIL / 0 error / 0 hang over the 23 `certification run against` lines. P-12 also requires every `view`, `occurrences`, and `at` answer to exit 0 with an empty `findings` member (the fourteenth plan's FIX_PLAN Task 2; H-5, SPEC 11.2: `runAnswer` fails any exit but 0, and the module-private `assertFindingFree` checks the bare `view` report, the first `occurrences` report, and every `at` report). Red/green check through a scratch wrapper of the same kind (`spawnSync` of `dist/cli/bin.js`, stdout written whole, the exit code forwarded unless the mode maps it), driven from a temporary self-test calling `runProductTests(binding, productTestSuite.select(["P-12"]), { concurrency: 1 })` with `XSPEC_PROPERTY_SEED=271828183` in the Vitest process's environment (one seed, 3 trials, 397 answers: 3 `view`, 6 `occurrences`, 388 `at`): a mode turning exit 0 into 1 for `view`/`at`/`occurrences`, and modes injecting one well-formed code-less finding (`{"code": null, "message": "…", "locations": [], "path": null, "identities": []}`, the document re-serialized) into exit-0 `view`, `occurrences`, or `at` answers, each passed before the change (~75 s apiece, a whole one-seed sweep) and each fails after it as a `PropertyFalsifiedError` naming the seed, shrunk in 4 steps to `specs/A.mdx` holding the anchor alone, at the first `view` (the exit-0 check; ~2 s), the first `view`, the first `occurrences`, or `at specs/A.mdx 0` (`assertFindingFree`; 2–6 s), the unmodified wrapper passing in ~78 s; against the empty stub P-12 fails at the exit-0 check of its first `view` (exit 87). P-12 alone against the built product passes in ~200–210 s on an idle machine. - The recorded configuration parse in `.xspec/graph.json` (`inputs.config`; SPEC 13.3; `src/core/config-data.ts`) is pretty-printed with two-space indentation, so a hand edit must match its multi-line form (a list spans one line per element). Since FIX_PLAN Task 7 of the Phase 10 plan written at 6694886 it is written and never read back: every command parses the configuration itself, and any hand edit of the store is a content mismatch that `query`, `at`, and every other refreshing read rewrite as `build` would. Hand check on a scratch workspace: `build`, copy the store, rewrite one recorded `targetTags` into a spelled order with a repeat (or a node's `"end"`), run `query nodes --json` or `at`, then `cmp` the store against the copy (byte-equal again once refreshed). A coverage session's recorded `targetTags`/`edgeKinds` are likewise read as sets: hand-edit them in `.xspec/reviews/<name>.json` and `review export <name>` reports the set forms, the session not corrupt. @@ -391,4 +422,5 @@ Build, test, and run instructions for this repository (nothing else belongs in t - Hand-probing chain-rewrite trivia (SPEC 6.4, 6.5, 6.6, 2.4, 14.20; the re-descent plan written at 6034904, its FIX_PLAN Task 151; `accessTokenStart` in `src/core/references.ts`, `segmentEdit` in `src/core/rename.ts`, `chainPrefixEdits` and `segmentDeletionEdits` in `src/core/move.ts`): rename's and the section move's chain rewrites replace tokens only — a segment's name token (its identifier, or its index literal with the quotes), and where a dot segment must become computed access (a new name that is no TypeScript identifier) its `.` token as well, replaced by `[` while the name token becomes the double-quoted literal and the `]` — so every whitespace, comment, and line-terminator byte between a chain's tokens stays where it is. `ClassifiedSegment.accessSpan` (and so `SegmentSpelling.accessRange`) starts at the segment's own `.` or `[` token — the name's, resp. the index's, full start (`node.name.pos`, `node.argumentExpression.pos`) minus one — never at the end of the preceding chain element. A move whose prefix replacement changes the segment count pairs old and new prefix segments from the chain's root: a longer new prefix gets its extra segments (6.4's fallback spelling: dot access for identifier-valid names, double-quoted computed access otherwise) inserted as one zero-length edit right after the last paired segment's last byte (`applyEdits` orders it after that segment's own edit, which ends there); a shorter one has each extra old segment's access deleted from its token through its last byte, the trivia before the token kept, and a line so left blank — whitespace (1.4) only, plus in a spec source a leading block-quote `>` prefix — is dropped (MDX ends a paragraph at a blank line inside a text-position embedding: `{text(O.p`, a line of two spaces, ` .y)}` fails to parse), adjacent blanked lines together, each with its own terminator while the chain continues past them, and with the terminator before the first where the chain ends on the last (so no byte outside the chain changes: SPEC 6.6 reports a reference rewrite at its occurrence). Before Task 151 a conversion replaced the whole access from the end of the preceding element, and a count-changing prefix was re-rendered from the end of the root, both dropping the trivia between. No suite test stages trivia inside a chain, so probe by hand: in a fresh `mktemp -d` workspace with `E6_CONFIG`, every line ending in LF, run `build --json`, the operation with `--preview --json` and then for real, read the rewritten files byte-wise, run `check --json` (exit 0, no finding, in every case below), and compare the preview document, the mapping, and `.xspec/journal` with a baseline build of the parent commit — a `git archive HEAD src tsconfig.base.json package.json` extract under its own `mktemp -d`, `node_modules` symlinked to the checkout's, built with `node_modules/.bin/tsc -p src` — which gives them byte-identical (only source bytes differ). Observed at Task 151: (a) `specs/A.mdx` = `<S id="a">`, `A`, `<S id="a.b">`, `B`, `</S>`, `</S>`; `specs/M.mdx` = `import A from "./A.xspec"`, a blank line, `<S id="m" d={[A /* c */ .a, A`, ` .a`, ` .b]}>`, `M`, `</S>`; `src/c.ts` = `import A from "../specs/A.xspec"`, `A`, ` // note`, ` .a`, ` .b`; after `rename specs/A.mdx a x-y` the `d` value is `d={[A /* c */ ["x-y"], A`, ` ["x-y"]`, ` .b]}` and `src/c.ts` is its import, `A`, ` // note`, ` ["x-y"]`, ` .b` (before: `A["x-y"]` each time, the comment, the line break, and the `// note` line gone); likewise `A . a` becomes `A [ "x-y"]`, `A./* c */a . b` becomes `A[/* c */"x-y"] . b`, `A. // c` over `a` becomes `A[ // c` over `"x-y"]`, `A [ 'a' ]` becomes `A [ 'x-y' ]`, and in MDX `{text(A . a)}` becomes `{text(A [ "x-y"])}`; `rename specs/A.mdx a z` changes the name tokens alone. (b) Lengthening: `specs/O.mdx` = `<S id="p">`, `P`, `</S>`, `<S id="x">`, `X`, `<S id="x.y">`, `Y`, `</S>`, `</S>`; `src/c.ts` = `import O from "../specs/O.xspec"`, `O /* keep */ . x`, `O`, ` // note`, ` .x`, ` .y`; `move specs/O.mdx#x specs/O.mdx#p.x` gives `O /* keep */ . p.x`, `O`, ` // note`, ` .p.x`, ` .y` (before: `O.p.x`, then `O.p.x` over ` .y`), and in a spec source `d={[O /* a */ . x, O`, ` .x // b`, ` .y]}` gives `d={[O /* a */ . p.x, O`, ` .p.x // b`, ` .y]}`; a cross-file `move specs/O.mdx#x specs/T.mdx#u.x` turns `O . x` into `T . u.x` and `O /* keep me */ .x` into `T /* keep me */ .u.x`; into a non-identifier parent (`move specs/O.mdx#x specs/O.mdx#a-b.x`) `O /* k */ . x` becomes `O /* k */ [ "a-b"].x` and `O['x']` becomes `O['a-b'].x` (before: `O["a-b"].x` both). (c) Shortening: `specs/O.mdx` holding `p` > `p.x` > `p.x.y`, `move specs/O.mdx#p.x specs/O.mdx#x`: `O.p /* c */ .x.y` becomes `O.x /* c */ .y`; `O.p // c`, ` .x`, ` .y` becomes `O.x // c`, ` .y`; `O`, ` .p`, ` .x`, ` .y` becomes `O`, ` .x`, ` .y`; `O.p`, ` .x` (the chain ending on the blanked line) becomes `O.x`, its last terminator kept; CRLF lines alike; a paragraph's `R {text(O.p`, ` .x`, ` .y)} end.` becomes `R {text(O.x`, ` .y)} end.`, in a block quote `> Q {text(O.p`, `> .x`, `> .y)} end.` becomes `> Q {text(O.x`, `> .y)} end.`, and `d={[O.p`, ` .x`, `]}>` becomes `d={[O.x`, `]}>`; to a non-identifier ID (`#p.x` to `#a-b`) `O.p`, ` .x`, ` .y` becomes `O["a-b"]`, ` .y`, and `O['p']`, ` ['x']` becomes `O['a-b']`. Moving `p.x.y` to `z` under a fourth level `p.x.y.w`: `O`, ` .p`, ` .x`, ` .y` becomes `O`, ` .z` (two adjacent lines dropped, no empty line left), with ` .w` after them it becomes `O`, ` .z`, ` .w`, `O.p.x // c`, ` .y` becomes `O.z // c`, and `O.p`, ` .x /* k */`, ` .y`, ` .w` becomes `O.z`, ` /* k */`, ` .w` (a comment keeps its line). - Hand-probing deep section towers (SPEC 1.3, 4, 4.1, 4.2, 6.4–6.6, 10.6, 12.0–12.3, 13.1; the Phase 10 plan written at d2655e3, its FIX_PLAN Task 163, after compliance reviewer A's `c69.mjs` and `c80.mjs`): Task 163's node script (`/tmp/claude-0/-home-user-xspec/08a79bea-e066-52cf-ac19-1be1615496b4/scratchpad/t163-scripts.5HE776/tower.mjs`, which may be gone; `node tower.mjs <bin.js> <fresh dir> <plain|text> <N> [label]`, with `MD=1` adding `markdown: { emit: true }` to the configuration, `SKIP_MOVES=1`, `ONLY=<step,…>`, and `NODE_FLAGS="<node options>"` passed to the product) stages, in a fresh `mkdtemp` run directory (nothing removed), the configuration `{ specs: { main: ["specs/**/*.mdx"] }, code: { app: ["src/**/*.ts"] } }`, `specs/A.mdx` holding N nested sections `a`, `a.a`, … (each ID one `.a` longer — the plain form, `c80.mjs`'s, one opening tag per line, then `x`, then N `</S>` lines; the text form, `c69.mjs`'s, a line `T<i>` after each opening tag), and `specs/C.mdx` = `<S id="c">C</S>` LF. It runs, as root with `NODE_OPTIONS` unset (no staged permission matters), `build --json`, `check --json`, `ids --json`, `ids --tree --json`, `ids --tree`, `show specs/A.mdx#a`, `query node specs/A.mdx --json`, `query subtree specs/A.mdx --json`, `occurrences --json`, `view specs/A.mdx --json`, `coverage --json`, `review create --strategy audit --name s`, `review status s --json`, `rename specs/A.mdx a b --preview --json`, the performed rename (every ID then beginning with `b`), and `check --json` in one workspace, and in two fresh copies `move specs/C.mdx#c specs/D.mdx#c` previewed and performed and `move specs/C.mdx specs/E.mdx`, each followed by `check --json`, recording every command's exit, time, standard output, and standard error, and the workspace's files (path, size, sha256) after `build` and after each move. Beside it, `compare.mjs <runA> <runB>` compares two runs' records byte for byte; `rcreate.mjs <bin.js> <fresh dir> <form> <N> [node options…]` runs the audit `review create` and `review status` alone, and `heap.mjs <bin.js> <fresh dir> <form> <N> <cmd…> [-- <cmd…>]…` single commands, both reporting peak RSS and the heap in use at exit through the `--import` hook `rss-hook.mjs` (`process.resourceUsage().maxRSS`, `v8.getHeapStatistics()`). Recursions removed at Task 163, each now an explicit-stack walk with byte-identical output: `collectNodes`'s `build` and `flattenPreOrder`'s `visit` in `src/core/emission.ts` (at `d2655e3`, from 5000 deep, `build`, `check`, `rename`, and both `move`s, previewed or performed, exited 70 with `xspec: internal error: RangeError: Maximum call stack size exceeded`, frames in `dist/core/emission.js`), `treeNodeJson` in `src/cli/commands/ids.ts` (`ids --tree --json` exited 70 at 4000 deep in the text form and 5000 in the plain), and `renderTreeHuman`'s nested `renderNode` there (`ids --tree` exited 70 at 6000). Every command then exits 0 at 4000, 5000, and 6000 in both forms but the audit `review create` (below). Times on 4 cores, each run beside one or two other probes: plain at 5000 — `build` 9.1 s, `check` 8.7 s, every read 8.5–10.5 s (`ids --json` 25.1 MB, `ids --tree --json` 26.7 MB, `ids --tree` 50.0 MB, `query subtree --json` 25.9 MB, `view --json` 60.9 MB), the rename preview 17.5 s (51.1 MB) and the performed rename 18.2 s, the moves 15–17 s; plain at 6000 — `build` 14.7 s, reads 12–15 s (`view --json` 85.1 MB, `ids --tree` 72.0 MB), the rename preview 28.4 s and the performed rename 30.7 s, the moves 23–24 s; text at 4000 with Markdown emitted — `build` 14.5 s, writing a 71,842,940-byte `specs/A.xspec.ts`, a 414,015-byte type companion, and 122,564,548 bytes of graph data, reads 11–16 s, the renames 19.0 and 21.2 s, the moves 17–19 s; text at 5000 — `build` 18.8 s, reads 17–21 s, the renames 27.4 and 32.5 s, the moves 23–37 s; text at 6000 (beside two others) — `build` 33.4 s, reads 25–33 s, the renames 44.5 and 64.5 s, the moves 37–42 s. Byte identity against `d2655e3`'s product (built in a fresh single-branch clone checked out at `d2655e3`): at 100 and 4000 deep (text form, Markdown emitted) every record matches but those `d2655e3` cannot produce (its `ids --tree --json` exits 70 at 4000) and the heap-abort reports below. Where its recursion gives out, the old product answers on a larger main-thread stack — `ulimit -s 2000000` in the shell that launches the probe (the hard limit is unlimited here) and `NODE_FLAGS="--stack-size=1000000"` — which gives `ids --tree --json` at 4000 and every command at 5000 and 6000; those runs (text at 5000, plain at 6000) match the new build's on the default stack in all 45 records but the heap-abort report. Memory bounds, not recursions (the d2655e3 plan's Not planned entries): at 8000 deep (plain) `build --json`, `check --json`, `ids --json`, and `view specs/A.mdx --json` each abort on V8's default heap (2096 MB here; "FATAL ERROR: Ineffective mark-compacts near heap limit", SIGABRT) after 25–35 s — the analysis itself, which peaks near 0.96 GB of heap at 5000 deep and 1.34 GB at 6000 (`build --json`, peak RSS 1.25 and 1.71 GB). The audit `review create` records n(n+1)/2 (item, scope node) entries over an n-deep tower (SPEC 10.6, 10.4), and its heap grows with them: plain at 1000 deep 264 MB in use at exit (3.5 s; a 2,914,684-byte session; `review status s --json` 1.6 s), at 2000 894 MB (13.7 s; 9,838,684 bytes; status 5.5 s), at 2500 969 MB (20.8 s; 14,800,684), at 3000 about 1.5 GB (33.7 s; 20,762,684; status 13.4 s), at 3500 near 1.95 GB at its peak (47.8 s; 27,724,684) while `review status s --json` aborts, and from 4000 (both forms, `d2655e3` alike) the creation aborts after 26–67 s, leaving no session (`review status s` exit 2). Under `node --max-old-space-size=11000` (`rcreate.mjs`'s node options) the 5000-deep creation exits 0 in 134 s (peak RSS 5.6 GB; 54,610,684 bytes) and `review status s --json` in 45 s (25,820,633 bytes): no recursion is met there. - Hand-probing call-stack depth (SPEC 14.20, 14.14, 12.0, 12.1, 13.5; the Phase 10 plan written at d2655e3, its FIX_PLAN Task 164, after compliance reviewer A's `c81.mjs`/`c47.mjs` and B's `g1.mjs`/`tsdeep2.mjs`/`tower.mjs`): since Task 164 the bin wraps `runInvocation` (`src/cli/reruns.ts`, the `(argv, cwd, stdout, stderr)` entry), which runs `main` (`src/cli/main.ts`, now one attempt) on the main thread and, when that attempt meets V8's `RangeError` `Maximum call stack size exceeded` (thrown, or carried as a `cause`: `isStackOverflow` in `src/core/stack-exhaustion.ts`) before its first effect — a non-empty write to stdout or stderr (the attempt's wrapped writers) or any mutation through `performWrite` in `src/workspace/writes.ts` — runs it again from the start, same argv and cwd value, on a `node:worker_threads` Worker (`src/cli/rerun-worker.ts`, compile cache enabled there too) with `resourceLimits.stackSizeMb` 64 and then 1024, the last attempt (`RERUN_STACK_SIZES_MB`); the worker's stdout and stderr reach the entry's writers as the UTF-8 strings it wrote, chunk by chunk under the writer's callbacks (`forward`), and its outcome is posted back. The three sites that used to answer from an overflow — `analyzeCodeSource` (the 14.20 "nesting exceeds" finding at [0, 0)), `topLevelStatementsOf` (null for a move's would-be code source), `parseConfiguration` (the 14.14 "nesting exceeds" error) — call `propagateWhileRerunPossible`, throwing the `StackExhaustion` signal (no `RangeError`) while a rerun is possible, and answer as at d2655e3 only in the last attempt or past an effect. The hold seam engages once per invocation (`holdSeamEngaged`, carried to the next attempt): a rerun past a created hold file proceeds without creating it again, so `--test-hold` changes no outcome (SPEC 13.5); acquisition and release are no effect — the unwinding attempt releases through `withMutationExclusivity`'s `finally`, and the rerun adds a new entry under the same pid. Since Task 165 the spec-source sites follow the same rule (SPEC 14.20: MDX's well-formedness is derivability alone, no parser-acceptance clause): `mdxAcorn` (`src/core/mdx-acorn.ts`) overrides acorn 8.17's `catchStackOverflow` (`propagateStackOverflow`; stock acorn raised the `SyntaxError` "Not enough stack space to parse input", which remark-mdx took for a grammar failure), so an overflow propagates as the `RangeError` it is, given `pos` = where the parse began (`micromark-util-events-to-acorn` places whatever acorn throws by `pos`, and for an ESM block without one throws its own `TypeError` "Cannot read properties of undefined (reading 'line')") and noted on its way (`noteStackOverflow` in `src/core/stack-exhaustion.ts`): remark-mdx wraps what acorn throws as the `cause` of its VFileMessage and, for a brace, tries each further `}` (`lastCrash`), so the failure it finally throws need not carry the overflow — on the main thread `<S id="a">` LF `> {` + 1000 parentheses + `}` LF `lazy` LF `</S>` throws "Unexpected lazy line in expression in container" with no cause. `parseMdx` and `isWellFormedSpecSource` (`src/core/mdx.ts`), `recordedParse`, `mdxSyntaxFailureOffset`, and `respellRefusedContent` (`src/core/mdx-syntax-failure.ts`), `lexesToNoToken` and `deriveContentExpression` (`src/core/mdx-acorn.ts`), and the pipeline's two spec-source catches call `propagateWhileRerunPossible` (which now also notes the overflow, and rethrows a `StackExhaustion` as is), and after every remark-mdx parse, thrown or returned, `propagateNotedOverflow`; only the last attempt, or one past an effect, answers as at d2655e3 — `parseFailureFinding` at [0, 0) for a throw that is not the grammar's (B2(b)'s, `estree-util-visit`'s recursive `visit` in events-to-acorn's position fixing, reaches `parseMdx` as a bare `RangeError`), and for the grammar's failure carrying an overflow at the place the grammar gave, unprobed (every probe would exhaust the same stack again: a 1,000,000-parenthesis container took 93 s probed, 8.5 s not); `deriveContentExpression` null (14.8); the probes' fallbacks. Measured on Node 22.22.0 (a one-frame recursion): the main thread recurses 12,530 frames, a 4 MB worker 49,658, 64 MB 836,090, 1024 MB 13,419,002; `new Worker` with an unsatisfiable `stackSizeMb` (1e6) throws `ERR_WORKER_INIT_FAILED` (EAGAIN) synchronously — counted as an exhausted attempt, the last attempt then running on the largest stack that started, or on the main thread; a worker starts in ~50 ms and reloads the module graph, so a rerun costs an ordinary invocation's time again. Telling which attempt answered without the product printing anything: run it with `NODE_DEBUG=worker` (Node's diagnostics, on stderr) and count the lines `starts worker script` — none: the main thread answered; one: the 64 MB worker; two: the 1024 MB one (`created Worker with ID <n>` also counts a worker whose start failed). The fallbacks, checked in scratch copies of `dist/` with `RERUN_STACK_SIZES_MB` edited in `dist/cli/reruns.js`: with no size that can start (`[1e6, 1e7]`) the last attempt runs on the main thread (B1(a) at 3000: the 14.20 overflow finding, exit 1); with `[64, 1e7]`, 100,000 nested parentheses exhaust the 64 MB worker, the 1e7 one fails to start, and a second 64 MB worker runs the last attempt (the 14.20 finding, exit 1); a worker given `maxOldGenerationSizeMb: 8` dies of heap exhaustion — `xspec: internal error: Error [ERR_WORKER_OUT_OF_MEMORY]: …`, exit 70. Probe outcomes at Task 164 (fresh build, `NODE_OPTIONS` unset, each staging in a fresh directory; configuration `specs: { main: ["specs/**/*.mdx"] }, code: { app: ["src/**/*.ts", "src/**/*.tsx"] }`): B1(a) (`export const b = (x: number) => x !== 0 && … && x !== N-1` below the marker `A.a` in `f`) `build --json` exit 0 finding-free at 800 (0.6 s), 3000 (1.2 s), and 20,000 (25 s), `occurrences --file src/g.ts --json` listing `A.a` at [57, 60) (source `src/g.ts#f`, [40, 62)) and `query edges --from src/g.ts#f --json` the `references` edge to `specs/A.mdx#a` at each; at 20,000 TypeScript binds in ~1.2 s and the rest is the analysis resolving each value-use `x` through the checker (`visitIdentifier`), whose name resolution walks the 20,000-deep parent chain (~1 ms each, quadratic); the else-if chain likewise (20,000 branches 24 s; 3000 1.5 s). A1 (`"s0" + … `): 3000 (0.7 s) and 100,000 operands (1.8 s), `.ts` and `.tsx`, the marker's occurrence and edge from `src/x.ts#f` (`src/x.tsx#f`). B1(c) (a tower `s`, `s.s`, … with a line `T<i>.` after each opening tag, beside `src/m.ts`'s N-segment marker): 1300 (2.6 s) and 2048 (4.7 s) finding-free, `query edges --from src/m.ts#f --json` one `references` edge to the 1300- and 2048-segment node; a 10,000-segment marker into a one-section file exit 1 with its `unknown-ts-reference` at [57, 20058). Nested functions 700 and 5000 (1.7 s), `g(1)(1)…` 3000 and 20,000 (1.0 s), nested parentheses around `1` 2000 and 20,000 (0.7 s) finding-free; 70,000 parentheses still fit 64 MB, 100,000 take the 1024 MB attempt (exit 0, 1.7 s, peak RSS 353 MB), and 1,000,000 and 3,000,000 exhaust it too: the 14.20 overflow finding at [0, 0), exit 1, ~3.5 s, peak RSS ~1.2 GB. Configuration: `main: ((…["specs/**/*.mdx"]…))` and `policy: [[…]]` 2000, 5000, and 20,000 deep rerun once and answer the ordinary 14.14 error (exit 2; "must be statically literal", "policy[0] must be a rule object"), identical in three runs. Determinism: A1's chain at 1600, 1700, 1800, 1900, and 2000 operands in 8 fresh workspaces each — all 40 runs exit 0 with one stdout digest and an empty stderr, while the main thread overflowed in 0, 0, 1, 6, and 7 of 8. Every command over B1(a) at 3000, a git repository (`check`, `ids`, `query nodes`, `occurrences`, `view`, `at specs/A.mdx 3`, `coverage`, each `--json`; the audit `review create` and `review status s --json`; after an edit to `specs/A.mdx`, `impact --base HEAD --json` and `review create --base HEAD`; `rename specs/A.mdx a b` and `move specs/A.mdx#a specs/B.mdx#a`, previewed and performed in fresh copies, then `check --json` finding-free) answers as over 600 terms (no rerun) — the same exit codes and documents but for `impact`'s `baseline` commit — at 1.2–2.2 s against 0.3–0.6 s, no `.xspec/lock` entry left after a mutating command. Byte parity: beside a 2000-section `specs/Big.mdx`, B1(a) at 600 and at 3000 give byte-identical `view specs/Big.mdx --json` (1,402,666 bytes), `ids --json`, `ids --tree`, `show specs/Big.mdx`, and `show specs/Big.mdx#b7 --json`. The seam: `rename specs/A.mdx a b --test-hold <abs path> --json` over B1(a) at 3000 created its hold file once; deleted (a lone `rm` of the literal path), the run reran once and performed the rename (exit 0, `mapping` `a` to `b`, the marker `A.b`), the lock released. Regressions at Task 164 under the unprivileged recipe, all passing: the §4, §5.7, §7, §12, and §14 files (18 files, 76 tests, 573 s together) and the §6.4–6.6, §13.5, and §16 P-8/P-10/P-11 files (16 files, 53 tests, 530 s; P-8, its TypeScript towers now analyzed on a rerun's stack, 103.9 s of test time, P-10 72.0 s, P-11 40.7 s), and `npm run test:windows` against a fresh exchange (9 of 10, the drive-mismatch arm failing by design). Spec-source probe outcomes at Task 165 (fresh build, `NODE_OPTIONS` unset, each staging in a fresh workspace under the configuration above, `build --json`, two runs each where timed): a body container `<S id="a">` LF `A {` + N `(` + `x` + N `)` + `}` LF `</S>` — `invalid-construct` at [13, 2N+16) at 560 (0.5 s), 600, 5000 (1.1 s), 10,000 (3.1 s, peak RSS 607 MB), and 20,000 (12.2 s, 1.84 GB); `<S id="d" d={((…x…))}>` — `invalid-argument` ("parentheses do not participate in a static property chain") at [13, 2N+14) at 560, 600, and 5000 (1.3–1.4 s); `export const x = [[…]]` LF LF + a section — `invalid-construct` (the export statement) at [0, 2N+17) at 560, 600, and 5000 (1.0 s); A's 10,000-operand `"x" + …` chains — `invalid-construct` [11, 60010) in a body container, `invalid-argument` [13, 60010) in `d={…}` and [11, 60016) in `{text(…)}` (3.2–3.6 s); B's chains beside `specs/B.mdx` (`<S id="s">` LF `S.` LF `</S>`) — `d={B.s…s}` `unknown-dependency` at the reference [40, 2N+41), `{text(B.s…s)}` `unknown-text-target` at its full braced container [38, 2N+47) (SPEC 14), at 5000 (1.1–1.7 s), 9000 (2.6–3.4 s, ~650 MB), and 20,000 segments (16–17 s, peak RSS 1.93–1.99 GB, the 64 MB worker answering); `<S id="a">` LF `> {` + 1000 parentheses + `}` LF `lazy` LF `</S>` — `invalid-construct` [13, 2016) (at 3f5c86d a 14.20, "Unexpected lazy line in expression in container" at 592); a 3000-deep container followed by an unclosed `{oops` at the end, and a 3000-deep `d` value beside `A {1 +* 2}` — their 14.20s at 6029 and 6023, as SPEC 14's rule places them in the 10-deep files (at 3f5c86d mid-nesting, 592 and 591, where the stack ran out). Determinism: the `d` chain at 4500, 5000, 5500, and 6000 segments in 8 fresh workspaces each — one stdout digest per size, exit 1, empty stderr, the main thread overflowing in 0, 2, 5, and 8 of 8. B's `tower.mjs` at 6000 (`specs/A.mdx` a 6000-deep tower, a line per level; `specs/D.mdx`'s 6000-segment `d` chain into its deepest node; `src/m.ts`'s 6000-segment marker): `build --json` finding-free (34 s, one rerun), `query edges --from specs/D.mdx#d --json` the `depends` edge and `--from src/m.ts#f` the `references` edge to the 6000-segment node (32–34 s); in a fresh copy `move specs/D.mdx#d specs/E.mdx#d --preview --json` (41 s) and the performed move (47 s) exit 0, then `check --json` finding-free (36 s). The last attempt: a body container of 1,000,000 or 3,000,000 parentheses — `unparseable-source` at the content's start [14, 14) ("Could not parse expression with acorn"), exit 1, 8.4–9.0 s, peak RSS ~1.35 GB (one overflow of the 1024 MB stack costs 6–9 s); the ESM array 1,000,000 deep — at the block's start [0, 0), 10.0 s. The heap bound, a memory bound rather than a recursion (the d2655e3 plan's Not planned): `estree-util-visit` copies its `parents` array at every level (`parents.concat(node)`), so a remark-mdx parse holds about depth²/2 references, and a `d` chain of 22,000 segments or more, or a container of 30,000 parentheses, exhausts the rerun worker's heap (V8's default, ~2 GB here) — `xspec: internal error: Error [ERR_WORKER_OUT_OF_MEMORY]: …`, exit 70, ~12 s — where 3f5c86d answered a 14.20 (exit 1). Regressions at Task 165 under the unprivileged recipe, all passing twice: `section-1.6-1.7`, `-2.1`, `-2.2-2.3`, `-2.4`, `-2.5-2.6`, `-2.7`, `-3`, `-11.2`, `-11.4`, `-11.5`, `-14`, `-14-ii`, `-14-iii` (13 files, 71 tests, 286 s) and `section-6.5`, `-6.5-ii` to `-vi`, `-6.6`, `-12.0-i`, `-16-p2-p3`, `-16-p8`, `-16-p12`, `-15` (12 files, 43 tests, 542 s; P-8 100.7 s, P-12 451.3 s of test time). Task 165's probes (under the scratchpad's `t165-exp.*`, which may be gone): Task 164's `stage.mjs` with the spec-source kinds `mdxparen`, `mdxd`, `mdxesm`, `mdxchain`, `mdxtext`, `mdxplus`, `mdxdplus`, `mdxtextplus`, `mdxmask`, `mdxlazy`, `mdxlazyflow`, `mdxdeepfail`, `mdxdeepfail2`, and `towerd` (B's tower), `tower-steps.sh <N> <log>` (step 4's build, queries, and move), and the library probes `mask-probe.mjs`, `esm-probe.mjs` (what remark-mdx throws on the main thread, and whether an overflow was noted), and `overflow-cost.mjs <stackMb> <N>`. Finding where an overflow happens (the d2655e3 planner's way): copy `dist/` into a fresh `mktemp -d` beside a `node_modules` symlink to the repository's, make the copy's catch sites hand the caught error to `globalThis.__ov`, and load an `--import` hook that sets `Error.stackTraceLimit = Infinity` and prints each handed error's frames (function names and counts); or run the library call alone on a Worker with a chosen `stackSizeMb` — e.g. TypeScript's `createSourceFile`, a no-lib single-file `createProgram`, `getSyntacticDiagnostics`, `getTypeChecker`, and `getSymbolAtLocation` over the file, timed per phase. Task 164's probes (under the scratchpad's `t164-exp.*`, which may be gone): `stage.mjs <kind> <N> [command …]` (kinds `and`, `andbig`, `plus`, `plustsx`, `tschain`, `tschainB`, `elseif`, `nestfn`, `calls`, `parens`, `cfgparens`, `cfgarray`, `sections`; `OUT=<file>` saves stdout, `HOOK=<module>` adds `--import`, `WSROOT=<dir>` the parent of its fresh workspaces), `cmds.mjs <N>` (the every-command sweep), `determinism.mjs <kind> <runs> <N…>`, and `rss-hook.mjs` (peak RSS of the whole process, its workers included, at exit). -- The known state after the Phase 10 plan (the re-descent's plan written at d2655e3 after the jump-back, its planning commit bcd8228, under patch 0001, `specs/patches/0001-external-ui-apis.md`, Stage: Tested; its Task 166, the plan's last task, deleted the plan — its final text, whose Ledger records where each task landed and the CI run that confirmed it, is `git show dffbe0f:specs/tmp/FIX_PLAN.md`; the previous Phase 10 plan's, written at abb7839 and closed at d2655e3, is `git show 5b8074b:specs/tmp/FIX_PLAN.md`, the one before it, written at 6034904 and closed at abb7839, `git show 32f5c06:specs/tmp/FIX_PLAN.md`, the one before that, written at f2ff6c3 and closed at 6034904, `git show 428bab5:specs/tmp/FIX_PLAN.md`, the one before that, written at 891fbc0 and closed at f2ff6c3, `git show 1eaee27:specs/tmp/FIX_PLAN.md`, and the one before that, closed at c62f451, `git show 8f5660d:specs/tmp/FIX_PLAN.md`). The three accepted residuals stay deferred to Phase 11 and fail no test: the bullets beginning "Known residual 14.20 location gaps", "Known SPEC 6.5 gap", and "Known SPEC 4.1/14.7 gap" above. The plan closed the d2655e3 determination's four gaps — reviewer A's two, over SPEC 1–6 (A1: a well-formed TypeScript code source holding a long `+` chain reported unparseable, identical workspaces answering differently from run to run near 1,700–1,900 operands; A2: sections nested about 5,000 deep crashing module emission), and reviewer B's two, from SPEC 7 on (B1: TypeScript code sources TypeScript accepts reported unparseable when the analysis ran out of call stack; B2: MDX files well-formed by derivability reported unparseable when an expression nests deeply or a reference chain is long); reviewer C, over SPEC.md outside its numbered sections, found none — in three tasks: Task 163 (5fbd017; A2 — emission's node collection and flattening, and `ids --tree`'s two tree walks, on explicit stacks, so section towers 5000–6000 deep build, check, rename, and move; the bullet beginning "Hand-probing deep section towers"), Task 164 (385d26d; A1 and B1 — an invocation that exhausts the call stack before its first effect reruns on a worker thread with a larger stack, the code-source and configuration sites signalling the overflow instead of answering 14.20 or 14.14, so well-formed TypeScript is analyzed whatever its depth; the bullets beginning "Hand-probing call-stack depth" and "The built product enables Node's on-disk V8 compile cache"), and Task 165 (11cc7b2; B2 and A's note on the spec-source side — the same rerun for spec sources, acorn's overflow propagating as itself and the MDX sites signalling it, so deep or long MDX expressions reach their ordinary outcome; the call-stack bullet), each confirmed by its push's CI run (1747, 1749, and 1751, each job green); the planning commit's run 1746 (bcd8228) and the follow-up pushes' runs 1748 (cdc3cd1), 1750 (3f5c86d), and 1752 (dffbe0f) completed with all three jobs green as well, none cancelled. The memory bounds the plan's spawns met past the reviewers' depths — `build`, `check`, `ids --json`, and `view --json` at 8000 nested sections, the audit `review create` and `review status` past about 3000, and the rerun worker's heap from a 22,000-segment `d` chain or 30,000 nested parentheses (exit 70) — are its Not planned entries, recorded in those two hand-probing bullets: no reviewer reported them, and a later determination may count them. VERIFY's opening figures at d2655e3 (a read-only step, so recorded here by Task 166): locally, the self project with no `dist/` — 40 files, 5183 tests passed, 452.95 s, certification 171 PASS / 48 FAIL / 0 error / 0 hang over 39 lines (all 9 conformers passing all 40 of their certified tests, each of the 30 violators failing at least one); `npm run test:local` — no test files (E-2's set is empty), exit 0; the suite and self projects together against the built product — 131 files (91 suite, 40 self), 5561 tests (378 suite, 5183 self), all passed, 2916.07 s on a machine shared with the three reviewers, the admin self-tests and T13.5-9's and T13.5-10's files left out, the E-6 writer test passing (17.6 s) and writing the exchange (74 files, 86,272 bytes); the Windows subset — 3 files, 10 tests, 9 passed in 35.89 s, the drive-mismatch arm failing by design, the byte-identity test passing (10.45 s); and CI run 1745 (id 40508353191, push event, attempt 1, the only run for the sha) at d2655e3 — `harness-self` 42 files, 5193 tests, 313.85 s (job 122203398973; both admin self-test files passing, 7 and 3 tests; certification 171/48/0/0 over 39 lines); `suite-linux` 135 files (93 suite, 42 self), 5573 tests, 2682.34 s (job 122203398817; T13.5-10's file 416.2 s, T13.5-9's 32.3 s, the E-6 writer 13.4 s; `e6-linux-outputs` 74 files, 30,642 bytes, artifact 12737834783); `suite-windows` 3 files, 10 tests, 28.18 s (job 122226238169; drive-mismatch 3115 ms, byte-identity 15214 ms). Run facts at dffbe0f, the product as Task 165 left it (11cc7b2) and the harness unchanged since f2ff6c3 (`git diff f2ff6c3 -- test/ .github/` empty). `npm ci` was not needed (the installed `node_modules/.package-lock.json` matched `package-lock.json` entry for entry, version and integrity, but for 29 optional packages for other platforms, which npm skips here); `npm run build`, `npm run typecheck`, and `npm run format:check` ran clean. Each local pass below ran in its own fresh single-branch clone, as CI checks out, since the checkout's long-lived `dist/` still holds the three stale modules of the build bullet above (and no others: every other `dist/` module has its source). The self project with no `dist/`, as CI's `harness-self` runs it — a clone under a fresh `mktemp -d` (`git clone -q --branch claude/xspec-ui-apis-4df8fa --single-branch /home/user/xspec <dir>/xspec`), `npm ci` there and no build, then `unshare --map-user=1000 --map-group=1000 -- env -u NODE_OPTIONS npm run test:self -- --exclude 'test/self/**/*.admin.test.ts' --reporter=verbose > <log> 2>&1` in the background, awaited by the `EXIT`-line poll above: 40 files, 5183 tests, all passed, none skipped, 403.96 s; certification 171 PASS / 48 FAIL / 0 error / 0 hang over the 39 `certification run against` lines — the 9 conformers passing all 40 of their certified tests, each of the 30 violators failing at least one, the 48 FAILs their expected outcomes. The suite and self projects together against the built product, as `npm test` runs them — a second fresh clone, `npm ci` and `npm run build` there, then `XSPEC_E6_EXCHANGE_DIR=<fresh dir> unshare --map-user=1000 --map-group=1000 -- env -u NODE_OPTIONS npx vitest run --config test/vitest.config.ts --project suite --project self --exclude 'test/self/**/*.admin.test.ts' --exclude 'test/suite/section-13.5-ii.test.ts' --exclude 'test/suite/section-13.5-v.test.ts' --reporter=verbose`, in the background on this 4-core machine with nothing else running: 131 files (91 suite, 40 self), 5561 tests (378 suite, 5183 self), all passed, none failed or skipped, 2364.93 s — no ` FAIL ` summary line (the log's 48 ` FAIL ` hits are all the certification runner's per-pair lines), `grep -oE '^[A-Za-z]*Error' <log>` empty, `undeclared-staging`, `mdx-derivability`, `harness error`, `HarnessStagingError`, `ProductRunTimeoutError`, and `ProductRunOutputOverflowError` occurring only in passing tests' titles (every hit on a ` ✓ ` line) and `timed out` nowhere; certification again 171/48/0/0 over 39 lines; the E-6 writer test passing (12.1 s) and writing the exchange (74 files, 86,272 bytes). `npm run test:windows` against that exchange, under the same recipe: 3 files, 10 tests, 9 passed in 29.23 s, its one failure the drive-mismatch arm (no `subst` off Windows: it fails loudly after its premise arm, by design), the byte-identity test passing (7.8 s). `npm run test:local`, under the same recipe: no test files (E-2's set is empty), exit 0. CI on dffbe0f (push-event run 40582694168, number 1752, attempt 1, the only run for the sha, read as the CI-log bullet above describes, each log fetched whole through `get_job_logs` with `return_content: false` and `curl -o`: `harness-self` 336 KB, `suite-linux` 873 KB, `suite-windows` 25 KB): `harness-self` green (job 122465999727; 42 files, 5193 tests, 324.24 s; both admin self-test files passing, `machine-staging` 7 tests and `pid-namespace-staging` 3; certification 171/48/0/0 over 39 lines); `suite-linux` green (job 122466000250; `npm test` 135 files (93 suite, 42 self), 5573 tests (380 suite, 5193 self), all passed, 2512.14 s, no ` FAIL ` summary line; T13.5-9's `section-13.5-v.test.ts` (30.0 s) and T13.5-10's `section-13.5-ii.test.ts` (398.5 s) passing, P-8's `section-16-p8.test.ts` 97.9 s, the E-6 writer 13.0 s; certification 171/48/0/0 over 39 lines; `e6-linux-outputs` uploaded, 74 files, 30642 bytes, artifact 12773036654); `suite-windows` green (job 122486978377; 3 files, 10 tests, 38.09 s, the drive-mismatch (4.7 s) and byte-identity (18.7 s) tests passing); the jobs 6, 42, and 1.5 min, the whole run 43.5 min. Task 166's commit (this file and the plan's deletion alone) carries dffbe0f's product and harness trees. No test is known to fail: every test must pass. +- Hand-probing SPEC 14.18 for spec-module bindings of no permitted form (SPEC 4, 4.5, 14, 14.15, 14.18, 7; the Phase 10 plan written at b63b527, its FIX_PLAN Task 168): `scanImportDeclaration` in `src/core/code-analysis.ts` registers a spec module import's value-level named binding of an export other than `default` and `text` (read as 2.4 reads it), and its namespace binding, as an `UnpermittedBinding` (type-only: `type-level`), whatever the specifier designates; the collision pass of `scanModuleLinks` still replaces a colliding identifier's entry. Every value-level use is then 14.18 at the identifier alone (`visitUnpermittedBindingUse`; `visitExportSpecifiers` and `visitImportEqualsUse` locate the identifier alone too), and `analyzeTextCall` records nothing for an argument rooted at one. In fresh `mktemp -d` workspaces (a spec group `main` over `specs/*.mdx`, `specs/A.mdx` holding `<S id="a">A</S>` and LF, a code group `app` over `src/**/*.ts`, the configuration importing from `"xspec"`, one `src/app.ts` per staging, run unprivileged with `check --json` and `build --json`, which agree), after `import { foo } from "../specs/A.xspec";` each of `foo(1);`, `export default foo({});`, `const z = foo;`, `foo;`, `foo.a.b;`, `foo["a"];`, `foo?.();`, `(foo as any)();`, `{ foo }`, `class C extends foo {}`, `foo<string>;`, `typeof foo` in an expression, `export default foo;`, `export { foo as bar };`, and `import X = foo.a;` adds one `unsupported-node-usage` at that `foo` beside the import's `invalid-import` (before Task 168: the `invalid-import` alone), as do `bar();` after `import { bar } from "../missing.xspec";` and `console.log(NS);` or `NS.a.b;` after `import * as NS from "../specs/A.xspec";`; `foo.a.b;` is no marker (no 14.7, no edge), as `text.a.b;` reports `text` alone; `text(foo)` beside `import A, { text } …` reports `foo` and nothing for the call, as `text(t)` reports `t` for another import's `text` binding; `foo(A.a)` reports `foo` and `A.a`. Unchanged: a type-only `foo` (`import type { foo }`, `import { type foo }`), type positions, a shadowing local, the contrast `import A from "../specs/missing.xspec";` with `console.log(A);` (14.15, 14.18 at `A`), and every same-scope collision (`import foo from "./x.js";` or `const foo = 1;` beside it: `foo(1);` 14.18 at `foo` and `foo.a;` 14.7, as a default binding's), while a same-named import in a nested function's scope leaves the top-level binding's own uses 14.18. The configuration as a discovered code source (a code group over `*.ts`, importing from `"./specs/A.xspec"` or `"./missing.xspec"`): `build --json` exits 1 with exactly the `invalid-import` at the declaration and one `unsupported-node-usage` at `defineConfig` in `export default defineConfig(`. Suites with a fresh pack as `XSPEC_PACKAGE_DIR`: `section-7-import` green (T7-9 and T7-10, 75.3 s wall); regressions `section-2.1`, `-2.4`, `-4`, `-4.1-4.2`, `-4.3-4.4`, `-4.5`, `-4.5-ii`, `-4.6`, `-5.7`, `-6.4`, `-6.5` to `-6.5-vi`, `-6.6`, `-11`, `-11.2` to `-11.6`, `-12.7`, `-14`, `-14-ii`, `-14-iii`, `-16-p8`, `-16-p11`, and `-16-p12`, 30 files, 135 tests green, 821.7 s wall. +- The known state after the Phase 10 plan (IP 0002's, under patch 0002, `specs/patches/0002-config-import-specifier.md`, Stage: Tested, on the branch `claude/relaxed-albattani-5v6l55` standing in for `patch/config-import-specifier`: written at b63b527 from Phase 10's first compliance determination, its planning commit d0cc9dd; its Task 171, the plan's last task, deleted the plan — its final text, whose Ledger records where each task landed and the CI run that confirmed it, is `git show 6acaf6e:specs/tmp/FIX_PLAN.md`; IP 0002's Phase 9 plan, written at e57210b and deleted at d18ad36, has its final text at `git show 21af7d9:specs/tmp/FIX_PLAN.md`. IP 0001's Phase 10 plans, newest first: the re-descent's, written at d2655e3 after the jump-back, its planning commit bcd8228, under patch 0001, `specs/patches/0001-external-ui-apis.md`, and deleted by its Task 166, `git show dffbe0f:specs/tmp/FIX_PLAN.md`; the one written at abb7839 and closed at d2655e3, `git show 5b8074b:specs/tmp/FIX_PLAN.md`; the one written at 6034904 and closed at abb7839, `git show 32f5c06:specs/tmp/FIX_PLAN.md`; the one written at f2ff6c3 and closed at 6034904, `git show 428bab5:specs/tmp/FIX_PLAN.md`; the one written at 891fbc0 and closed at f2ff6c3, `git show 1eaee27:specs/tmp/FIX_PLAN.md`; and the one closed at c62f451, `git show 8f5660d:specs/tmp/FIX_PLAN.md`). The three accepted residuals stay deferred to Phase 11 and fail no test: the bullets beginning "Known residual 14.20 location gaps", "Known SPEC 6.5 gap", and "Known SPEC 4.1/14.7 gap" above; IP 0002 leaves them outside its patch, its release included (issue #8). The plan closed the b63b527 determination's gaps — reviewer A's two, over SPEC 1–6 (A1: `checkImport` refused every configuration import specifier but `"xspec"`; A2: a value-level use of a spec-module binding other than the default and `text` exports was never reported as 14.18), and reviewer B's five, from SPEC 7 on (B1 and B2, A1's and A2's causes seen from 7 and 14.18; B3: the `defineConfig` module declared five type exports beside `defineConfig`; B4: no CommonJS entry, so `require` found no `dist/index.cjs` and TypeScript no `dist/index.d.cts` for a file it compiles as CommonJS; B5: members of 7.6's type-error class type-checked); reviewer C, over SPEC.md outside its numbered sections, found none — with the Phase 8 scaffold's note (rework `src/index.ts`, add `src/index.cts`) and the plan's Measured at planning 1 (the scaffold's `.js` import entry failing 7.6's runtime contract on 22.0.0 for the installation name `node_modules`, which no test stages), in four tasks: Task 167 (1ef5005; A1 and B1 — `checkImport` in `src/core/config.ts` takes any static string literal as the import's module specifier and reads no specifier value), Task 168 (aba0d72; A2 and B2 — a spec module import's binding of no permitted form is tracked, each value-level use 14.18 at its identifier; the bullet beginning "Hand-probing SPEC 14.18 for spec-module bindings"), Task 169 (ad60726, AGENTS.md at 76e8e57; B3, B5, and Measured 1 — `src/index.ts` became `src/index.mts`, built to `dist/index.mjs` and `dist/index.d.mts`, with one export and a non-generic exact configuration type over unexported aliases, `package.json`'s `import` route and top-level `types` following), and Task 170 (809a932, AGENTS.md at cfc142e; B4 — `src/index.cts`, built to `dist/index.cjs` and `dist/index.d.cts`, an `export =` of `{ defineConfig }` with the same type; the build bullet above). Their pushes' CI runs: 1897 (1ef5005), 1899 (aba0d72), and 1901 (76e8e57), each with the harness job and the Windows leg green and the full suite failing only known open failures of tasks not yet landed, and 1903 (cfc142e), all three jobs green and the full suite failing nothing; the planning commit's run 1896 (d0cc9dd) and the follow-up pushes' runs 1898 (ec6e7d3), 1900 (470cfcb), and 1902 (f2aec57) were cancelled by the next push. The plan's opening figures at b63b527: CI run 1895 (id 41169891268) — the harness job green (54 files, 7295 tests, 520.86 s; both admin self-test files passing, 7 and 3 tests; certification 172 PASS / 50 FAIL / 0 error / 0 hang over its 222 pairs, all 10 conformers passing every pair and each of the 32 violators failing at least one), the full suite red (154 files, 7688 tests, 12 failed, 2079.49 s: T7-9, T7-10, P-19, T7.6-1 to T7.6-7, P-17, and P-18, each a diagnosed `HarnessAssertionError`, the built product predating IP 0002's product changes), and the Windows leg green (3 files, 10 tests, 28.77 s); and VERIFY's local runs — the suite and self projects 150 files, 7676 tests, the same 12 failing, 2559.94 s; the self project with no product 52 files, 7285 tests, all passing, 495.89 s, certification 172/50/0/0. Run facts at 6acaf6e, the product as Task 170 left it (809a932) and the harness unchanged since b63b527 (`git diff b63b527 -- test/ .github/` empty), each local pass in its own fresh single-branch clone (`git clone -q --branch claude/relaxed-albattani-5v6l55 --single-branch /home/user/xspec <a fresh mktemp -d>/xspec`, then `npm ci` there), with E-1's six releases provisioned as `XSPEC_NODE_RELEASES_DIR`. The self project with no `dist/`, as CI's harness job runs it — no build, then `XSPEC_NODE_RELEASES_DIR=<releases> unshare --map-user=1000 --map-group=1000 -- env -u NODE_OPTIONS -u NODE_PATH -u XSPEC_PACKAGE_DIR npx vitest run --config test/vitest.config.ts --project self --exclude 'test/self/**/*.admin.test.ts' --reporter=verbose > <log> 2>&1` in the background, awaited by the `EXIT`-line poll: 52 files, 7285 tests, all passed, 524.08 s; certification 172 PASS / 50 FAIL / 0 error / 0 hang over its 42 `certification run against` lines (222 pairs; the 10 conformers passing every pair, each of the 32 violators failing at least one). The suite and self projects together against the packed product, as `npm test` runs them — a second clone, where `npm run build`, `npm run typecheck`, and `npm run format:check` ran clean and `bash .github/scripts/pack-package.sh <a fresh dir>` packed `@modularcloud/xspec` 0.2.0 (`dist/` holding `index.mjs`, `index.cjs`, `index.d.mts`, `index.d.cts`, `cli/`, `core/`, and `workspace/`), then `XSPEC_PACKAGE_DIR=<package dir> XSPEC_NODE_RELEASES_DIR=<releases> XSPEC_E6_EXCHANGE_DIR=<a fresh dir> unshare --map-user=1000 --map-group=1000 -- env -u NODE_OPTIONS -u NODE_PATH npx vitest run --config test/vitest.config.ts --project suite --project self --exclude 'test/self/**/*.admin.test.ts' --exclude 'test/suite/section-13.5-ii.test.ts' --exclude 'test/suite/section-13.5-v.test.ts' --reporter=verbose`, in the background on this 4-core machine with nothing else running: 150 files (98 suite, 52 self), 7676 tests (391 suite, 7285 self), all passed, none failed or skipped, 3031.59 s — no ` FAIL ` summary line (the log's 50 ` FAIL ` hits are all the certification runner's per-pair lines), `grep -oE '^[A-Za-z]*Error' <log>` empty, `undeclared-staging`, `mdx-derivability`, `harness error`, `HarnessStagingError`, `HarnessAssertionError`, `ProductRunTimeoutError`, and `ProductRunOutputOverflowError` occurring only in passing tests' titles (every hit on a ` ✓ ` line) and `timed out` nowhere; certification again 172/50/0/0 over 42 lines; IP 0002's tests all passing (T7.6-3 340.4 s, T7.6-4 129.6 s, P-17 77.5 s, P-19 61.9 s, T7-9 56.4 s, P-18 41.7 s, T7-10 39.9 s, T7.6-5 32.5 s, T7.6-1 12.2 s, T7.6-7 9.3 s, T7.6-2 5.7 s, T7.6-6 3.1 s); the E-6 writer test passing (13.7 s) and writing the exchange (74 files, 86,272 bytes). `npm run test:windows` against that exchange, under the same recipe: 3 files, 10 tests, 9 passed in 36.57 s, its one failure the drive-mismatch arm (no `subst` off Windows: it fails loudly after its premise arm, by design), the byte-identity test passing (9.3 s). `npm run test:local`, under the same recipe: no test files (`test/local/` holds only `.gitkeep`), exit 0. CI on 6acaf6e (run 1904, id 41197546944, `pull_request` event of PR #9, attempt 1, the only run for the sha; each log fetched whole through `get_job_logs` with `return_content: false` and `curl -o`, as the CI-log bullet above describes): the harness job green (job 124526654235; 54 files, 7295 tests, all passed, 514.14 s; both admin self-test files passing, `machine-staging` 7 tests and `pid-namespace-staging` 3; certification 172/50/0/0 over 42 lines; `certification.test.ts` 305.0 s, `s10-node-release-driver.test.ts` 104.1 s); the full suite green (job 124526654376; `npm test` 154 files (100 suite, 54 self), 7688 tests (393 suite, 7295 self), all passed, 3147.07 s; the slowest files `section-12.0-iv.test.ts` 610.2 s, `section-16-p12.test.ts` 501.1 s, T13.5-10's `section-13.5-ii.test.ts` 415.5 s, `certification.test.ts` 394.1 s, and `section-7.6.test.ts` 366.2 s, with `section-7.6-ii.test.ts` 163.5 s, `section-7-import.test.ts` 94.4 s, P-19 62.2 s, P-17 55.9 s, P-18 35.4 s, T13.5-9's `section-13.5-v.test.ts` 33.7 s, and the E-6 writer 13.5 s; certification 172/50/0/0 over 42 lines, the log's 50 ` FAIL ` hits its per-pair lines; `e6-linux-outputs` uploaded, 30642 bytes, artifact 13042632342); the Windows leg green (job 124537554012; 3 files, 10 tests, all passed, 49.97 s, the drive-mismatch (4.6 s) and byte-identity (21.9 s) tests passing); the jobs 9.25, 53, and 1.5 min, the whole run 54.6 min (run 1903 at cfc142e, the same product and harness trees, took 8.9, 40.4, and 1.1, its `npm test` 2391.72 s). Task 171's commit (this file and the plan's deletion alone) carries 6acaf6e's product and harness trees. No test is known to fail: every test must pass. diff --git a/README.md b/README.md index 5a07bdf9..c0aaacdf 100644 --- a/README.md +++ b/README.md @@ -53,14 +53,14 @@ xspec rename specs/AUTH.mdx auth.login auth.signIn --preview # see a refactori ## Getting started -Requires **Node.js ≥ 22**. Install it from npm as a development dependency, under the name `xspec`: +Requires **Node.js ≥ 22**. Install it from npm as a development dependency: ```sh -npm install --save-dev xspec@npm:@modularcloud/xspec -npx xspec version +npm install --save-dev @modularcloud/xspec +npx @modularcloud/xspec version ``` -The alias makes `import { defineConfig } from "xspec"` in your `xspec.config.ts` resolve, which gives your editor type support. You can also install it globally with `npm install -g @modularcloud/xspec`, or try it without installing via `npx @modularcloud/xspec <command>`. +The package provides the `xspec` command and the `defineConfig` function that your `xspec.config.ts` imports with `import { defineConfig } from "@modularcloud/xspec"`, so your editor and `tsc` type-check your configuration. You can also install it globally with `npm install -g @modularcloud/xspec`, or try it without installing via `npx @modularcloud/xspec <command>`. Always give npm and npx the full scoped name: the unscoped name belongs to an unrelated package. Then follow **[docs/getting-started.md](docs/getting-started.md)** to set up a project in minutes. @@ -72,7 +72,7 @@ Usage guides live in [`docs/`](docs/README.md): |---|---| | [Getting started](docs/getting-started.md) | Install → first project → first coverage report | | [Writing specs](docs/writing-specs.md) | The `.mdx` syntax: sections, IDs, `d`, `text()`, tags | -| [Configuration](docs/configuration.md) | `xspec.config.ts`: groups, Markdown, coverage profiles, policy | +| [Configuration](docs/configuration.md) | `xspec.config.ts`: groups, Markdown, coverage profiles, policy, type checking | | [TypeScript integration](docs/typescript.md) | Generated modules, markers, `text()`, compiler setup | | [CLI reference](docs/cli.md) | Every command, flag, exit code, finding code, and convention | | [Coverage](docs/coverage.md) | Profiles, boundaries, modes, CI gating | diff --git a/docs/README.md b/docs/README.md index 3582d234..45d111c5 100644 --- a/docs/README.md +++ b/docs/README.md @@ -42,7 +42,7 @@ Read in order if you are new: 1. **[Getting started](getting-started.md)**: install, create a project, first build, first coverage report. 2. **[Writing specs](writing-specs.md)**: the `.mdx` source syntax, covering sections, IDs, dependencies, embedding, tags, and Markdown output. -3. **[Configuration](configuration.md)**: `xspec.config.ts`, covering spec and code groups, Markdown emission, coverage profiles, and policy rules. +3. **[Configuration](configuration.md)**: `xspec.config.ts`, covering spec and code groups, Markdown emission, coverage profiles, policy rules, and type checking the file. 4. **[Using specs from TypeScript](typescript.md)**: generated modules, `text()`, dependency markers, and compiler setup. Reference and workflows: diff --git a/docs/cli.md b/docs/cli.md index fbe3e403..8147efff 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -260,7 +260,7 @@ An operand containing `#` is a `file#id` pair, and one without is a file. Mixing $ xspec version { "interface": "1", - "product": "0.2.0" + "product": "0.3.0" } ``` diff --git a/docs/configuration.md b/docs/configuration.md index bc112291..8be799f2 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -8,7 +8,7 @@ Commands find the file by searching upward from the working directory. The searc xspec **parses the configuration statically and never executes or imports it**. The file must consist of exactly: -1. an import of `defineConfig` from the module specifier `"xspec"` (aliasing allowed; no `type` or `defer` modifier, no import attributes), and +1. an import of `defineConfig` whose module specifier is any plain single- or double-quoted string (aliasing allowed; no `type` or `defer` modifier, no import attributes), and 2. a default export of one call to that binding, whose argument is built only from object literals (plain identifier or string keys), array literals, plain quoted strings, and `true`/`false`. No spreads, no computed values, and no other statements are allowed; comments are fine anywhere. String values are read exactly as written, with no escape sequences interpreted. The file must be valid UTF-8 without a byte-order mark. @@ -19,16 +19,60 @@ This makes configuration incapable of side effects or environment-dependent beha - an unknown key anywhere in the argument, or a key repeated within one object; - an empty group, profile, or rule name, or one containing U+FFFD. -`defineConfig` is an identity function whose only job is editor type support while you write the file. Because xspec never resolves the import, the CLI works even when the package isn't installed in your project. For type support (or to keep your own `tsc` happy if it includes the config file), the specifier `"xspec"` must resolve. The package is published as `@modularcloud/xspec`, so install it under that name with an alias, or exclude the config file from your tsconfig: +xspec never resolves, loads, or interprets the import's specifier, and reads nothing on its account. Whatever the specifier names (your installed package, a path, a URL, or nothing at all), the configuration means the same, so the CLI works whether or not the import resolves. The specifier's spelling only has to leave the file well-formed TypeScript: an escape sequence that TypeScript rejects makes the file a configuration error. + +## Type checking the configuration + +Import `defineConfig` from the package your project installed. With the plain install from [Getting started](getting-started.md#install), that's `"@modularcloud/xspec"`: ```sh -npm install --save-dev xspec@npm:@modularcloud/xspec +npm install --save-dev @modularcloud/xspec +``` + +```ts +import { defineConfig } from "@modularcloud/xspec" ``` +The package's root module exports `defineConfig` and nothing else (no other value and no types), and it needs no `@types` package. Your editor and `tsc` then check the file against the configuration's shape: + +- A valid configuration type-checks with no errors, whatever its group names and whether or not you alias the import. +- Mistakes in the shape are type errors: + - an unknown key at any level; + - a missing required key: `specs`, `markdown`'s `emit`, and the profile and rule fields marked required below; + - a value of the wrong kind, such as a string where a list belongs; + - a string outside a field's allowed values: `targets`, `boundaryKind`, `mode`, `type`, a selector's `kind`, an entry of `edgeKinds` or `kinds`; + - a selector that doesn't use exactly one of `group`, `files`, and `tags`, or that has `kind` without `group`; + - an empty `targetTags`, `edgeKinds`, `kinds`, or selector `tags` list. +- Every other configuration error may or may not be a type error. These include a profile or selector naming a group that doesn't exist, or an ambiguous group name without its kind; empty, duplicate, or U+FFFD-bearing names; a malformed `outDir`; a glob outside the root; a key repeated within one object; a capture error; and a file matched by both a spec and a code group. xspec's own checks are the authority: every command reports these as configuration errors. + +`defineConfig` returns the very value you pass it and does nothing else. On Node.js 22 or later, run with no loader or module-resolution options, the package loads through both `import` and `require`, and neither loading it nor calling `defineConfig` has any other effect. xspec never runs the file, but your own tooling may. + +**What's covered.** This type checking is specified for TypeScript 5.9.3 checking the configuration file on its own, as the program's one root file, in either of two setups: + +- `strict` on, `moduleResolution` set to `node10`, `node16`, `nodenext`, or `bundler` (with `module` at its default under `node10`, or at a value the mode requires), and every other option at its default; +- exactly the options `tsc --init` writes, for a file TypeScript compiles as an ES module. + +Other TypeScript releases and option sets aren't covered. Within those setups, keep the file plain: + +- No backslashes outside comments: no escape sequences or line continuations in keys, values, names, or the specifier. xspec reads every string as spelled, while TypeScript decodes escapes, so the two could disagree. +- No comment that TypeScript reads as a directive (`@ts-ignore`, `@ts-expect-error`, `@ts-nocheck`, `@jsxImportSource`, or a triple-slash directive), since such comments change what TypeScript reports. +- Import `defineConfig` by its name, as in `import { defineConfig }` or `import { defineConfig as config }`, and don't alias it to `require`, `exports`, or a reserved word. + +The import reaches the installed package only when nothing else claims its name first, such as a `package.json` of your own named `@modularcloud/xspec` in the configuration file's directory or above it. SPEC 7.6 lists the exact conditions. + +**CommonJS projects.** Without `"type": "module"` in your `package.json`, TypeScript compiles `xspec.config.ts` as CommonJS, and under the options `tsc --init` writes (they turn on `verbatimModuleSyntax`) it rejects the file's `import` declaration. Either: + +- name the file `xspec.config.mts`, which TypeScript always compiles as an ES module, and pass it to every command with `--config xspec.config.mts`, since the upward search looks only for `xspec.config.ts`; or +- declare `"type": "module"` in your `package.json`. + +Under the strict setup above, a CommonJS project's `xspec.config.ts` type-checks as it is. + +> **Upgrading from 0.2.x:** guides for earlier releases installed the package under an alias so that the import could name `"xspec"`. You no longer need that: install `@modularcloud/xspec` as above, change the import to `"@modularcloud/xspec"`, and remove the aliased entry from your `package.json`. Until you do, the old setup keeps working, since the import may name the package by whatever name it's installed under. + ## Full example ```ts -import { defineConfig } from "xspec" +import { defineConfig } from "@modularcloud/xspec" export default defineConfig({ specs: { @@ -89,6 +133,13 @@ A file matched by both a spec group and a code group is a configuration error. T - files under `.xspec/`; - configured Markdown output destinations. +The configuration file itself isn't excluded. A code group whose globs match it (a root-level `*.ts`, for example) makes `xspec.config.ts` a code source like any other, and its import is then checked as any code file's import is. The configuration stays valid either way, but as a source: + +- a specifier ending in `.xspec`, or a relative one naming a derived file (a name carrying `.xspec.`, a path under `.xspec/`, or a Markdown output destination), is an `invalid-import` finding, so `build` and `check` fail; +- with Markdown emission on, a `move` whose destination would emit Markdown to the path that a relative specifier names is refused (`refused-invalid-destination`). + +A package-name specifier such as `"@modularcloud/xspec"` triggers neither. + ## `markdown` — pure-Markdown emission ```ts diff --git a/docs/getting-started.md b/docs/getting-started.md index 77d353fa..7c2d14cf 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -4,21 +4,23 @@ This walkthrough takes you from an empty directory to a validated project with c ## Install -xspec requires **Node.js ≥ 22**. It's published on npm as `@modularcloud/xspec`. Install it into your project as a development dependency under the name `xspec`: +xspec requires **Node.js ≥ 22**. It's published on npm as `@modularcloud/xspec`. Install it into your project as a development dependency: ```sh -npm install --save-dev xspec@npm:@modularcloud/xspec -npx xspec version +npm install --save-dev @modularcloud/xspec +npx @modularcloud/xspec version ``` -The alias does two things. It installs the package as `xspec`, the module name that `xspec.config.ts` imports `defineConfig` from (see below), so your editor gets type support. It also puts the `xspec` command in `node_modules/.bin`. +The package gives your project two things. It puts the `xspec` command in `node_modules/.bin`. It also provides the `defineConfig` function that `xspec.config.ts` imports from `"@modularcloud/xspec"` (see below), so your editor and `tsc` type-check your configuration. + +Always give npm and npx the full scoped name, `@modularcloud/xspec`: the unscoped name belongs to an unrelated package. Two other ways to run it: - **Globally**: `npm install -g @modularcloud/xspec`. - **Once, without installing**: `npx @modularcloud/xspec <command>`. -The rest of the documentation writes `xspec <command>`. With a local install, run it as `npx xspec <command>` or from an npm script. +The rest of the documentation writes `xspec <command>`. With a local install, run it as `npx @modularcloud/xspec <command>` from your project, or as `xspec <command>` in an npm script. To work on xspec itself, build it from a checkout instead: clone `https://github.com/modularcloud/xspec`, then run `npm ci && npm run build && npm link`. @@ -28,7 +30,7 @@ An xspec project is any directory with an `xspec.config.ts` at its root. The con ```ts // xspec.config.ts -import { defineConfig } from "xspec" +import { defineConfig } from "@modularcloud/xspec" export default defineConfig({ specs: { @@ -53,7 +55,7 @@ export default defineConfig({ Two things to know about this file: - xspec **parses it statically and never executes it**, so it must be purely declarative (literals only). See [Configuration](configuration.md) for the full schema. -- The `import { defineConfig } from "xspec"` exists for editor type support. xspec itself never resolves it, so the CLI works whether or not the import resolves. If your own `tsc` run includes `xspec.config.ts`, install the package under the `xspec` alias as above, or exclude the config file from your tsconfig. +- The `import { defineConfig } from "@modularcloud/xspec"` exists for type checking: with the package installed, your editor and `tsc` flag mistakes in the file's shape, such as an unknown key or a missing required one, as you type. xspec itself never resolves the import, so the CLI works whether or not it resolves. If your `package.json` has no `"type": "module"` and your tsconfig turns on `verbatimModuleSyntax` (as `tsc --init` writes it), see [Type checking the configuration](configuration.md#type-checking-the-configuration). ## Write a first spec diff --git a/docs/machine-interface.md b/docs/machine-interface.md index a2be2fe7..c1b0e8b2 100644 --- a/docs/machine-interface.md +++ b/docs/machine-interface.md @@ -26,7 +26,7 @@ Two limits to design around: $ xspec version { "interface": "1", - "product": "0.2.0" + "product": "0.3.0" } ``` diff --git a/package-lock.json b/package-lock.json index 528431fd..5e1c2616 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@modularcloud/xspec", - "version": "0.2.0", + "version": "0.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@modularcloud/xspec", - "version": "0.2.0", + "version": "0.3.0", "license": "MIT", "dependencies": { "acorn": "^8.17.0", diff --git a/package.json b/package.json index 4f7d2f43..d6c7b9bf 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@modularcloud/xspec", - "version": "0.2.0", + "version": "0.3.0", "description": "Requirement traceability for specifications written in MDX: typed spec modules, reference validation, dependency policy, coverage, impact analysis, and staged reviews.", "license": "MIT", "repository": { @@ -30,10 +30,17 @@ "bin": { "xspec": "dist/cli/bin.js" }, + "types": "./dist/index.d.mts", "exports": { ".": { - "types": "./dist/index.d.ts", - "default": "./dist/index.js" + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/specs/CERTIFICATIONS.md b/specs/CERTIFICATIONS.md index 00effe56..6728857c 100644 --- a/specs/CERTIFICATIONS.md +++ b/specs/CERTIFICATIONS.md @@ -1,10 +1,10 @@ # xspec Certifications -This document specifies the fixture products that certify selected tests of `specs/TEST-SPEC.md` under the certification protocol of TEST-SPEC.md §17 (C-1, C-2). A **conformer** conforms to `specs/SPEC.md` within its stated scope, with the simplest behavior that does so. A **violator** is its conformer with exactly one specified behavioral deviation. A test is **certified** when it passes against the conformer and fails against each violator that targets it. Fixtures are implemented as part of the test harness and are driven through the identical blackbox surfaces as the product (C-2: an executable/workspace binding and nothing else); this document describes them only in terms of SPEC.md's interfaces, contracts, seams, and observability features and prescribes no implementation details. +This document specifies the fixture products that certify selected tests of `specs/TEST-SPEC.md` under the certification protocol of TEST-SPEC.md §17 (C-1, C-2). A **conformer** conforms to `specs/SPEC.md` within its stated scope, with the simplest behavior that does so. A **violator** is its conformer with exactly one specified behavioral deviation. A test is **certified** when it passes against the conformer and fails against each violator that targets it. Fixtures are implemented as part of the test harness and are driven through the identical blackbox surfaces as the product (C-2: the product binding — the executable, and the package directory the `defineConfig` module is distributed as (7.6) — with the workspace, and nothing else); this document describes them only in terms of SPEC.md's interfaces, contracts, seams, and observability features and prescribes no implementation details. No scope below includes the `defineConfig` module, and no in-scope test drives H-2's module channel, so each fixture is bound with its executable and no package directory, as S-7's second sweep binds its stub product. -Selection is deliberately incomplete (PROCESS.md). A fixture exists here only where a vacuous pass is an elevated risk: negative and absence-of-effect tests whose staging, byte-compare, or form-decode wiring could silently miss the behavior under test, temporal behavior, tests routed through the `--test-hold` seam (SPEC.md 13.5), and the reachability of property tests' generated inputs. Harness-side defects that make a conforming input or answer fail — builder, capture, decode, oracle, and driver defects — are spurious fails, not vacuous passes; TEST-SPEC.md gates them by self-test rather than certification (S-2, S-3, S-6, S-8, and S-9 — the last verifying, independently of any product, that every MDX source TEST-SPEC.md declares well-formed, the MDX sources the scopes below stage among them, derives under the grammar 14.20 fixes, that every TypeScript source and configuration file it declares well-formed is accepted by the release 14.20 fixes both as module code and as script code, and that every source it declares unparseable (14.20) is not — MDX text that does not derive, TypeScript text rejected under both readings: a class S-9 itself places outside certification, since a conformer judging 14.20 on its accepting side alone passes an ill-formed fixture exactly as its violators do), and no fixture here targets them. No Bug Report exists, so no fixture is justified empirically. Every test not named in an in-scope set below is deliberately uncertified (see Exclusions). There are no spec modules, so there are no module certification files. +Selection is deliberately incomplete (PROCESS.md). A fixture exists here only where a vacuous pass is an elevated risk: negative and absence-of-effect tests whose staging, byte-compare, or form-decode wiring could silently miss the behavior under test, temporal behavior, tests routed through the `--test-hold` seam (SPEC.md 13.5), and the reachability of property tests' generated inputs. Harness-side defects that make a conforming input or answer fail — builder, capture, decode, oracle, and driver defects — are spurious fails, not vacuous passes; TEST-SPEC.md gates them by self-test rather than certification (S-2, S-3, S-6, S-8, and S-9 — the last verifying, independently of any product, that every MDX source TEST-SPEC.md declares well-formed, the MDX sources the scopes below stage among them, derives under the grammar 14.20 fixes, that every TypeScript source and configuration file it declares well-formed is accepted by the release 14.20 fixes both as module code and as script code, and that every source and configuration file it declares unparseable (14.20) is not — MDX text that does not derive, TypeScript text rejected under both readings: a class S-9 itself places outside certification, since a conformer judging 14.20 on its accepting side alone passes an ill-formed fixture exactly as its violators do), and no fixture here targets them. No Bug Report exists, so no fixture is justified empirically. Every test not named in an in-scope set below is deliberately uncertified (see Exclusions). There are no spec modules, so there are no module certification files. -Each conformer entry states its **scope** — the SPEC.md behaviors and command surface it implements and the workspace shapes it accepts — and its **in-scope tests**: the named subset (C-1) the certification runner executes against the conformer and each of its violators. Every in-scope test passes against the conformer. Each violator entry states its scope (its conformer's), its single deviation, the tests it certifies, and its expected failures: exactly the certified tests fail against it, and every other in-scope test passes. Where TEST-SPEC.md leaves an in-scope test's fixture content open and an expected-failure set — or the conformer's ability to pass within scope — depends on the choice, the entry states that choice as a **staging constraint** — a condition certification imposes on the harness's fixture for the named test, binding alongside C-1. Every conformer, whatever its scope, locates configuration as 7 states — by upward search for `xspec.config.ts` from the working directory, or at the path `--config <path>` names, resolved against the working directory (12.0) — and resolves configured paths and globs relative to the configuration file's directory, the workspace root; `--test-hold <path>` likewise resolves against the working directory (12.0). An in-scope test may therefore run from any working directory H-2 lets it choose — T7-4's path-resolution staging from a subdirectory of the workspace included — and no fixture fails a test on that choice. Every conformer likewise reads its arguments under the invocation grammar of 12.0 — flag tokens standing anywhere, a value-taking flag taking the whole next token whatever it looks like, arity fixed by name across commands (`--test-hold` value-taking on every command, so `build --test-hold --json` consumes `--json` as its value and leaves JSON out of effect, T13.5-1), the remaining tokens matching the synopsis exactly, a surplus operand a usage error — and, with JSON in effect, reports every usage error in the exit-2 error document of 12.7: the grammar is universal (12.0), so no in-scope usage-error assertion is left to a fixture's own parser. +Each conformer entry states its **scope** — the SPEC.md behaviors and command surface it implements and the workspace shapes it accepts — and its **in-scope tests**: the named subset (C-1) the certification runner executes against the conformer and each of its violators. Every in-scope test passes against the conformer. Each violator entry states its scope (its conformer's), its single deviation, the tests it certifies, and its expected failures: exactly the certified tests fail against it, and every other in-scope test passes. Where TEST-SPEC.md leaves an in-scope test's fixture content open and an expected-failure set — or the conformer's ability to pass within scope — depends on the choice, the entry states that choice as a **staging constraint** — a condition certification imposes on the harness's fixture for the named test, binding alongside C-1. Every conformer, whatever its scope, locates configuration as 7 states — by upward search for `xspec.config.ts` from the working directory, or at the path `--config <path>` names, resolved against the working directory (12.0) — and resolves configured paths and globs relative to the configuration file's directory, the workspace root; `--test-hold <path>` likewise resolves against the working directory (12.0). An in-scope test may therefore run from any working directory H-2 lets it choose — T7-4's path-resolution staging from a subdirectory of the workspace included — and no fixture fails a test on that choice. Every conformer reads the configuration's import as 7 states too: its module specifier is any static string literal (2.4), never interpreted, resolved, or loaded, and the configuration file is a source only where a configured group discovers it. Every conformer likewise reads its arguments under the invocation grammar of 12.0 — flag tokens standing anywhere, a value-taking flag taking the whole next token whatever it looks like, arity fixed by name across commands (`--test-hold` value-taking on every command, so `build --test-hold --json` consumes `--json` as its value and leaves JSON out of effect, T13.5-1), the remaining tokens matching the synopsis exactly, a surplus operand a usage error — and, with JSON in effect, reports every usage error in the exit-2 error document of 12.7: the grammar is universal (12.0), so no in-scope usage-error assertion is left to a fixture's own parser. ## CONF-CORE — operational core: exclusion seam, journal, durable files, review reads @@ -56,7 +56,7 @@ Each conformer entry states its **scope** — the SPEC.md behaviors and command * **Deviation:** `check` modifies the journal: each `check` invocation that is not refused as a usage or configuration error (exit 2) appends one fixed line to `.xspec/journal`, creating the file when absent. The appended line is inert to the fixture's own journal handling: read back as neither an identity mapping (5.4) nor a malformed entry (no 14.13, so no later command is gated by it, 13.3), with graph data and every other derived byte independent of how many such lines the journal holds (13.4). A single deviation: 6.1's rule that the journal is written by `rename` and `move` alone broken for `check`; `build`, every other read command, mutating commands, and the entries `rename`/`move` append are unchanged. * **Certifies:** T13.5-4. * **Expected failures:** exactly T13.5-4 (the `check` it runs while a mutating command is held appends its line, so the held-state comparison made once its reads have exited meets the journal grown past the pre-invocation bytes it asserts; the reads' answers — `check` clean, the inert line meeting no 14.13 and moving no derived byte — and the holder's entry, alone in the lock directory, are unmoved — a staging constraint, TEST-SPEC.md leaving open on which workspace each of T13.5-4's arms runs: its reads during a hold run on a workspace of their own, and no `check` runs on the workspaces of its `build` arm and its storm or on the twins they compare against, so that nothing appends there — `build` and the storm's `query`s are unchanged — and the `build` arm's held-state comparison and twin comparison, and the storm's final byte-equality to a clean build, hold as against the conformer. The test fails against this violator on that one comparison alone: one made before the reads ran, or re-baselined past each run that completes during the hold, passes it). All other in-scope tests pass: T6.1-2 compares the entries of the same operation on identical workspace states, which remain byte-identical; T10.4-5 byte-compares the session file, which is untouched, and its review reads answer ungated — the inert lines meet no 14.13, so 13.3's gate never turns them into exit-1 non-answers; the remaining 13.5 tests' compares are unmoved by the appends — under a staging constraint on T13.5-1, which VIOL-CORE-READERENTRY and VIOL-CORE-BUILDWAIT cite as well: its held run and its no-hold twin drive the same command sequence, and neither drives `build` or a read command between the mutating command's start and the final-state compare — the seam flag rides the mutating command, which this deviation leaves unchanged, so any `check` the shared sequence runs appends alike on both sides, and no `check` while held breaks the held-state comparison or desynchronizes the twins' journals; T13.5-2's byte-compare covers the refused mutating command alone, which appends nothing, and no `check` while command 1 is held breaks the held-state comparison made then (the scope's staging constraint on T13.5-2, T13.5-3, and T13.5-8); T13.5-3's runs and their twins start from copies of one built workspace on which, under the same constraint, no `build` or read command runs, so both sides hold the same lines; and T13.5-8's compares bracket its refused invocations alone under the same constraint — mutating commands, unchanged, and a `rename --preview` refused exit 2, which appends nothing — no `build` or read command running inside a bracket or while a command is held, and a `check` that establishes one of its failing workspaces, exiting 1 and appending one inert line, running outside every bracket and every hold. -* **Note:** the representative value of this violator for the suite's other never-modifies assertions (T6.1-1's journal sweep and T13.4-5's compares around `build` and the reads above all — see Exclusions — and T12.0-11, T12.1-4, T13.3-3, T6.4-3, T6.5-4, T6.5-20, T6.5-21, T6.6-2, T13.4-9, T13.4-10, and the answer-side compares of T11.2-1/T11.2-6/T11.6-4) holds insofar as those assertions share the compare-around-command machinery certified here — T13.5-4's comparison of the workspace, the journal among its paths, once its reads, `check` among them, have exited, the one ground on which T13.5-4 fails against this violator; the Exclusions lean on exactly that condition. +* **Note:** the representative value of this violator for the suite's other never-modifies assertions (T6.1-1's journal sweep and T13.4-5's compares around `build` and the reads above all — see Exclusions — and T12.0-11, T12.1-4, T13.3-3, T6.4-3, T6.5-4, T6.5-20, T6.5-21, T6.6-2, T13.4-9, T13.4-10, T7-10(c), and the answer-side compares of T11.2-1/T11.2-6/T11.6-4) holds insofar as those assertions share the compare-around-command machinery certified here — T13.5-4's comparison of the workspace, the journal among its paths, once its reads, `check` among them, have exited, the one ground on which T13.5-4 fails against this violator; the Exclusions lean on exactly that condition. ### VIOL-CORE-PERSISTREADS @@ -213,7 +213,7 @@ Each conformer entry states its **scope** — the SPEC.md behaviors and command ## CONF-DISC — configuration-driven discovery -**Scope.** Workspaces of trivial single-section `.mdx` sources whose file and directory names carry glob-significant bytes, plus, as T7-6 stages them, files at derived-classified paths and an import target unmatched by every group; spec groups and, as T7-6's code-group exclusion arm and single-casing arms and T7-4's literal-`\` arm stage them, code groups (7.2) of well-formed `.ts` sources spelling no marker, `text` call, or module-linking form whose specifier names a spec module or designates a derived-file path (4, 14.15) — each discovered code source an edgeless whole-file code location (4.6), nothing in scope giving a code file an edge — both kinds under the glob grammar of 7 (a no-match group, and the empty `specs` and `code` maps, are valid with zero sources); as T7-6's invalid-source arm and extension twin stage them (below), a spec source at a path 7.1 bars, a spec-group file lacking the `.mdx` extension, and code-group files that are no well-formed TypeScript; imports of 2.1's single-default-binding form, resolving lexically against the importing file's directory to a discovered source (2.1), an undiscovered target failing with 14.15; `markdown` with `emit: true` as T7-6's destination arm stages it and as its invalid-source arm and extension twin pin it, next to sources, and emission disabled — `markdown` absent or `emit: false`, either spelling 7.3 admits — as that arm's control stages it, destinations classified by configuration alone (7.3); symbolic links present in the tree; no `coverage`, `policy`, or git; content of derived and emitted files beyond path is out of scope. Staging constraints: T7-6's exclusion arms but its invalid-source and single-casing arms are staged on both group sides — the spec side observed through `ids`, the code side through `query edges --from <path>` (11.1): on a workspace passing `build`'s validations, each excluded path a code glob matches — the module `build` generated next to its source (13.1) above all, a file under `.xspec/`, and an enabled emit destination — is refused as a path in no configured group (exit 2, 12.0), beside a discovered code source's whole-file location answering exit 0, T7-3's idiom for code discovery; and the staged code globs match, beyond those derived-classified paths, only the well-formed `.ts` sources above, no spec-group file among them; and no derived-classified path lies within the reach of both a spec glob and a code glob — the `.xspec/` file and the destination the spec side's arms match distinct from those the code glob matches, neither side's globs reaching the other side's derived paths, or the two sides staged in separate workspaces — so 14.14's both-groups rule stays dormant under the conformer's 13.4 exclusion and with that exclusion lifted alike (VIOL-DISC-DERIVED). T7-6's single-casing arms are code-side alone, each on a workspace passing `build`'s validations: `src/a.XSPEC.ts` under the code glob `src/*.ts` and, on the Linux leg, `.XSPEC/a.ts` under `.XSPEC/*.ts`, each a well-formed `.ts` source as above, are discovered — listed among `inventory`'s `sources`, their whole-file locations answering `query edges --from` exit 0 — 13.4's name tests being byte-wise (12.0). T7-6's invalid-source arm and its control are staged as TEST-SPEC.md pins them, exempt from those constraints — emission next to sources, a spec glob `specs/*.mdx`, a code group globbing `specs/*.md`, and `specs/a'b.mdx`, a spec source at a path 7.1 bars (14.19), beside a plain file `specs/a'b.md` holding `)`, no well-formed TypeScript (14.20) — and so is its extension twin — emission next to sources, a spec glob `specs/*.txt` matching `specs/A.txt`, and a code group globbing `specs/*.md` matching plain files `specs/A.md` and `specs/A.txt.md`, each holding `)` — each observed by `check` alone — a staging constraint: each such workspace is staged from scratch and no `build` succeeds on it, so no record exists (13.3) and `check` reports exactly the findings of `build`'s validations (12.2), 14.10's mismatch forms being undetectable on a failing workspace and its recorded-file form meeting no record (14.10, T12.2-4): with emission enabled, `specs/a'b.md` remains the invalid source's configured emit destination, though nothing is emitted on a failing workspace (12.1), its derived paths following the `NAME.mdx` name shape alone (13.1, 7.3), so 13.4 excludes that path and the condition-19 finding stands alone; with emission disabled, the path is no emit destination, the code group discovers it, and its condition-20 finding stands beside the condition-19 one; and in the twin `specs/A.txt`, lacking `.mdx`, has no derived path (13.1, 7.3), so neither `.md` file is excluded and its condition-19 finding stands beside a condition-20 finding for each. Command surface: `build` and `ids` (12.3) as the observation of the discovered spec set, and `inventory` (11.6) in its full 12.7 document form over the scope's workspaces — T7-4's observation that a glob matching nothing is configured as spelled (`configuration`, `globs` as configured), and T7-6's single-casing arms' `sources`; `query edges --from <path>` (11.1) as the observation of the discovered code set — for a discovered code source's whole-file location, exit 0 with its empty edge enumeration, the JSON document 11 makes its only output form; for a path in no configured group, an excluded derived path included, the usage error of 12.0 (exit 2, the error document of 12.7), a check preceding the gate of 13.3 (12.0), which the staging keeps dormant; `check` (12.2) as T7-6's invalid-source arm, its control, and its extension twin drive it, over their validation-failing workspaces alone (above); the configuration-error behavior of 14.14/12.0 for patterns resolving outside the workspace root, and the source-error reporting of 14.15, 14.19, and 14.20 — 14.19's missing-extension form, which binds spec-group files alone, reporting T7-6's extension twin's `specs/A.txt` alone, every other staged spec-group match lacking `.mdx` a derived-classified path the 13.4 exclusion keeps out of the discovered set, while its path-character form (7.1) reports T7-6's invalid source, and 14.20 reports the invalid-source control's code source and the twin's two `.md` files alone. A staging constraint: every command the in-scope tests drive is drawn from this surface — T7-4's and T7-5's observations of the discovered set, which TEST-SPEC.md leaves open (T7-5 names none), ride `build`'s exit and findings, `ids`, and `inventory`'s listing of every discovered source (11.6) over the groups their fixtures alone declare — spec groups, and the one code group of T7-4's literal-`\` arm, whose discovered set `inventory` lists (VIOL-DISC-DERIVED's constraint) — and T7-6's ride the observations pinned above; `view`, `query nodes`, and every other read are not served. Contracts under certification: glob semantics of 7 — `*`, `?`, `**` (any segments only as a whole pattern segment, each `*` of an in-segment `**` the single-segment wildcard), byte-wise case-sensitive matching, dot-segment rule, every other character a literal (`\` included, the configuration literal read verbatim, 2.4), and the outside-root decision by spelling alone (a leading `/` or a depth falling below zero a configuration error, 14.14; a `.`, `..`, or empty segment inside the root matching nothing; a drive-qualified spelling ordinary segments) — discovery's refusal to follow symbolic links, and the source exclusion of 13.4 (`.xspec.` names, `.xspec/` paths, and enabled emit destinations in no spec or code group — an invalid source's destination included, derived paths following the `NAME.mdx` name shape alone, so that a spec-group file lacking `.mdx` has none, 13.1, 7.3 — its name tests byte-wise and case-sensitive, 12.0), with 7.1's path-character bar (14.19) as T7-6's invalid-source arm stages it. +**Scope.** Workspaces of trivial single-section `.mdx` sources whose file and directory names carry glob-significant bytes, plus, as T7-6 stages them, files at derived-classified paths and an import target unmatched by every group; spec groups and, as T7-6's code-group exclusion arm and single-casing arms and T7-4's literal-`\` arm stage them, code groups (7.2) of well-formed `.ts` sources spelling no marker, `text` call, or module-linking form whose specifier names a spec module or designates a derived-file path (4, 14.15) — each discovered code source an edgeless whole-file code location (4.6), nothing in scope giving a code file an edge — both kinds under the glob grammar of 7 (a no-match group, and the empty `specs` and `code` maps, are valid with zero sources); as T7-6's invalid-source arm and extension twin stage them (below), a spec source at a path 7.1 bars, a spec-group file lacking the `.mdx` extension, and code-group files that are no well-formed TypeScript; imports of 2.1's single-default-binding form, resolving lexically against the importing file's directory to a discovered source (2.1), an undiscovered target failing with 14.15; `markdown` with `emit: true` as T7-6's destination arm stages it and as its invalid-source arm and extension twin pin it, next to sources, and emission disabled — `markdown` absent or `emit: false`, either spelling 7.3 admits — as that arm's control stages it, destinations classified by configuration alone (7.3); symbolic links present in the tree; no `coverage`, `policy`, or git; content of derived and emitted files beyond path is out of scope. A staging constraint, TEST-SPEC.md leaving open where the globs it does not pin are written, the directory of T7-4's bare `*` (`*` does not match `.hidden`) among them: no spec glob an in-scope test stages matches the configuration file, which lies at the workspace root (7), T7-4's bare `*` being written below the root over a directory whose files are `.mdx` sources and the dotfile alone. Discovered by a spec group, the configuration file would be a spec-group file lacking `.mdx` (14.19) whose content is analyzed as a spec source's (2.1, 2.7; 14: an invalid path masks nothing), so that `build` and the gated `ids` (13.3) would exit 1 reporting 14.19 beside 14.15 at its import and 14.16 at its export, or beside 14.20 where its bytes do not derive as MDX (7; T7-10(e)) — findings this scope does not serve, which T7-4's and T7-5's observations through `build` and `ids` (below) would meet. A code glob matching it is harmless: the configuration file is then a discovered code source as the scope's others are — well-formed, its import's specifier naming no spec module and designating no derived-file path — an edgeless whole-file location (4.6). Staging constraints: T7-6's exclusion arms but its invalid-source and single-casing arms are staged on both group sides — the spec side observed through `ids`, the code side through `query edges --from <path>` (11.1): on a workspace passing `build`'s validations, each excluded path a code glob matches — the module `build` generated next to its source (13.1) above all, a file under `.xspec/`, and an enabled emit destination — is refused as a path in no configured group (exit 2, 12.0), beside a discovered code source's whole-file location answering exit 0, T7-3's idiom for code discovery; and the staged code globs match, beyond those derived-classified paths, only the well-formed `.ts` sources above, no spec-group file among them; and no derived-classified path lies within the reach of both a spec glob and a code glob — the `.xspec/` file and the destination the spec side's arms match distinct from those the code glob matches, neither side's globs reaching the other side's derived paths, or the two sides staged in separate workspaces — so 14.14's both-groups rule stays dormant under the conformer's 13.4 exclusion and with that exclusion lifted alike (VIOL-DISC-DERIVED). T7-6's single-casing arms are code-side alone, each on a workspace passing `build`'s validations: `src/a.XSPEC.ts` under the code glob `src/*.ts` and, on the Linux leg, `.XSPEC/a.ts` under `.XSPEC/*.ts`, each a well-formed `.ts` source as above, are discovered — listed among `inventory`'s `sources`, their whole-file locations answering `query edges --from` exit 0 — 13.4's name tests being byte-wise (12.0). T7-6's invalid-source arm and its control are staged as TEST-SPEC.md pins them, exempt from those constraints — emission next to sources, a spec glob `specs/*.mdx`, a code group globbing `specs/*.md`, and `specs/a'b.mdx`, a spec source at a path 7.1 bars (14.19), beside a plain file `specs/a'b.md` holding `)`, no well-formed TypeScript (14.20) — and so is its extension twin — emission next to sources, a spec glob `specs/*.txt` matching `specs/A.txt`, and a code group globbing `specs/*.md` matching plain files `specs/A.md` and `specs/A.txt.md`, each holding `)` — each observed by `check` alone — a staging constraint: each such workspace is staged from scratch and no `build` succeeds on it, so no record exists (13.3) and `check` reports exactly the findings of `build`'s validations (12.2), 14.10's mismatch forms being undetectable on a failing workspace and its recorded-file form meeting no record (14.10, T12.2-4): with emission enabled, `specs/a'b.md` remains the invalid source's configured emit destination, though nothing is emitted on a failing workspace (12.1), its derived paths following the `NAME.mdx` name shape alone (13.1, 7.3), so 13.4 excludes that path and the condition-19 finding stands alone; with emission disabled, the path is no emit destination, the code group discovers it, and its condition-20 finding stands beside the condition-19 one; and in the twin `specs/A.txt`, lacking `.mdx`, has no derived path (13.1, 7.3), so neither `.md` file is excluded and its condition-19 finding stands beside a condition-20 finding for each. Command surface: `build` and `ids` (12.3) as the observation of the discovered spec set, and `inventory` (11.6) in its full 12.7 document form over the scope's workspaces — T7-4's observation that a glob matching nothing is configured as spelled (`configuration`, `globs` as configured), and T7-6's single-casing arms' `sources`; `query edges --from <path>` (11.1) as the observation of the discovered code set — for a discovered code source's whole-file location, exit 0 with its empty edge enumeration, the JSON document 11 makes its only output form; for a path in no configured group, an excluded derived path included, the usage error of 12.0 (exit 2, the error document of 12.7), a check preceding the gate of 13.3 (12.0), which the staging keeps dormant; `check` (12.2) as T7-6's invalid-source arm, its control, and its extension twin drive it, over their validation-failing workspaces alone (above); the configuration-error behavior of 14.14/12.0 for patterns resolving outside the workspace root, and the source-error reporting of 14.15, 14.19, and 14.20 — 14.19's missing-extension form, which binds spec-group files alone, reporting T7-6's extension twin's `specs/A.txt` alone, every other staged spec-group match lacking `.mdx` a derived-classified path the 13.4 exclusion keeps out of the discovered set, the configuration file never one (above), while its path-character form (7.1) reports T7-6's invalid source, and 14.20 reports the invalid-source control's code source and the twin's two `.md` files alone. A staging constraint: every command the in-scope tests drive is drawn from this surface — T7-4's and T7-5's observations of the discovered set, which TEST-SPEC.md leaves open (T7-5 names none), ride `build`'s exit and findings, `ids`, and `inventory`'s listing of every discovered source (11.6) over the groups their fixtures alone declare — spec groups, and the one code group of T7-4's literal-`\` arm, whose discovered set `inventory` lists (VIOL-DISC-DERIVED's constraint) — and T7-6's ride the observations pinned above; `view`, `query nodes`, and every other read are not served. Contracts under certification: glob semantics of 7 — `*`, `?`, `**` (any segments only as a whole pattern segment, each `*` of an in-segment `**` the single-segment wildcard), byte-wise case-sensitive matching, dot-segment rule, every other character a literal (`\` included, the configuration literal read verbatim, 2.4), and the outside-root decision by spelling alone (a leading `/` or a depth falling below zero a configuration error, 14.14; a `.`, `..`, or empty segment inside the root matching nothing; a drive-qualified spelling ordinary segments) — discovery's refusal to follow symbolic links, and the source exclusion of 13.4 (`.xspec.` names, `.xspec/` paths, and enabled emit destinations in no spec or code group — an invalid source's destination included, derived paths following the `NAME.mdx` name shape alone, so that a spec-group file lacking `.mdx` has none, 13.1, 7.3 — its name tests byte-wise and case-sensitive, 12.0), with 7.1's path-character bar (14.19) as T7-6's invalid-source arm stages it. **In-scope tests:** T7-4, T7-5, T7-6. @@ -240,6 +240,28 @@ Each conformer entry states its **scope** — the SPEC.md behaviors and command * **Certifies:** T7-6. * **Expected failures:** exactly T7-6 (its exclusion arms: a staged `.xspec.`-named `.mdx` file matched by a glob enters the discovered set; a file under `.xspec/` is discovered where a pattern spells the dot segment literally, discovery now listing `.xspec/`; with emission enabled, a glob-matched file at a source's destination — always a non-`.mdx` name, destinations ending `.md` (13.2) — is reported as 14.19 — each observably failing the arm's no-error non-discovery assertion; on the code-group side, each excluded path the code glob matches — the module `build` generated next to its source, the staged file under `.xspec/`, the enabled destination — enters the discovered code set as a member of its code group alone (the scope's staging keeps every derived-classified path out of the reach of both a spec glob and a code glob, so the lifted exclusion never makes one a file matched by both, 7.2's configuration error: 14.14, exit 2 with the configuration-error document of 12.7, preceding all source analysis, 12.0), so `query edges --from` no longer refuses it as a path in no configured group: it answers exit 0 with an empty enumeration where every discovered file parses, and exit 1 at the gate of 13.3 — the workspace now failing `build`'s validations — where one does not (14.20) or where the spec side's 14.19 finding shares the workspace, the discovered-source control answering alike, never the asserted exit 2 (12.0), so the arm fails on the exit code whatever the parse outcome; in the invalid-source arm, the code glob's match at the invalid source's emit destination `specs/a'b.md` enters the discovered code set, `check` reporting its condition-20 finding beside the condition-19 one where the arm asserts that one alone, the emission-disabled control unmoved; the import arm is untouched, the zero-source arm too where its globs reach no derived path, and so are the extension twin, whose `specs/A.txt` has no derived path, and the single-casing arms, whose sources no exclusion reaches on either side; the test fails on the exclusion arms in any case). T7-4 and T7-5 pass under a staging constraint: their fixtures declare no code group but T7-4's literal-`\` arm's, whose glob `src/a\*.ts` matches no derived-classified path, stage no `.xspec.`-bearing names, write no pattern naming `.xspec/`, leave `markdown` absent, and observe discovery only while no generated file exists — each arm's observation is a first `build`, or an `ids` or `inventory` no `build` precedes (refresh writes graph data alone, 13.3; `inventory` writes nothing, 11.6) — so no pattern whose reach exceeds `.mdx` names (T7-4's bare `*`) ever confronts the conformer's own next-to-source output (13.1), and their wildcard patterns cannot reach its graph data past the unchanged dot-segment rule. +## CONF-IMPORT — the configuration's import specifier + +**Scope.** T7-9's workspace outside its install stagings, as P-19 draws over it: one configured spec group globbing `specs/*.mdx` over `specs/A.mdx` and `specs/B.mdx`; `markdown` with `emit: true`, emitting next to sources (7.3, 13.2); no code group, `coverage`, `policy`, git, or `node_modules`, so that no configured group discovers the configuration file — a staging constraint, T7-9 leaving open its code groups, of which it bars only one matching the configuration file, and the sources' content: no code group at all, the conformer serving none, and each source a trivial single-section source, its one section carrying an `id` alone around plain text, as T7-9(d)'s `specs/A.mdx` does (`<S id="a">A</S>`). The configurations in scope differ from their twins' in the import's module specifier alone, each twin importing from `"xspec"`: each specifier a static string literal TypeScript 5.9.3's scanner accepts (14.20), as P-19 draws it — either quote style; text shaped as bare, scoped, relative, absolute, and URL specifiers, and the empty string; escape sequences of every form the scanner accepts — the hexadecimal escape, the Unicode escape in its four-digit form and in its braced form (`\u{…}`), the single-character escapes, and `\0` before a non-digit — and line continuations; and U+FFFD and other non-ASCII code points. Configuration within scope as 7 states: the specifier read as spelled (2.4) and never interpreted, resolved, or loaded, so that validity and every answer are independent of it, and well-formedness (14.20) judged on its accepting side alone — every draw well-formed, which S-9 verifies before the product is driven on it — so nothing in scope presents a configuration error or a finding. Command surface: `build`, `check`, `ids` (12.3), and `inventory` (11.6) in its full 12.7 document form, each under `--json` and behaving per 12.0 and 13.3 over such workspaces — `build` generating each source's module (13.1) and its Markdown next to it (13.2) and writing graph data whose record lists the derived paths generated (13.3), the record `inventory` reports (11.6); content of modules, Markdown, and graph data beyond path, byte-determinism (12.0), and the record is out of scope, but for one clause: no module's or Markdown file's content depends on anything in the configuration file that a draw and its twin spell differently, so that the two write them byte-identical — P-19's comparison across two workspaces whose configuration files differ, which 12.0's determinism over identical input does not cover. A staging constraint, P-19 citing T7-9's assertions without naming their commands: each draw and its twin drive exactly the commands of T7-9(a) and (c) — `build`, `check`, `ids`, and `inventory`, each under `--json` — and are compared as those arms compare them. Contracts under certification: 7's acceptance of every static string literal, in either quote style, as the configuration import's module specifier, read as spelled — escape sequences and line continuations included — and never interpreted, resolved, or loaded. + +**In-scope tests:** P-19. + +**Justification.** P-19 searches the spellings of the configuration's import specifier, of which T7-9's fixed arms stage, well-formed, a single hexadecimal escape, a single line continuation, a single-quoted name, and a raw U+FFFD — the Unicode escape in both its forms, the single-character escapes, and `\0` are P-19's alone — so its value rests on its draws reaching them as spelled: criterion (a)'s reachability case, the one P-1, P-2, and P-15 carry. Its staging hazards are two. The first is the one CONF-LEFTOVER answers for file names, moved into a literal: tooling that handles a literal as its value — a code printer serializing a drawn value, which spells it with the printer's own quotes and escapes or none, or text whose escape sequences were decoded on their way into the harness — stages another spelling of the same value, well-formed, which S-9 accepts, and the class goes silently unreached, each such draw answering as its twin for every product, so that a product refusing a specifier whose spelling is not its value — a configuration error (14.14) where its twin loads — passes P-19; handed a drawn spelling as its content instead, a printer escapes each `\` the spelling holds, so that of the escape forms drawn the escaped backslash alone reaches the product. The second is a formatter normalizing quotes, which re-spells a literal without decoding it and stages the single-quoted form as a double-quoted one, so that a product reading double-quoted specifiers alone passes P-19. Each class has its own violator: C-1 judges whole tests, so a deviation moving both would leave one class's reach uncertified, P-19 failing through the other either way (as in CONF-LEFTOVER). VIOL-IMPORT-BRACED refuses the braced Unicode escape of a code point at or below U+FFFF, a spelling value printers do not choose: decoding removes it, a value printer replaces it with a spelling of its own — braced, where it writes that form at all, only above U+FFFF — and a printer handed the spelling turns it into an escaped backslash before ordinary characters, which the violator reads as the conformer does; VIOL-IMPORT-SINGLE refuses the single-quoted form. P-19 fails against each on every run whose draws reach its form as spelled — certifying that they do. Certification does not reach a corruption confined to the forms P-19 draws beside those two — four-digit Unicode escapes decoded while braced ones survive, or raw non-ASCII code points spelled as escapes while every escape survives, say. The document accepts that residual rather than staging a violator per form: decoding, and every printer, an ASCII-only one among them, whatever it is handed, re-spell the braced form with whatever else they re-spell, and a formatter normalizes quotes, keeping non-ASCII code points as it finds them — so each tool the hazards name meets one of the two violators, as line-separator normalization rewrites both of VIOL-VALID-SEP's code points at once (CONF-VALID). T7-9's fixed escape-spelled, single-quoted, and raw-U+FFFD arms ride this certification (see Exclusions). + +### VIOL-IMPORT-BRACED + +* **Scope:** CONF-IMPORT. +* **Deviation:** The braced form of the Unicode escape sequence (`\u{…}`) is not recognized in the configuration's import specifier where its code point is at or below U+FFFF: a specifier spelling one is judged not well-formed TypeScript (14.20), so its configuration is a configuration error (14.14), every command exiting 2 with the configuration-error document of 12.7. A braced escape begins where the grammar 14.20 fixes begins one — at a `\` that itself begins an escape sequence and is followed by `u{` — never at a `\` that a preceding `\` escapes: `\\u{…}` spells a single-character escape followed by the ordinary characters `u{…}`, and a specifier so spelled is read as the conformer reads it. A single deviation: one escape form of the grammar 14.20 fixes dropped, for the specifier and those code points alone; a braced escape of a code point above U+FFFF, the Unicode escape's four-digit form, every other escape sequence, line continuations, either quote style, and every other spelling are read as the conformer reads them. +* **Certifies:** P-19. +* **Expected failures:** exactly P-19 (on each draw whose specifier spells a braced Unicode escape of a code point at or below U+FFFF, begun by a `\` that itself begins an escape sequence, `build`, `check`, `ids`, and `inventory` each exit 2 with that document, concerning `xspec.config.ts`, where the property asserts its twin's exit 0 and answers; every other draw — one whose braced escapes all lie above U+FFFF, or whose `u{` follows a `\` that a preceding `\` escapes, among them — and each twin loads and answers as against the conformer) — a staging constraint, P-19 leaving open which code points its braced draws spell: they include code points at or below U+FFFF. There is no other in-scope test. + +### VIOL-IMPORT-SINGLE + +* **Scope:** CONF-IMPORT. +* **Deviation:** A single-quoted module specifier is refused: the configuration's import is read only where its specifier is double-quoted, a configuration whose specifier is single-quoted being a configuration error (14.14), every command exiting 2 with the configuration-error document of 12.7. A single deviation: one quote style of the static string literal 2.4 defines dropped, for the specifier alone; a double-quoted specifier — whatever its text, escapes, line continuations, and code points — and every other literal of the configuration are read as the conformer reads them. +* **Certifies:** P-19. +* **Expected failures:** exactly P-19 (on each draw whose specifier is single-quoted, `build`, `check`, `ids`, and `inventory` each exit 2 with that document, concerning `xspec.config.ts`, where the property asserts its twin's exit 0 and answers; every other draw, and each twin, importing from the double-quoted `"xspec"`, loads and answers as against the conformer). There is no other in-scope test. + ## CONF-AVAIL — availability answers and JSON datum forms **Scope.** Workspaces of configured spec groups of `.mdx` sources at valid-UTF-8, `#`-free, U+FFFD-free workspace-relative paths free of the characters 7.1 bars there (`"`, `'`, `\`, U+000A, U+000D, U+2028, U+2029) — imports (2.1, resolved lexically: a non-canonical specifier designating the same discovered source, T11.4-4), `d` props, and `{text(...)}` embeddings as the in-scope fixtures stage them — a staging constraint: embeddings spelling nothing beside the call, the further forms of 2.3 (T2.3-3) lying outside this scope, and no MDX comment (2.7), no in-scope test staging one — and a spec source unparseable by encoding where T11.4-4's masked-target arm stages one — a staging constraint: a file beginning with a byte-order mark (1.6), its condition-20 finding the zero-length range at offset 0 (14) — never invalid UTF-8 with a non-empty well-formed prefix (its finding then located past offset 0, 14), and never a syntax failure, the offset rules of 14 for both lying outside this scope — the file masked (11.2: no view, its finding accompanying only when it is itself requested, an embedding into it the embedding file's own 14.6); one code group (7.2) only as T11.4-4's wrong-kind-target arm stages it — a staging constraint: its glob matches one `.mdx` file that no spec-group glob matches, a discovered code source, so a specifier designating it names no spec source (2.1, 14.15) and no view domain holds it (11.2), and T11.4-4, the sole in-scope test declaring a code group, drives `view` alone, so no in-scope invocation reads the code source's content, which is out of scope; no `markdown`, `coverage`, `policy`, or git. Command surface: `view`, with and without `--text` — the bare whole-domain form (neither operands nor `--file`: every discovered spec source viewed, 11.4) and the operand and `--file` forms, each as staged — and `occurrences` — the bare unrestricted form (no `--file`: the entire discovered set, 11.3, as T11.2-4 and T11.3-4's unrestricted arm drive it) and `--file` and `--to` as staged — each answering in the form-exact 12.7 document forms. A staging constraint: every command the in-scope tests drive is drawn from this enumerated surface — in particular, no in-scope staging drives `at` (the 11.2 preamble's third surface, not served by this conformer), T11.2-4's occurrence-record observations ride `occurrences` and `view`, T11.2-2's no-occurrence arm rides its one file's view — the view's `occurrences` (11.4) — and T11.4-3 drives `view` alone — its tag-set-form arm asserts the form on the `view` node, and its mention of `query node` and `show --json` is read as the cross-reference to T12.7-1 it cites, those surfaces asserted where their data arise (T2.6-1's `query node` tags; T12.4-1's field-by-field equality with `query node`) and not served here: on T11.4-3's own fixture, failing `build`'s validations (14.17), the gate of 13.3 would turn either read back unanswered (exit 1), so no assertion of the form could ride them there. Contracts under certification: the availability rules of 11.2 — parse-local structure and positional trees (a section inside an invalid non-section element parenting per 11.4), spelled-identity definedness (structural validity, 1.3, among its chain conditions: a structurally invalid bearer and its descendants undefined, T11.2-2), interpreted tags and coverage in the value forms of 12.7 — a tag set in byte order, duplicates collapsed, never case-folded, `[]` when tagless; a coverage attribute the string `"required"` or `"none"` — as T11.4-3's form arms assert them, resolution through defined identities, whole-value expansion poisoning, own and subtree text judged apart (T11.2-4) and both defined through the rules of 3 (1.6; emission out of scope), and removal classification by syntactic form — a stray element preserved by its own tags, the sections and embeddings it encloses classified by their own forms (11.2), as T11.2-4's enclosure arm stages it: a `<div>` in flow position at the root level holding a section and an embedding, its one condition-16 finding located opening tag through closing tag (14), the section a child of the root in the tree (the positional enclosure of 11.4), the embedding's occurrence recorded with the root as its `source`, and under `--text` the root's own text carrying the element's tags with the section's contribution excised and the embedding expanded (1.6, 3) — occurrence records per 5.7/11.3 with `source` withheld as one datum where undefined, the `--file` domain restriction and `--to` selection of 11.3, the raw attribute and import data of 11.4 — every attribute a tag spells listed by form, a valueless bare name (`<S id>`, `<S id="x" tags>`) included, its interpreted datum unavailable and its finding condition 17, never condition 1 (T11.2-2, T11.4-3); every import declaration with its binding name (the default binding's identifier, a non-default clause beside it notwithstanding, as T11.4-4's two-clause arms stage it, each such declaration invalid, 2.1, a 14.15 finding beside it; the stated `null` of 12.7 for the side-effect-only, named-only, and namespace-only forms, each invalid likewise, its binding name never the marker, 11.4) and its resolved target, the discovered spec source its specifier designates under 2.1, parseable or not, whatever the declaration's binding form, explicitly unavailable where specifier form or discovery defines none (11.4): a specifier of invalid form (the bare specifier) or one designating no discovered spec source (a file that does not exist, `./typo.xspec`, or a discovered code source), the invalidity a located 14.15 beside it (T11.4-4); the declaration's range its own characters, a spelled `;` among them (14.20; T11.4-4's semicolon-terminated arm) — `imports` and `occurrences` each in document order (11.4, 12.7), findings accompanying per 11.2/14 with stable codes and located ranges for the staged conditions (14.1, 14.2, 14.3, 14.4, 14.5, 14.6, 14.9, 14.15, 14.16, 14.17, and 14.20 at offset 0 as staged above), and the exit discipline of 11.2 (any finding or explicitly-unavailable datum → exit 1 with the full answer emitted; complete and finding-free → exit 0). Graph-data content and refresh behavior beyond the answers are out of scope: no in-scope test observes either. @@ -305,13 +327,15 @@ Considered against the selection criteria and deliberately left uncertified; eac * **T13.5-6, T13.5-7, T7-8, T14-9, T14-10** (workspace isolation; write-refused and interrupted mutation; discovery's read scope; environment refusals): T13.5-6 is squarely in criterion (a)'s temporal class, its concurrent mutations meeting cross-workspace interference only where their schedules overlap, but that isolation is the harness's own H-1 obligation, exercised on every parallel run of the suite (E-3), not on this test's schedules alone; and its held arms — a mutating command held in one workspace leaving the other's prompt and unrefused, exit 0, for sibling workspaces and for a root nested inside another — are positive outcomes, failing loud against a product whose exclusion spans the two, over a staging of plain directory nesting that no tooling rewrites. T13.5-7, T14-9, and T14-10 stage the environment's refusal (14.24, 14.25) by permission removal — T13.5-7 and T14-9 for a mutating command while it is held at the seam (T13.5-1's choreography, certified via the CONF-CORE lock violators) and before the invocation for `build` and the refreshing reads (T13.5-7(f), (h); T14-9's reporter-set arms), acquisition's own refusals staged before the invocation instead (T13.5-10(d), below), T14-10 by read-permission removal on files and directories, before the invocation in arms (a) through (h) and (j) through (l) — no hold involved, their mutating commands, (b)'s `rename` refused with the journal's finding and (g)'s representative `rename`, unheld — and in (i)'s acquisition arms, which are T13.5-10(d)'s stagings, verified on the harness itself and excluded with that test (below), while (i)'s second-discovery arm makes a directory unlistable during a hold, T13.5-12(e)'s staging, which rides the seam choreography the CONF-CORE lock violators certify (below): the refusal is the environment's, not the product's, so a staging that misses — ineffective, or applied after the write or read it should refuse — leaves the command succeeding where a refusal is asserted, an exit-2 error document or the finding a refused read maps to (T14-10's table), a loud failure, and E-1 makes the harness verify each staging on itself before invoking the product, an ineffective one a harness error (H-11), never a pass or a skip; T7-8 inverts that polarity — a directory no glob reaches below, a dot-directory, an entry outside discovery's examination, and `.xspec` beneath a glob reaching below it, each staged refused where discovery must never meet the refusal (7) — so there a staging that misses passes a product that would have met the refusal, and that same verification on the harness itself is what braces the test, a product meeting the refusal failing loud (exit 2 where the twin's outcome is asserted); their operative assertions are positive — each per-command state byte-compared against an unrefused twin (H-6), the error document's `write-failure` or `read-failure` code with its concerned path, the condition each refused read maps to (T14-10's table), `check`'s exact report of what a stopped operation leaves, and T13.5-7(b)'s residue, the emptied lock directory its read-only `.xspec` keeps release from deleting, asserted present, which braces at the same path every other arm's absence of `.xspec/lock` — and a conformer passing them would carry the whole write and read surface (Markdown emission under `outDir`, git baselines, code groups, sessions, every refreshing read — P-8's scope argument). T13.5-7's kill arm, a robustness check unsynchronized by design (E-5) — its kills past the lift land as timing decides, its assertion disjunctive over the states 13.5 admits — is excluded with the rest of the test on that scope, C-1 judging whole tests; the held-point choreography it shares is VIOL-CORE-EARLYWRITE's on T13.5-1, and the lock path's state after its kills T13.5-3's past-the-hold arm's, certified via VIOL-CORE-EARLYRELEASE. * **T13.5-9 through T13.5-12 and T13.4-12** (the exclusion's reach; acquisition; release; rediscovery under exclusivity; the transient lock path): their operative assertions are positive outcomes — the busy refusal's code and path from another environment, working directory, path to the root, or user (T13.5-9); acquisition's write and read failures with their concerned paths (T13.5-10(a), (d)), a leftover's takeover with the twin's result (b), the busy refusal among staged leftovers and over a live entry made unreadable or altered (c), acquisition over an interfered hold or another machine's holder (e), the takeover of an entry recording the acquirer's own identifier, beside it an entry of a byte-different name (f), and proceeding with `.xspec` unlistable (h); `.xspec/lock` absent, or its stated residue present, after each ending, and the twin's outcome or the read failure where release meets an unlistable lock directory (T13.5-11); the effect of a change made during the hold (T13.5-12); and `check` clean, `inventory`'s and `ids`' answers the leftover-free twin's, and `build` exiting 0 beside an untouched leftover (T13.4-12) — each failing loud against the product it targets, while their stagings — a second user and a second mount, fresh process-identifier namespaces, permission removals, the bracketing of a live entry by dead entries and leftovers in both orders, two runs sharing an identifier — are verified on the harness itself before use, an ineffective staging a harness error (E-1, H-11), never a pass or a skip. A product keeping its exclusion state anywhere but the lock directory fails loud the held-state comparison every held arm makes (TEST-SPEC.md 13.5), the held run's entry absent from `.xspec/lock`; their absences of `.xspec/lock` are braced by its presence asserted at the same path — a dead run's entry after a kill, the entry a refused deletion leaves (T13.5-11(d)), a staged leftover's kind, name, and content after each command (T13.4-12); their lock-path inclusions for commands that acquire nothing share the comparison machinery VIOL-CORE-READERENTRY certifies (its note's condition); T13.5-12's during-hold stagings ride the seam choreography the CONF-CORE lock violators certify, its waits for the hold file among it (VIOL-CORE-LATEHOLD); and T13.5-10(g) admits either outcome by 13.5's MAY. T13.5-10(b)'s one unbraced staging, its symbolic links into foreign directories — a removal following one deletes what the target holds, and with the target empty the arm passes against that product — rides VIOL-LEFTOVER-FOLLOWLINK's certification of P-15 representatively, insofar as it shares that leftover-staging machinery, as T13.4-4's link arm rides VIOL-ORPHAN-LINKTARGET's. A conformer serving them whole would carry the section-form `move` of T13.5-10(h) and the TypeScript-marker rewriting of T13.5-12(a)'s code-source arm (6.5, 6.4, 4.5 — the P-5 argument above) and, for T13.4-12, `inventory`, `version`, and the preview documents of performable operations, the derived-file delta of 6.6 among them (P-8's scope argument). * **T6.1-1 and T13.4-5** (journal lifecycle; durable protection): T6.1-1 byte-compares the journal around every command surface — `occurrences`, `view`, `at`, `inventory`, `version`, and the previews of 6.6 among them — so a conformer passing it whole would serve all of 11 and 6.6 (P-8's scope argument), and T13.4-5's session-file arm stages a git baseline, a path-blocks session, an audit session's split, a coverage session over a profile, and a section-form `move`, so one passing it whole would carry the baseline, path-blocks, coverage, and section-move engines (the P-5, P-6, P-13, and P-16 argument above) — each outside every scope here. Their never-modified compares around `build` and the reads are the compare-around machinery VIOL-CORE-CHATTYREADS certifies over the same journal on T13.5-4, whose read set the scope constrains (its note's condition), and T13.4-5's session-file compares — around the reads, and around its `rename` and `move` — the session-file compare VIOL-CORE-PERSISTREADS certifies on T10.4-5, representative insofar as they share that machinery; there the compare alone discriminates, the reads T13.4-5 runs afterwards presenting the recorded nodes under their current identities alike for a product writing those identities into the session files. T6.1-1's lifecycle negative — no journal after `build` in a fresh workspace — is braced in-test by the positive at the same path (the file appears at `.xspec/journal` with the first `rename`/`move`), so a mislocated absence check fails loud rather than passing silently, and T13.4-5's never-regenerated negative — a deleted session file not recreated — by the review naming it exiting 2 as an unknown session. +* **T7-9 and T7-10** (the configuration's import; the configuration file as a source): their operative assertions are positive — each spelling and designation of T7-9(a) and (c), and each baseline configuration of T7-10(d), answering exactly as its `"xspec"` twin, exit codes, documents, generated files, and decoded impact and review items compared; T7-9(b)'s scanner-rejected escapes, S-9 verifying them unparseable under both readings, and T7-10(d)'s baseline spelling one, each reported in its stated error document; and T7-10's findings for the discovered configuration — 14.15 at its import declaration, 14.18 at its call, 14.16 at its export statement, and 14.19 concerning it — its gated reads, its refused `move`, and its failing baselines, each beside its undiscovered twin's clean outcome — each failing loud against the product it targets; the converse arm's unrewritten import is braced by its discovered twin's refusal over the same import, and the modifies-nothing compares share the compare-around machinery VIOL-CORE-CHATTYREADS certifies (its note's condition). Their stagings against a read on the specifier's account are verified or braced in-test as to their effect where the harness places them: T7-9(c)'s permission stagings are verified on the harness itself (E-1, T14-10's discipline), and every FIFO — at a designated path, as a package's manifest in T7-9(d), at a working-tree path in T7-10(d) — is asserted afterwards still a FIFO in place (S-3), so a staging whose effect misses — no FIFO made, or a read the environment still permits — fails loud. No assertion braces their placement — at the path the specifier designates or, for an installed package, where resolving `N` from the configuration file's directory looks: a FIFO, a refused file, or a package placed anywhere else is met by no product, conforming or not, and its arm then passes the very products its staging targets. The trap package of T7-9(d), staged again in T7-10(d), is moreover the one staging there whose effect no assertion braces — a product loading the import behind a silent fallback passes the trap arm wherever the trap's entry never runs — but T7-9(d)'s FIFO-manifest arm, under the same three names, catches that product loud wherever its loading reads the installed package's manifest before its entry, as Node.js's resolution does, the FIFO blocking the read until its guard trips (S-3), a catch resting on the same placement; a loader that never opens a manifest other than a plain file, or that loads a baseline's import alone, meets the trap alone — residuals, the placements' and the trap's, this document accepts, since a conformer serving T7-9 whole would carry `view`, `review list`, and `rename` beside `build`, `check`, `ids`, and `inventory`, 14.20's rejecting side over the configuration file — (b)'s four scanner-rejected escapes, each a configuration error (14.14) — and a package directory whose manifest gives (d)'s third name, for that one staging. T7-9(a)'s escape-spelled arms — its hexadecimal escape and its line continuation — target the products P-19 searches for, readers refusing a specifier whose spelling is not its value, and a staging that decoded either leaves the arm equal to its twin, passing every product (one dropping the continuation's `\` alone leaves the literal unterminated, which S-9 rejects); its single-quoted `'xspec'` and its raw U+FFFD share that hazard — a formatter or printer normalizing quotes stages the first as exactly its twin's `"xspec"`, the arm then passing every product, one reading double-quoted specifiers alone included, and a printer spelling non-ASCII as escapes stages the second with no U+FFFD among its characters, the arm then passing the very product it targets, one applying 7's U+FFFD bar to every literal as spelled (2.4). These four ride CONF-IMPORT's certification representatively, insofar as they share the machinery that brings P-19's draws — either quote style and raw non-ASCII code points among them — to the product as spelled: decoding, and a printer serializing a literal's value or handed its spelling, leave no braced escape of a code point at or below U+FFFF, a corruption VIOL-IMPORT-BRACED catches, and a formatter normalizing quotes re-spells the single-quoted form, one VIOL-IMPORT-SINGLE catches, while a step confined to the other forms — raw non-ASCII spelled as escapes while every escape survives, say — goes unreached, the residual CONF-IMPORT's justification accepts. And (a)'s `"XSPEC"` is a single-casing arm asserting its twin's answers, positive. A conformer serving T7-10 whole would carry git baselines with `impact` and `review create` and `status` over them, the file-form `move` with 6.5's destination refusals and its preview, and the gated reads (the P-5 and P-6 argument above). * **Section 4 consumer-side and type-level tests**: their vacuous-pass hazard lives in the TypeScript tooling driver, which S-4 self-tests, in each configuration H-2 fixes, against known non-xspec fixtures, each configuration's module settings detected in effect; a conformer would need the full generated-module contract (skeleton, branding, documentation, navigation). The TypeScript-side occurrence and range enumerations (T1.7-2, T5.7-1 through T5.7-4, T11.3-1) sit behind the same wall — a conformer serving them carries the full 4.5/4.6 unit analysis — and their byte-precise enumerations against precomputed expectations fail loud, the record form they decode certified through the CONF-AVAIL datum-form violators; T1.4-5's access arms are positive — `build` and `check` clean, each edge reported, the consumer compile of the dot and quoted spellings, at TypeScript 5.9.3 under both of H-2's configurations, riding the same driver — so a product rejecting or misquoting a spelling fails loud. T6.5-9's and T6.5-18's compile-clean observations ride the same driver — S-4 checks each diagnostic kind's detection directly, the import-conflicts-with-local-declaration and duplicate-identifier kinds T6.5-9's module-scope value-level lures turn on among them — and no lure rests on the compile alone: those module-scope lures root the rewritten markers at nothing against a product taking one, so the `references` edges asserted beside the compile are absent and `check` reports 14.15 beside 14.7 where the test asserts it clean, while its parameter run's lures, shadowing the added binding at the moved markers in `f` rather than colliding with it (4.5), root those markers at the parameter against a product taking one, the asserted `references` edges absent behind a clean `check`; its `type`-alias lure, colliding with nothing to xspec (4.5) and caught by the compile only where the generated default export has a type meaning, is T6.5-22(a)'s name check's for every product (above); and its spec-source arm's freshness clauses — the compiler-provided names and one identifier bound twice — are 14.15's, `check` clean asserted beside the positive `view` listing of two distinct `name`s and the contiguous block's bytes (T6.5-13(g)); T4-4's type-only arms and T4.5-4's callee-side and `using`-shadowing arms pair each no-edge negative with an in-test positive control (the ordinary-binding statements recording their edges, and the mixed combination's condition-18 finding; the condition-18 finding, and the `embeds` occurrence or the chain's edge recorded outside the shadowing scope), so a product resolving by name fails the paired positive rather than passing silently; T4.5-8's same-scope collisions pair each no-edge negative with the condition-15 and condition-7 findings asserted beside it and with type-level controls whose edges are recorded, its type-only side's no-finding arms standing beside the value-level arms that report 14.15 over the same declarations; T4-5's import collisions, type-only or not, and T4.5-9's calls through a colliding `text` identifier pair theirs the same way — the condition-15 finding locating both declarations beside condition 7 or condition 18 at the chain, the `type text = number` control recording its edge — as does T4.4-1's finding contract, its condition-7-alone and condition-8-alone arms braced by the condition asserted, its `identities` a form-exact literal (`["specs/B.mdx"]`; `[]` over the invalid path), and the call's occurrence beside the finding decoded through the CONF-AVAIL-certified record form; T4-6, T4.5-10, and T4.5-11, compiling nothing (T4.5-10), sit behind the 4.5/4.6 wall above and brace their negatives in-test likewise: T4.5-11's collisions in a nested import's own scope assert beside each absence the condition-15 finding locating every colliding declaration — with condition 7 or condition 18 at the spelling, or with the exact record set of the chains and calls each import still roots — its shadowing contrasts recording in the same file the edge of a chain the import roots beside each chain a declaration roots, or asserting the file's exact edge and record sets, and its type-only side standing beside its value-level parameter arm, which reports 14.15 over the same parameter and the import's value-level twin; T4.5-10's visibility-boundary negatives — a chain spelled where a nested import's scope does not reach, or in a file other than the import's, recording no edge, no occurrence, and no finding — pair each with the same test's chain inside that kind of container recording its edge, the bare-block script among them across the file boundary, on workspaces whose asserted exit 0 holds every staged specifier to a discovered source (14.15); and their other arms, like T4-6's, assert recorded edges and exact record sets, located 14.15 and 14.18 findings, or an exit 0 beside each absence, each failing loud against the product it targets; T4-2's side-effect-only arm is a positive validity assertion (exit 0) on a form binding nothing, its specifier held to the rule by two asserted 14.15 arms, and its spellings naming no module — `require` calls, a triple-slash directive, a plain string, template-literal `import()` calls — pair their no-finding, no-edge negatives with the marker's edge listed beside them and the file move's one specifier rewrite; and the constructor, decorator, declaration-file, and legacy-`module` arms of T4.6-1, T4.6-3, and T1.7-2 are positive attributions and precomputed ranges, T4.6-3's controls — `x.dts.ts` and its kin, the single-casing ones among them — keeping `path#f` beside the declaration files losing it; and T2.4-5's verbatim-literal negatives assert their 14.5–14.7 findings present beside an escape-free control recording its edge, their discriminating half — the consumer type-checking clean against the generated module — riding the same S-4 channel. +* **The `defineConfig` module's tests (T7.6-1 through T7.6-7, P-17, P-18)**: their vacuous-pass hazards lie, but for the composition residual below, in two drivers, which TEST-SPEC.md self-tests directly before any product exists, kind by kind, where certification would reach only the kinds a selective set of violators targets (S-4, S-10): the TypeScript driver — S-4 detecting each setting of 7.6's covered setups in effect through stand-ins the setting decides, the verdict's reach into declaration diagnostics, and T7.6-1's export listing's sight of an interface declared without `export` and of an export assignment's members — and the Node.js release driver with the runtime observations — S-10 confirming each provisioned release and each route the one exercised, a check certification cannot make at all, every fixture's module answering alike on every release and route, and each of T7.6-6's and T7.6-7's observations catching a stand-in that exhibits its effect. 7.6's pairing rule braces each negative in-test: a shape-violation verdict counts only where its valid twin type-checks in the same setup and placement, so a program failing for a cause it shares with its twin — an unresolved specifier, a missing or misplaced package, a setting not in effect — fails the arm loud, and each absence T7.6-6 and T7.6-7 assert counts only where the same run loaded the module and saw `defineConfig` return its argument, T7.6-7's FIFOs asserted afterwards still FIFOs in place (S-3). What the pairing leaves lies inside the preamble's elevated class, a negative arm whose staging silently misses the behavior under test: an edit (T7.6-3) or mutant (P-18) carrying, beside its violation, an error every `defineConfig` type meets — a repeated key, say, which TypeScript reports only after parsing, so that S-9, judging well-formedness alone (14.20), passes the file — fails to type-check against a permissive `defineConfig` exactly as against a conforming one, its valid twin type-checking still. The hazard lies in the harness's own composition of edits TEST-SPEC.md spells out in plain ASCII (`specs: ["a/*.mdx"]`, `emit: "true"`, `"Direct"`, `"contains"`), not in bytes tooling normalizes, the hazard CONF-VALID certifies, and the document accepts it as a residual: C-1 judges whole tests, so a violator permissive in the type-error class — the pairing rule's `any`-typed `defineConfig` — fails T7.6-3 and P-18 wherever any one of their arms or mutants is composed right, certifying only that one is, while certifying each arm's composition would take a violator per arm, permissive at that arm's violation class, member, and position alone — completeness — beside a conformer serving the module channel, 7.6's type contract whole, which no scope here carries. Their remaining assertions are positive — one declared export, each valid file type-checking, each placement and open case faring as the canonical one, `defineConfig` returning its argument by SameValue — and fail loud against the product they target; and P-17's and P-18's draws reach no class without a deterministic anchor whose failure is loud — names, placement forms, holding directories, setups, releases, and routes by T7.6-4 and T7.6-6; aliased bindings, string-literal keys, comments, the `Object` members and `__proto__` as names, the empty, omitted, and repeated forms, and each violation class at each position by T7.6-2 and T7.6-3 — beyond combinations of those and what TypeScript's typing of the argument does not observe, key order among it. No scope here therefore serves the module channel. * **T10.1-4 session-corruption arms, T10.1-6, T10.7-15, and the precedence pairs**: the per-arm precision hazard of T10.1-4 is real, but its recorded-creation-parameters arm requires a baseline or coverage session and its decomposed-item arm a path-blocks session's file, dragging git or coverage machinery into an otherwise lean scope. T10.1-6's occupancy arms are positive outcomes — condition 22 concerning `.xspec/reviews` or `.xspec`, condition 23 for the area, the unknown-session usage error where no session directory exists — beside no-write compares on the compare-around machinery, as is its mutating-command arm, each mutating command failing at acquisition first with the error document's `write-failure` concerning `.xspec` (T13.5-10(a)). Its `create` ordering arms and T10.7-15's stale-stays-stale arms are absence-of-effect assertions — graph data byte-identical around a subcommand an outcome ends — each braced in-test by `check` afterwards still reporting the graph-data unit form beside the edited source's per-file staleness, which a product refreshing first leaves unreported; T10.7-15's other arms assert positive outcomes where the wrong product's differs — a refusal, the condition-21 finding, the gate's findings, a usage error, or a refreshed record — its refusal arms under T14-9's and T14-10's stagings, verified on the harness itself (E-1). T10.1-5's and T12.0-10's gate-precedence pairs carry their own discriminating contrasts in-test (the `check`-vs-subcommand and valid-twin comparisons), and T12.0-14's grammar arms each pair the refused spelling with the accepted one on the same fixture (`ids --config --json` against `ids --json --config`, `ids --` against `ids`, `--name -a` creating the session `-a`), a lenient parser failing the pair. * **The review-operation refusal negatives (T10.3-2's re-block refusal; T10.7-9/10's refused `split` and `resolve`)**: refusals of 10.7 carry no stable code (14), so a wrong-reason refusal is in-test indistinguishable for any product and the error-identity representatives reach none of them; what discriminates instead is asserted beside each refusal — the same test flips one condition and the same subcommand succeeds (T10.3-2's dependent resolves once its blocker is re-resolved; T10.7-9 asserts the successful split beside its other-kind and childless-root refusals; T10.7-10 asserts `resolve` succeeding on any unblocked item beside its refused blocked one) — so a wrong-reason refusal fails its paired positive arm rather than passing silently, and a violator would carry the blocking, decomposition, and re-derivation machinery those tests assert around the refusals for one exit-code assertion already braced in-test. * **Previews and the unreadable-record cluster (T6.6-2 through T6.6-6, T6.5-7; 14.23 at T12.2-2, T13.3-2, T11.6-4)**: T6.6-2's modifies-nothing compare shares the compare-around machinery certified via VIOL-CORE-CHATTYREADS (its note's condition), and T6.6-3's runs-while-held arm shares the drive-during-hold choreography certified via the CONF-CORE lock violators (T13.5-2's refused second command and T13.5-4's concurrent reads and `build` are the same staging, the wait for `build`'s exit while the hold stands certified via VIOL-CORE-BUILDWAIT), and its acquisition arms pair each preview's answer — byte-identical to the unobstructed twin's, or the invalid-workspace refusal of 6.4 with T10.1-6's finding — with the real operation's acquisition error on the same staging, positive both, a staged leftover's survival beside them asserted by its kind and content (its lock-path inclusion that of VIOL-CORE-READERENTRY's note); T6.6-4 and T6.5-7 are positive edits byte-asserted against precomputed offsets and independently composed expected files (loud) — T6.6-4(b)'s `import-addition` admitting whichever of the two pre-operation offsets 6.5 admits where a collapsed origin deletion or import removal makes one composed position (both in T6.5-13(i)/(k), T6.5-11(a)/(b), and T6.5-18; the end alone in T6.5-23(h) through (j)), a latitude the byte contract closes, and its coincidence arms counting the zero-length entries the tie-break cannot order; T6.6-3's refusal equivalence over T6.5-16's, T6.5-17's, T6.5-20's, T6.5-21's, and T14-7's shapes is a positive same-findings compare against the operation's own report; and the shape-blind 14.23 stagings are self-controlled — each state's reachability is positively asserted in-test or by its sibling on the same staging (the condition-23 finding's presence, `inventory`'s recorded-unavailable report, `check`'s unit-form finding), so a staging accident fails loud rather than passing silently. * **`inventory` and `version` (T11.6-1 through T11.6-4, T12.6-1/2)**: the anchoring, resolved-configuration, derived-map, occupancy, and listing arms are positive and byte-asserted, the `lock` member among them — `".xspec/lock"` exactly, from every working directory, whatever occupies the lock path and while a command is held (T11.6-1, T11.6-3); T11.6-4's no-parse/no-write negatives ride the certified compare-around machinery, and every broken state it must ignore is positively reported from the same staging by its home reporter (T13.3-3, T10.1-4, T12.2-2); T12.6-2 carries its own discriminating pair — `build` exits 2 on the very fixture `version` must answer from. * **The 12.7 form sweeps and the code contracts (T12.7-1 through T12.7-3, T14-6, T14-7, T14-8, T14-11; the performed-operation form at T6.4-1, T6.5-1, T6.6-2)**: 12.7's value forms are universal (H-3) — asserted literally on the pinned document forms and, through the value-blind H-3 decode, on the unpinned surfaces T12.7-1 sweeps (`query` rows, `show --json`, the review payloads) — so the decode rigor the sweeps depend on is certified representatively through the CONF-AVAIL datum-form violators, where the marker and the stated `null` are densest: the two states a defaulting decoder collapses. A range carried as `[start, end]` or `{"from", "to"}` has no such collapse to hide behind — it fails the literal `{"start", "end"}` assertion unless an adapter re-maps it, the harness discipline H-3 forbids and S-5's wrong-shape feed probes — and staging a fixture per surface and per condition would be completeness. The stable-code, refusal-reason, location-cardinality, and per-condition range assertions (T6.4-3's two-bearer collision arm, T14-11's precomputed offsets, T14-7's `identities` over invalid destination paths — plain-string literals over the path as spelled, `["specs/new.txt#x y"]`, form-exact — and its `refused-cycle` and `refused-invalid-rewrite` location sets, computed as the spellings rooted at an added binding whether or not a `reference-rewrite` would report them, among them) are positive identity checks that fail loud when a staged condition does not fire — the finding is then absent altogether, and the assertion with it — or fires at another range; and the performed-operation document is a form-exact literal (`{"findings", "mapping"}`, its `mapping` byte-equal to the preview's), failing loud under any other member set. * **The well-formedness contract and the brace-content classes (T14-12; the 14.20 and 14.16 arms of T2.3-3, T2.7-1, T2.7-3, T2.7-4, and T2.4-2; T14-3's `d={]}`; T14-11's `d={}`, parenthesized, comma-sequence, spread, elision, and encoding-offset arms; T1.6-5's offset; T2.1-3's and T4.5-8's one-block arms; T5.7-2's token-bound and line-comment arms)**: every arm asserts either a condition's identity by its stable code at a precomputed byte offset — 14.20's zero-length range where the text does not derive, the ordinary finding (14.15, 14.16, 14.17, 14.8) or the recorded occurrence's span where it does — or, for T14-12's release, language-level, code-source-whitespace, and post-parse pins, a well-formed file's clean `build` and `check` with its marker's edge recorded: a positive check that fails loud against a product handing an ESM block to a parser enforcing early errors (14.20 reported where 14.15 or 14.16 is asserted), scanning a container or an attribute value to its first `}`, or bounding tokens by ASCII whitespace alone (the asserted range absent or elsewhere), or parsing at another TypeScript release, language level, or Unicode version, or a code source by ECMAScript's lexical grammar or under TypeScript's post-parse grammar checks (a well-formed file masked as 14.20, or U+1C89 admitted where 14.20 is asserted); the absences asserted beside them — no 14.20 beside the 14.15 or 14.16 finding, no second finding for an attribute value expression, no edge and no occurrence beside a 14.16 — are braced by the finding asserted on the same staging. Their exotic bytes (U+0085, U+200B, U+180E, U+00A0, U+FEFF, U+2028, U+2029, Unicode 15.1's other space separators — U+1680, U+2000 through U+200A, U+202F, U+205F, U+3000 — U+2EBF0, U+1C89, the ill-formed UTF-8 sequences) are the hazard class CONF-VALID and CONF-MD certify, but every such negative arm is pinned by byte offsets: a byte tooling normalizes changes the file's byte length and every precomputed offset past it, so a corrupted staging fails loud against a conforming product rather than passing vacuously — T2.7-4's carriage-return twin, the one arm a normalization (U+000D to U+000A) would leave at the same byte length, rides the lone-CR staging VIOL-MD-CR certifies on T3-4 and P-2 through the same builder — and the positive arms holding them, T14-12's well-formed pins among them, rest on the builder's fidelity to declared bytes, S-2's round-trip to gate. The positive comment and embedding forms of T2.7-4 and T2.3-3, and T3-7's ESM-block comments, are among the classes P-2 composes: CONF-MD admits them in scope, so the conformer passes P-2 only by classifying them as 14.20 does, and a product misclassifying one fails the byte-asserted emission of the form's deterministic twin loud — so no violator deviating on comment or embedding classification is staged, and the twins themselves stay outside CONF-MD's read surface (T3-7 and T2.7-4 assert `view`'s `comments`, and T3-7 its `imports`; T2.3-3 and T2.7-4 carry the negative arms above). -* **The single-casing probes and the Windows leg (the casing arms of T7-1, T7-4, T10.1-2, T10.1-3, T12.0-6; E-6)**: their discrimination is the Windows leg's to carry by design — on Linux the masking is by construction — and the non-discovery and exit-2 wiring they ride is certified via VIOL-DISC-DIALECT and the error-identity representatives, T7-1's a positive outcome (the root's configuration loaded, `build` and `check` exit 0); a case-folding fixture would re-prove that wiring on another rule. The suffix and name tests T12.0-6 enumerates beside them, each probed in a single casing on the Linux leg (T2.1-2, T4-2, T4.6-3, T6.5-4, T7-2, T7-6, T7.1-1, T7.3-1, T14-5), are no filesystem's to mask — a product folding case there folds it in its own comparison, on either leg — and each arm asserts a positive outcome (a finding, a refusal, a discovered source, a kept attribution, a clean `build`) or, at T4-2's import declaration, a no-edge negative over plain ASCII bytes no tooling rewrites; T7-6's arms ride CONF-DISC's scope as positive discovery assertions. E-6's representative fixture is a product-to-itself byte compare across the two legs (H-4) — its specifier-computation, inserted-terminator, and exclusion probes included, the last a busy refusal's error document and a dead run's takeover on each leg — positive and loud on the leg that exposes a native-separator, native-terminator, or native-process-list product, no harness oracle standing between. +* **The single-casing probes and the Windows leg (the casing arms of T7-1, T7-4, T10.1-2, T10.1-3, T12.0-6; E-6)**: their discrimination is the Windows leg's to carry by design — on Linux the masking is by construction — and the non-discovery and exit-2 wiring they ride is certified via VIOL-DISC-DIALECT and the error-identity representatives, T7-1's a positive outcome (the root's configuration loaded, `build` and `check` exit 0); a case-folding fixture would re-prove that wiring on another rule. The suffix and name tests T12.0-6 enumerates beside them, each probed in a single casing on the Linux leg (T2.1-2, T4-2, T4.6-3, T6.5-4, T7-6, T7.1-1, T7.3-1, T14-5), are no filesystem's to mask — a product folding case there folds it in its own comparison, on either leg — and each arm asserts a positive outcome (a finding, a refusal, a discovered source, a kept attribution, a clean `build`) or, at T4-2's import declaration, a no-edge negative over plain ASCII bytes no tooling rewrites; T7-6's arms ride CONF-DISC's scope as positive discovery assertions. E-6's representative fixture is a product-to-itself byte compare across the two legs (H-4) — its specifier-computation, inserted-terminator, and exclusion probes included, the last a busy refusal's error document and a dead run's takeover on each leg — positive and loud on the leg that exposes a native-separator, native-terminator, or native-process-list product, no harness oracle standing between. * **The remaining negative matrices and refusals (2.1 import negatives — T2.1-2's lexical-resolution and above-root arms included, 2.4 — T2.4-5's MDX arms, 2.7, 4.x imports and markers, 5.3 cycles, 6.1 journal integrity — T6.1-3, 6.3 baseline failures — T6.3-5's exit-2 arms beside its positive repository-resolution arms, and T6.3-6's, each asserting its error's code (`journal-error`, or `null` for git data), 6.4/6.5 refusals — T6.5-6's refused self-move with its journal compare, T6.5-16's `refused-invalid-rewrite` shapes, each standing beside a movable control, its would-be text not well-formed (verified underivable by S-9 independently of the product) or holding no admissible offset for an addition it needs, T6.5-17's `refused-moved-import` arms beside their positive counterpart, T6.4-3's and T6.5-4's barred-character arms, and T6.5-20's and T6.5-21's destination reasons beside their performed controls and exemptions included, their findings positive form-exact checks — the stable code, the located construct and rooted spellings or import ranges, `identities` in byte order or exactly `[]` — absent altogether against a product performing the move, and their applicability arms (`refused-invalid-rewrite` withheld under an intrinsically invalid `<new-id>`, which `refused-invalid-id` then reports alone, while `refused-moved-import`, carrying no such qualifier, reports beside it; the target's text judged only where an insertion point exists) the masking structure this bullet closes on, 7.x configuration validation — T7-1's occupancy, T7-2's verbatim, encoding, repeated-key, and import-modifier, T7-3's U+FFFD, and T7.1-1's path-character arms — the last beside its valid code-source control — included, and T7.3-1's graph-data-area arms beside their look-alike controls and its classification arms (an enabled emit destination matched by a spec glob undiscovered, whether or not emission has yet run: the non-discovery class CONF-DISC certifies at its sharpest on T7-6's destination arm, braced here in-test by the emission-off twin under which the same would-be destination is discovered, 7.3, so a glob that never reaches the path fails the twin loud rather than passing the negative silently), 10.1 session-name and non-session negatives, 12.0 usage errors — T12.0-5's malformed-value positions, T12.0-10's barred-character arms, and T12.0-14's grammar arms, the argument, spelling, and domain-and-exit matrices of the machine-interface surfaces — T11-2's syntactic `--tag` acceptance, T11.2-5, T11.3-2/3, T11.4-2, T11.5-2, T12.0-13, and T11-6's unknown-unit and `@N` arms and its forbidden-name unit arms (positive answers with the unit's edges, exit 0), their answer-side decode rigor the CONF-AVAIL-certified machinery and their exit assertions S-3's — T11.4-5's consultation-domain negatives, the 13.4 symlink write refusals and their byte-compares — T13.4-6, and T6.5-4's symbolic-link component arms, whose link-and-target byte-compares are braced by the refusal's stable code and exit 1, which a product writing through the link fails first — the derived-path relations of 13.4 and 14.22 — T13.4-9 and T13.4-10, one condition-22 finding asserted per offending path beside the workspace byte-compare, and the source relations of T13.4-9(d) and T6.5-20(c), whose miss deletes a source behind a reported success, asserting the refusal positively, so that a staging missing the relation fails against a conforming product, which then builds or moves where the refusal is asserted (T13.4-4: a directory holding nothing discovered is replaced) — the 14.19/14.20 path and encoding negatives — T1.5-2, T1.6-5, and T11.2-3, whose byte-level staging is exactly what S-2's builder round-trip self-tests, and the masking, confinement, and reporter-matrix contracts of 14 — T14-3, T14-4, and T12.2-4's no-condition-10-or-12 negatives, each beside the validation finding and the positive recorded-file form asserted on the same stagings)** and the remaining absence-of-effect sweeps (T12.0-11, T12.1-4, T12.2-3, T13.3-3, the answer-side no-write compares of T11.2-1/T11.2-6, and T11.2-6's finding-free answer beside `build`'s condition-22 report of the same obstruction): they share the double-invalidity, error-identity and masking, and compare-around structures certified representatively through CONF-VALID, VIOL-CORE-CHATTYREADS, and the CONF-AVAIL datum-form violators — representative insofar as those tests share the certified machinery (the VIOL-CORE-CHATTYREADS note's condition); certifying each would be completeness, which this document must not pursue. * **T13.4-4's link arm** (a symbolic link at a derived file's own path replaced as the occupant, nothing written through it): none of the arm's assertions braces its link — with the link missing, `build` writes a plain file at the path for a product writing through a link exactly as for a conforming one, so against both the link is gone, a plain file is present, no error is reported, and the target is unchanged on both sides of its before-and-after compare. That link is T13.4-11(c)'s staging, though — a symbolic link to a file replacing the occupant at a derived file's path, its target compared before and after — which VIOL-ORPHAN-LINKTARGET certifies, a harness whose link staging misses failing that certification; the arm rides it representatively, insofar as it shares that staging machinery (the violator's note), and a violator writing through the link would re-prove the same staging, which would be completeness. diff --git a/specs/DEVOPS.md b/specs/DEVOPS.md index db21bad6..ffa6f2d6 100644 --- a/specs/DEVOPS.md +++ b/specs/DEVOPS.md @@ -14,21 +14,22 @@ This document defines how release, merge, and deploy actions are performed for t The normal Release-phase flow for a completed patch is: -1. **Release commit.** One ordinary commit on the patch branch, pushed before the merge, that removes retired plans (Release-phase guidance → Release-commit cleanup), sets the version when the release warrants a minor bump (→ Versioning), drops any temporary CI trigger the branch was given (such as a `push:` entry used while its PR was conflicted — pull-request runs take over once the PR is mergeable), carries the `docs/` and `README.md` updates for the patch's user-visible changes (→ Docs) so the docs land on `main` together with the change, carries any DEVOPS.md update the release needed, and flips the patch's `Stage:` to `Complete`. +1. **Release commit.** One ordinary commit on the patch branch, pushed before the merge, that removes retired plans (Release-phase guidance → Release-commit cleanup), sets the version when the release warrants a minor bump (→ Versioning), drops any temporary CI trigger the branch was given (such as a `push:` entry used while its PR was conflicted — pull-request runs take over once the PR is mergeable), carries the `docs/` and `README.md` updates for the patch's user-visible changes (→ Docs) so the docs land on `main` together with the change, carries the corrections and lessons the run held for the release step (→ Held corrections and lessons), carries any DEVOPS.md update the release needed, and flips the patch's `Stage:` to `Complete`. 2. **Merge** the PR with a merge commit once CI is green on the PR's latest head (never with red CI; never squash or rebase). -3. **After the merge lands:** open the parked-work issue (→ Parked work), post the run notes on the merged PR (→ Run notes), and delete the merged branch and any stale process branches (→ Branches). -4. **Follow the release.** The standing npm release procedure below publishes the merge commit automatically; follow `main`'s CI and Release runs until the version is published and tagged. There is no other per-release tagging, publishing, or Developer step. +3. **After the merge lands:** add the release's parked work to the parked-work issue (→ Parked work), post the run notes on the merged PR (→ Run notes), and name in the release report the merged branch and any stale process branches, for the Developer to delete (→ Branches). +4. **Follow the release.** The standing npm release procedure below publishes the merge commit automatically; follow `main`'s CI and Release runs until the version is published and tagged. There is no other per-release tagging or publishing step, and no Developer step but deleting the branches the release report names (→ Branches). ## Release-phase guidance (standing; Developer, 2026-10-28) -Recorded at IP 0001's release (PR #7) so that these situations are not asked again. +Recorded at IP 0001's release (PR #7), and extended at IP 0002's release (PR #9), so that these situations are not asked again. - **Scaffold drift on main.** When a PR conflicts because `main` carries a newer process scaffold than the branch was cut from (agents and prompts, `CLAUDE.md`, `specs/PROCESS.md`, `specs/CLAUDE-PROCESS.md`, template resets of `specs/GOALS.md` or `specs/PHILOSOPHY.md`), the Developer decides how the PR lands: ask first. Precedent: for PR #7 against main's `63bcb3f`, the Developer chose to take main's version as it is. The one conflicting file, `specs/PHILOSOPHY.md`, was made byte-identical to main's on the branch by its owner, Liaison, so the PR merged cleanly with no merge from `main` into the branch, and main's other changes (the newer scaffold, the removal of `sdg-bootstrap/SKILL.md`, and the empty `GOALS.md`, which the Developer explicitly approved) landed unchanged. -- **Versioning.** A release that adds commands or changes existing behavior bumps the minor version: the release commit sets `package.json`'s version to the next minor version (patch component 0), keeping `package-lock.json` consistent. Any other release, a docs-only follow-up included, takes the automatic patch bump (npm releases → Versioning). Precedent: IP 0001, which added commands, released as `0.2.0`. +- **Versioning.** A release that adds commands or changes existing behavior bumps the minor version: the release commit sets `package.json`'s version to the next minor version (patch component 0), keeping `package-lock.json` consistent. Any other release, a docs-only follow-up included, takes the automatic patch bump (npm releases → Versioning). Precedents: IP 0001, which added commands, released as `0.2.0`; IP 0002, which changed existing behavior, set `0.3.0`. - **Release-commit cleanup.** Retired plans tracked under `deleted/` (finished `FIX_PLAN` files moved there when deleting them was refused) are removed with `git rm` in the release commit; git history keeps them. -- **Parked work.** Follow-up proposals and deferred known gaps (accepted residuals) are recorded at release in one GitHub issue on this repository: each drafted follow-up proposal as approved, and each deferred gap as documented, saying whether a follow-up is planned. A parked follow-up is not started and gets no patch file at release; it enters the process later through its normal intake. +- **Held corrections and lessons** (Liaison, 2026-10-31, at IP 0002's release). The release commit also carries the corrections the run held for the release step in technical documents, such as `specs/IMPLEMENTATION.md`, and the run's agent-facing lessons, recorded in `AGENTS.md`. +- **Parked work.** Follow-up proposals and deferred known gaps (accepted residuals) are recorded at release in one GitHub issue on this repository: each drafted follow-up proposal as approved, and each deferred gap as documented, saying whether a follow-up is planned. A parked follow-up is not started and gets no patch file at release; it enters the process later through its normal intake. Issue #8 is the parked-work issue, and each later release adds one comment to it rather than opening a new issue (Liaison, 2026-10-31, at IP 0002's release). - **Run notes.** The notes collected during the run for the release step (refusals and safety-rule slips, infrastructure incidents, points the specs leave unspecified, measured scale limits, stale documentation and leftovers) are posted as one comment on the merged PR when it merges. Nothing is scheduled from them unless the Developer says so. -- **Branches.** After the merge has landed, the merged patch branch and any stale process branches (fully contained in the merged line, nothing pending) are deleted. Branches the process did not create are never touched. +- **Branches.** After the merge has landed, the merged patch branch and any stale process branches (fully contained in the merged line, nothing pending) are to be deleted. Deleting a branch is a manual Developer step (Liaison, 2026-10-31, at IP 0002's release), because the session proxy refuses it ("Write access to this GitHub API path is not permitted through this proxy.", HTTP 403, at IP 0001's release). The release report names the branches to delete, and no session tries any other route. Branches the process did not create are never touched. - **Docs** (Developer instruction, 2026-10-28, superseding the earlier rule that documentation was the Developer's own work outside the release flow). Documentation is a standing part of every change: whenever a change alters what users see or do, `docs/` and `README.md` are updated alongside it. At release, the release commit carries those updates for the patch's changes (step 1 above), so the docs land on `main` together with the change. A follow-up for an already-merged patch is an ordinary commit pushed straight to `main` (→ Post-update actions). How the docs are written (Developer's clarification, 2026-10-28, given for IP 0001's follow-up): - They cover every user-visible change the patch made: new or changed commands, options, outputs, findings, error behavior, configuration keys, and limits. - `specs/SPEC.md` and the patch document are the authority, so the docs describe only what they specify. diff --git a/specs/IMPLEMENTATION.md b/specs/IMPLEMENTATION.md index 58de793d..2ea1d1dc 100644 --- a/specs/IMPLEMENTATION.md +++ b/specs/IMPLEMENTATION.md @@ -6,12 +6,12 @@ Technical choices for building xspec and its test harness. This document adds no ### Language and runtime -- TypeScript (current 5.x, `strict`), ES modules throughout, compiled with `tsc`. +- TypeScript (current 5.x, `strict`), compiled with `tsc`. ES modules throughout, except that the `defineConfig` module also has a CommonJS entry (`src/index.cts`, built to `dist/index.cjs`) beside its ES entry (`src/index.mts`, built to `dist/index.mjs`), because SPEC 7.6 requires it to load through `require`, with no option, on every Node.js 22 release. - Runs on Node.js, active LTS lines (currently 22/24); no APIs beyond the oldest supported LTS, no platform-specific code paths. ### Distribution -- One npm package, `xspec`, providing the `xspec` bin and the `defineConfig` export that `xspec.config.ts` imports. +- One npm package, `@modularcloud/xspec`, providing the `xspec` bin and the `defineConfig` export that `xspec.config.ts` imports. - The package is a build-time tool: generated modules and their companions are self-contained (SPEC 13.1) and consumer code never depends on `xspec` at runtime. ### Key libraries diff --git a/specs/PHILOSOPHY.md b/specs/PHILOSOPHY.md index 36a8601a..fbda4f7e 100644 --- a/specs/PHILOSOPHY.md +++ b/specs/PHILOSOPHY.md @@ -11,3 +11,8 @@ IMPORTANT: This file may only be edited and interpreted by Liaison. Only Liaison ## Product identity - The spec never ties the product to a literal package or distribution name. The name the product is published under (today the npm package `@modularcloud/xspec`) is a distribution detail, and users must be able to use the product under that name with a plain install: no aliasing, and no reason to install some other package that happens to share a short name. (Developer, 2026-10-28) + +## Residual gaps + +- When a narrow, low-impact gap turns up late in a run, in the product or in how the test harness checks it, finish the current work and accept the gap exactly as it is. Record it honestly and park it for a follow-up change through the normal process, rather than reopening finished phases to close it. Accepting a gap means no partial mitigation, workaround or tests for it in the current run. A gap that hurts behavior users rely on still goes to Developer. (Developer, 2026-10-22, on TypeScript being unable to report a type error for requirement paths named after members of `Object`: "this seems like a minor issue that doesn't hurt most use cases and id rather finish this feature than put in a fix", and "just accept the error as is and we will add the sentence to the spec and implement later through the official process".) + - Applied by Liaison on 2026-10-29 to two limits on how the harness checks IP 0002's promise that xspec never resolves the configuration's import: trap placement, and four fixed import spellings. Each could hide a product fault only together with a second, harness fault. The loud failure modes are still caught, and the randomized spelling test keeps the coverage. diff --git a/specs/SPEC.md b/specs/SPEC.md index a89ecf04..3af4c80d 100644 --- a/specs/SPEC.md +++ b/specs/SPEC.md @@ -4,7 +4,7 @@ xspec is a requirement-traceability tool for specifications written in MDX. An xspec source file is an MDX document in which requirement sections are marked with `<S>` or `<Spec>` tags. xspec compiles these documents into strongly typed TypeScript modules and optional pure Markdown output, and builds a project-wide dependency graph. The graph is used to validate references and structure, enforce dependency policy, measure coverage, analyze the impact of changes, manage staged review work, and answer ad-hoc queries. -The complete interface to xspec consists of: the `xspec` command-line executable, the `xspec.config.ts` project configuration, the source-file syntax, the generated TypeScript modules, and the files xspec writes to the workspace. Every behavior in this specification is observable through these surfaces. +The complete interface to xspec consists of: the `xspec` command-line executable, the `xspec.config.ts` project configuration, the `defineConfig` module (7.6), the source-file syntax, the generated TypeScript modules, and the files xspec writes to the workspace. Every behavior in this specification is observable through these surfaces. xspec performs no network access. xspec reads git data only where explicitly stated and never performs git write operations. @@ -98,7 +98,7 @@ A code location is presented with its source range in exactly two outputs: occur ### 2.1 Imports -xspec source files import nothing from xspec; `<S>`, `<Spec>`, and `text` are provided by the compiler. The only imports permitted in an xspec source file are other spec modules: +In an xspec source file, `<S>`, `<Spec>`, and `text` are provided by the compiler, and the only imports permitted are other spec modules: ```mdx import BASE from "./BASE.xspec" @@ -376,7 +376,7 @@ Renames or moves performed by editing files directly, without the commands, prod xspec projects are configured by `xspec.config.ts`, a TypeScript module whose default export is produced by `defineConfig`: ```ts -import { defineConfig } from "xspec" +import { defineConfig } from "<installed-name>" export default defineConfig({ specs: { @@ -408,7 +408,11 @@ export default defineConfig({ }) ``` -The configuration is declarative — data, not executed code. The file MUST consist of exactly an import of `defineConfig` from the module specifier `"xspec"` (optionally aliased; no `type` or `defer` modifier and no import attributes) and a default export of one call to that binding, whose sole argument is statically literal: object literals with non-computed identifier or string-literal keys, array literals, static string literals (2.4), and the boolean literals `true` and `false` — no other statement or expression form, no spread, no computed value; comments are permitted anywhere and contribute nothing. The file's bytes MUST be valid UTF-8 and MUST NOT begin with a byte-order mark, as a source file's must (1.6). Configuration therefore cannot carry side effects, environment-dependent values (12.0), or network access; a configuration file that violates the encoding rule, is not well-formed TypeScript (14.20), or does not conform is a configuration error (14.14). +The example's `"<installed-name>"` stands for the name `N` under which the project installed the `defineConfig` module's package (7.6). + +The configuration is declarative — data, not executed code. The file MUST consist of exactly an import of `defineConfig` (optionally aliased; no `type` or `defer` modifier and no import attributes) whose module specifier is any static string literal (2.4), and a default export of one call to that binding, whose sole argument is statically literal: object literals with non-computed identifier or string-literal keys, array literals, static string literals (2.4), and the boolean literals `true` and `false` — no other statement or expression form, no spread, no computed value; comments are permitted anywhere and contribute nothing. The file's bytes MUST be valid UTF-8 and MUST NOT begin with a byte-order mark, as a source file's must (1.6). Configuration therefore cannot carry side effects, environment-dependent values (12.0), or network access; a configuration file that violates the encoding rule, is not well-formed TypeScript (14.20), or does not conform is a configuration error (14.14). + +Wherever xspec reads a configuration, a baseline's (6.3) included, it never executes the file and never interprets, resolves, or loads its import's specifier, making no read and no network access on the specifier's account, and so reading it applies none of the rules 4 and 14.15 set for a TypeScript file's imports. A configuration's validity, and everything xspec derives from it as configuration, are independent of what, if anything, the specifier designates — nothing, an unreadable path, a workspace file (the configuration file itself included), or a network location alike — and of its spelling wherever that spelling leaves the file well-formed TypeScript (14.20): a bare or scoped package name, a relative or absolute path, a URL, and the empty string are accepted alike, in either quote style and with escape sequences, line continuations, or U+FFFD, while an escape TypeScript's scanner rejects, such as those of `"\x4"`, `"\u{110000}"`, `"\01"`, and `"\8"`, leaves the file not well-formed (14.20), a configuration error (14.14). No command's outcome therefore depends, through a configuration's import, on the `defineConfig` module or on whether a project installed it. The rules of 4 and 14.15 reach the configuration file only where a configured group discovers it: xspec then analyzes it as it does every source it discovers (2.1, 4), its import declaration included, with the consequences 6.3, 6.5, 12.1, 13.3, and 14.15 give any source, while the configuration itself stays valid. Every command except `version` (12.6), which loads no configuration, locates the configuration by upward search for `xspec.config.ts` from the working directory, or uses the path given by the global `--config <path>` option. The upward search stops at the nearest directory — the working directory itself first — holding an entry named `xspec.config.ts`, whatever occupies it. The configuration file is the occupant of the path so found or named, read only when it is a plain file: any other occupant — a directory, a symbolic link whatever it targets, or anything else — is missing or invalid configuration (14.14), never read through, and a plain file the environment refuses to read is invalid configuration too (14.14, 14.25). `specs` is required; `code`, `markdown`, `coverage`, and `policy` are optional — omitting one means no code groups, no Markdown emission, no coverage profiles, or no policy rules, respectively; an empty `coverage` or `policy` list is valid and equivalent to omitting the key. Unknown keys anywhere in the `defineConfig` argument — a top-level key, or a field of `markdown`, a profile, a rule, or a selector — are a configuration error (14.14). So are a key repeated within one object literal — an identifier key and a string-literal key spelling the same name included, whatever TypeScript's own diagnosis of the repetition — and an empty group, profile, or rule name (`""`). A group, profile, or rule name containing U+FFFD is a configuration error (14.14): no argument value carries the character (12.0), and configured names are named in arguments. All configured paths and globs resolve relative to the configuration file's directory, which is the workspace root. Glob matching, like every path comparison (12.0), is byte-wise: workspace-relative paths are matched as their UTF-8 bytes, and a discovered source file whose workspace-relative path is not valid UTF-8 or contains U+FFFD is invalid (14.19). Globs support exactly `*` (any possibly empty run of bytes within one path segment), `?` (one byte within a segment), and `**` (any number of whole segments, including none — with this meaning only as a whole pattern segment; elsewhere each `*` of a `**` is the single-segment wildcard); matching is case-sensitive; a path segment beginning with `.` is matched only by a pattern segment written with a leading `.`. A discovered file's workspace-relative path is the directory-entry names descending from the workspace root, joined with `/` (1.5), so it carries no `.`, `..`, or empty segment. Whether a glob lies outside the workspace root is decided by its spelling alone — here and for the `--file` patterns of 11 and 12.3: reading its `/`-separated segments in order from a depth of zero, a `..` segment lowers the depth by one; a `.` segment, an empty segment (a doubled or trailing `/`), and a `**` segment, which may match no segment at all, leave it unchanged; and every other segment raises it by one (a drive-qualified spelling is ordinary segments). A glob beginning with `/`, or whose depth ever falls below zero, is outside the root, a configuration error (14.14); every other glob is inside, its `.`, `..`, and empty segments matching nothing. Discovery never follows symbolic links: a symbolic link — to a file or to a directory, broken or not — is never a discovered source and is never traversed, so symlinked, cyclic, or workspace-external content never enters the discovered set. Discovery reads only what deciding that set takes: it lists a directory — the workspace root, or one reached from it through directories alone — exactly when some configured spec or code glob matches a path below it, paths under `.xspec/`, which 13.4 excludes, counting for none; and it examines the kind of exactly those entries of a listed directory whose paths such a glob matches or that it would list were they directories. So under `specs/**/*.mdx` alone neither a root-level `data/` nor a dot-directory below `specs/` is ever listed, readable or not (14.25). Discovery of source files is controlled exclusively by configuration; derived files are never discovered as sources (13.4); imports resolve references between files but never add files to the workspace (2.1). A group whose globs match no files is valid, as is a `specs` or `code` map with no groups: discovery simply yields fewer, possibly zero, sources. @@ -459,6 +463,59 @@ Semantics, evaluated over dependency edges of the rule's kinds: Violations are findings reported by `xspec check` — and only by `check`, and only on a workspace passing `build`'s validations: `build` does not evaluate policy, and a failing workspace defines no graph to constrain (12.1, 14.12) — with the rule name and the offending edge, and cause exit code 1. +### 7.6 The `defineConfig` module + +The `defineConfig` module is the module xspec provides for a configuration's import to name (7): it exports exactly one binding, `defineConfig` — no other value and no type (type contract and runtime, below). + +**Package and installation.** The module is distributed as a package: a directory whose root holds a `package.json` manifest, the form TypeScript's and Node.js's resolution of installed dependencies read. The module is the package's root entry, the one a specifier naming the package with no subpath designates; no other module of the package carries a contract, whether a specifier with a subpath designates it or a file of the package is imported by its path. These definitions concern the module alone: they make no claim about how the `xspec` executable is provided or run. + +* Installing the package under a name `N` places it, exactly as distributed, at `node_modules/N` in its holding directory, as the directory itself or as a symbolic link to it. The holding directory is the importing file's directory or one of its ancestors, read along the file's physical path, every symbolic link among its components resolved (as 11.6 reads anchoring), and is not itself named `node_modules`, a directory TypeScript's lookup and `require`'s skip. A copy, a symbolic-link install, and an aliased install — one whose `N` differs from the name the package's manifest gives — are therefore alike. +* `N` is `name` or `@scope/name`, where `scope` and `name` are each a non-empty run of lowercase ASCII letters, digits, `-`, `.`, and `_` beginning with a letter or digit, the whole at most 214 characters — except a name in the `@types` scope, which TypeScript reserves for declaration packages; a name in the `@typescript` scope whose `name` begins with `lib-`, the form under which TypeScript looks up replacements for its libraries (`@typescript/lib-es5`); and, for Node.js's resolution and the runtime contract on a given release, a name that release resolves to one of its own built-in modules (`fs`, `path`). +* Nothing else need be installed: the module needs no other package and no `@types` declarations, and nothing outside the package but TypeScript's own libraries and the runtime's built-ins. Installation is that placement alone, with no package-manager run, install-time step, or network access. + +**Reach.** No literal package or distribution name names the module, and no name is privileged. With the package installed under `N`, a module specifier spelling exactly `N` designates the module along TypeScript's one route, in every covered setup (below) — the covered file's import declaration, whatever module format TypeScript applies to that file — and along Node.js's routes, on every release and in every run the runtime contract covers (below): `import`, as a static import in an ES module or a dynamic `import()` in a module of either kind, and `require` in a CommonJS module. It does so wherever four conditions hold, each ruling out what those tools do before they reach the installed package — a resolution elsewhere or, for the last, a failure of Node.js's routes: + +* Nothing nearer. Write `S` for `N` cut before the first `.` of its last segment, or `N` itself where that segment has none (`a` for `a.js` and `a.b`), `D` for the name under which TypeScript looks up declarations for `N` (`@types/N`, or `@types/scope__name` for `@scope/name`), and `T` for `D` cut the same way. In the holding directory, no entry but the placement occupies a path beginning `node_modules/S.` — no `N.js` or `N.d.ts` and, for `N` `a.js`, no `a.ts` — and in every directory from the importing file's own up to, but excluding, the holding directory (none where the two coincide), no entry occupies `node_modules/N` or `node_modules/D`, or a path beginning `node_modules/S.` or `node_modules/T.`. +* No self-reference: no `package.json` in the importing file's directory or one of its ancestors gives a `name` that TypeScript or Node.js reads as `N` or as a leading part of it — a `name` that, each `\` read as `/`, is empty, or is `N` or `N`'s scope (`@scope` for `@scope/name`) with or without one trailing `/`. +* Physical naming: TypeScript is given the importing file by its physical path, and Node.js loads it by that path. +* Well-formed manifests: every `package.json` in the importing file's directory or one of its ancestors is a readable file holding, as UTF-8 with no byte-order mark, a JSON object that repeats no member name, whose `name` and `type` members, where present, are strings, and none of whose strings escapes a lone surrogate (`"\ud800"`). + +**Covered setups.** The type contract holds under TypeScript at release 5.9.3, the release 14.20 names, in each covered setup: the program below, under one of the two option sets that follow, for a covered file (below) that set covers. + +* Program: the configuration file is the one root file, Reach's conditions holding, and nothing else enters the program but TypeScript's libraries for the option set and what that file's import declaration brings in — files of any kind, and the libraries they reference, included. Neither an `@types` package TypeScript includes automatically nor a module it imports implicitly (`react/jsx-runtime` under `jsx` `react-jsx`) adds anything else. Every library in the program is TypeScript's own, as its release ships it, none replaced by an installed package (`@typescript/lib-es2015`). Other packages, `typescript` among them, may be installed. The project may be an ES-module or a CommonJS one: ES-module when the `package.json` nearest the configuration file — in its directory, or else in the nearest ancestor holding one — holds an object whose `type` member is `"module"`, and CommonJS otherwise, a project with no `package.json` included. +* Strict defaults, covering every covered file: `strict` on; `moduleResolution` one of `node10`, `node16`, `nodenext`, and `bundler`, the modes that find installed packages; `module` at its default under `node10` and, under the other modes, at a value the mode requires — `node16`, `node18`, `node20`, or `nodenext` under `node16` and `nodenext`, and `es2015`, `es2020`, `es2022`, `esnext`, or `preserve` under `bundler`. Every other option is at its default, so `skipLibCheck` is off and the package's own declaration files count. +* Initialized-project options, covering each covered file TypeScript compiles as an ES module (a name ending in `.mts`, or in `.ts` or `.tsx` in an ES-module project): exactly the option set release 5.9.3's `tsc --init` writes — `module` `nodenext`, `target` `esnext`, `types` `[]`, `jsx` `react-jsx`, `moduleDetection` `force`, and these ten on: `strict`, `declaration`, `declarationMap`, `sourceMap`, `verbatimModuleSyntax`, `isolatedModules`, `exactOptionalPropertyTypes`, `noUncheckedIndexedAccess`, `noUncheckedSideEffectImports`, and `skipLibCheck` — with every other option at its default. A file TypeScript compiles as CommonJS is outside this set: under it, TypeScript rejects that file's import declaration whatever the module declares. +* A file type-checks when the compiler reports no error for that program, in any of its files. + +**Covered files.** The type contract concerns a configuration file in 7's declarative form whose import names the module by a specifier spelling exactly `N`, whose path ends in `.ts`, `.mts`, `.cts`, or `.tsx` and is no declaration-file name (4.6's file-name rule), and which meets each of these conditions: + +* It spells no `\` outside its comments: no identifier or string literal carries an escape sequence or line continuation, so every key, value, and the specifier read the same as spelled (2.4) and as TypeScript reads them — otherwise keys distinct as spelled, `"ab"` and `"a\x62"`, collide for TypeScript, and a key or value invalid as spelled, `"\x73pecs"` or `mode: "\x64irect"`, conforms for it. +* It carries no comment TypeScript reads as a directive or pragma, whatever its effect: a triple-slash directive (`/// <reference … />`), a comment directive in a line or block comment (`@ts-ignore`, `@ts-expect-error`), or a pragma (`@ts-nocheck`, `@jsxImportSource`). +* It imports `defineConfig` by that identifier, never by a string-literal import name (`{ "defineConfig" as d }`, a TypeScript error under `module` `es2015` and `es2020`), and binds it to a name strict module code admits as a binding — the first of 6.5's rules for an added import's identifiers — and to neither `require` nor `exports`, which TypeScript reserves in a file it compiles as CommonJS. + +**Type contract.** In every covered setup: + +* Exports: the module, as TypeScript resolves the covered file's import, declares exactly one export, `defineConfig`, a value with no type or namespace meaning, and no other export, type-only or not. TypeScript's synthetic default — the default import it admits, for interoperation with CommonJS, of a module declaring none, as in a file it compiles as CommonJS — is not an export the module declares. +* Valid configurations: a covered file valid under 7 type-checks, whatever spelling it carries — an aliased binding, string-literal keys, comments, and any group name, one spelling a member of TypeScript's global `Object` interface or `__proto__` included. +* Shape violations: a covered file holding one or more violations of the type-error class (below) does not type-check: TypeScript reports at least one error in the file, its locations and messages unpinned, possibly fewer errors than violations. + +The type-error class is exactly: + +* an unknown key (7) at any level; +* a missing required key: `specs`, `markdown`'s `emit`, and the keys 7.4 and 7.5 mark required for a profile and a rule; +* a value of a kind 7 does not admit in its position, a list's element included: a boolean, string, list, or object where 7 gives the position another kind; +* a string outside the values 7 enumerates for its position: `targets`, `boundaryKind`, `mode`, `type`, a selector's `kind`, an element of `edgeKinds` or `kinds`; +* a selector not in exactly one of its forms (7.5): one using more than one of `group`, `files`, and `tags`, one using none of them, or one carrying `kind` without `group`; +* an empty list where 7.4 or 7.5 forbids one: `targetTags`, `edgeKinds`, a rule's `kinds`, or a selector's `tags`. + +Every other configuration error (14.14) carries no type-level requirement either way: a covered file whose violations all lie outside the class may type-check or not. Among them are cross-references between names (a profile's `target` and `boundary`, a selector's `group`, a kind required because a name is ambiguous), the name and character rules (empty, duplicate, and U+FFFD-bearing names, `outDir`'s form), globs outside the root, a key repeated within one object literal, the capture rules, and a file matched by both a spec and a code group. + +**Runtime.** On every release of the Node.js 22 line and of every later line, Node.js run with no option, environment variable, or module customization hook that changes how modules are resolved or loaded — so with no user condition (`--conditions`, `-C`), no loader or customization hook (`--loader`, or one `--import` registers), and none of these through `NODE_OPTIONS` — and the module loaded through `import` or `require` as Reach describes: + +* The module's exports are exactly `defineConfig`: an `import` namespace holds that one export, and a `require` result has that one own enumerable property, symbol-keyed properties counted as well as string-keyed ones. +* `defineConfig` returns its first argument and does nothing else: the very value passed, whatever it is, neither examined, copied, nor modified; `undefined` when called with none; any further arguments ignored. +* Beyond the runtime's own resolution of the specifier and loading of the package's files, neither loading the module nor calling `defineConfig` has any effect: no filesystem read outside the package, no filesystem write, no network access, no output on standard output or standard error, and no change to the global object or to any other state of the process. + ## 8. Coverage Coverage is graph reachability over dependency edges between non-root participants, not proof of semantic correctness. A target requirement is covered for a profile when a permitted path exists from a boundary node to it: in `direct` mode a single edge, in `transitive` mode a path of one or more edges, using only the profile's `edgeKinds`. `contains` edges never grant coverage and never appear in coverage paths. Root nodes never appear in coverage paths either, in either mode — not as boundary node, intermediate, or target: a spec group serving as `boundary` contributes only its non-root requirement nodes as boundary nodes, and a dependency edge whose source or target is a root — a root-sourced `embeds` edge (2.3), or a `d`, `text(...)`, or marker reference targeting a root — never extends a covering path. This exclusion is coverage-scoped: roots remain nodes of their groups (8.2), and root-sourced and root-targeted dependency edges remain ordinary dependency edges for policy (7.5), impact (9.2), effectiveHash (5.5), and `query` (11). @@ -756,7 +813,7 @@ Document forms — each a single JSON document whose top level is an object; eve ### 13.1 Generated TypeScript -`NAME.mdx` generates, in the source file's directory, the TypeScript module `NAME.xspec.ts`, beginning with the generated-file header (4), together with whatever companion files beside it are needed so that the specifier `./NAME.xspec` resolves for consumers: type checking (4.1), hover documentation and go-to-definition into the source `.mdx` (4.2), and runtime behavior (4.3–4.5) MUST all hold under standard TypeScript tooling with no xspec runtime dependency. Every companion file is named `NAME.xspec.` plus a suffix, so the module and all companions carry `.xspec.` in their names and are derived files under the source-discovery exclusion (13.4). Per-source derived paths are defined by this `NAME.mdx` name shape alone: a spec-group file without the `.mdx` extension (14.19) generates no module and emits no Markdown (13.2) — it has no generated-module path and no Markdown emit destination (7.3, 11.6). +`NAME.mdx` generates, in the source file's directory, the TypeScript module `NAME.xspec.ts`, beginning with the generated-file header (4), together with whatever companion files beside it are needed so that the specifier `./NAME.xspec` resolves for consumers: type checking (4.1), hover documentation and go-to-definition into the source `.mdx` (4.2), and runtime behavior (4.3–4.5) MUST all hold under standard TypeScript tooling with no runtime dependency on xspec, its `defineConfig` module (7.6) included. Every companion file is named `NAME.xspec.` plus a suffix, so the module and all companions carry `.xspec.` in their names and are derived files under the source-discovery exclusion (13.4). Per-source derived paths are defined by this `NAME.mdx` name shape alone: a spec-group file without the `.mdx` extension (14.19) generates no module and emits no Markdown (13.2) — it has no generated-module path and no Markdown emit destination (7.3, 11.6). ### 13.2 Markdown output diff --git a/specs/TEST-SPEC.md b/specs/TEST-SPEC.md index 657bb5da..849690c5 100644 --- a/specs/TEST-SPEC.md +++ b/specs/TEST-SPEC.md @@ -2,7 +2,7 @@ This document is the source of truth for the xspec test harness. It specifies a blackbox, end-to-end test suite for every requirement in `specs/SPEC.md`, and the self-tests that establish confidence in the harness itself before any product code exists (red-green: the harness is implemented first and every product-facing test must fail against a missing or empty product without crashing the harness). -The harness treats xspec strictly as a black box. Tests drive the product exclusively through the surfaces SPEC.md declares complete: the `xspec` command-line executable, the `xspec.config.ts` project configuration, the source-file syntax, the generated TypeScript modules (consumed only under standard TypeScript tooling), and the files xspec writes to the workspace. No test may observe, assume, or depend on implementation internals, and no statement in this document prescribes product code, program structure, libraries, or a test framework. +The harness treats xspec strictly as a black box. Tests drive the product exclusively through the surfaces SPEC.md declares complete: the `xspec` command-line executable, the `xspec.config.ts` project configuration, the `defineConfig` module (installed exactly as its package is distributed, and consumed only by TypeScript 5.9.3's compiler and the Node.js runtime: H-2's module channel, 7.6), the source-file syntax, the generated TypeScript modules (consumed only under standard TypeScript tooling), and the files xspec writes to the workspace. No test may observe, assume, or depend on implementation internals, and no statement in this document prescribes product code, program structure, libraries, or a test framework. Sections 1–15 of this document mirror sections 1–15 of SPEC.md one-to-one. Every normative statement in SPEC.md section *N* is covered by tests in section *N* here (cross-references are explicit where one test covers statements from several sections), so coverage can be verified requirement by requirement. SPEC.md's unnumbered document preamble also carries requirements — no network access; git read only where explicitly stated, never written — covered by this introduction, T12.0-11/12, and E-1. Sections 16–18 define property-based/fuzz testing, harness self-testing and certification, and execution/CI requirements. @@ -16,14 +16,14 @@ xspec declares no external third-party hosted dependencies (SPEC.md: xspec perfo These requirements bind the harness implementation regardless of test framework choice (the framework itself is unspecified here and chosen by IMPLEMENTATION.md). -* **H-1 Workspace isolation.** Every test constructs a fresh, self-contained workspace in a unique temporary directory: `xspec.config.ts`, source files, and (when needed) a local git repository with scripted commits. Tests share no mutable state. Two harness instances MUST be able to run concurrently on the same machine (unique temporary roots), satisfying SPEC.md 13.5 isolation from the observer side. Self-containment reaches above the workspace wherever an arm turns on it: an arm presuming nothing above its staging root — a failed upward search and its `.` concerned path (T7-1, T12.7-3, T14-10(k)), or a workspace directory that is no repository and lies inside none (T6.3-5(c), T6.3-6(b), T12.0-12) — runs only once the harness has verified, under the environment it runs the product in, that no ancestor of that root holds an entry named `xspec.config.ts` and that the root lies inside no git working tree; an unmet precondition is a harness error (H-11), never a pass, a product failure, or a skip (H-9), as an ineffective permission staging is (T14-9). -* **H-2 Blackbox drive.** Tests invoke the `xspec` executable as a subprocess with controlled working directory, arguments, and environment — and, for 13.5's reach and identifier stagings alone, its user identity and process-identifier namespace (T13.5-9, T13.5-10(e), (f), (g); E-1) — and observe: exit code, standard output, standard error, and workspace file state. Consumer-side contracts (generated modules, type errors, runtime behavior, hover/go-to-definition) are exercised by compiling and running small consumer TypeScript programs under standard TypeScript tooling with no xspec runtime dependency (SPEC.md 13.1). That tooling's configurations are fixed here, so that no verdict turns on a choice this document leaves open. 13.1 requires its guarantees under standard TypeScript tooling — every standard configuration in which the consumer forms SPEC.md mandates are themselves valid, the extensionless relative specifier `./NAME.xspec` resolving and the import syntax of 4 compiling — a universal no suite enumerates, so the suite samples it at two such configurations, which differ in two settings that decide which import and export forms TypeScript accepts in a module: the module format it checks for, with that format's resolution, and whether each file must be transpilable on its own. Both run TypeScript 5.9.3, the release 14.20 fixes — its compiler and its language service (hover, go-to-definition) — with `strict` enabled and `target` ESNext with that target's default library, every option not named here at the release's default. The *CommonJS configuration* sets `module` CommonJS under its default (`node10`) resolution. The *ES-module configuration* sets `module` ESNext with `moduleResolution` `bundler` and enables `isolatedModules` and `verbatimModuleSyntax`: there, in a module other than a declaration file, an export assignment (`export =`) and an import assignment (`import … = require(…)`) are rejected, ECMAScript-module output admitting neither, and so are a type named in an `export { … } from` re-export without a `type` modifier (`isolatedModules`) and a type imported without one (`verbatimModuleSyntax`) — forms the CommonJS configuration accepts. Every type-checking and language-service assertion this channel makes is made under each configuration, with the same expectation: a program type-checks clean when it carries no diagnostic anywhere — in the consumer and in every generated module and companion it reaches alike — and a type-error assertion expects compilation to fail with the program's diagnostics at the consumer references under test alone; so a generated module or companion that either configuration rejects fails wherever the suite type-checks it, whatever the other configuration accepts. Every consumer program and TypeScript fixture file the channel compiles is valid under both configurations but for the diagnostics its assertion expects. Runtime behavior is exercised under the CommonJS configuration alone: the consumer program, with the generated module it imports, is compiled at that release in that configuration to CommonJS JavaScript — the output 6.5's timeliness rule contemplates — written outside the workspace, and that output is executed under the Node.js runtime the suite runs on, no package named `xspec` installed or resolvable; the ES-module configuration's output keeps the extensionless specifier, which Node.js's ECMAScript-module loader never resolves, so that configuration is type-checked and served, never executed. A configuration in which no product could meet 13.1 is never used: ECMAScript-module `node16`/`nodenext` resolution, under which an extensionless relative specifier never resolves, and `verbatimModuleSyntax` beside CommonJS output, which rejects the mandated import syntax itself. No other channel into the product exists — in particular, invoking the product in-process (importing product code or calling a product-internal entry function) is not a permitted channel for any test, fast paths included: SPEC.md's complete interface is the executable, an in-process entry is an implementation detail outside that interface, and subprocess invocation carries the process-level contract the suite asserts (exit codes, stream separation, working directory, environment, termination; 12.0, 13.5). +* **H-1 Workspace isolation.** Every test constructs a fresh, self-contained workspace in a unique temporary directory: `xspec.config.ts`, source files, and (when needed) a local git repository with scripted commits. Tests share no mutable state. Two harness instances MUST be able to run concurrently on the same machine (unique temporary roots), satisfying SPEC.md 13.5 isolation from the observer side. Self-containment reaches above the workspace wherever an arm turns on it: an arm presuming nothing above its staging root — a failed upward search and its `.` concerned path (T7-1, T12.7-3, T14-10(k)), or a workspace directory that is no repository and lies inside none (T6.3-5(c), T6.3-6(b), T12.0-12) — runs only once the harness has verified, under the environment it runs the product in, that no ancestor of that root holds an entry named `xspec.config.ts` and that the root lies inside no git working tree; an unmet precondition is a harness error (H-11), never a pass, a product failure, or a skip (H-9), as an ineffective permission staging is (T14-9). The verification reaches what TypeScript and Node.js read above a staging too (7.6, 13.1): an arm staging the `defineConfig` module (7.6; P-17, P-18) or compiling or running a consumer program (H-2) runs only once the harness has verified, under the environment those tools run in — TypeScript taking a directory inside the staging as its current one, Node.js run with no `NODE_PATH` and a fresh `HOME` — that no ancestor of the staging root holds a `package.json` or a `node_modules` entry and that none of Node.js's global module folders holds a package, so that no manifest outside the staging decides a project's module kind, names a self-reference, or breaks Reach's manifest condition (7.6), and no `@types` package, library replacement (`@typescript/lib-…`), or copy of the product's package enters a program or a module search from above; an unmet precondition is likewise a harness error (H-11), never a pass, a product failure, or a skip. +* **H-2 Blackbox drive.** Tests invoke the `xspec` executable as a subprocess with controlled working directory, arguments, and environment — and, for 13.5's reach and identifier stagings alone, its user identity and process-identifier namespace (T13.5-9, T13.5-10(e), (f), (g); E-1) — and observe: exit code, standard output, standard error, and workspace file state. Consumer-side contracts (generated modules, type errors, runtime behavior, hover/go-to-definition) are exercised by compiling and running small consumer TypeScript programs under standard TypeScript tooling with no runtime dependency on xspec, its `defineConfig` module included (SPEC.md 13.1). That tooling's configurations are fixed here, so that no verdict turns on a choice this document leaves open. 13.1 requires its guarantees under standard TypeScript tooling — every standard configuration in which the consumer forms SPEC.md mandates are themselves valid, the extensionless relative specifier `./NAME.xspec` resolving and the import syntax of 4 compiling — a universal no suite enumerates, so the suite samples it at two such configurations, which differ in two settings that decide which import and export forms TypeScript accepts in a module: the module format it checks for, with that format's resolution, and whether each file must be transpilable on its own. Both run TypeScript 5.9.3, the release 14.20 fixes — its compiler and its language service (hover, go-to-definition) — with `strict` enabled and `target` ESNext with that target's default library, every option not named here at the release's default. The *CommonJS configuration* sets `module` CommonJS under its default (`node10`) resolution. The *ES-module configuration* sets `module` ESNext with `moduleResolution` `bundler` and enables `isolatedModules` and `verbatimModuleSyntax`: there, in a module other than a declaration file, an export assignment (`export =`) and an import assignment (`import … = require(…)`) are rejected, ECMAScript-module output admitting neither, and so are a type named in an `export { … } from` re-export without a `type` modifier (`isolatedModules`) and a type imported without one (`verbatimModuleSyntax`) — forms the CommonJS configuration accepts. Every type-checking and language-service assertion this channel makes is made under each configuration, with the same expectation: a program type-checks clean when it carries no diagnostic anywhere — in the consumer and in every generated module and companion it reaches alike — and a type-error assertion expects compilation to fail with the program's diagnostics at the consumer references under test alone; so a generated module or companion that either configuration rejects fails wherever the suite type-checks it, whatever the other configuration accepts. Every consumer program and TypeScript fixture file the channel compiles is valid under both configurations but for the diagnostics its assertion expects. Runtime behavior is exercised under the CommonJS configuration alone: the consumer program, with the generated module it imports, is compiled at that release in that configuration to CommonJS JavaScript — the output 6.5's timeliness rule contemplates — written outside the workspace, and that output is executed under the Node.js runtime the suite runs on, nothing resolvable there by package name — no copy of the product's package under any name least of all, since 7.6 lets a project install it under any (13.1), H-1 verifying the precondition; the ES-module configuration's output keeps the extensionless specifier, which Node.js's ECMAScript-module loader never resolves, so that configuration is type-checked and served, never executed. A configuration in which no product could meet 13.1 is never used: ECMAScript-module `node16`/`nodenext` resolution, under which an extensionless relative specifier never resolves, and `verbatimModuleSyntax` beside CommonJS output, which rejects the mandated import syntax itself. The `defineConfig` module (7.6) has a channel of its own, the *module channel*: the product's package directory, exactly as distributed — given to the harness beside the executable (C-2), and presuming nothing about how the executable is provided, 7.6's definitions concerning the module alone — is placed under a name `N` the test chooses and reached only by a module specifier spelling exactly `N`, as 7.6's tests stage it: its declarations type-checked by TypeScript 5.9.3's compiler in 7.6's covered setups, and the module loaded through `import` and `require` by the Node.js releases E-1 provisions, the harness observing, in processes it launches, the values the module yields and those processes' output streams, state, and surrounding files. The directory given holds exactly what the package's distribution carries, and nothing installed into it afterwards — never a development tree, whose installed dependencies, absent from the distribution (the tree's own `node_modules`), would resolve inside the placed copy wherever the package's declaration files or entry import another package, so that every arm of 7.6 passed while 7.6's requirement that nothing else need be installed went untested. A subpath, or a file of the package named by its path, carries no contract (7.6) and is never a channel. No other channel into the product exists — in particular, invoking the product in-process otherwise (importing any other product code, the executable's included, or calling a product-internal entry function) is not a permitted channel for any test, fast paths included: SPEC.md's complete interface is the executable, the module, and the surfaces above, an in-process entry is an implementation detail outside that interface, and subprocess invocation carries the process-level contract the suite asserts (exit codes, stream separation, working directory, environment, termination; 12.0, 13.5). * **H-3 Output adapters, form-exact documents, and universal value forms.** SPEC.md 12.7 fixes two tiers of concrete JSON shape. Document forms — the whole document's member set, `null`-vs-omission, `[]`-vs-`null`, and orderings — are pinned for every findings-only report, the exit-2 error document, the performed `rename`/`move` report (6.4, 6.5: `{"findings", "mapping"}`), and the surfaces of 6.6, 11.3–11.6, and 12.6: assertions on those documents are form-exact end to end, and no adapter may re-map, rename, or coerce them — output differing from 12.7 in shape is a conformance failure, never an adapter fixture (T12.7-1..3). Value forms are universal: 12.7 fixes "the value forms every JSON output uses" — a source range is `{"start", "end"}`, a path a plain string or the marked byte form, an identity a string, unavailability exactly `{"unavailable": true}`, a finding the 12.7 finding form (findings arrays the member `"findings"`, in 12.7 order), an occurrence record the 12.7 record form, a coverage attribute the string `"required"` or `"none"`, a tag set or kind set the 12.7 set form (tags in byte order, duplicates collapsed; kinds in 5.2's order) — and 12.6 versions that whole contract, so these forms bind wherever their data appear in any JSON output, pinned document or not. Where SPEC.md leaves a document's shape unpinned, fixing its information content instead (12.0) — the command JSON of `query`, `ids`, `show`, `coverage`, `impact`, and the `review` payloads — assertions go through a thin decoding adapter that maps the product's actual output onto the information model this document asserts against (nodes, categories, counts, paths, …). The adapter's latitude is exactly the surrounding unpinned shape — which members hold which data, nesting, grouping — never the value forms: a located value-form datum is asserted literally (T12.7-1's unpinned-surface arms), and a product carrying it in any other shape — a range as `[start, end]` or `{"from", "to"}` in a `query` row or a review payload — fails, the adapter never mapping it back. Adapters are the only place aware of unpinned shape; they may be adjusted to shape, never to values, and they MUST fail loudly (test error, not pass) when required information is absent. Human-readable reports are asserted only for required information (via robust matching), never exact wording. Report forms: an assertion on a report reads the form its test names; a test naming neither reads the `--json` document, form-exact or adapter-decoded as above; and the human report of every command that has one — every command but the JSON-only surfaces of 10.7, 11, and 12.6 — is asserted, decoded by a human-report adapter held to the rules above (shape-aware, value-blind, failing loudly when required information is absent), by T12.0-15 on the fixtures it names and by each test naming the human form. Where a test stages a corrupt or tampered product-written file whose concrete shape SPEC.md leaves opaque, the transformation is applied to a file the product itself wrote, never fabricated from an assumed layout: where a shape is discernible — the session file's JSON objects and sorted keys (T10.1-4; 10.1, 13.4) — the staging lives in this same adapter layer, shape-aware, value-blind, and failing loudly when the shape does not match; where SPEC.md enumerates no layout at all — graph data, 13.3 — the staging is shape-blind and no adapter is involved: truncation or garbage over the whole operational path set (T6.6-6 and the tests staging its record corruption), or, where reads' answers are asserted and `check`'s verdict is predicted only from what the reads and `inventory` observe of the staged state (T13.3-5(a)), partial tampering — single bytes altered and files truncated at seeded offsets within that set's files, and files mixed from two product-written states — whose effect on the record and on `check`'s comparison no test predicts from the staging itself (H-4). * **H-4 Byte assertions.** Where SPEC.md requires byte determinism or exact bytes (12.0 determinism, 3 Markdown output, 6.5 move edits, 13.4 stable ordering), tests assert byte equality. Where SPEC.md declares content opaque (journal entry content 6.1, graph data content 13.3), tests assert only the stated observable contract (location, line-orientation, append-only effect, refresh/staleness behavior) and MUST NOT pin opaque bytes across product versions — except for determinism checks comparing the product to itself. The lock directory's entries (13.4) are opaque further still — coordination state outside 12.0's determinism, dependent on the machine and process that wrote them — so no test pins an entry's name, content, or permissions, nor compares entries across runs but by 13.5's own inequality: tests observe the lock path's kind, its entries' count and kinds (each a plain file, 13.5), one entry's byte-identity, name and content, across a span in which acquisition and release alone may touch it, the harness's own staging of its permissions aside, the span beginning past the harness's own alteration of its content where it makes one (T13.5-2, T13.5-10(c)), that entry's name's place, in byte order and in the filesystem's listing, among the names staged beside it — dead runs' entries' included — to stage leftovers around it (T13.5-10(c)), and that name itself, to give a non-entry the harness stages in that entry's place (T13.5-10(e)), each a staging choice asserting nothing, and that two runs' entries bear byte-different names (13.5: an entry's name distinguishes its run, no other run's entry ever bearing it; T13.5-10(e), (f)) — an inequality, pinning no name, content, or form. An entry's permissions being the product's own, and acquisition and release reading no entry's content (13.5), a product may make its entries unreadable to their owner: where an entry's own mode refuses the harness's read of it — to compare or to copy it — or its write to it — to alter its content (T13.5-10(c)) — the harness grants itself that permission for that read or write alone and restores the product's mode at once, before any further product invocation or the lifting of any hold; whether that change of mode counts as 13.5's interference changes no expectation, each run faring as the lock directory decides, the entry's name unchanged (T13.5-10(c)). * **H-5 Exit codes and streams.** Every test asserts the exact exit code and, where relevant, the stdout/stderr separation of 12.0: reports and findings are stdout content; usage/configuration error messages and all other diagnostics are stderr content; when JSON output is in effect — the `--json` flag given, a `--json` token read as a flag and never as another flag's value or an operand after `--` (12.0's grammar, T12.0-14), even when the arguments are themselves the error, or a JSON-only surface (10.7, 11, 12.6) — stdout is exactly one JSON document, on exit 2 the error document of 12.7; when it is not in effect, exit-2 stdout is empty, the standard-error message then carrying the error's stable code and concerned path wherever 14 defines them (T12.0-15). * **H-6 Determinism protocol.** Tests marked *determinism* run the same command twice (or rebuild the same workspace in two separate directories) and assert byte-identical outputs and written files, after normalizing nothing — the lock path `.xspec/lock` and everything under it excepted, outside 12.0's determinism (13.4, H-4): every comparison of written files across runs or workspaces, determinism and twin comparisons alike, excludes it, which matters only where a leftover survives a run (a kill, a refused release deletion: T13.5-3, T13.5-11), a run whose release completes leaving none (13.5); and so does the comparison of a mutating command's run against its own pre-invocation state, acquisition's and release's writes there counting as no modification (13.5), the lock path's state after such a run asserted wherever a test states it (T13.5-11). The exclusion reaches no further: a run of a command that acquires nothing — `build`, `check`, `version`, a preview (6.6), and every read command (`ids`, `show`, `coverage`, `impact`, `query`, `occurrences`, `view`, `at`, `inventory`, and the `review` subcommands but `create`, `resolve`, and `split`) — makes no write there (13.4: no write but acquisition and release touches the lock path), so its comparison against its own pre-invocation state — wherever a test asserts that such a run modifies or writes nothing, or compares the workspace before and after it, no other run acquiring, releasing, or being killed meanwhile — includes the lock path: whatever occupied it before, nothing, a leftover, or a held run's entry, occupies it afterwards byte-identical, nothing added beside it (T13.4-12, T13.5-4). Workspace-relative path rules (1.5) make this well-defined across directories. * **H-7 Traceability.** The harness maintains a machine-readable mapping from test ID to the SPEC.md passage(s) it covers. The map's keys are: SPEC.md's unnumbered document preamble (T12.0-11/12, E-1); every numbered subsection; and every numbered section's own body text outside its subsections (3, 4, 5, 7, 8, 9, 10, 11, 14, and 15 — sections 1, 2, 6, 12, and 13 carry no requirements outside their subsections and are covered through them). A harness self-check (17) fails if any key lacks at least one mapped test, or if a test maps to a nonexistent key. -* **H-8 Red-green compatibility.** The full suite MUST be runnable when no product is installed (or against a deliberately empty stub): every product-facing test fails with a diagnosed assertion failure — never a harness crash, hang, or false pass. Self-tests (17) and certification MUST pass before the product exists. +* **H-8 Red-green compatibility.** The full suite MUST be runnable when no product is installed (or against a deliberately empty stub): every product-facing test fails with a diagnosed assertion failure — never a harness crash, hang, or false pass. The module channel counts as part of the product: with no package directory given, or an empty stub package (S-7), every test of 7.6 fails likewise, none passing on a negative arm alone (7.6's pairing rule). Self-tests (17) and certification MUST pass before the product exists. * **H-9 No skips.** A test that cannot run in GitHub CI is implemented as a local-only test, executed by the local suite; it is never marked skipped. The local-only set is currently empty (18). * **H-10 Time and randomness.** The harness introduces no wall-clock or randomness dependence into assertions; fuzz/property tests (16) use seeded, reproducible generators and report the seed on failure. The hang guards of S-3 are the one place the clock can reach a verdict: a guard detects non-termination and asserts nothing about speed. SPEC.md leaving speed unbounded, no finite guard is beyond every conforming product's reach; S-3 makes every guard spanning several invocations compositional over the own guards of the invocations and harness steps it spans, so a product's speed meets the clock only where one invocation outlasts its own guard — the guard carrying the suite's margin for product speed — and a conforming product tripping any guard exposes a harness defect (E-5), never a product failure. * **H-11 Answer-scale capacity.** For every input the suite stages — deterministic fixtures and generator draws (16) alike — the harness MUST capture, decode, and evaluate every answer SPEC.md permits a conforming product to give at that input's scale, nesting depth and document size included: the capture of H-2's observed output streams, the H-3/12.7 decoding, and every subsequent per-datum traversal of an answer document (16's property walks included) succeed, with harness-internal capacity limits — capture included — dimensioned to the scales the suite itself stages; an exhausted capture limit MUST surface as a loud harness error, never as silent truncation, since a truncated capture is observationally indistinguishable from a product emitting a partial document (P-8, P-11). A harness-side failure while capturing or evaluating an answer — a crash, hang, or exhausted internal limit — is reported as a defect in the harness, never as a diagnosed product failure and never as a pass: H-8's rule generalized beyond the missing-product run, H-3's fail-loudly rule beyond absent information. S-8 (17) gates this capacity, capture through evaluation, before any product exists. @@ -326,26 +326,49 @@ Occurrences are observed through `xspec occurrences` (11.3) and per-file views ( ## 7. Project Configuration -* **T7-1 Location.** Configuration found by upward search from a nested working directory; `--config <path>` (resolved against the working directory, 12.0) overrides the search; no configuration reachable → configuration error (14.14, exit 2) — by a failed upward search, and by `--config` naming a nonexistent file (missing configuration, 14.14; concerned paths per T12.7-3), the latter never a plain usage error; a refused examination of a directory the search examines is a read failure, never absence (T14-10(k)). Occupancy (7, 14.14): the upward search stops at the nearest directory holding an entry named `xspec.config.ts`, whatever occupies it — with a valid configuration at the root and, in the working directory beneath it, an entry `xspec.config.ts` that is a directory, and separately a symbolic link to that valid root configuration, every command but `version` exits 2 with 14.14, the error document's concerned path that entry (`xspec.config.ts`, the working directory's own) — never the file above, never read through the link (a product following the link loads the valid configuration and exits 0, failing the arm); `--config` naming such a directory or link exits 2 likewise. The entry's name is compared byte-wise and case-sensitively (7, 12.0): with the valid root configuration and, in a working directory beneath it, a plain file `XSPEC.config.ts` holding `)` (no well-formed TypeScript; matched by no group's glob) and no entry named `xspec.config.ts`, the search passes that directory and loads the root's configuration — `build` and then `check`, each run from there, exit 0 — a single-casing probe, stageable on any filesystem and rerun on the Windows leg (E-6), failing a product that matches the name case-insensitively or finds the file through a case-insensitive filesystem lookup, reads it, and exits 2 with 14.14. -* **T7-2 Declarative form.** Each fails with 14.14 (exit 2): a configuration file that is not well-formed TypeScript (a syntax error); missing `defineConfig` import; import from a specifier other than `"xspec"` — `"XSPEC"` among them, a single-casing arm (12.0: no case folding anywhere); extra statements; a non-literal argument (spread, computed key, template literal, identifier reference, function call, number where boolean expected — refused by form, 7 admitting no numeric literal); a `null` literal, outside 7's literal set though `inventory` reports unset members as `null` (12.7) — `markdown: { emit: true, outDir: null }` and a profile's `targetTags: null`, one arm each, failing a product that reads `null` as an omitted member; a default export that is not one call to the (optionally aliased) binding; a call without a sole argument (7: one call whose sole argument is statically literal) — `defineConfig()`, and `defineConfig({…}, {})`, its first argument an otherwise valid configuration, discriminating a product reading the first argument alone; and a numeric-literal key, `specs: { 1: ["specs/*.mdx"] }` (7: non-computed identifier or string-literal keys), which TypeScript admits and a product reading keys loosely takes for a group named `1`. An aliased `defineConfig` import is valid. The import carries no `type` or `defer` modifier and no import attributes (7): `import type { defineConfig } from "xspec"`, `import { type defineConfig } from "xspec"`, `import defer { defineConfig } from "xspec"`, and `import { defineConfig } from "xspec" with { type: "json" }`, each followed by an otherwise valid `export default defineConfig({…})`, each → 14.14, exit 2 — every one text accepted by TypeScript 5.9.3 both as module code and as script code (14.20), so the declarative form of 7 decides it, never a parse failure; a product reading the binding loosely accepts them all. String-literal keys are part of the accepted form (7): a configuration declaring a spec group and a code group under string-literal keys whose names are not TypeScript identifiers (`"my-group"`, `"test-code"`) loads without error, both groups discover their globs' files, and the names resolve wherever group names are referenced — a coverage profile with `target: "my-group"`, `boundary: "test-code"` reports its coverage (8), and a policy rule's selector `{ group: "my-group" }` matches the group's nodes (7.5) — discriminating a product that accepts identifier keys alone, which refuses a valid configuration no other spelling can declare (a non-identifier group name has only the string-literal form). Verbatim literals (7, 2.4): a glob spelled with an escape sequence (`"specs/\u002A.mdx"`) is read as its characters — matching no discovered file, its group discovering zero sources — and a group name so spelled (`"prod\u0075ct"`) names a group whose spelling contains `\`: a profile's `target: "product"` is then an unknown group (14.14) while `target: "prod\u0075ct"` resolves. Encoding (7, 14.14): a configuration file that is not valid UTF-8, and one beginning with a byte-order mark, each → 14.14, exit 2. Object-literal keys (7, 14.14): a key repeated within one object literal — `specs: {…}, specs: {…}` at top level, and `product: […], "product": […]` inside `specs`, an identifier key and a string-literal key spelling the same name — each → 14.14, whatever TypeScript's own diagnosis of the repetition; an empty name — a spec group `""`, a code group `""`, a profile `name: ""`, a rule `name: ""`, one arm each — → 14.14. Comments (7): line and block comments anywhere — before the import, inside the argument between keys and inside a glob list, after the export — contribute nothing: the configuration loads and `inventory`'s `configuration` is byte-identical to its comment-free twin's. -* **T7-3 Keys.** `specs` missing → 14.14. Omitted optional keys, each with its stated observation: `code` — no code groups: a marker-bearing `.ts` file is undiscovered, the unfiltered `query edges` list carries no edge from it, and naming it in `--from` is unknown (exit 2, 11); `markdown` — no emission: no `.md` is written for any source (T3-6); `coverage` — no profiles: `xspec coverage` reports zero profiles and exits 0; `policy` — no rules: `check` on a workspace whose edges would violate T7.5-2's rule, with the rule omitted, reports no policy findings and exits 0. Empty lists (7): `coverage: []` and `policy: []` are valid and equivalent to omitting the key — zero profiles reported, no policy findings. Unknown keys at top level, in `markdown`, in a profile, in a rule, and in a selector each → 14.14. Value shapes (7, 7.1, 7.2; 14.14: a configuration that does not conform, an otherwise invalid group shape) — each → 14.14, one arm each: a spec group and a code group whose value is a single string rather than a list (`product: "specs/**/*.mdx"`); a glob list holding a non-string element (`[true]` — a literal 7 admits in form, never as a glob); `coverage` and `policy` given as an object rather than a list (`coverage: {}`); and `specs` and `code` given as a list rather than a map of groups — discriminating a product that reads the declarative form loosely, accepting whatever its own loader tolerates. Names containing U+FFFD (7, 14.14): a spec group, a code group, a profile, and a rule named with a U+FFFD (one arm each) → 14.14, exit 2. +* **T7-1 Location.** Configuration found by upward search from a nested working directory; `--config <path>` (resolved against the working directory, 12.0) overrides the search; no configuration reachable → configuration error (14.14, exit 2) — by a failed upward search, and by `--config` naming a nonexistent file (missing configuration, 14.14; concerned paths per T12.7-3), the latter never a plain usage error; a refused examination of a directory the search examines is a read failure, never absence (T14-10(k)). Occupancy (7, 14.14): the upward search stops at the nearest directory holding an entry named `xspec.config.ts`, whatever occupies it — with a valid configuration at the root and, in the working directory beneath it, an entry `xspec.config.ts` that is a directory, and separately a symbolic link to that valid root configuration, every command but `version` exits 2 with 14.14, the error document's concerned path that entry (`xspec.config.ts`, the working directory's own) — never the file above, never read through the link (a product following the link loads the valid configuration and exits 0, failing the arm); `--config` naming such a directory or link exits 2 likewise. The entry's name is compared byte-wise and case-sensitively (7, 12.0): with the valid root configuration and, in a working directory beneath it, a plain file `XSPEC.config.ts` holding `)` (no well-formed TypeScript; matched by no group's glob) and no entry named `xspec.config.ts`, the search passes that directory and loads the root's configuration — `build` and then `check`, each run from there, exit 0 — a single-casing probe, stageable on any filesystem and rerun on the Windows leg (E-6), failing a product that matches the name case-insensitively or finds the file through a case-insensitive filesystem lookup, reads it, and exits 2 with 14.14. Configuration file names (7: `--config` names any path, the file judged by the grammar its name selects, 14.20): `--config xspec.config.mts`, `--config xspec.config.cts`, and `--config xspec.config.tsx`, each naming a plain file at the root that holds a valid configuration's bytes, no `xspec.config.ts` existing, each load — `build` and `check` exit 0, and `inventory`'s `configuration` is byte-identical to its twin's, which names the same bytes `xspec.config.ts` — failing a product that admits a `.ts` name alone. The `.tsx` name selects TSX, a choice no file in 7's declarative form observes: its literals, identifiers, calls, and comments read alike under either grammar, and an ill-formed file is 14.14 under both. +* **T7-2 Declarative form.** Each fails with 14.14 (exit 2): a configuration file that is not well-formed TypeScript (a syntax error); missing `defineConfig` import; extra statements; a non-literal argument (spread, computed key, template literal, identifier reference, function call, number where boolean expected — refused by form, 7 admitting no numeric literal); a `null` literal, outside 7's literal set though `inventory` reports unset members as `null` (12.7) — `markdown: { emit: true, outDir: null }` and a profile's `targetTags: null`, one arm each, failing a product that reads `null` as an omitted member; a default export that is not one call to the (optionally aliased) binding; a call without a sole argument (7: one call whose sole argument is statically literal) — `defineConfig()`, and `defineConfig({…}, {})`, its first argument an otherwise valid configuration, discriminating a product reading the first argument alone; and a numeric-literal key, `specs: { 1: ["specs/*.mdx"] }` (7: non-computed identifier or string-literal keys), which TypeScript admits and a product reading keys loosely takes for a group named `1`. Wrapped forms and call variants (7: the file consists of exactly the import and a default export of one call to that binding whose sole argument is statically literal — no other statement or expression form, comments alone permitted beside them; 4.6 reads a wrapper as another expression): each over an otherwise valid argument → 14.14, exit 2, one arm each — the call wrapped, `export default defineConfig({…}) satisfies object`, `export default (defineConfig({…}))`, and `export default defineConfig({…})!`; the argument wrapped, `defineConfig({…} as const)` and `defineConfig(({…}))`; a value inside it wrapped, `markdown: { emit: true as boolean }` and `specs: ({…})`; and the call spelled with syntax outside 7's list, which is no comment — `export default defineConfig<object>({…})`, carrying type arguments, and `export default defineConfig?.({…})`, an optional call. Each is a text TypeScript 5.9.3 accepts (14.20), so 7's form decides it, never a parse failure, and none, outside that form, is a covered file of 7.6 — though `as const`, `satisfies`, and, for a generic `defineConfig`, type arguments are what a TypeScript author reaches for. Each arm fails a product that skips TypeScript's outer expressions (parentheses, type assertions, `satisfies`, and non-null assertions) before reading the form, or reads a call by its callee and arguments alone. An aliased `defineConfig` import is valid, and so is one whose module specifier is any static string literal (7; T7-9). Binding forms (7: exactly an import of `defineConfig`, optionally aliased): a string-literal import name, `import { "defineConfig" as d } from "xspec"` with `export default d({…})` over an otherwise valid argument, is that import, aliased — the name, read verbatim (2.4), spelling `defineConfig` — and loads, `inventory`'s `configuration` byte-identical to its identifier-named twin's (TypeScript 5.9.3 parses the form; 7.6 leaves it outside the type contract's covered files alone); its escape-spelled twin, `import { "define\x43onfig" as d } from "xspec"`, read verbatim, imports no `defineConfig` → 14.14; and a default import (`import defineConfig from "xspec"` with `export default defineConfig({…})`), a namespace import (`import * as X from "xspec"` with `export default X.defineConfig({…})`), an extra default binding (`import d, { defineConfig } from "xspec"`), and an extra named binding (`import { defineConfig, other } from "xspec"`), each beside an otherwise valid default export, each → 14.14, exit 2 — failing a product that reads the binding loosely. The import carries no `type` or `defer` modifier and no import attributes (7): `import type { defineConfig } from "xspec"`, `import { type defineConfig } from "xspec"`, `import defer { defineConfig } from "xspec"`, and `import { defineConfig } from "xspec" with { type: "json" }`, each followed by an otherwise valid `export default defineConfig({…})`, each → 14.14, exit 2 — every one text accepted by TypeScript 5.9.3 both as module code and as script code (14.20), so the declarative form of 7 decides it, never a parse failure; a product reading the binding loosely accepts them all. Statement forms (7: exactly an import of `defineConfig` and a default export of one call to that binding, no other statement form): TypeScript's two CommonJS-interop statements, one arm each over an otherwise valid argument — an export assignment, `export = defineConfig({…})` beside `import { defineConfig } from "xspec"`, which is no default export, and an import assignment, `import defineConfig = require("xspec")` beside `export default defineConfig({…})`, which binds the module itself and, like the default and namespace imports above, imports no `defineConfig` — each → 14.14, exit 2: each is text TypeScript 5.9.3 accepts both as module code and as script code (14.20; S-9), so 7's form decides it, never a parse failure — failing a product that takes an export assignment for a default export or an import assignment for an import of `defineConfig`. Statement order (7 fixes which statements the file holds, never their order; an import binds its name throughout its module, so a call spelled before it calls that binding): `export default defineConfig({…})` followed by `import { defineConfig } from "xspec"`, over an otherwise valid argument — text TypeScript 5.9.3 accepts both as module code and as script code (14.20) — loads: `build` and `check` exit 0, and `inventory`'s `configuration` is byte-identical to its import-first twin's, failing a product that requires the import to come first. String-literal keys are part of the accepted form (7): a configuration declaring a spec group and a code group under string-literal keys whose names are not TypeScript identifiers (`"my-group"`, `"test-code"`) loads without error, both groups discover their globs' files, and the names resolve wherever group names are referenced — a coverage profile with `target: "my-group"`, `boundary: "test-code"` reports its coverage (8), and a policy rule's selector `{ group: "my-group" }` matches the group's nodes (7.5) — discriminating a product that accepts identifier keys alone, which refuses a valid configuration no other spelling can declare (a non-identifier group name has only the string-literal form). Verbatim literals (7, 2.4): a glob spelled with an escape sequence (`"specs/\u002A.mdx"`) is read as its characters — matching no discovered file, its group discovering zero sources — and a group name so spelled (`"prod\u0075ct"`) names a group whose spelling contains `\`: a profile's `target: "product"` is then an unknown group (14.14) while `target: "prod\u0075ct"` resolves. Keys and enumerated values are read as spelled too (7, 2.4; the spellings 7.6's covered-file bar cites): a top-level key `"\x73pecs"` is an unknown key, `specs` then missing → 14.14; `mode: "\x64irect"` in an otherwise valid profile → 14.14; and `specs: { "ab": ["a/*.mdx"], "a\x62": ["b/*.mdx"] }` declares two groups, no key repeated — it loads, `inventory` reporting both, each discovering its own glob's file — failing a product that decodes escapes, which accepts the first two and refuses the third. Identifier keys are read as spelled alike (7, 2.4; 7.6's covered-file bar reads every key as spelled, an identifier's as a string literal's, where TypeScript decodes an identifier's Unicode escapes) — the identifier twins of the key arms above, each text TypeScript 5.9.3 accepts (14.20): a top-level key `\u0073pecs` is an unknown key, `specs` then missing → 14.14; `specs: { ab: ["a/*.mdx"], a\u0062: ["b/*.mdx"] }` declares two groups, no key repeated — it loads, `inventory` reporting both, each discovering its own glob's file; and a spec group keyed `prod\u0075ct` names a group whose spelling contains `\`, so a profile's `target: "product"` is an unknown group (14.14) while `target: "prod\u0075ct"` resolves — each failing a product that reads an identifier key by its decoded name, whatever it makes of a string literal's escapes. Encoding (7, 14.14): a configuration file that is not valid UTF-8, and one beginning with a byte-order mark, each → 14.14, exit 2. Object-literal keys (7, 14.14): a key repeated within one object literal — `specs: {…}, specs: {…}` at top level, and `product: […], "product": […]` inside `specs`, an identifier key and a string-literal key spelling the same name — each → 14.14, whatever TypeScript's own diagnosis of the repetition; an empty name — a spec group `""`, a code group `""`, a profile `name: ""`, a rule `name: ""`, one arm each — → 14.14. Comments (7): line and block comments anywhere — before the import, inside the import declaration between each two of its tokens (`import /* c */ { /* c */ defineConfig /* c */ } /* c */ from // c` U+000A `"xspec" /* c */`), inside the argument between keys and inside a glob list, after the export — contribute nothing: the configuration loads and `inventory`'s `configuration` is byte-identical to its comment-free twin's. +* **T7-3 Keys.** `specs` missing → 14.14. Omitted optional keys, each with its stated observation: `code` — no code groups: a marker-bearing `.ts` file is undiscovered, the unfiltered `query edges` list carries no edge from it, and naming it in `--from` is unknown (exit 2, 11); `markdown` — no emission: no `.md` is written for any source (T3-6); `coverage` — no profiles: `xspec coverage` reports zero profiles and exits 0; `policy` — no rules: `check` on a workspace whose edges would violate T7.5-2's rule, with the rule omitted, reports no policy findings and exits 0. Empty lists (7): `coverage: []` and `policy: []` are valid and equivalent to omitting the key — zero profiles reported, no policy findings. An empty glob list is valid too, 7 barring an empty list only for `targetTags`, `edgeKinds`, a rule's `kinds`, and a selector's `tags` (7.4, 7.5, 14.14), and a group whose globs match no files being valid (7): with `specs: { product: [] }` alone, and separately with a code group `app: []` beside a spec group globbing `specs/*.mdx` over `specs/A.mdx`, the configuration loads — `build` and `check` exit 0 — and `inventory` reports the group with `globs` exactly `[]` (12.7: `globs` as configured) and no source in it, the empty group discovering zero sources — failing a product that refuses an empty glob list as an invalid group shape. Unknown keys at top level, in `markdown`, in a profile, in a rule, and in a selector each → 14.14. Value shapes (7, 7.1, 7.2; 14.14: a configuration that does not conform, an otherwise invalid group shape) — each → 14.14, one arm each: a spec group and a code group whose value is a single string rather than a list (`product: "specs/**/*.mdx"`); a glob list holding a non-string element (`[true]` — a literal 7 admits in form, never as a glob); `coverage` and `policy` given as an object rather than a list (`coverage: {}`); and `specs` and `code` given as a list rather than a map of groups — discriminating a product that reads the declarative form loosely, accepting whatever its own loader tolerates. Names containing U+FFFD (7, 14.14): a spec group, a code group, a profile, and a rule named with a U+FFFD (one arm each) → 14.14, exit 2. * **T7-4 Globs.** Semantics fixtures: `*` any possibly empty run of bytes within one path segment; `?` exactly one byte within a segment; `**` whole segments including none; case-sensitive matching — including a single-casing probe stageable on any filesystem: a group whose only pattern is `SPECS/*.mdx` over a workspace directory `specs/` holding `A.mdx` discovers zero sources (rerun on the Windows leg, E-6, where a product matching globs through case-insensitive filesystem lookups wrongly discovers the file); byte semantics (7: paths match as their UTF-8 bytes), on the Linux leg — a file whose name contains a two-byte code point (`é.mdx`): `?.mdx` does not match it while `??.mdx` and `*.mdx` do, discriminating bytes from characters; a dotfile matched only by a pattern segment written with a leading `.` — wildcards never match dot-segments: `a/**/b.mdx` does not match `a/.h/b.mdx`, `*` does not match `.hidden`, `?x` does not match `.x`; a pattern resolving outside the workspace root → 14.14. All paths resolve relative to the configuration file's directory. Literal metacharacters (7: globs support exactly `*`, `?`, `**` — every other character is a literal): a pattern segment containing `[1]`, `{a,c}`, `!`, or `+(x)` matches exactly the file name containing those characters and never what a character-class, brace-expansion, negation, or extglob dialect would match — `a[1].mdx` matches `a[1].mdx` and not `a1.mdx`; `b{a,c}.mdx` matches `b{a,c}.mdx` and not `ba.mdx` or `bc.mdx`; and `\` is a literal byte, never an escape (Linux leg, where a file name can hold it): a code group globbing `src/a\*.ts` — the configuration literal read verbatim (2.4, T7-2) — discovers `src/a\b.ts` and not a sibling `src/ab.ts`, where a product reading `\` as a glob escape discovers neither and one interpreting the literal's escape discovers both (the `--file` twin: T12.0-5). Outside-root decision by spelling alone (7; staged here on group globs, on a policy selector's `files` glob in T7.5-1 and T7.5-4): `a/../../x/*.mdx` and `**/../x/*.mdx` (the depth falling below zero) and `/specs/*.mdx` (a leading `/`) each → 14.14, exit 2, even when the root's parent holds a matching file; `a/../b/*.mdx`, `./specs/*.mdx`, `specs//*.mdx`, and `specs/*.mdx/` are inside the root and match nothing — a group holding only such a glob discovers zero sources, exit 0, `inventory` reporting the glob as configured — since discovered paths carry no `.`, `..`, or empty segment, each arm staged beside the file its glob's lexical normalization matches (`b/B.mdx` for the first, `specs/A.mdx` for the rest), so a product normalizing patterns before matching discovers it and fails; the arm whose outside-root decision lexical normalization reverses, `**/../x/*.mdx` — outside by its spelling, inside as `x/*.mdx` once `**/..` cancels — is staged on each `--file` surface too (11.1, 11.3, 11.4, 12.3: T11-2, T11.3-2, T11.4-2, T12.3-1), where every inside-root arm likewise stages a discovered file its normalization matches; a drive-qualified spelling (`C:/specs/*.mdx`) is ordinary segments, inside and matching nothing on the Linux leg; and `a**b.mdx` treats each `*` as the single-segment wildcard, matching `axxb.mdx` and never `a/b.mdx` (7: `**` means any segments only as a whole pattern segment). * **T7-5 Symbolic links.** A symlinked file matched by a glob is not discovered; a symlinked directory is not traversed (contents undiscovered); broken links ignored; a symlink cycle does not hang discovery; workspace-external content behind a link never enters the discovered set. * **T7-6 Discovery boundaries.** Derived files are never discovered as sources even when globs match them (`.xspec.` names, `.xspec/` paths, Markdown emit destinations while emission is enabled, 13.4) — an invalid source's emit destination included, per-source derived paths following the `NAME.mdx` name shape alone (13.1, 7.3). The invalid-source arm stages emission next to sources, a spec glob `specs/*.mdx`, a code group globbing `specs/*.md`, and `specs/a'b.mdx` (holding `<S id="a">A</S>`; invalid by 7.1's bar, T7.1-1) beside a plain file `specs/a'b.md` holding `)`, which is not well-formed TypeScript (14.20). `check` exits 1 with exactly one finding, `specs/a'b.mdx`'s condition 19 — never a condition-20 finding for `specs/a'b.md`, which a product deriving emit destinations for valid sources alone discovers as a code source and reports. Control: with emission disabled the path is no emit destination (7.3), and `check` reports `specs/a'b.md`'s condition-20 finding beside the condition-19 one. The extension twin (7.3, 13.1: a spec-group file without the `.mdx` extension emits nothing and contributes none), staged separately with emission enabled next to sources: a spec glob `specs/*.txt` matching `specs/A.txt` (holding `<S id="a">A</S>`; 14.19) and a code group globbing `specs/*.md` matching plain files `specs/A.md` and `specs/A.txt.md`, each holding `)` — `check` exits 1 with exactly three findings, `specs/A.txt`'s condition 19 and a condition-20 finding for each `.md` file, as with emission disabled, no emit destination arising from the file — failing a product that derives a Markdown destination for it by replacing or suffixing its extension and so excludes one of them from discovery. The exclusion's name tests are byte-wise and case-sensitive (13.4, 12.0): a code source `src/a.XSPEC.ts`, matched by a code glob `src/*.ts`, carries no `.xspec.` in its name, and — on the Linux leg, where `.XSPEC` is a directory of its own rather than the graph-data area — a code source `.XSPEC/a.ts`, matched by a code glob `.XSPEC/*.ts` (its leading `.` spelled, 7), lies under no `.xspec/`: each is discovered — listed among `inventory`'s `sources`, and `query edges --from <path>` answering exit 0 for its whole-file location (T7-3's idiom for code discovery), never the usage error of a path in no configured group — single-casing arms failing a product that folds case in the exclusion. An import never adds an unmatched file to the workspace (2.1: the target must already be discovered, else 14.15); a group with no matches and an empty `specs`/`code` map are valid with zero sources. * **T7-7 Validation on a built workspace.** 7 and 14.14 bind every command that loads the configuration in every workspace state, a built one whose graph data is current included: the configuration path's occupant and the sources discovered are judged as they stand at the invocation. T7-1's occupancy arms root no built workspace — the occupant lies in a working directory beneath the root, holding no `.xspec` — and T7.2-1's both-groups file, T13.5-8, and T13.5-12(d) drive no read on a built state, so a product reusing a recorded configuration parse whenever the configuration's bytes, read through a link, and its recorded sources' hashes match passes them all. Two arms, each staged on a valid workspace after a `build` that leaves graph data current, every command run from the root under `--json`: (a) the root's `xspec.config.ts` replaced by a symbolic link to a file holding its byte-identical content — the target inside the workspace at a path no group matches, and separately outside it; (b) a file created that both a spec group and a code group match, the groups' globs overlapping on no path occupied at the build (a spec group globbing `src/**/*.mdx` beside a code group globbing `src/**/*`, then `src/x.mdx` created). In each, `build`, `check`, `ids` and `occurrences` (a read of each family 13.3 names), `inventory`, a `rename --preview`, and a `rename` of an operation succeeding on the unstaged twin each exit 2 with the error document — `code` `"configuration-error"`, `path` `"xspec.config.ts"` (T12.7-3) — nothing modified, `.xspec/lock` absent afterwards, and the link and its target byte-identical; `version` exits 0 (12.6). A product reading the configuration through the link loads the valid configuration and answers, failing (a). * **T7-8 Discovery's read scope.** 7: discovery reads only what deciding the discovered set takes — it lists a directory exactly when some configured spec or code glob matches a path below it, paths under `.xspec/` counting for none, and examines the kind of exactly those entries of a listed directory whose paths such a glob matches or that it would list were they directories — so a directory no glob reaches below is never listed, readable or not (14.25). Under the globs `specs/**/*.mdx` and `src/**/*.ts`, on a freshly built, valid workspace, a root-level directory `data/` and a dot-directory `specs/.cache/` — no glob matching a path below either, `**` matching no `.`-led segment (7) — are each staged unlistable (T14-10's discipline, Linux leg: read permission removed, search permission kept, the harness verifying on itself that its own listing is refused): every command that loads configuration — `build`, `check`, `ids`, `view`, `inventory`, `review list`, and a `rename`, each representative — exits and answers exactly as on a twin holding neither directory, its exit code and standard output equal to the twin's and the files it writes byte-equal to the twin's, never `read-failure`, each outcome also asserted as such a workspace gives it (H-5), so that the test stays red against S-7's stub, whose runs equal its twin's: `build` and `check` exit 0 finding-free, `ids` exits 0 with its listing, `view` and `inventory` answer finding-free, exit 0, `review list` exits 0, and the `rename` exits 0 with its applied mapping — failing a product that walks the whole tree, or descends into dot-directories, and meets the refused listing. T14-10(g) stages the listed side, a directory discovery lists made unlistable. The kind half: a directory discovery lists is staged with its read permission kept and its search permission removed (Linux leg, `r--`; the harness verifying on itself that its own listing of the directory succeeds and its own examination of an entry's kind there is refused), holding only entries outside that scope — under the same globs, `specs/sub/` holding only the dot-named plain file `specs/sub/.keep` (`**` matching no `.`-led segment, so no glob matches the entry or reaches below it), and, separately, with a spec glob `docs/*.mdx` added to the configuration, `docs/` holding only `docs/notes.txt` (no glob matching it or reaching below it). Discovery lists the directory, and a conforming product examines neither entry, whether or not it learns kinds from the listing: each representative command above, on such a freshly built, valid workspace, exits and answers exactly as on a twin without the entry — exit code and standard output equal to the twin's, the files it writes byte-equal to the twin's, each outcome the one the first half asserts — never `read-failure`, failing a product that examines the kind of every entry of a directory it lists. T14-10's unstageable kind-read clause concerns kind reads a product must make; here a conforming product makes none. The carve-out (7: paths under `.xspec/`, which 13.4 excludes, count for none, so a glob reaching below the area never makes discovery list it): with the spec glob `.xspec/*.mdx` added beside the globs `specs/**/*.mdx` and `src/**/*.ts` (its leading `.` spelled, 7), on a freshly built, valid workspace whose `.xspec` is then made unlistable but searchable and writable (`-wx`, T13.5-10(h)'s staging, verified on the harness itself first), `build`, `check`, `ids`, and `view` each exit and answer exactly as on a twin staged alike but without that glob — exit code and standard output equal to the twin's, never `read-failure` — `build` exiting 0 finding-free, `ids` 0 with its listing, and `view` 0 finding-free, as such a workspace gives them (H-5), while `check`, which a conforming product's own refused listing of `.xspec` outside discovery may meet as condition 23's state (14.25) and report as the unreadable-record unit form (14.10), is asserted equal to the twin's alone — failing a product whose discovery lists `.xspec` once a glob reaches below it and meets the refusal as discovery's read failure. Neither `inventory`, whose `configuration` reports the added glob, nor the files the runs write — graph data, whose opaque content (13.3, H-4) a configuration differing by that glob may change — is compared. A discovery that lists `.xspec` and takes the refusal as condition 23's state — the area's own occupant's (14.25) — passes: a residual, that refusal being the only observation of such a listing. +* **T7-9 Configuration import.** 7: the import's module specifier is any static string literal (2.4), and wherever xspec reads a configuration it never executes the file and never interprets, resolves, or loads the specifier, making no read and no network access on its account — validity, and everything xspec derives from the configuration, independent of what the specifier designates and of its spelling, wherever the file stays well-formed (14.20). Each arm runs on a valid workspace — a spec group globbing `specs/*.mdx` over `specs/A.mdx` and `specs/B.mdx`, emission enabled next to sources, no code group matching the configuration file. In (a) and (c), each arm's configuration differs from its twin's in the specifier alone, the twin importing from `"xspec"`, and `build`, `check`, `ids`, and `inventory`, each under `--json`, exit and answer as on the twin — exit code and standard output equal, `build` and `check` exiting 0 finding-free — `inventory`'s `configuration` byte-identical, and the generated modules and emitted Markdown byte-identical (graph data, whose opaque content a differing configuration file may change, is not compared, as in T7-8). (a) Spellings: the bare names `"XSPEC"` (a single-casing arm, 12.0: no case folding) and `"left-pad"`; the scoped name `"@acme/config"`; the relative path `"./lib/define.js"` and the absolute path `"/opt/define.mjs"`; the URL `"https://example.com/define.js"`, under the denied network every product invocation has (E-1); the empty string `""`; the single-quoted `'xspec'`; an escape sequence, `"\x78spec"`; a line continuation, `"xs\` U+000A `pec"`; and a raw U+FFFD, `"x` U+FFFD `spec"` — the last failing a product that applies 7's U+FFFD bar on names to every literal. (b) Scanner-rejected escapes: `"\x4"`, `"\u{110000}"`, `"\01"`, and `"\8"` as the specifier, each a scanning error of TypeScript 5.9.3 under both readings (S-9), leave the file not well-formed (14.20): `build`, `check`, `ids`, and `inventory`, each under `--json`, report 14.14, exit 2, the error document's `code` `"configuration-error"` and `path` `"xspec.config.ts"` (T12.7-3). (c) Designations: a relative specifier designating nothing (`"./nowhere.js"`); one designating a plain file the environment refuses to read (`"./locked.js"`, T14-10's discipline, Linux leg) — its content refused, its kind still examinable; one designating a path below a directory stripped of its read and search permission both (`"./sealed/define.js"`, `sealed/` holding `define.js` and staged mode `000`, T14-10(l)'s discipline, Linux leg, verified on the harness itself), so that every route to the designated path — its kind (14.25), its content, the directory's listing — is refused; one designating a FIFO (`"./fifo"`), afterwards still a FIFO and unopened, each command ending within its guard (S-3); one designating a directory (`"./specs"`); and the configuration file itself, `"./xspec.config"` and `"./xspec.config.ts"`. A read on the specifier's account that the product survives — one the environment permits, or a refused one it ignores — reaches nothing H-2's channel observes, no test observing a system call (S-3), and admits no discriminating staging (recorded here as T6.5-6 records its unstageable clauses). (d) Installs (7: no command's outcome depends, through a configuration's import, on the `defineConfig` module or on whether a project installed it; 7.6: no name is privileged): a configuration importing from `"N"` beside a trap package at `node_modules/N` — its manifest naming an entry that, if loaded, writes a marker file into the workspace, prints to both streams, and exits non-zero — and, separately, beside a `node_modules/N` whose `package.json` is a FIFO, each staged under three names `N`: `trap`; `xspec`, the executable's name; and the `name` the module channel's package manifest gives, read as T7.6-4(a) reads it, wherever that is a name of 7.6's grammar (the last two coinciding where that `name` is `xspec`). Each such arm runs T7-8's representative commands — `build`, `check`, `ids`, `view`, `inventory`, `review list`, and `rename specs/A.mdx a b`, `specs/A.mdx` holding `<S id="a">A</S>` — each under `--json`, against its twin, the same workspace and configuration holding no `node_modules`: each command exits and answers exactly as on the twin — exit code and standard output equal, the files it writes byte-equal to the twin's (H-6's lock-path exclusion aside), the two configurations being byte-identical — and as such a workspace gives it (H-5), so that the arm stays red against S-7's stub, whose runs equal its twin's: `build` and `check` exit 0 finding-free, `ids` 0 with its listing, `view` and `inventory` 0 finding-free, `review list` 0, and the `rename` 0 with its applied mapping; no marker is written, neither stream carries anything the entry prints, the FIFO stays unopened, and every command ends within its guard (S-3). Each arm fails a product that executes the configuration or resolves or loads its import — for every specifier, or only where the specifier spells a name it privileges, its own above all: such a product refuses a specifier for its spelling or designation, hangs on a FIFO, or runs the trap. +* **T7-10 The configuration file as a source.** 7: the rules of 4 and 14.15 reach the configuration file only where a configured group discovers it, and xspec then analyzes it as it does every source it discovers, its import declaration included, with the consequences 6.3, 6.5, 12.1, 13.3, and 14.15 give any source, while the configuration itself stays valid. On a valid workspace — a spec group globbing `specs/*.mdx` over `specs/A.mdx` (holding `<S id="a">A</S>`), emission enabled next to sources — the configuration imports, one arm each, from `"./specs/A.xspec"` (a spec module import binding `defineConfig`, neither the default nor the `text` export), `"./missing.xspec"` (designating no discovered spec source), `"./specs/A.xspec.ts"` and `"./.xspec/x"` (relative specifiers designating derived-file paths, 13.4), and `"./specs/A.md"` (`specs/A.mdx`'s emit destination while emission is enabled, 7.3). (a) Undiscovered: with no code group matching the configuration file, each arm is valid — `build` and `check` exit 0, no 14.15 — failing a product that applies a source's import rules to every configuration. (b) Discovered: with a code group globbing `*.ts`, and separately one whose glob is `xspec.config.ts`, the configuration is a code source, and in each arm `build` and `check` exit 1 reporting 14.15 — a spec-module binding other than the default and `text` exports, a `.xspec` specifier designating no discovered spec source, or a relative specifier designating a derived-file path (4) — a located condition: each such finding locates the configuration's import declaration in `xspec.config.ts` by the import range of 11.4, its `path` `null` (12.7). In the two `.xspec` arms the declaration is a spec module import (4), so `defineConfig` is a spec-module binding (14.15) and its call a value-level use 4.5 does not sanction (14.18): beside 14.15, `build` and `check` report 14.18 locating `defineConfig` at that call (14). No arm reports any other finding, and none 14.14 or exit 2: the configuration stays valid, and `inventory` answers exit 0 with no finding, listing `xspec.config.ts` among its `sources` in that code group. Control: importing from `"xspec"`, the discovered configuration is clean — `build` and `check` exit 0 — and its whole-file location exists (`query edges --from xspec.config.ts`, exit 0; T7-3's idiom). (c) Consequences, each on the discovered configuration beside its undiscovered twin: after a successful `build` under the control's `"xspec"`, the specifier changed to `"./missing.xspec"`, `build` exits 1 and modifies nothing, every derived file and all graph data byte-identical to the state before it (12.1), and the gated reads — `ids` and `query nodes`, representative — exit 1 reporting exactly `build`'s findings, that arm's 14.15 and 14.18 ((b)), and modify nothing (13.3); with the configuration importing from `"./specs/B.md"` — no `specs/B.mdx` existing, so the specifier designates no derived-file path and the workspace is valid — `move specs/A.mdx specs/B.mdx` is refused with `refused-invalid-destination`, exit 1, nothing modified, the destination's would-be emit path being designated by the configuration's specifier (6.5, as T6.5-20(d) stages a code source's designation), while the undiscovered twin moves, exit 0; and a commit `c1` whose discovered configuration imports from `"./missing.xspec"`, the working tree's workspace valid, fails `impact --base c1` and `review create --base c1 --name n` as T6.3-4's baseline failing validation does — exit 2, `code` and `path` `null`, no session written (6.3) — while the undiscovered twin's commit resolves. The converse, 6.5 reaching no undiscovered configuration: with the configuration importing from `"./specs/A.xspec"`, valid undiscovered ((a)), `move specs/A.mdx specs/B.mdx --preview` exits 0 listing no edit in `xspec.config.ts`, and the `move` exits 0 leaving `xspec.config.ts` byte-identical, `build` and `check` then exiting 0 — failing a product that counts the configuration's import among the paths by which other files import the moved file's generated module (6.5) and rewrites it to `"./specs/B.xspec"` — while its discovered twin, invalid per (b), is refused as 6.4's invalid workspace: exit 1, (b)'s findings for that arm reported alone, nothing modified. (d) Baselines (7: a baseline's configuration, 6.3, is read alike): a commit `c1` whose undiscovered configuration imports from `""`, `"./nowhere"`, or `"XSPEC"`, or — what the specifier designates varied, as T7-9(c) and (d) vary it for the current configuration — from `"./fifo"`, a FIFO at that path in the working tree, or from `"trap"`, T7-9(d)'s trap package at `node_modules/trap` in the working tree (one arm each), and whose sources differ from the working tree's by one section's edited text: `impact --base c1` exits 0, its impact information, decoded through H-3's adapter — categories with their attributions, collapsed chains, deleted and added identities, and each impacted location with its witness edge and path (9.3) — equal to that against the twin commit importing from `"xspec"`, the edited section `changed` (5.6); the reports are never compared byte for byte, the two commits' identities differing and a conforming product free to echo the resolved one (E-6). In the FIFO and trap arms, `review create --base c1 --name n` and then `review status n`, which resolves and reconstructs the recorded baseline, reading its configuration again (10.7), run as well: each exits 0, and the items `status` reports, decoded through H-3's adapter — their kinds, scopes, statuses, and blocked states — equal those the same two commands report against the twin commit. In the FIFO arm the FIFO stays a FIFO, unopened, each command ending within its guard (S-3); in the trap arm no marker is written and neither stream carries anything the trap's entry prints. And a commit whose configuration spells `"\x4"` as its specifier, not well-formed (14.20): `impact --base c1` exits 2 with T6.3-4's code-less usage error naming `xspec.config.ts`. Each arm fails a product that reads a baseline configuration's specifier unlike the current one's, or resolves, loads, or reads through it. (e) Discovered by a spec group (2.1, 7.1): the configuration importing from `"xspec"`, spelled with no blank line inside its default export so that, read as MDX, its import and its export derive as ESM blocks (14.20). (i) With the spec group globbing `specs/*.mdx` and `xspec.config.ts`, and separately `specs/*.mdx` and `*.ts`, `xspec.config.ts` is a spec-group file without the `.mdx` extension: `build` and `check` each exit 1 reporting 14.19 concerning it and, its content analyzed as a spec source's (2.1, 2.7; 14: an invalid path masks nothing, only an unparseable file masking the conditions inside it), 14.15 locating its import declaration and 14.16 its export statement — never 14.14, never exit 2 — and `inventory` exits 0, listing `xspec.config.ts` among that group's sources, its `derived` entry's `module` and `markdown` `null` (13.1, 11.6; T7.1-1). (ii) A configuration named `xspec.config.mdx`, given by `--config` on every invocation, no `xspec.config.ts` existing — judged as plain TypeScript, the grammar its name selects (14.20), as T7-1's `.mts`, `.cts`, and `.tsx` names are — and matched by a spec glob `*.mdx` beside `specs/*.mdx`, is a spec source: `build` and `check` each exit 1 reporting 14.15 locating its import declaration (2.1: a named binding, its specifier designating no spec source) and 14.16 its export statement (2.7) — never 14.14, never exit 2 — and `inventory` exits 0, listing `xspec.config.mdx` among that group's sources with its generated-module path, `xspec.config.xspec.ts` (13.1). Each beside its undiscovered twin — the spec group globbing `specs/*.mdx` alone — whose `build` and `check` exit 0; each fails a product that never takes the configuration file for a spec source, or answers 14.14 where a spec group matches it. +* **T7-11 Configured names.** 7 bars a group, profile, or rule name only when it is empty or contains U+FFFD, so the members of TypeScript's global `Object` interface and `__proto__`, which 7.6 spells out, are names like any other. Each arm runs on an otherwise valid workspace: (a) a spec group named `__proto__`, spelled once as an identifier key and once as a string-literal key, one named `constructor`, and one named `hasOwnProperty`, each globbing `specs/*.mdx` over `specs/A.mdx`, and code groups so named globbing `src/*.ts` over `src/a.ts`, one arm each: the configuration loads, `build` and `check` exit 0, and `inventory` reports the group under its name with its source; (b) a profile named `toString` and a `forbidden` rule named `toString` over an offending edge: `inventory` reports both, `coverage toString` reports the profile, and `check` reports the rule's violation under that name, exit 1; (c) a profile's `target`, its `boundary`, and a rule's selector `group`, each naming `__proto__` or `constructor`, one arm each: with a group of that name configured the reference resolves — the profile's coverage reported, the rule evaluated — and with none it is an unknown group, 14.14, exit 2; and (d) with no such profile configured, `coverage constructor` and `coverage __proto__` each name an unknown profile, the usage error of 12.0 (exit 2). Each arm fails a product that looks configured names up in a plain object, where `constructor` and `__proto__` name inherited members and a group named `hasOwnProperty` shadows the method such a product calls on that object. * **T7.1-1 Spec groups.** A file in two spec groups is valid (and coverage/policy see it in both); a spec-group match without `.mdx` → 14.19 — a wrong-case extension among them: `specs/A.MDX`, holding `<S id="a">A</S>` and matched by a spec glob `specs/*.MDX` with emission enabled, has no `.mdx` extension (12.0: paths compare byte-wise and case-sensitively, no case folding anywhere) — 14.19, and `inventory`'s `derived` entry for it carries `module` and `markdown` `null`, as for every spec-group file without the extension (13.1, 11.6) — a single-casing arm failing a product that folds case in the extension test. Path characters (7.1): a spec-group file whose workspace-relative path contains `"`, `'`, `\`, U+000A, U+000D, U+2028, or U+2029 → 14.19, one arm per character in the file name (`specs/a'b.mdx`, …) plus one with `'` in a directory component (`specs/it's/a.mdx`) — the `"`, `\`, U+000A, and U+000D arms staged on the Linux leg, as T1.5-2 stages its non-UTF-8 arm — each file still discovered and reachable as T11.2-3's invalid-path files are: the finding concerns its path, and a glob-reached `view` serves its tree with every identity unavailable. Control: a code-group file `src/it's\x.ts` — `'` and `\` in a code source's path — is valid, 7.1 binding spec groups alone (14.19's code-source forms are `#`, U+FFFD, and non-UTF-8): `build` and `check` exit 0, a marker in it recording its edge from that whole-file location, discriminating a product that applies the bar to every source. * **T7.2-1 Code groups.** Code groups act as coverage boundaries and the impacted-code population (asserted in 8/9); a file matched by both a spec and a code group → 14.14. * **T7.3-1 Markdown config.** `markdown` absent → no emission; `emit: false` → none; `emit: true` → emission next to each source; `markdown` present without `emit` → 14.14 (7.3: `emit` is required when `markdown` is present); a well-formed literal of the wrong type for a scalar field — `emit: "true"` (7.3: a boolean) and `outDir: true` (a path), one arm each — → 14.14, exit 2, never coerced (T7-2's number-for-boolean arm is refused by form, these by type); `outDir` redirects preserving workspace-relative paths; `outDir` not in plain workspace-relative form → 14.14, one arm each (7.3): `""`, `"/out"`, `"./out"`, `"out/../x"`, `"out//x"`, and `"out/"`, while `"out/sub"` is valid; an `outDir` naming the graph-data area or a path under it → 14.14, exit 2, one arm each (7.3): `".xspec"` and `".xspec/md"` — while the look-alikes `".xspec2"` and `".xspecs/md"` are valid, emission writing each destination under them (T13.4-8), anchoring 11.6's claim that graph data is the only derived file under the area — and so, on the Linux leg, are the single-casing spellings `".XSPEC"` and `".XSPEC/md"` (12.0: compared byte-wise, no case folding), failing a product that folds case in the bar; emit-destination classification follows `emit` (with emission off, a path that would be a destination can be a discovered source; with it on, it cannot — 7.3/13.4, asserted via discovery and via the import rule of T4-2); classification is by configuration alone, "whether or not emission has yet run" (7.3): in a workspace where no emission has ever run — emission enabled, source `specs/A.mdx`, a user-authored file at its destination `specs/A.md`, a spec-group glob matching both — a read command (`ids`, representative; its 13.3 refresh never emits) succeeds treating the destination as no source: the `.md` file is not discovered (no 14.19 from the non-`.mdx` match) and its bytes are untouched, discriminating a product that classifies destinations by existing emitted output rather than by configuration. * **T7.4-1 Profile validation.** Two profiles sharing a `name` → 14.14 (7.4: unique profile name); a profile lacking any one of the required `name`, `target`, `boundary`, or `mode` fields (one fixture per field) → 14.14; `targets` other than `"leaves"`/`"all"`, `mode` other than `"direct"`/`"transitive"`, `boundaryKind` other than `"spec"`/`"code"` → each 14.14; unknown `target` group name → 14.14; `target` naming an existing code-only group → 14.14 (7.4: `target` must be a configured spec group's name — the wrong-kind reference of 14.14, discriminating against validation over all group names); unknown `boundary` group name → 14.14; `boundaryKind: "spec"` naming a code-only group and `boundaryKind: "code"` naming a spec-only group (the referenced name is not of the required kind, either direction) → each 14.14; empty `targetTags` → 14.14; empty `edgeKinds` → 14.14; `edgeKinds` not a subset of `["depends", "embeds", "references"]` (7.4; an otherwise invalid profile shape, 14.14) — holding the non-dependency kind `"contains"`, an unknown token (`"depend"`), and a non-string element (`true`), one arm each → 14.14, discriminating a product that accepts and ignores a stray member or lets `contains` grant coverage (8); a non-string `targetTags` element (`[true]`) → 14.14 likewise; `boundaryKind` required when the boundary name is both a spec and a code group (absent → 14.14) and inferred when unambiguous; unknown profile name at `coverage <name>` → usage error (12.0). Set reading (7.4, 12.7): `targetTags: ["z", "a", "a"]` and `edgeKinds: ["references", "depends", "depends"]` are valid — a repeated element collapses — `inventory` reporting `targetTags` exactly `["a", "z"]` (byte order, collapsed) and `edgeKinds` exactly `["depends", "references"]` (5.2's order, however configured), and the profile's coverage report equal to its `["a", "z"]`/`["depends", "references"]` twin's (T11.6-2). * **T7.4-2 Profile semantics.** `targets` defaults to `"leaves"`; `"all"` includes internal nodes; `targetTags` restricts to nodes carrying at least one listed tag; `edgeKinds` defaults to all three and restricts paths when given (each via coverage runs, 8). -* **T7.5-1 Rule validation.** Two rules sharing a `name` → 14.14 (7.5: unique rule name); a rule lacking any one of the required `name`, `type`, `from`, or `to` fields (one fixture per field) → 14.14; `type` other than `"forbidden"`/`"allowedOnly"` → 14.14; empty `kinds` → 14.14; `kinds` not a subset of the dependency edge kinds (7.5; an otherwise invalid rule shape, 14.14) — holding `"contains"`, an unknown token (`"depend"`), and a non-string element (`true`), one arm each → 14.14; empty selector `tags` → 14.14; a non-string selector `tags` element (`[true]`) → 14.14; a selector with zero or two of `group`/`files`/`tags` → 14.14; an unknown group name in a selector → 14.14; a selector `kind` mismatching its group's kind (`kind: "spec"` naming a code-only group; `kind: "code"` naming a spec-only group) → each 14.14; ambiguous group name without `kind` → 14.14; a capture wildcard appearing more than once in `from` → 14.14 (a capture violation); `to` referencing a capture absent from `from` → 14.14. Selector globs (7: whether a glob lies outside the workspace root is decided by its spelling alone, a `files` selector's — capture-bearing patterns included — as a group's, T7-4): a rule whose `from` is `{ files: "../x/*.ts" }` and one whose `from` is the capture pattern `{ files: "a/../../$1.ts" }` (each's depth falling below zero), and one whose `to` is `{ files: "/src/*.ts" }` (a leading `/`) — one arm each, each rule otherwise valid → 14.14, exit 2, discriminating a product that vets group globs alone (the inside-root counterpart: T7.5-4). Set reading (7.5, 12.7): a rule's `kinds: ["embeds", "depends", "embeds"]` and a selector's `tags: ["b", "a", "b"]` are valid, `inventory` reporting `kinds` exactly `["depends", "embeds"]` and the selector's `tags` exactly `["a", "b"]`, and the rule's `check` findings equal to its collapsed twin's. +* **T7.5-1 Rule validation.** Two rules sharing a `name` → 14.14 (7.5: unique rule name); a rule lacking any one of the required `name`, `type`, `from`, or `to` fields (one fixture per field) → 14.14; `type` other than `"forbidden"`/`"allowedOnly"` → 14.14; empty `kinds` → 14.14; `kinds` not a subset of the dependency edge kinds (7.5; an otherwise invalid rule shape, 14.14) — holding `"contains"`, an unknown token (`"depend"`), and a non-string element (`true`), one arm each → 14.14; empty selector `tags` → 14.14; a non-string selector `tags` element (`[true]`) → 14.14; a selector with zero or two of `group`/`files`/`tags` → 14.14; a selector carrying `kind` without `group` — `{ files: "src/*.ts", kind: "code" }`, `{ tags: ["a"], kind: "spec" }`, and `{ kind: "spec" }`, one arm each → 14.14 (7.5: `kind` belongs to the group form alone; 7.6 names the violation), failing a product that vets `kind` only beside `group`; an unknown group name in a selector → 14.14; a selector `kind` mismatching its group's kind (`kind: "spec"` naming a code-only group; `kind: "code"` naming a spec-only group) → each 14.14; ambiguous group name without `kind` → 14.14; a capture wildcard appearing more than once in `from` → 14.14 (a capture violation); `to` referencing a capture absent from `from` → 14.14. Selector globs (7: whether a glob lies outside the workspace root is decided by its spelling alone, a `files` selector's — capture-bearing patterns included — as a group's, T7-4): a rule whose `from` is `{ files: "../x/*.ts" }` and one whose `from` is the capture pattern `{ files: "a/../../$1.ts" }` (each's depth falling below zero), and one whose `to` is `{ files: "/src/*.ts" }` (a leading `/`) — one arm each, each rule otherwise valid → 14.14, exit 2, discriminating a product that vets group globs alone (the inside-root counterpart: T7.5-4). Set reading (7.5, 12.7): a rule's `kinds: ["embeds", "depends", "embeds"]` and a selector's `tags: ["b", "a", "b"]` are valid, `inventory` reporting `kinds` exactly `["depends", "embeds"]` and the selector's `tags` exactly `["a", "b"]`, and the rule's `check` findings equal to its collapsed twin's. * **T7.5-2 forbidden.** An edge whose source matches `from` and target matches `to` is a finding of `check` (rule name + offending edge, exit 1); non-matching edges are not; `kinds` restricts which edges are evaluated. An offending edge spelled twice (`d={[BASE.a, BASE.a]}`, one edge, 5.2) is exactly one finding — one per rule and offending edge (14.12) — never one per spelling. * **T7.5-3 allowedOnly.** Every edge from a `from`-matching source must have a `to`-matching target; each violating edge is a separate finding. * **T7.5-4 Selectors.** `group` (with `kind` where needed) matches nodes of spec groups and code locations of code groups; `files` matches by glob, under 7's glob rules — an inside-root spelling's `.`, `..`, and empty segments matching nothing (7): on a workspace whose code source `src/a.ts` holds a marker on a node of group `product` (a `references` edge, 4.5) — each rule below on its own such workspace, built under that rule's configuration, since a configuration changed after a build may leave graph data stale (T13.4-11(a)) — a `forbidden` rule from `{ files: "./src/*.ts" }` to `{ group: "product" }` loads without error and `check` reports no policy finding, exit 0, where its twin from `{ files: "src/*.ts" }` reports that edge as a violation, exit 1 (T7.5-2) — discriminating a product that normalizes a selector glob's spelling before matching; `tags` matches nodes carrying at least one listed tag. * **T7.5-5 Captures.** `$1-$2.ts` against `a-b-c.ts` captures `a` and `b-c`; `*$1*` against `abc` captures `a`; a capture never matches `/` or the empty string; a `to` with captures matches only when expansions agree (mirror-structure policy fixture passes for agreeing pairs, violates for disagreeing ones); left-to-right shortest-match disambiguation is deterministic (repeat runs identical). Literal `$` forms (7.5: a capture is exactly `$` followed by one digit `1`–`9` — every other `$` is a literal byte in either pattern, never a capture or a capture violation): patterns containing `$0`, a trailing `$`, and `$` before a non-digit, staged in `from` and in `to` (one arm each), load without 14.14 — a `to` containing `$0` or ending in `$` references no absent capture — and match exactly the paths spelling those literal bytes: `a$0.ts` matches the file `a$0.ts` and never `ab.ts` (what a capture reading would match), and a trailing-`$` pattern matches only the `$`-suffixed name. * **T7.5-6 build vs check.** `build` succeeds and regenerates output on a workspace full of policy violations (12.1); only `check` reports them (14.12). +### 7.6 The `defineConfig` module + +7.6 is tested through H-2's module channel alone. Four rules bind every test here. + +*Placement.* The product's package directory, exactly as distributed (exactly what its distribution carries, nothing installed into it afterwards, never a development tree: H-2), is installed by placement alone — no package-manager run, install step, or network access (7.6) — under a name `N` of 7.6's grammar outside its exclusions (never an `@types` name or an `@typescript/lib-` name, and on a runtime arm never a name the release resolves to a built-in module), in a fresh staging whose ancestors H-1 has verified. The canonical placement is a copy at `node_modules/N` in the importing file's own directory, `N` a fixed unscoped, dot-free name of the harness's choosing that differs from the name the package's manifest gives — so the canonical install is an aliased one — with nothing else installed anywhere TypeScript or Node.js looks: no other package and no `@types` declarations (7.6: nothing else need be installed). T7.6-4 and T7.6-5 vary the placement. Every staging meets Reach's four conditions — nothing nearer, no self-reference, physical naming (each tool given the importing file by its physical path), and well-formed manifests — and, on a type-checking arm, 7.6's program and covered-file conditions; where a condition fails, 7.6 promises nothing, and no arm asserts anything there. + +*Covered setups.* Every type-checking arm runs in every covered setup, the matrix whole. The configuration file, the program's one root file, is named with each of `.ts`, `.mts`, `.cts`, and `.tsx` in each of three projects — an ES-module project, whose nearest `package.json` holds `"type": "module"`, and two CommonJS projects, one whose nearest `package.json` has no `type` member and one with no `package.json` at all — and TypeScript 5.9.3 judges it under each option set covering it: the fourteen strict defaults — `strict` on, with `moduleResolution` `node10` and `module` at its default; `node16` and `nodenext`, each with `module` `node16`, `node18`, `node20`, and `nodenext`; and `bundler` with `module` `es2015`, `es2020`, `es2022`, `esnext`, and `preserve` — for every file, and the initialized-project set, exactly the options 7.6 lists, for each file TypeScript compiles as an ES module (`.mts` in every project, `.ts` and `.tsx` in the ES-module one): 173 programs per arm. Every option a set does not name stays at the release's default for that set — `target` included, which the release derives from `module`, and `skipLibCheck` off under the strict defaults — so these setups are not H-2's consumer configurations, which fix `target` ESNext. No setup is sampled away: the declaration file TypeScript resolves, the module format it applies, and the library it checks against all vary across the matrix — under `module` `node16` a file TypeScript compiles as CommonJS cannot import a package that serves only an ES-module entry, while under `node20` it can. Nor is any case: every suite run checks every pairing of setup and case, the CI service's per-job limits met by splitting the suite across parallel jobs, never by trimming it (E-1). How the harness reaches each verdict is otherwise open wherever it drops no pairing and stays sound for what the case checks: parsed library files may serve many programs, and, since a file in 7's declarative form declares nothing outside its own module, the files a setup and placement share — the libraries and the package's — may be checked once, with the program's options and global diagnostics, and each case's verdict read from its configuration file's own diagnostics beside theirs. + +*Verdict.* A file type-checks when TypeScript reports no error for its program, in any of the program's files (7.6): options, global, syntactic, semantic, and declaration diagnostics alike, the last arising wherever a set turns `declaration` on, as the initialized set does — there, a package whose `defineConfig` returns an interface it does not export fails a valid file's default export through a declaration diagnostic alone (TS4082). A file fails to type-check, as a shape-violation arm asserts, when TypeScript reports at least one error located in the configuration file, the program's other files aside, its locations, messages, and count unpinned (7.6). Compiler output, where any is written, lands outside the staging. + +*Pairing.* No assertion here stands as a bare negative. A shape-violation arm passes only where its valid twin — the same file without the violation — type-checks in the same setup and placement, and an absence a runtime arm asserts (no output, write, or change) only where the same run loaded the module and saw `defineConfig` return its argument. So a missing or stub package fails every arm (H-8, S-7), and a permissive one — its `defineConfig` declared to take `any` — fails the shape-violation arms. + +* **T7.6-1 Declared exports.** In every covered setup, the module TypeScript resolves the covered file's import to declares exactly one export, `defineConfig`, carrying a value meaning and neither a type nor a namespace meaning, and no other export, type-only or not (7.6). The exports are read from TypeScript's own resolution of that import in that program — the compiler's listing of the module's exports together with, where the module declares an export assignment (`export =`), the members of the assigned value that a named import binds, each with its meanings, every name included — never probed by names the harness chooses: a declaration module holding neither an export list (`export {}`) nor an export assignment exports each of its top-level declarations, an interface it never marks `export` among them, which only such a listing sees; and a module whose export assignment assigns a value carrying `defineConfig` alone — the typing of a CommonJS entry, whose `require` result 7.6's runtime contract reads by its own properties — declares that one export, though the compiler's listing of its exports proper is empty. Each setup is read through its own resolution, so a package serving different declaration files to `import` and to `require`, or to different resolution modes, is checked through each. TypeScript's synthetic default is no declared export (7.6): a default import of the module that type-checks only through TypeScript's interoperation with CommonJS — in a file TypeScript compiles as CommonJS, or of a module declaring an export assignment — is no violation, while a declared default export is one. +* **T7.6-2 Valid configurations.** Each of these covered files, valid under 7 — `defineConfig` imported by its identifier and bound to a name strict module code admits, never `require` or `exports`; no `\` outside its comments; no comment TypeScript reads as a directive or pragma (7.6) — type-checks in every covered setup: (a) every key and field 7 defines present, and every value 7 enumerates at each of its positions — `specs` and `code` with two groups each, `markdown` with `emit` `true` and `outDir`, two profiles each carrying `name`, `target`, `targetTags`, `targets`, `boundary`, `boundaryKind`, `mode`, and `edgeKinds`, between them `targets` `"leaves"` and `"all"`, `boundaryKind` `"spec"` and `"code"`, and `mode` `"direct"` and `"transitive"`, and rules of both `type`s carrying `kinds`, their selectors in all three forms, the group form without `kind` and with each of `"spec"` and `"code"` — each of `"depends"`, `"embeds"`, and `"references"` an element of a profile's `edgeKinds` and of a rule's `kinds`; (b) (a)'s file with `defineConfig` imported under an alias and every key spelled as a string literal; (c) (a)'s file with line and block comments before the import, between keys, inside lists, and after the export; (d) the minimal configuration, `specs` holding no group; and (e) group names spelling the members of TypeScript's global `Object` interface — `constructor`, `toString`, `toLocaleString`, `valueOf`, `hasOwnProperty`, `isPrototypeOf`, and `propertyIsEnumerable` — and `__proto__`, as spec and code group names, spelled as identifier keys in one file and as string-literal keys in another, each referenced as a profile's `target` or `boundary` and as a selector's `group` (with its kind where a name is both a spec and a code group's), and profiles and rules so named; and (f) the empty, omitted, and repeated forms 7 admits — in one file, `code: {}`, `coverage: []`, `policy: []`, and `markdown: { emit: false }` beside a `specs` group; in another, a file like (a)'s with every optional field omitted — `markdown` without `outDir`, each profile carrying only `name`, `target`, `boundary`, and `mode`, each rule without `kinds`, and each group selector without `kind`, its group names unambiguous so that no kind is required (7.4, 7.5); and in a third, (a)'s file with one spec group's and one code group's glob list empty (`[]`: 7 bars an empty list only for `targetTags`, `edgeKinds`, a rule's `kinds`, and a selector's `tags`, 14.14) and an element repeated in each list 7.4 and 7.5 read as a set — `targetTags`, `edgeKinds`, a rule's `kinds`, and a selector's `tags` (a repeated element collapses; T7.4-1, T7.5-1). A `defineConfig` type that lacks an admitted value, narrows `emit` to one boolean (`true` in (a), `false` in (f)), demands a non-empty `coverage`, `policy`, or glob list or a set-read list free of repeats, or requires an optional field fails here. +* **T7.6-3 Shape violations.** In every covered setup, each of these files — T7.6-2(a)'s file with one violation of 7.6's type-error class applied, that file its valid twin — fails to type-check: an unknown key at the top level, in `markdown`, in a profile, in a rule, and in a selector; each missing required key — `specs`, `markdown`'s `emit`, a profile's `name`, `target`, `boundary`, and `mode`, and a rule's `name`, `type`, `from`, and `to`; at every position to which 7 gives a kind — `specs`, `code`, and each group; a group's glob elements; `markdown`, `emit`, and `outDir`; `coverage`, each profile, each profile field, and each element of its lists; `policy`, each rule, each rule field, and each element of `kinds`; and each selector, each selector field, and each element of its `tags` — each kind among a boolean, a string, a list, and an object that 7 does not admit there (`specs: ["a/*.mdx"]`, `emit: "true"`, `targetTags: "a"`, `kinds: [true]`, `from: "src/*.ts"`); a string outside the values 7 enumerates, at each enumerated position — `targets`, `boundaryKind`, `mode`, `type`, a selector's `kind`, and an element of `edgeKinds` and of a rule's `kinds` — near misses among them (`"Direct"`, `"depend"`), and, as an element of `edgeKinds` and of a rule's `kinds`, `"contains"`, the edge kind 5.2 defines and 7.4 and 7.5 leave out, which a type built on every edge kind admits; each selector-form violation — each two of `group`, `files`, and `tags` together, all three, none (`{}`), and `kind` without `group`, beside `files`, beside `tags`, and alone; each forbidden empty list — `targetTags`, `edgeKinds`, a rule's `kinds`, and a selector's `tags`; and one file holding several of these violations at once. Configuration errors outside the class — cross-references between names, the name and character rules, globs outside the root, a key repeated within one object literal, the capture rules, and a file in both a spec and a code group — carry no type-level requirement either way (7.6): no arm stages one for a verdict. +* **T7.6-4 Placements.** Each placement below stands in for the canonical one in a run of T7.6-1, of T7.6-2(a) with T7.6-3's unknown-top-level-key arm paired to it in every covered setup, and of T7.6-6's exports and identity assertions along every route on every release E-1 provisions, and fares as the canonical placement does (7.6: copy, symbolic-link, and aliased installs are alike): (a) a copy under the `name` the package's manifest gives — the non-aliased install — wherever that is a name of 7.6's grammar outside its exclusions; (b) `node_modules/N` a symbolic link to a copy of the package directory placed elsewhere in the staging, under no `node_modules`; (c) names across 7.6's grammar — a scoped name, a name beginning with a digit, a name holding `-` and `_`, the dotted names `a.js` and `a.b`, whose `S` differs from `N` (each beside an unrelated package at `node_modules/a`, which Reach does not bar, and no `a.ts` beside `a.js`), and an unscoped and a scoped name each exactly 214 characters long; (d) the holding directory a strict ancestor of the importing file's directory, and, separately, an ancestor of the file's physical path alone — the file's directory also reachable through a symbolic link elsewhere in the staging, on whose path that ancestor does not lie — each tool given the physical path (7.6: the holding directory is read along it); and (e) other packages installed — TypeScript 5.9.3's package at `node_modules/typescript` and an unrelated package beside the placement, and, the holding directory a strict ancestor, an unrelated package in the importing file's own directory — none of them an `@types` package, which TypeScript would add to the program (7.6's program condition); and (f), in the type-checking runs alone — T7.6-1, and T7.6-2(a) with its paired arm — `N` `fs`, and separately `path`, names a provisioned release resolves to built-in modules: 7.6 excludes such a name from Node.js's resolution and the runtime contract alone, so TypeScript's route covers it, and no runtime arm stages it (the Placement rule). +* **T7.6-5 Reach's open cases.** Stagings meeting every condition of Reach while leaving open what none of them bars, each run as T7.6-4's placements are: (a) an ancestor `package.json` whose `name` (`"unrelated"`) TypeScript and Node.js read as neither `N` nor a leading part of it; (b) an ES-module project beneath an ancestor `package.json` holding `"type": "commonjs"`, and a CommonJS project — its nearest `package.json` without `type` — beneath an ancestor holding `"type": "module"`; and (c) a nearest `package.json` holding `"type": "commonjs"`. +* **T7.6-6 Runtime exports and identity.** On each Node.js release E-1 provisions — a release of 22.0–22.11, on which `require` cannot load an ES module without a flag, among them — run with no option, no environment variable (`NODE_OPTIONS` and `NODE_PATH` among them), no user condition, and no loader or customization hook that changes how modules are resolved or loaded (7.6), the module is loaded along each of Node.js's routes from a harness-written importing module in the importing file's place: a static `import` from an ES module (`.mjs`), a dynamic `import()` from an ES module and from a CommonJS module (`.cjs`), and `require` from a CommonJS module. In each run: (a) exports — an `import` namespace's own string-keyed properties are exactly `defineConfig`, failing, for one, a CommonJS-only entry, whose namespace carries `default`; and a `require` result's own enumerable properties, string- and symbol-keyed alike, are exactly `defineConfig`, failing an enumerable `__esModule`; (b) identity — `defineConfig(v)` returns `v` itself, compared by SameValue, for an object, an array, a function, a symbol, `null`, `undefined` passed explicitly, a string, a boolean, a bigint, and the numbers `0`, `-0`, and `NaN`; a call with no argument returns `undefined`; and a call with further arguments returns its first; and (c) no examination, copy, or modification — called with a first argument that is a Proxy over a function whose every trap records its invocation, and a second argument likewise, `defineConfig` returns the first Proxy itself with no trap invoked; and called with a frozen object, it returns that object without throwing. +* **T7.6-7 Runtime: no effect.** In T7.6-6's runs, beyond the runtime's own resolution of the specifier and loading of the package's files, loading the module and making T7.6-6's calls have no effect (7.6): (a) output — standard output is empty, and standard error is exactly the release's printed forms of the process warnings the run emits, in order, as the runtime delivers them to a `warning` listener registered on `process` before the importing module's own loading begins — on the static-`import` route every static dependency is resolved, loaded, and evaluated before any of the importing module's own code runs, and a warning the runtime raises meanwhile (DEP0151's along `import`) may reach listeners before then too, as the release schedules its delivery, so harness-written code registers the listener and only then loads the importing module, by its physical path — each printed as the release prints its own: `(node:<pid>)`, the warning's bracketed code where it carries one, its type, its message, which may span lines, and its detail where it carries one, the first warning followed by the hint line the release appends to it — and no captured warning's stack begins in the package's files, its first frame naming one of them. The release emits warnings of its own in resolving the specifier and loading the package's files, whatever the package's manifest and layout draw — the experimental warning for loading an ES module through `require`, on a release that emits one, and deprecations of manifest forms, such as DEP0128's invalid `main` beside an `index.js` along `require` and DEP0151's `main` lookup along `import` — each created in the runtime's own code, its stack beginning outside the package's files, so 7.6's exception admits them; a warning the module emits through the runtime's warning facility begins its stack in the package's files, and text the module writes to standard error, in the warning form or not, has no captured warning behind it, so each fails, as does every other byte; the importing module reports its observations outside both streams and every compared path; (b) writes — no entry is created, modified, or removed in the staging, the package's placement included, in the working directory, or in the fresh `HOME` and `TMPDIR` each run is given, each compared entry by entry before and after, a plain file by its bytes as well and a FIFO, as (e)'s are, by its kind alone, never opened (S-3); (c) process state — unchanged across the load and the calls, observed as the global object's own properties with their descriptors (read without invoking accessors), the own properties of the global built-in constructors and namespace objects and of those constructors' prototypes, the extensibility and the prototype of each of these objects, the global object included, `process`'s own properties with their descriptors (read likewise), `process.env`, the process title, the working directory, `process.exitCode`, the `write` each of `process.stdout` and `process.stderr` resolves to, the listeners registered on `process` — (a)'s `warning` listener among them, registered before the state is first read, and both before the importing module's own loading begins ((a)) — and the pending timers and handles the runtime reports — none left to keep the process alive, each run ending on its own once its importing module completes — a set S-10 confirms the stand-ins' loads leave unchanged; (d) network — every run network-denied (E-1), an attempted access failing rather than reaching a network; and (e) reads — FIFOs named `xspec.config.ts` in the working directory, in the importing module's directory, and in `HOME`, each afterwards still a FIFO and unopened, every run ending within its guard (S-3). The rest of the read, write, network, state, and output clauses admits no discriminating staging (recorded here as T6.5-6 records its unstageable clauses): a read of any other path outside the package, a write outside the staging, the working directory, `HOME`, and `TMPDIR`, a network attempt the module itself swallows, and a change to process state that none of (c)'s observations reflects — the runtime's internal state, or state a native addon keeps — reach nothing the module channel observes, no test observing a system call (S-3); and a change to a standard stream's own properties other than its `write`, which the release's own warning output changes too, and a warning the module causes whose stack begins outside the package's files — one the runtime creates in its own code for a built-in the module uses (the experimental-feature warning of a built-in module it loads), or one the module emits with its own frames cut from the stack — are told apart from the release's own changes and warnings by nothing the channel observes, no test observing which code caused a change or a warning. + ## 8. Coverage * **T8-1 Direct mode.** A single dependency edge from a boundary node to the target covers it; a two-edge path does not. @@ -507,7 +530,7 @@ Tests here drive `occurrences`, `view`, and `at`; the per-surface contracts are * **T12.0-3 --config.** Every command accepts `--config <path>`; a relative path resolves against the working directory, not the workspace root. * **T12.0-4 Flag repetition.** Repeating a flag on any command → exit 2; list-valued flags take one comma-separated value (`--kinds depends,embeds`). * **T12.0-5 Argument addressing.** `<node>`, `<graph-node>`, `<file>`, and `--file` arguments are workspace-relative with `/` separators, independent of the working directory (run each representative command from a subdirectory — `move` among them, its destination naming a path nothing need occupy: run from `specs/`, the file form `move specs/A.mdx specs/B.mdx` relocates the file to the workspace-relative `specs/B.mdx`, and, on a fresh copy, the section form `move specs/A.mdx#a specs/C.mdx#a` creates its target file at `specs/C.mdx` — never at `specs/specs/…`, where a product reading the destination against the working directory writes it); `--test-hold <path>` resolves against the working directory (13.5). Native-separator and normalization negatives (12.0: read as spelled, compared byte-wise, no normalization): an argument spelled with `\` (`specs\A.mdx`), with a `.` segment (`./specs/A.mdx`), or with an empty segment (`specs//A.mdx`) names no workspace file — discovered paths carry no `.` or empty segment (7), and `\` is an ordinary byte, no separator, so `specs\A.mdx` names only a discovered file of that very path, none staged here, never `specs/A.mdx` (12.0) — and is an unknown-file usage error, exit 2 (`show` and `view` as representatives); the `\` arm discriminates on the Windows leg (E-6), where `\` is the native separator, the other two on either leg. The positive side of `\` (12.0; Linux leg, where a file name can hold it): with a discovered spec-group file `specs/a\b.mdx` staged — an invalid source path (condition 19, 7.1) — `view 'specs/a\b.mdx'` and `at 'specs/a\b.mdx' 0` name that file, membership holding and its identities unavailable, exit 1 with the condition-19 finding (T11.2-3), never the unknown-file exit 2 — as T12.0-13 does for `#`; and with a valid code source `src/a\b.ts` staged beside `src/ab.ts`, each marking a node, `occurrences --file 'src/a\b.ts'` lists the first file's occurrence alone and `occurrences --file 'src/a\*.ts'` likewise — `\` a literal byte of the pattern, never an escape of `*` (7) — where a product reading it as an escape matches neither file (the configured-glob twin: T7-4). Malformed values (12.0, the value-level rule): an argument value that is not valid UTF-8 (raw bytes in the OS argument vector, Linux leg) → usage error, exit 2; an argument value containing U+FFFD — stageable on both legs — → usage error, exit 2, in every position: a `<node>` (`show 'specs/A.mdx#a�'`), a `<file>` operand (`view 'specs/A�.mdx'`), a `--file` glob, a `--tag`, a `--to`, a `<new-id>` (`rename specs/A.mdx a 'b�'`, never `refused-invalid-id`, 6.4), a session name, a `--note` text, a `--base` ref, and a `--config` or `--test-hold` path (the free-text and foreign values 12.0 names as the only ones ever refused for a genuine U+FFFD) — each of the syntax class, reported without loading configuration (T12.0-10), the error document's `code` `null`. -* **T12.0-6 Case and bytes.** IDs, tags, identities, session names, and paths compare byte-wise case-sensitively: `A.mdx` vs `a.mdx` identities are distinct; `--tag Foo` does not match `foo`; no Unicode normalization (NFC vs NFD spellings of one tag are two tags). Single-casing path probe, stageable on any filesystem: in a workspace whose only source is `specs/A.mdx`, an argument `specs/a.mdx` (`show`, representative) names no workspace file — paths compare byte-wise — and is an unknown-file usage error, exit 2; rerun on the Windows leg (E-6), where a product resolving path arguments through case-insensitive filesystem lookups wrongly finds the file. Every suffix and name test SPEC.md applies to a path or specifier is case-sensitive alike, each probed in a single casing: the `.mdx` extension of 7.1, of a discovered file (T7.1-1's `specs/A.MDX`) and of a move destination (T6.5-4's `specs/B.MDX`); a specifier's `.xspec` ending in either kind of source (T2.1-2's `./B.XSPEC`; T4-2's `../specs/B.XSPEC`, an import declaration's and an export declaration's); the configuration's `"xspec"` specifier (T7-2's `"XSPEC"`); 13.4's `.xspec.` file name, in the source exclusion (T7-6's `src/a.XSPEC.ts`) and in 4's derived-file designation (T4-2's `../specs/NAME.XSPEC.ts`); the graph-data area's name `.xspec`, in 13.4's exclusion (T7-6's `.XSPEC/a.ts`), in 4's designation (T4-2's `../.XSPEC/x`), and in 7.3's `outDir` bar (T7.3-1's `.XSPEC` and `.XSPEC/md`); 4.6's declaration-file names (T4.6-3's `x.D.ts`, `x.d.TS`, `x.d.MTS`, and `x.d.CTS`); the configuration file's name in 7's upward search (T7-1's `XSPEC.config.ts`, rerun on the Windows leg, E-6); the `.tsx` grammar selection of 14.20 (T14-5's `src/x.TSX`); and a session file's `.json` (T10.1-3's `NAME.JSON`). The exceptions are exactly 12.0's two: the create-time session-name collision (T10.1-2) and 6.5's match of a JSX pragma's name regardless of ASCII case (T6.5-22's `/* @JSX h */` arm). Byte order where UTF-16 code-unit order departs from it: T12.0-16. +* **T12.0-6 Case and bytes.** IDs, tags, identities, session names, and paths compare byte-wise case-sensitively: `A.mdx` vs `a.mdx` identities are distinct; `--tag Foo` does not match `foo`; no Unicode normalization (NFC vs NFD spellings of one tag are two tags). Single-casing path probe, stageable on any filesystem: in a workspace whose only source is `specs/A.mdx`, an argument `specs/a.mdx` (`show`, representative) names no workspace file — paths compare byte-wise — and is an unknown-file usage error, exit 2; rerun on the Windows leg (E-6), where a product resolving path arguments through case-insensitive filesystem lookups wrongly finds the file. Every suffix and name test SPEC.md applies to a path or specifier is case-sensitive alike, each probed in a single casing: the `.mdx` extension of 7.1, of a discovered file (T7.1-1's `specs/A.MDX`) and of a move destination (T6.5-4's `specs/B.MDX`); a specifier's `.xspec` ending in either kind of source (T2.1-2's `./B.XSPEC`; T4-2's `../specs/B.XSPEC`, an import declaration's and an export declaration's); 13.4's `.xspec.` file name, in the source exclusion (T7-6's `src/a.XSPEC.ts`) and in 4's derived-file designation (T4-2's `../specs/NAME.XSPEC.ts`); the graph-data area's name `.xspec`, in 13.4's exclusion (T7-6's `.XSPEC/a.ts`), in 4's designation (T4-2's `../.XSPEC/x`), and in 7.3's `outDir` bar (T7.3-1's `.XSPEC` and `.XSPEC/md`); 4.6's declaration-file names (T4.6-3's `x.D.ts`, `x.d.TS`, `x.d.MTS`, and `x.d.CTS`); the configuration file's name in 7's upward search (T7-1's `XSPEC.config.ts`, rerun on the Windows leg, E-6); the `.tsx` grammar selection of 14.20 (T14-5's `src/x.TSX`); and a session file's `.json` (T10.1-3's `NAME.JSON`). The exceptions are exactly 12.0's two: the create-time session-name collision (T10.1-2) and 6.5's match of a JSX pragma's name regardless of ASCII case (T6.5-22's `/* @JSX h */` arm). Byte order where UTF-16 code-unit order departs from it: T12.0-16. * **T12.0-7 Determinism.** Representative sweep: `build` outputs, generated files, graph data, Markdown, journal entries, session files, and every report are byte-identical across repeated runs and across content-identical workspaces at different absolute paths (no wall-clock, randomness, absolute paths, or environment leakage; run with differing irrelevant environment variables) — the lock directory's entries excepted, coordination state outside the rule (12.0, 13.4; H-4, H-6), none of which a run ending normally leaves behind. * **T12.0-8 Shortest-path tie-break.** Where one shortest path is reported (coverage 8.2, impact 9.3, reachable 11), among equal-length candidates the element-wise byte-least node-identity sequence is reported (dedicated fixtures per command). * **T12.0-9 Exit-code partition.** A table-driven sweep asserting one representative per class per command family: 0 (success and informational reports: `ids`, `show`, `impact` with differences, `query`, review reads including fully-resolved `next`, `coverage` without `--check`, `version`, and complete finding-free answers — `occurrences`/`view`/`at` over a clean domain, `inventory`, a successful preview; 11.2, 11.6, 6.6); 1 (findings: failing `build`, `check` findings, `coverage --check` uncovered, refused `rename`/`move` and their refused previews, refused review operations, corrupt-session reports, and answers carrying findings or explicitly-unavailable data — emitted in full; 11.2, 11.6, 6.6); 2 (usage/configuration: unknown command; unknown flag; missing required flag/argument; invalid flag value; unknown profile/session/group/item/node/file — except `occurrences --to`, where only a malformed spelling is a usage error, T11.3-3; wrong-kind operands — a code source where a spec source or a requirement-node identity is required; invalid session name; configuration errors; unreadable baseline; a mutating command refused at acquisition, its workspace busy (13.5, 14.26; T13.5-2); a write the environment refuses, 14.24, T14-9; a read it refuses, 14.25, T14-10). @@ -564,7 +587,7 @@ Assertions here — and wherever these forms appear across the suite — are for ### 13.1 Generated TypeScript * **T13.1-1 Layout.** `NAME.mdx` generates `NAME.xspec.ts` in the source file's directory, plus companions each named `NAME.xspec.<suffix>`; every generated file carries `.xspec.` in its name; the set is recorded such that later builds remove orphans (T12.1-3). -* **T13.1-2 Standalone consumption.** In a consumer project with only standard TypeScript tooling installed (no xspec runtime dependency), in each configuration H-2 fixes: `import SPEC, { text } from "./NAME.xspec"` resolves; the consumer's program — the generated module and every companion it reaches included — type-checks with no diagnostic, so a module form either configuration rejects fails here whatever the other accepts (an export or import assignment under ECMAScript-module output, a type re-exported through `export { … } from` without a `type` modifier under `isolatedModules`; H-2); type checking (4.1) and hover and go-to-definition (4.2) work; and, in the CommonJS configuration, runtime `text`/markers (4.3–4.5) work. This is the umbrella E2E for section 4's consumer tests. +* **T13.1-2 Standalone consumption.** In a consumer project with nothing installed in or above it — the standard TypeScript tooling being the harness's own, run against the project — so that it has no runtime dependency on xspec, its `defineConfig` module included (nothing resolvable from the consumer's location by package name, no copy of the product's package under any name least of all — H-2, verified as H-1 states), in each configuration H-2 fixes: `import SPEC, { text } from "./NAME.xspec"` resolves; the consumer's program — the generated module and every companion it reaches included — type-checks with no diagnostic, so a module form either configuration rejects fails here whatever the other accepts (an export or import assignment under ECMAScript-module output, a type re-exported through `export { … } from` without a `type` modifier under `isolatedModules`; H-2); type checking (4.1) and hover and go-to-definition (4.2) work; and, in the CommonJS configuration, runtime `text`/markers (4.3–4.5) work. This is the umbrella E2E for section 4's consumer tests. ### 13.2 Markdown output @@ -635,7 +658,7 @@ Sections 1–13 exercise each numbered condition in its home context; this secti ## 16. Property-Based and Fuzz Tests -Property tests generate inputs from seeded, reproducible generators (H-10), assert spec-derived invariants, and shrink failures — a hang excepted, which ends its property unshrunk (S-3). Each property is also anchored by the deterministic fixtures of sections 1–15; properties exist to search the input space, not to replace them. Except where a property stages invalid or imperfect input by design — P-1's invalid draws, P-8, P-11 — generated workspaces are valid by construction and generated edits preserve validity: the generators follow the grammar of 2 (prose bytes that open no construct — no `<`, `{`, or import-like line — well-formed sections with structurally valid IDs whose segments and tags draw from 1.4's valid alphabet — `"`, `'`, `\`, `&`, U+2028, U+2029, and U+FFFD excluded — spec-group paths free of the characters 7.1 bars there (`"`, `'`, `\`, U+000A, U+000D, U+2028, U+2029; 14.19), resolving imports and references, each reference segment spelled with dot access only where 1.4's identifier test admits it — TypeScript 5.9.3's identifier characters at ESNext, which ECMAScript 2024 admits alike (1.4) — and otherwise as computed access with a static string literal (2.4), so that no draw's derivability depends on a Unicode version past 15.1, whose well-formedness 14.20 leaves unfixed (S-9)) and compose in-line constructs only as the MDX grammar derives them (14.20; T3-3's staging constraint): an in-line section, tag, or expression container spans paragraph-continuation lines alone — no blank line, no line beginning a construct that interrupts a paragraph, no line holding tags or expression containers alone — an in-line section closes within its paragraph, and P-5 draws a multi-line in-line section for a move only in the shapes T6.2-3 stages — its boundary lines agreeing, both flow-position or both text-position at the destination, never the one-sided spellings 6.2 and 6.5 refuse; S-9 verifies before any product exists that every composed form derives, and each draw is checked the same way before the product is driven on it, a failing draw reported as a harness error with its seed (H-10, H-11's rule), never as a product failure and never as a draw to skip — so every oracle here is evaluated over documents that build and a generator artifact never surfaces as a product failure. Validity being guaranteed by construction, a `build` failure on a draw is a product failure, reported with its seed (H-10), never a draw to skip: conditioning the properties on exit 0 instead would let a rejecting product pass them vacuously. +Property tests generate inputs from seeded, reproducible generators (H-10), assert spec-derived invariants, and shrink failures — a hang excepted, which ends its property unshrunk (S-3). Each property is also anchored by the deterministic fixtures of sections 1–15; properties exist to search the input space, not to replace them. Except where a property stages invalid or imperfect input by design — P-1's invalid draws, P-8, P-11, P-18's violating mutants — generated workspaces are valid by construction and generated edits preserve validity: the generators follow the grammar of 2 (prose bytes that open no construct — no `<`, `{`, or import-like line — well-formed sections with structurally valid IDs whose segments and tags draw from 1.4's valid alphabet — `"`, `'`, `\`, `&`, U+2028, U+2029, and U+FFFD excluded — spec-group paths free of the characters 7.1 bars there (`"`, `'`, `\`, U+000A, U+000D, U+2028, U+2029; 14.19), resolving imports and references, each reference segment spelled with dot access only where 1.4's identifier test admits it — TypeScript 5.9.3's identifier characters at ESNext, which ECMAScript 2024 admits alike (1.4) — and otherwise as computed access with a static string literal (2.4), so that no draw's derivability depends on a Unicode version past 15.1, whose well-formedness 14.20 leaves unfixed (S-9)) and compose in-line constructs only as the MDX grammar derives them (14.20; T3-3's staging constraint): an in-line section, tag, or expression container spans paragraph-continuation lines alone — no blank line, no line beginning a construct that interrupts a paragraph, no line holding tags or expression containers alone — an in-line section closes within its paragraph, and P-5 draws a multi-line in-line section for a move only in the shapes T6.2-3 stages — its boundary lines agreeing, both flow-position or both text-position at the destination, never the one-sided spellings 6.2 and 6.5 refuse; S-9 verifies before any product exists that every composed form derives, and each draw is checked the same way before the product is driven on it, a failing draw reported as a harness error with its seed (H-10, H-11's rule), never as a product failure and never as a draw to skip — so every oracle here is evaluated over documents that build and a generator artifact never surfaces as a product failure. Validity being guaranteed by construction, a `build` failure on a draw is a product failure, reported with its seed (H-10), never a draw to skip: conditioning the properties on exit 0 instead would let a rejecting product pass them vacuously. * **P-1 Segment/tag validity.** Generator over code points (weighted toward boundaries: whitespace/control classes of 1.4, U+00A0/U+0085 — valid, in neither class — U+2028/U+2029 — in neither class, yet invalid under 1.4's quote-and-escape bullet — `.`/`#`, the quote, escape, and character-reference characters `"` `'` `\` `&` and U+FFFD — each invalid, 1.4 — forbidden names, and glob metacharacters of common dialects — `[` `]` `{` `}` `!` `+` `(` `)` — which are ordinary valid segment characters): the segment property judges the staged spelling's resulting split — a draw containing `.` can be spelled as no single segment (1.4: `.` is the ID separator) and stages as that many segments, its bearer nested beneath the ancestor chain the split's prefixes spell, so the structural rule holds whenever the segments are valid (a `.`-free draw stages as one top-level segment; structural-rule outcomes are T1.3-2..4's, never this oracle's) — asserting acceptance by `build` iff every resulting segment satisfies 1.4; likewise tags, with `.` allowed and whitespace never reaching tag validation — a generated value containing whitespace stages as multiple tags (2.6 splits on runs of whitespace), so the tag property asserts acceptance iff every resulting token satisfies 1.4 (zero tokens: accepted as an omitted prop, T2.6-2). Staging discipline (2.7, 2.4: an `id` or `tags` value is a plain single- or double-quoted static string read verbatim, no escape or character-reference form being interpreted): each draw is spelled in the quote kind its content admits — double quotes for a draw containing `'`, single quotes for one containing `"`, either otherwise — and since 1.4 makes every draw containing `"` or `'` invalid, such a draw is staged in the other quote kind and predicted rejected (14.4), never set aside; a draw containing both quote characters admits no static-string spelling and is not staged — invalid under the oracle too, so its exclusion loses no prediction. That the product accepts both quote kinds alike is T2.7-3's deterministic question, not this generator's. * **P-2 Markdown compilation.** Random documents composed of prose blocks — fenced code blocks and inline code spans spelling tag-, import-, and expression-like bytes included (T3-1's grammar boundary: such bytes are content) — nested sections, imports — ESM blocks carrying JavaScript comments beside their imports, content under 3 (T3-7) — comments in every form of 2.7 (`{/* … */}` single- and multi-line, `{}`, block-comment sequences, line-comment containers, and the run-on `{// c}` form, T2.7-4) with ECMAScript-only whitespace between braces, drawn from U+FEFF, U+2028, U+2029, and every Unicode 15.1 space separator but U+0020 (U+00A0, U+1680, U+2000 through U+200A, U+202F, U+205F, and U+3000; 14.20, T2.7-4), and embeddings with whitespace and comments beside the call — block comments before and after it, a line comment before it, and the run-on `{// c}` form holding the call (T2.3-3) — over mixed line terminators, with content weighted toward the whitespace/non-whitespace boundary code points of 1.4 (U+00A0, U+0085, and U+2028 included): compiled output equals an independent oracle implementing the removal/replacement/line-drop rules of 3 (the oracle lives in the harness); compilation is deterministic; content bytes outside removed constructs are preserved. @@ -653,26 +676,30 @@ Property tests generate inputs from seeded, reproducible generators (H-10), asse * **P-14 Sources vanishing under reads.** 14.25: a discovered source found absent when its content is read — removed or relocated since discovery — reads as undiscovered, as though discovery had not yielded it (T13.5-12's unstageable clause). Random valid workspaces holding a spec source that no other file references — and, in a second series, a code source a configured code group matches that no other file imports, holding a marker on a section of a spec source (4.5), so that its presence changes `occurrences`' answer, `build`'s graph data, and the graph data the `rename` below regenerates — the flipped source, in either series, referencing no identity the `rename` below renames, which so rewrites no flipped path; while refreshing reads (`ids`, `query nodes`, `occurrences`, and `view` of another file — and, in the spec-source series, `view` of the flipped source and `at` of it at a within-file offset, each naming it as its `<file>` operand) run repeatedly and concurrently, that source is repeatedly removed or relocated outside every group's globs and then restored, each change one atomic rename, so no partial file ever stands at a discovered path: each read's exit code and standard output equal those of a quiescent run on the workspace with the source present or of one with it absent — never a `read-failure` for the vanished file and never a crash. A read naming the flipped source answers, with it absent, the unknown-file usage error (12.0; 11.4, 11.5: exit 2, `code` `null`), never condition 20 for it at offset 0 — 14.25's outcome for a source whose content read the environment refuses — failing a product that, its operand check passed, reads the named file by its path and takes the file's absence for a refused read. `build` and `check` are driven likewise, each run alone — no other xspec command beside it — from the workspace built quiescently with the source present, while the source flips: `build`'s exit code, standard output, and the derived files and graph data it leaves together equal those of one quiescent `build` from that state, with the source present or with it absent (H-6); `check`'s exit code and standard output equal those of one quiescent `check` on that state, with the source present or absent; neither ever reports a `read-failure` for the vanished file or crashes. The mutating commands are driven likewise, as T13.5-12 defers to this property: a `rename` of a section in another file and a `review create --strategy audit --name n`, each run alone on a fresh copy of that built workspace while the source flips — their content reads following the rediscovery of 13.5 — each run's exit code, standard output, and the files it leaves — sources, journal, session, derived files, and graph data, the paths the harness flips aside — equal those of one quiescent run of the same command from that state with the source present or with it absent (H-6), never a `read-failure` for the vanished file and never a crash. * **P-15 Leftover trees.** 13.5: acquisition removes every leftover in the lock directory — everything there but its own entry, a directory with all it holds and a symbolic link itself, never its target — and reads no file's content; T13.5-10(b)'s fixed trees anchor this property. Seeded random leftover trees are staged in `.xspec/lock` on a freshly built valid workspace holding an `audit` session `s` created while it was valid: varied depth and breadth; names beginning with `.` and, on the Linux leg, names that are not valid UTF-8; plain files with every permission removed; symbolic links to files and to directories outside the workspace, and dangling ones; and FIFOs — the lock directory's own top level holding no plain file (T13.5-10(b): such a file may read as an entry in 13.5's gap, which MAY refuse), and every generated directory listable, searchable, and writable, so the outcome is never 14.25's or 14.24's (T13.5-10(d)). Each draw runs one mutating command drawn from `rename`, `move`, `review create`, `resolve`, and `split`, an operation succeeding on a leftover-free twin, under `--json`: it completes promptly, no FIFO opened, and exits 0 with its result byte-equal to the twin's, `.xspec/lock` absent once it ends, every link's target outside the workspace byte-identical afterward and nothing written through a link (13.4) — failing a product whose removal skips names beginning with `.`, mis-decodes a name that is not valid UTF-8 and so cannot remove it, stops short of a tree's depth, or follows a link. * **P-16 path-blocks generation.** 10.5 pins `path-blocks` generation combinatorially — visiting and skipping, roots visited as N (T10.5-8), node links — a deleted node under its baseline parent through the journal, a present node under its current parent, also where a section move has given it a new one (T10.5-9) — each kind's scope, context, and origin with the `d`-target counting rule (T10.5-3), impact edges of both kinds (T10.5-7), blocking chains (T10.5-2), and the total order (T10.5-4) — and the deterministic fixtures sample it pointwise. Random valid workspaces of spec and code sources — nested sections, `d` references, `{text(...)}` embeddings (root-sourced ones included), `coverage` and `tags` attributes, and code locations bearing markers and `text(...)` calls — are committed as a baseline and then changed by P-6's random interleavings of edits (own-text, metadata, and embedding edits, section and file additions and deletions, and child reorders), journaled renames, and journaled moves of both forms, the section-form ones drawn under P-5's discipline (its constraints on the workspaces they move within included; every draw a move the product performs) and including moves into another parent, which leave the moved node's current parent other than its baseline parent (10.5); `review create --base` against that baseline yields exactly the items an independent oracle of 10.5 derives from P-6's graph-diff oracle (its categories with their originating nodes, identities mapped through the journal suffix, and 9.2's impacted code over impact edges in either graph): the same kinds and scope nodes; each item's scope set, context, and origin exactly; each item's `blockedBy` as the set of the kinds and scope nodes of the items it names; and the item order of 10.5 — scope nodes compared as canonical identities (10.4) and presented under their current identities. `reason` (informational, 10.2) and the recorded hashes are not compared. The oracle passes its own fixed vectors before the property trusts it (S-6). +* **P-17 Installation names (7.6).** Seeded draws of `N` from 7.6's grammar — unscoped and scoped, each segment a run of lowercase letters, digits, `-`, `.`, and `_` beginning with a letter or digit, weighted toward a `.` in the last segment (`S` then differing from `N`), digit-first segments, and lengths up to the 214-character bound — never an `@types` name, an `@typescript/lib-` name, or a name the drawn release resolves to a built-in module, each crossed with a drawn placement form (a copy, or a symbolic link to a copy elsewhere in the staging), a drawn holding directory (the importing file's own or an ancestor), a covered setup drawn from 7.6's matrix, and a release and route drawn from T7.6-6's, every condition of Reach holding: T7.6-1's exports assertion holds, T7.6-2(a)'s file type-checks with T7.6-3's unknown-top-level-key arm paired to it, and T7.6-6's exports and identity assertions hold along the drawn route. +* **P-18 Type contract over generated configurations (7.6).** Seeded draws of configurations valid under 7 by construction, each a covered file — key order, and the choice of identifier or string-literal key, drawn per key; the binding's name drawn among those strict module code admits, never `require` or `exports`; comments drawn between tokens, their bodies free of `@` and never a `///` line, so none is a directive or pragma; optional keys and fields drawn present or absent; each group's glob list drawn empty or not, and each list 7.4 and 7.5 read as a set (`targetTags`, `edgeKinds`, a rule's `kinds`, a selector's `tags`) drawn with repeated elements or without (T7.6-2(f)); group, profile, and rule names drawn from identifier and non-identifier spellings free of `\`, quotes, line terminators, and U+FFFD, weighted toward the members of TypeScript's global `Object` interface and `__proto__`; every reference resolving, every kind given where a name is ambiguous, and every name distinct where 7 requires it — each type-checks in a covered setup drawn from 7.6's matrix (T7.6-2). Each draw is then given one violation drawn from 7.6's type-error class — its member, position, and offending value drawn — and the mutant fails to type-check in the same setup, paired with its draw (T7.6-3). Draws and mutants alike are checked well-formed before TypeScript judges them (S-9), a failing one a harness error reported with its seed (H-10). +* **P-19 Configuration import spellings (7).** Seeded draws of the configuration's module specifier as a static string literal TypeScript 5.9.3's scanner accepts — either quote style; text shaped as bare, scoped, relative, absolute, and URL specifiers, and the empty string; every escape form the scanner accepts (`\x`, `\u`, `\u{…}`, the single-character escapes, `\0` before a non-digit) and line continuations; U+FFFD and other non-ASCII code points — over T7-9's workspace, no group discovering the configuration file: each draw loads and answers as its `"xspec"` twin does, under T7-9's assertions. Each draw is checked well-formed before the product is driven on it (S-9, 16). ## 17. Self-Tests and Certification Confidence that the harness itself is correct comes primarily from certification against `specs/CERTIFICATIONS.md`, with internal self-tests only for harness machinery certification does not exercise (PROCESS.md). The harness MUST provide a certification runner that can execute the full suite (or a named subset) against an arbitrary fixture product supplied per CERTIFICATIONS.md. * **C-1 Certification protocol.** For each fixture in `specs/CERTIFICATIONS.md`: every in-scope test passes against the conformer; for each violator, exactly the tests it certifies fail against it and all other in-scope tests pass. A certified test's certification MUST run green before the product is implemented (red-green gate). Certification results are part of the harness's CI output. -* **C-2 Fixture interface.** Fixtures are driven through the identical blackbox surfaces as the product (H-2): the runner takes an executable/workspace binding and nothing else, so certifying and testing use one code path. +* **C-2 Fixture interface.** Fixtures are driven through the identical blackbox surfaces as the product (H-2): the runner takes the product binding — the executable, and the package directory 7.6's module is distributed as, holding exactly what its distribution carries and never a development tree (H-2's module channel) — with the workspace, and nothing else, so certifying and testing use one code path. * **S-1 Traceability self-check.** The H-7 map is complete and well-formed (fails on unmapped H-7 keys or dangling references). * **S-2 Workspace builder.** The fixture builder writes exactly the declared bytes (round-trip check including CRLF/CR content, invalid-UTF-8 blobs, BOMs, symlinks, and git fixtures with scripted commits), with scale vectors at the suite's staged maxima — a document nested at least at P-8's giant-nesting floor and one at the largest document size the suite stages (deterministic fixtures and generator draws alike, 16), each read back byte-complete — so a truncating writer or recursion-limited serializer cannot silently stage shallower or smaller inputs than declared, P-8's floor going unmet while deterministic tests still pass against their equally-shrunken expectations (the input-side counterpart of S-8's answer-side capacity gate) — certification cannot exercise builder bugs that make fixtures diverge from their declarations. * **S-3 Subprocess driver.** Captures exit codes and keeps stdout/stderr separated (verified against a known-behavior stand-in command); enforces per-test working directories; detects hangs via timeout and reports them as failures, not skips. Hang guards, suite-wide: a guard detects non-termination — a run blocking on a FIFO, or waiting out a hold the harness keeps standing, included, which is all a test's "promptly" asserts; with the FIFO's own state afterward — in place and still a FIFO, or gone where its removal is asserted — termination is likewise all its "no FIFO opened" and "unopened" assert, since an open that does not block reaches no H-2 channel and SPEC.md bars reading such an occupant (7, 13.4, 13.5), never examining it, so no test observes a product's system calls or fails one that examines a FIFO without reading it — and asserts nothing about speed, which SPEC.md leaves unbounded (H-10), so no finite guard is beyond every conforming product's reach; the sizing below lets a product's speed meet the clock only through a single invocation outlasting its own guard. Every product invocation carries its own guard, sized to the work that invocation stages, its inputs' scale included (P-8's nesting floor, H-11), with generous margin for the loaded local and CI runs E-5 covers — the suite's margin for product speed lives in these guards, where generosity costs detection nothing, a hang ending its test (below). Each step of the harness's own work between invocations — staging, decoding, evaluation — carries a guard of its own likewise, sized to the work it stages, answers at H-11's scale included, with the same margin, its tripping a harness defect (H-11), never a product failure. A guard spanning several invocations — a test's, a trial's, a property's, or a held run's across the invocations the harness drives during its hold — is compositional: never less than the sum of the own guards of the invocations and harness steps it spans, whatever the span's length — P-12's and T11.5-1's every-offset sweeps, P-10, P-11, P-14, and T13.5-13's trial loops included — so it cannot fire while each of them is inside its own guard; a span guard fixed apart from what it spans, or scaled below that bound, is a harness defect however far a given product's runs fall below it, and a span may carry none beyond those own guards. A span whose count is known only once staged — following from what the product writes, as T13.3-5(a)'s trials over the files it writes under `.xspec/` and the stagings one per companion path `recorded` lists (T6.5-20(a), (c), (e), T13.4-9(e)), or from how a failure shrinks, as a property's shrink phase, entered only once the property has failed — derives any guard it carries from its invocations and steps as it stages them, never fixing one in advance. A wait or loop the harness runs only beside given invocations, its iteration count following from their timing alone — awaiting a product event, as a hold file's appearance or each run's exit (T13.5-13), confirming readers still run before a mutating command starts (P-10), T13.5-5's polling during repeated builds, or P-14's flips while reads run — ends at the latest once those invocations have all exited, so it counts as one harness step under their own guards, never as a span whose count must be fixed or derived, and any guard it carries is no less than the compositional bound over those invocations. Time limits the CI service imposes on a job or runner (E-1) are no guards of the harness and lie outside this rule; every limit the harness sets, a test framework's per-test or per-file timeout included, is a guard held to it. A tripped guard is a failure that ends its test — a property's reported with its seed (H-10), unshrunk — so a hanging product costs one guard per test, never one per staged invocation; and a conforming product that trips any guard exposes a harness defect (E-5), never a product failure. Conformer and violators answering far below every guard, guard sizing is harness behavior certification cannot exercise, so the rule is checked before any product exists (H-8): against the stand-in, a span of stand-in invocations, each taking a fixed, substantial delay, passes at a length whose total delay exceeds one invocation's own guard, while a single stand-in invocation that never terminates fails as a hang, ending its test within its own guard; for every span the suite stages — each test, trial loop, and property at the fixed seeds (E-5) — whose count its staging fixes, the most invocations and harness steps it can stage counted from its staging alone, generators run and no product driven, each wait or loop beside given invocations counted as one step and any guard it carries checked against the bound over those invocations, the guard the harness applies is no less than the compositional bound over them; and, for every span whose count is known only once staged, that derivation is exercised against stand-in stagings of differing counts — stand-in file sets under `.xspec/` for T13.3-5(a), stand-in `recorded` sets for the companion stagings, and, for each property's shrink phase, stand-ins failing the property at differing draws — the guard applied at each count no less than the bound over it; so a fixed or under-scaled span guard, P-12's among them, fails before any product exists rather than once a product's runs approach it. Certification runs through this same driver (C-2), so a driver defect is a spurious verdict on every fixture, not a deviation any fixture can target. -* **S-4 TypeScript tooling driver.** In each configuration H-2 fixes, detects a known type error, a known definition location, and a known hover text in a hand-written non-xspec fixture project compiled and served in that configuration, so section 4's consumer assertions cannot pass vacuously — among the type errors one located in a module the consumer imports, outside the consumer file, a clean verdict covering the whole program (H-2). Each configuration's module settings are detected in effect through hand-written modules the other configuration accepts: under the ES-module configuration, TypeScript's rejection of an export assignment, of an import assignment, of a type re-exported through `export { … } from` without a `type` modifier, and of a type imported without one; under the CommonJS configuration, its rejection of a top-level `await` — so a driver serving one configuration's settings for the other's, which would make that configuration's legs a rerun of the other's, fails before any product exists. Certification supplies products, not consumer projects, and reaches the tooling only through whichever violators target section 4 (a selective set, CERTIFICATIONS.md); a driver blind to a diagnostic kind passes conformer and violator alike wherever no violator targets that kind, so each kind's detection is checked directly. +* **S-4 TypeScript tooling driver.** In each configuration H-2 fixes, detects a known type error, a known definition location, and a known hover text in a hand-written non-xspec fixture project compiled and served in that configuration, so section 4's consumer assertions cannot pass vacuously — among the type errors one located in a module the consumer imports, outside the consumer file, a clean verdict covering the whole program (H-2). Each configuration's module settings are detected in effect through hand-written modules the other configuration accepts: under the ES-module configuration, TypeScript's rejection of an export assignment, of an import assignment, of a type re-exported through `export { … } from` without a `type` modifier, and of a type imported without one; under the CommonJS configuration, its rejection of a top-level `await` — so a driver serving one configuration's settings for the other's, which would make that configuration's legs a rerun of the other's, fails before any product exists. Certification supplies products, not consumer projects, and reaches the tooling only through whichever violators target section 4 (a selective set, CERTIFICATIONS.md); a driver blind to a diagnostic kind passes conformer and violator alike wherever no violator targets that kind, so each kind's detection is checked directly. 7.6's covered setups are detected in effect likewise, before any product exists, through hand-written non-xspec fixtures and stand-in packages whose verdicts the setting under test decides, wherever release 5.9.3 gives a setting's value an effect of its own: each `moduleResolution` and `module` value of the matrix — an `exports`-only stand-in, which `node10` alone does not resolve; an ES-module-only stand-in imported from a file TypeScript compiles as CommonJS, rejected under `module` `node16` and `node18` and admitted under `node20` and `nodenext`; import attributes on an import of a JavaScript module, in a file TypeScript compiles as an ES module, rejected under `module` `node16` and admitted under `node18`; `Object.groupBy`, which the library of `nodenext`'s default target brings and that of `node20`'s does not; and, under `bundler`, `import.meta`, rejected by `es2015`, a string-literal import name, rejected by `es2020`, import attributes, rejected by `es2022`, and an import assignment, admitted by `preserve` alone; the initialized set's own options — `verbatimModuleSyntax`, `exactOptionalPropertyTypes`, `noUncheckedIndexedAccess`, `noUncheckedSideEffectImports`, `skipLibCheck` (an error inside a stand-in's declaration file), and `types` `[]` (an `@types` stand-in it keeps out of the program); the strict defaults' `strict` — a stand-in whose declaration file leaves a parameter implicitly typed, an error `strict` alone raises there, `skipLibCheck` being off (under the initialized set, a dropped `strict` already surfaces as an options error, `exactOptionalPropertyTypes` requiring `strictNullChecks`); the module format the project and the extension imply (`import.meta`, rejected in a file TypeScript compiles as CommonJS under the `node16` and `nodenext` modes); the verdict's reach into declaration diagnostics — under the initialized set, a stand-in whose `defineConfig` returns an interface it does not export fails a valid default export through TS4082 alone, every other diagnostic kind empty (7.6's verdict); and T7.6-1's export listing — a stand-in declaring an interface without `export`, and no `export {}`, lists that interface among its exports, and one whose export assignment assigns a value carrying `defineConfig` and one other member lists both. A driver serving one setup's settings for another's or dropping one, a verdict blind to a diagnostic kind, or a listing blind to an implicit export or to an export assignment's members fails here, never only against a product. * **S-5 Output adapters.** Each adapter (H-3) rejects documents missing required information (fed synthetic wrong-shape documents) rather than defaulting. Every fixture emits conforming shapes (C-2 drives them as products), so an adapter defaulting absent information passes conformer and violator alike — the vacuous pass no fixture is defined to produce. * **S-6 Oracles.** The Markdown oracle (P-2), the glob/capture oracle (P-7), the coverage-reachability oracle (P-13), the section-move category oracle (P-5), the baseline graph-diff oracle (P-6), and the path-blocks generation oracle (P-16) pass their own fixed vector suites before being trusted by property tests, each derived from SPEC.md's worked material: 3, 7.5, and 15 respectively for the first three; 6.2's worked straddling-line shape in T6.2-3's three stagings (the worked shape with spaces before its closing tag, its both-sided U+000B/U+000C spelling, and the `body</S>` variant with such a remainder), each to top level and into a flow-position parent, plus the clean-boundary case of T6.2-3, T6.2-4's pinned final-position shapes and its `changed` twin, and T6.2-3's sibling stagings (d) and (e) for the section-move oracle; 5.6's three worked examples plus the added/deleted convention of T5.6-6 for the graph-diff oracle; and 15's worked session — its four items — with the pinned item lists of T10.5-1, T10.5-7, T10.5-8, and T10.5-9 for the path-blocks generation oracle. An oracle defect makes a conformer fail spuriously — a spurious fail, which no violator can reveal (as S-8). The name analysis behind T6.5-22(a)'s universal assertion — which names a receiving file declares, in any scope and at value or type level, which it references, and which 6.5 bars there — likewise passes its own fixed vector suite before any test that adds an import, P-5's draws included, trusts it: vectors built from T6.5-22's stagings, each a file with candidate names and the verdict the analysis must reach on each, in both directions — counted: `helper` declared only in a function body and, separately, only as a type, `T` bound only by an import declaration nested in a function body (`function f() { import T from "../specs/target.xspec" }`, T6.5-24(b)), `target` bound only by a parameter (`function f(target: unknown) {}`, T6.5-9's parameter run), `Record` in a type annotation, the undeclared global `test` of a call `test(…)`, `Foo` of `<Foo />`, `x` of `x.foo`, and `t` of `{ text as t }`; not counted: `div` of `<div />`, `foo` of `x.foo`, a label (`L` of `L: for (;;) break L`), and the `text` that `{ text as t }` spells for the other module; and barred, in a TSX file, the factory name of each pragma T6.5-22(b) stages — `h` of `/** @jsx h */`, of `/* @JSX h */`, of `// @jsx h`, and of `/** @jsx h */` inside a function body, `preact` of `/** @jsx preact.h */`, and `Frag` of `/** @jsxFrag Frag */` — and, in every kind of file, though it neither declares nor references them, each name T6.5-22's constraint list spells or ranges over — its reserved and strict-mode-barred words, `require` and `exports`, each global-object property (`decodeURI`, one of clause 19's function properties; each constructor from `AggregateError` through `WeakSet`, `Object` among them; `escape` and `unescape`, Annex B's), `Iterator`, `AsyncIterator`, and `SuppressedError` — and a `__`-prefixed name (`__x`); `React`, barred in each of T6.5-22(b)'s `.tsx` receivers, the one spelling JSX and the one spelling none, and in neither a spec source nor a `.ts` file; and `S`, `Spec`, and `text`, barred in a spec source and not in a `.ts` file — so that each name T6.5-22(b)'s lures target is a vector in every kind of file its lures stage, with the verdict 6.5 gives it there. Certification reaches the analysis only through whichever violators target T6.5-22 (a selective set, CERTIFICATIONS.md): an analysis too narrow passes conformer and violator alike for every class no violator targets, and one too broad fails a conforming product spuriously only when that product picks a name the analysis miscounts, which a conformer may never do — so each class's verdict is checked directly. -* **S-7 Red-green sweep.** Against an empty stub product (every command exits with an unexpected code and no output), every product-facing test fails with a diagnosed assertion and the suite completes without harness errors (H-8). +* **S-7 Red-green sweep.** Against an empty stub product (every command exits with an unexpected code and no output) beside an empty stub package (a directory holding only a manifest naming no entry; H-2's module channel), and again with no package directory given, every product-facing test fails with a diagnosed assertion and the suite completes without harness errors (H-8) — 7.6's tests failing through their pairing (7.6), never passing on a negative arm alone. * **S-8 Answer-scale capacity.** The H-3/12.7 decoders and every answer-document walk the suite performs succeed, every datum evaluated without harness error, on synthetic conforming-form documents at the maximum answer scale H-11 obliges: the scale of the largest answers SPEC.md permits a conforming product over the inputs the suite stages (deterministic fixtures and generator draws, 16, alike) — expansion blowup included, a `view --text` answer multiplying embedded subtree text through each expansion level past its staged input's own size — never merely the staged inputs' size; among them a `view` document nested at least as deep as P-8's giant-nesting floor. Capture is gated at the same scale through S-3's stand-in mechanism: a stand-in command emitting the largest of these synthetic documents on standard output is driven through the H-2 capture path product invocations use, and the captured bytes MUST be complete and identical to what the stand-in emitted. So the capacity H-11 requires is gated and regression-guarded, capture through evaluation, before any product exists (H-8's ordering). Certification cannot exercise this class: a harness-side failure against a conforming answer is a spurious fail, not a vacuous pass or a missed deviation, so no CERTIFICATIONS.md fixture reaches it. -* **S-9 Fixture well-formedness.** Every MDX source this document declares well-formed — each deterministic fixture's files, and every form the generators of 16 compose for input 16 declares valid by construction (every property's draws but P-1's invalid draws and P-8's and P-11's fuzzed input), in the fixed vector set of those forms and, at property time, in each draw — derives under the grammar 14.20 fixes (MDX syntax at major version 3, decided by derivability alone, its identifier characters — an expression's and a JSX name's alike — and its space separators those of Unicode 15.1, judged code point by code point), and every MDX source this document declares unparseable (14.20) does not; the check is made by a means independent of the product — it lives in the harness, as S-6's oracles do — and runs before any product exists for the deterministic fixtures and the form vectors (H-8), each draw's failure being reported as a harness error with its seed (16, H-10), never as a product failure or a draw to skip. The forms 14.20 admits by derivability but a grammar-implementing tool rejects under a rule beyond it — ECMAScript's early errors: two imports binding one identifier in one ESM block (T2.1-3, T4.5-8), `export { nope }`, `{1 = 2}`, `{let}`, and `{010}` (T14-12) — are the check's known allowances, each named, so that derivability is what is checked rather than a tool's acceptance; an allowance is never granted to a form 14.20 does not admit, and a declared-unparseable form the check rejects only under such a rule is a declaration defect the check cannot see (T14-12 fixes that boundary). The Unicode version is 14.20's, never the checking tool's: a tool whose tables postdate 15.1 admits U+1C89, a Unicode 16 letter, as an identifier character, one judging a JSX name one UTF-16 code unit at a time rejects U+2EBF0 there, which 14.20 admits, and one whose tables predate Unicode 6.3 takes U+180E, a format character under 15.1, for a space separator — so the check judges T14-12's element and attribute names holding U+2EBF0 well-formed, and T2.7-4's `{` U+180E `}` unparseable, whatever such a tool reports; and no fixture or draw is MDX text deriving only under a Unicode version past 15.1, whose well-formedness 14.20 leaves unfixed, as none is TypeScript text accepted read one way only (below) — the generators spelling a reference segment with dot access only where 1.4's identifier test admits it (16). TypeScript sources alike — 14.20 fixing TypeScript's grammar at release 5.9.3, TSX or plain as the file name selects (by 14.20's rule, the name compared byte-wise, 12.0: T14-5's `src/x.TSX` is judged as plain TypeScript, whatever grammar the parser's own file-name detection would pick), at the language level ESNext, derivability there being that release's acceptance: every code source and configuration file this document declares well-formed, deterministic fixture or generated form, is accepted by that release both as module code and as script code, every one it declares unparseable is rejected under both readings, and no fixture is text the release accepts read one way only — the top-level `await` forms 14.20 names, whose well-formedness SPEC.md leaves unfixed (T14-12) — each checked by that release's own parser, a dependency of the harness independent of the product, before any product exists and, for a draw, before the product is driven on it; the rules 14.20 excludes beyond parsing — post-parse grammar checks, name binding, type checking — take no part, so T14-12's post-parse arms, T4-2's relative-name and undeclared module declarations, T7-2's modifier-bearing configuration imports, and the nested, statement-body, and decorated or modified declarations of T4-6, T4.5-10, T4.5-11, T6.5-24 through T6.5-26, and T14-11 check as well-formed. Certification cannot exercise this class: a conformer — the simplest behavior conforming within its scope — may judge 14.20 on its accepting side alone, so an ill-formed fixture — MDX or TypeScript — passes conformer and violators alike — a vacuous pass no fixture is defined to produce — and an ill-formed generator draw surfaces only as a spurious product failure; what S-9 verifies is this document's own declarations of well-formedness. +* **S-9 Fixture well-formedness.** Every MDX source this document declares well-formed — each deterministic fixture's files, and every form the generators of 16 compose for input 16 declares valid by construction (every property's draws but P-1's invalid draws and P-8's and P-11's fuzzed input), in the fixed vector set of those forms and, at property time, in each draw — derives under the grammar 14.20 fixes (MDX syntax at major version 3, decided by derivability alone, its identifier characters — an expression's and a JSX name's alike — and its space separators those of Unicode 15.1, judged code point by code point), and every MDX source this document declares unparseable (14.20) does not; the check is made by a means independent of the product — it lives in the harness, as S-6's oracles do — and runs before any product exists for the deterministic fixtures and the form vectors (H-8), each draw's failure being reported as a harness error with its seed (16, H-10), never as a product failure or a draw to skip. The forms 14.20 admits by derivability but a grammar-implementing tool rejects under a rule beyond it — ECMAScript's early errors: two imports binding one identifier in one ESM block (T2.1-3, T4.5-8), `export { nope }`, `{1 = 2}`, `{let}`, and `{010}` (T14-12) — are the check's known allowances, each named, so that derivability is what is checked rather than a tool's acceptance; an allowance is never granted to a form 14.20 does not admit, and a declared-unparseable form the check rejects only under such a rule is a declaration defect the check cannot see (T14-12 fixes that boundary). The Unicode version is 14.20's, never the checking tool's: a tool whose tables postdate 15.1 admits U+1C89, a Unicode 16 letter, as an identifier character, one judging a JSX name one UTF-16 code unit at a time rejects U+2EBF0 there, which 14.20 admits, and one whose tables predate Unicode 6.3 takes U+180E, a format character under 15.1, for a space separator — so the check judges T14-12's element and attribute names holding U+2EBF0 well-formed, and T2.7-4's `{` U+180E `}` unparseable, whatever such a tool reports; and no fixture or draw is MDX text deriving only under a Unicode version past 15.1, whose well-formedness 14.20 leaves unfixed, as none is TypeScript text accepted read one way only (below) — the generators spelling a reference segment with dot access only where 1.4's identifier test admits it (16). TypeScript sources alike — 14.20 fixing TypeScript's grammar at release 5.9.3, TSX or plain as the file name selects (by 14.20's rule, the name compared byte-wise, 12.0: T14-5's `src/x.TSX` is judged as plain TypeScript, whatever grammar the parser's own file-name detection would pick), at the language level ESNext, derivability there being that release's acceptance: every code source and configuration file this document declares well-formed, deterministic fixture or generated form, is accepted by that release both as module code and as script code, every one it declares unparseable is rejected under both readings, and no fixture is text the release accepts read one way only — the top-level `await` forms 14.20 names, whose well-formedness SPEC.md leaves unfixed (T14-12) — each checked by that release's own parser, a dependency of the harness independent of the product, before any product exists and, for a draw, before the product is driven on it; the rules 14.20 excludes beyond parsing — post-parse grammar checks, name binding, type checking — take no part, so T14-12's post-parse arms, T4-2's relative-name and undeclared module declarations, T7-2's modifier-bearing configuration imports, string-literal import names, and export and import assignments, and the nested, statement-body, and decorated or modified declarations of T4-6, T4.5-10, T4.5-11, T6.5-24 through T6.5-26, and T14-11 check as well-formed, while T7-9(b)'s specifier escapes — `"\x4"`, `"\u{110000}"`, `"\01"`, and `"\8"`, scanning errors of that release — check as unparseable under both readings. Certification cannot exercise this class: a conformer — the simplest behavior conforming within its scope — may judge 14.20 on its accepting side alone, so an ill-formed fixture — MDX or TypeScript — passes conformer and violators alike — a vacuous pass no fixture is defined to produce — and an ill-formed generator draw surfaces only as a spurious product failure; what S-9 verifies is this document's own declarations of well-formedness. +* **S-10 Node.js release driver.** 7.6's runtime arms (T7.6-6, T7.6-7, P-17) rest on a driver certification cannot check: every fixture's module answers alike on every release and route, so a driver serving one release or one route for all of them passes conformer and violators alike and leaves the arm on 22.0–22.11's `require` vacuous. Before any product exists, on each release E-1 provisions: the release in effect is the one provisioned, as the running process reports its version, a listed release left unprovisioned being a harness error (E-1); each run carries no option, no `NODE_OPTIONS` or `NODE_PATH`, and no condition, loader, or hook, and has a fresh `HOME`; each route is the one exercised — the importing module's own kind confirmed, and a stand-in dual package, whose ES-module and CommonJS entries each report their own format when loaded, answering the `import` routes from its ES-module entry and the `require` route from its CommonJS one — and an ES-module-only stand-in's `require` route fails on each provisioned release before 22.12.0 and loads on each later one; two minimal stand-in packages, one with an ES-module entry and one with a CommonJS entry, leave T7.6-7(c)'s observed state unchanged, and their loading output along each route passes T7.6-7(a)'s output oracle, as does that of stand-ins whose manifests draw the release's own deprecations — an invalid `main` beside an `index.js` along `require`, and an ES-module package's `main` lookup along `import`, wherever the release prints one — so the oracle admits the runtime's own loading output; and each observation T7.6-6 and T7.6-7 make detects what it exists for — stand-ins that print while loading, to standard output, to standard error outside the release's warning form, and to standard error in that form, a line of their own after a warning the release prints included, emit a process warning through the runtime's warning facility, write a file, add a global, add an own property to a built-in constructor (`Array`) and to a namespace object (`Math`), alter a built-in prototype, make the global object non-extensible, change the prototype of a built-in prototype, replace a property of `process` (`process.emitWarning`), set a variable in `process.env`, set the process title, change the working directory (`process.chdir`), replace a standard stream's `write`, set `process.exitCode`, register a `process` listener, start a timer, return a copy of their argument, touch a trap of an argument's Proxy, or open one of the FIFOs are each caught by the matching observation — so no absence passes through a blind observer. Certification reaches these observations only through whichever violators target T7.6-6 and T7.6-7 (a selective set, CERTIFICATIONS.md): an observation blind to one kind of effect passes conformer and violator alike wherever no violator targets that kind, so each observation's detection is checked here directly, as S-4 checks each diagnostic kind's. ## 18. Execution and CI -* **E-1 GitHub CI.** The full suite — sections 1–17, certification included — runs in GitHub CI on Linux runners. CI provides no network access guarantees beyond dependency installation; the suite itself MUST pass with network access disabled after setup (xspec performs no network access; the harness needs none). Product invocations run with network access denied, so product behavior that relies on network access fails its tests rather than passing through a silent fallback (SPEC.md preamble) — the enforceable contract is exactly that the suite passes with network denied. The Linux leg runs product invocations as an unprivileged user, so the permission-based stagings of environment refusals (T13.5-7, T14-9, T14-10) take effect; the harness verifies each such staging on itself before invoking the product and treats an ineffective one — a privileged runner — as a harness error (H-11), never a pass or a skip (H-9). 13.5's machine-wide stagings — T13.5-9's second user and second mount, and T13.5-10(e)'s, (f)'s, and (g)'s fresh process-identifier namespaces — are made with the administrative access GitHub's hosted Linux runners grant the job, outside every product invocation, which stays unprivileged; the harness verifies them on itself likewise (T13.5-9), a runner withholding that access failing them as a harness error, never a skip. +* **E-1 GitHub CI.** The full suite — sections 1–17, certification included — runs in GitHub CI on Linux runners; where the CI service's per-job limits require it, the suite is split across parallel jobs whose union is the whole suite, every verdict reported, and never trimmed to fit them — no test, arm, or pairing of 7.6's covered setups and cases dropped. CI provides no network access guarantees beyond dependency installation; the suite itself MUST pass with network access disabled after setup (xspec performs no network access; the harness needs none). Product invocations run with network access denied, so product behavior that relies on network access fails its tests rather than passing through a silent fallback (SPEC.md preamble) — the enforceable contract is exactly that the suite passes with network denied. The Linux leg runs product invocations as an unprivileged user, so the permission-based stagings of environment refusals (T13.5-7, T14-9, T14-10) take effect; the harness verifies each such staging on itself before invoking the product and treats an ineffective one — a privileged runner — as a harness error (H-11), never a pass or a skip (H-9). 13.5's machine-wide stagings — T13.5-9's second user and second mount, and T13.5-10(e)'s, (f)'s, and (g)'s fresh process-identifier namespaces — are made with the administrative access GitHub's hosted Linux runners grant the job, outside every product invocation, which stays unprivileged; the harness verifies them on itself likewise (T13.5-9), a runner withholding that access failing them as a harness error, never a skip. The Node.js releases on which the module channel loads the module (T7.6-6, T7.6-7, P-17) are exercised on the Linux leg alone, each provisioned by the environment before the run — in CI, at setup — beside the one the suite runs on: no test downloads a runtime, so those runs stay network-denied, as product invocations are. A listed release the environment has not provisioned — on a local run without it, say — is a harness error (H-11) for every run needing it, never a skip (H-9) and never a product failure. The list follows a rule and is pinned by exact version, so consecutive runs exercise the same releases (E-5) and an update through the normal change process stays mechanical: from the 22 line, 22.0.0, its first release; 22.11.0, the last on which `require` cannot load an ES module without a flag; 22.12.0, the first on which it can; and the line's newest release; and, of every later line still supported upstream — Current or LTS, Maintenance LTS included — when the list is set, its newest release, no line past its end of life (23, 25) or without a release yet being sampled. Set on 2026-10-29, the rule yields 22.0.0, 22.11.0, 22.12.0, 22.23.4, 24.22.2, and 26.13.0. * **E-2 Local-only tests.** Tests that cannot run in GitHub CI are implemented as local-only tests, collected in a separately invocable local suite, and never marked skipped (PROCESS.md). This set is currently empty; symlink, permission-refusal, kill/interruption, and concurrency tests — 13.5's reach and identifier stagings included (T13.5-9, T13.5-10(e), (f), (g); E-1) — run on Linux CI, 13.5's busy refusal, dead-run takeover, and release probed on the Windows CI leg as well (E-6), and case-sensitivity assertions run on Linux CI with their discriminating single-casing probes rerun on the Windows CI leg (E-6). Any future local-only test MUST document why CI cannot run it. * **E-3 Parallelism.** The suite runs its tests in parallel and MUST pass under parallel execution; multiple suite instances can run on one machine concurrently (H-1, T13.5-6). 13.5's machine-wide stagings stay safe under both: each mount and namespace is its test's own, at a path unique to the suite instance, and is removed by it; the second user (T13.5-9) is made idempotently under a fixed name and never removed by a run, so concurrent instances share it without interfering, each test's workspace its own (H-1). * **E-4 No production keys, no external services.** The suite uses no credentials and contacts no hosted services (there are none to test; git fixtures are local). diff --git a/specs/patches/0002-config-import-specifier.md b/specs/patches/0002-config-import-specifier.md new file mode 100644 index 00000000..e1a77951 --- /dev/null +++ b/specs/patches/0002-config-import-specifier.md @@ -0,0 +1,117 @@ +# 0002 — Configuration import not tied to a package name + +- **Type:** Improvement Proposal (IP) +- **Stage:** Complete +- **Branch:** `claude/relaxed-albattani-5v6l55` (harness-designated for this session; stands in for `patch/config-import-specifier`) + +## Motivation + +`SPEC.md` requires the configuration file to import `defineConfig` from the module specifier `"xspec"`, which ties every project's configuration to one literal package name. The name the product is distributed under is a distribution matter, separate from the `xspec` command, and on the public package registry the bare name `xspec` belongs to an unrelated package. A project that installs the product under its distributed name must therefore alias the install so that `"xspec"` resolves, or go without editor and `tsc` type support for its configuration. An instruction to install or run the bare name fetches the unrelated package. Developer never intended the specification to name a package. + +This proposal frees the import's module specifier and leaves the specification naming no package at all. Type support for the configuration is a promise the product makes, so `SPEC.md` takes it on: the product's own importable module, which exports `defineConfig`, joins the product's interface with a type contract that a test can check offline under any name it installs the product as. + +Archival — Developer's words (2026-10-28), verbatim: + +> yes, fix the config import + +> wait, i thought you meant the docs need to update to reflect the true import name? + +> yes i lets make this IP. will there be any pitfalls due to the name collision of the "xspec" package? it was actually never my intention to tie the spec to the literal package name xspec. + +Archival — goals recorded at intake by Liaison on Developer's behalf (2026-10-28), verbatim: + +> - With a plain `npm install --save-dev @modularcloud/xspec`, a project can write the config's import under that package's name and get editor and `tsc` type support, with no npm alias. +> - Existing config files that import `defineConfig` from `"xspec"` keep working. +> - The spec names no literal package or distribution name for this. How it states which import is accepted is for the spec work to settle. +> - `docs/` and `README.md` are updated alongside. The alias install step goes, and nothing leads users to `npm install xspec` or `npx xspec`, which fetch an unrelated package owned by another maintainer. + +## Non-goals + +- The `xspec` command name does not change. +- No other configuration change. The file's name and location, `--config`, the encoding rules, the `defineConfig` binding and its aliasing, the excluded `type` and `defer` modifiers and import attributes, the default export's single call with its statically literal argument, and every key, value, and error rule of 7 and 14.14 stay as they are. +- No programmatic interface beyond `defineConfig`. The new module exports exactly that one binding (change 2): no command, graph, or configuration-loading API, and no named configuration type. +- The three accepted residuals parked in issue #8 stay outside this patch, its release included: the syntax-failure location gaps of 14.20, the gap of 6.5 for TypeScript import removals joined by automatic semicolon insertion, and the TypeScript type error of 4.1 and 14.7 for a requirement path whose last segment names a member of TypeScript's global `Object` interface. + +## Proposed `SPEC.md` changes + +The following describes the behavior `SPEC.md` is to define, at the rigor `SPEC.md` requires. Exact wording and placement are settled in spec refinement. + +### 1. Any module specifier + +The declarative form of 7 keeps its import constrained exactly as now: one import declaration binding `defineConfig`, optionally aliased, with no `type` or `defer` modifier and no import attributes. The one change is that its module specifier may be any static string literal (2.4). + +- **Reading the file as configuration.** Wherever xspec reads a configuration, a baseline's configuration (6.3) included, it never interprets, resolves, or loads the specifier, and reads nothing on its account. A configuration's validity, and everything xspec derives from the configuration, are independent of what, if anything, the specifier designates, and of its spelling wherever that spelling leaves the file well-formed TypeScript (14.20). + - Every such spelling is therefore accepted alike: a bare or scoped package name, a relative or absolute path, a URL, the empty string, either quote style, and spellings carrying escape sequences, line continuations, or U+FFFD. A spelling TypeScript's scanner rejects — an escape such as those of `"\x4"`, `"\u{110000}"`, `"\01"`, and `"\8"` — leaves the file not well-formed, a configuration error (7, 14.14). + - A specifier designating nothing, an unreadable path, a workspace file (the configuration file itself included), or a network location is accepted equally, and xspec makes no read and no network access for it. +- **The one exception: the configuration file as a source.** Where a configured group discovers the configuration file, xspec analyzes it as it does every source it discovers (2.1, 4), its import declaration included, the specifier read as any source's (2.4). + - For a code group, a specifier ending in `.xspec`, or a relative one designating a derived-file path (13.4), gives that source an invalid-import finding (14.15), beside any other the source carries, while the configuration itself stays valid. The finding fails `build` and `check`, turns back the gated reads (13.3), and leaves a baseline whose workspace holds it unreconstructable (6.3). + - Likewise for a code group, while Markdown emission is enabled, a move whose destination would emit Markdown to a path the configuration file's relative specifier designates is refused (`refused-invalid-destination`, 6.5). + - No rewrite of 6 applies to the configuration file. Its declarative form holds no reference, and its import binds `defineConfig` itself, never a spec module's default or `text` export, so wherever the file is a source, its import, when its specifier ends in `.xspec`, is invalid (14.15), and no workspace a rewrite runs on (6.4, 6.5) holds such an import. + +### 2. The product's module + +The interface listed in `SPEC.md`'s opening gains one surface: the product's own module, which exports exactly one binding, `defineConfig` — no other value and no type (Type contract and Runtime, below). + +- **Package and installation.** The module is distributed as a package: a directory whose root holds a `package.json` manifest, the form TypeScript's and Node.js's resolution of installed dependencies read. The module is the package's root entry, the one a specifier naming the package with no subpath designates. No other module of the package carries a contract, whether a specifier with a subpath designates it or a file of the package is imported by its path. These definitions concern the module alone: they make no claim about how the `xspec` executable is provided or run. + - Installing the package under a name `N` places it, exactly as distributed, at `node_modules/N` in its holding directory, as the directory itself or as a symbolic link to it. The holding directory is the importing file's directory or one of its ancestors, read along the file's physical path, every symbolic link among its components resolved (as 11.6 reads anchoring), and is not itself named `node_modules`: TypeScript's lookup and `require`'s skip such a directory. A copy, a symbolic-link install, and an aliased install (one whose `N` differs from the name the package's manifest gives) are therefore alike. + - `N` is `name` or `@scope/name`, where `scope` and `name` are each a non-empty run of lowercase ASCII letters, digits, `-`, `.`, and `_` beginning with a letter or digit, the whole at most 214 characters — except a name in the `@types` scope, which TypeScript reserves for declaration packages; a name in the `@typescript` scope whose `name` begins with `lib-`, the form under which TypeScript looks up replacements for its default libraries (`@typescript/lib-es5`); and, for Node.js's resolution and the runtime contract on a given release, a name that release resolves to one of its own built-in modules (`fs`, `path`). + - Nothing else need be installed: the module needs no other package and no `@types` declarations, and nothing outside the package but TypeScript's default libraries and the runtime's built-ins. Installation is that placement alone, with no package-manager run, install-time step, or network access. +- **Reach.** No literal package or distribution name names the module, and no name is privileged. With the package installed under `N`, a module specifier spelling exactly `N` designates the module along each tool's routes: + - TypeScript's one route, in every covered setup (below): the covered file's import declaration, whatever module format TypeScript applies to that file. + - Node.js's routes, on every release and in every run the runtime contract covers (below): `import` — a static import in an ES module, or a dynamic `import()` in a module of either kind — and `require` in a CommonJS module. + + The specifier does so wherever three conditions hold, each ruling out a resolution those tools make before they reach the installed package: + - Nothing nearer. Write `S` for `N` cut before the first `.` of its last segment, or `N` itself where that segment has none (`a` for `a.js` and `a.b`), `D` for the name under which TypeScript looks up declarations for `N` (`@types/N`, or `@types/scope__name` for `@scope/name`), and `T` for `D` cut the same way. + - In the holding directory, no entry but the placement occupies a path beginning `node_modules/S.`: no `N.js` or `N.d.ts` and, for `N` `a.js`, no `a.ts`. + - In every directory from the importing file's own up to, but excluding, the holding directory (none where the two coincide), no entry occupies `node_modules/N` or `node_modules/D`, or a path beginning `node_modules/S.` or `node_modules/T.`. + - No self-reference: no `package.json` in the importing file's directory or one of its ancestors gives a `name` that TypeScript or Node.js reads as `N` or as a leading part of it: a `name` that, each `\` read as `/`, is empty, or is `N` or `N`'s scope (`@scope` for `@scope/name`) with or without one trailing `/`. + - Physical naming: TypeScript is given the importing file by its physical path, and Node.js loads it by that path. +- **Covered setups.** The type contract holds under TypeScript at release 5.9.3 (the release 14.20 names) in each covered setup: the program below, under one of the two option sets that follow, for a covered file (below) that set covers. + - Program: the configuration file is the one root file, Reach's conditions holding, and the program holds no other file but TypeScript's default libraries, none of them replaced by an installed package, and the package's own declaration files, though other packages, `typescript` among them, may be installed. The project may be an ES-module or a CommonJS one: ES-module when the `package.json` nearest the configuration file — in its directory, or else in the nearest ancestor holding one — declares `"type": "module"`, and CommonJS otherwise, a project with no `package.json` included. + - Strict defaults, covering every covered file: `strict` on; `moduleResolution` one of `node10`, `node16`, `nodenext`, and `bundler`, the modes that find installed packages; `module` at its default under `node10` and, under the other modes, at a value the mode requires — `node16`, `node18`, `node20`, or `nodenext` under `node16` and `nodenext`, and `es2015`, `es2020`, `es2022`, `esnext`, or `preserve` under `bundler`. Every other option is at its default, so `skipLibCheck` is off and the package's own declaration files count. + - Initialized-project options, covering each covered file TypeScript compiles as an ES module (a name ending in `.mts`, or in `.ts` or `.tsx` in an ES-module project): exactly the option set release 5.9.3's `tsc --init` writes — `module` `nodenext`, `target` `esnext`, `types` `[]`, `jsx` `react-jsx`, `moduleDetection` `force`, and these ten on: `strict`, `declaration`, `declarationMap`, `sourceMap`, `verbatimModuleSyntax`, `isolatedModules`, `exactOptionalPropertyTypes`, `noUncheckedIndexedAccess`, `noUncheckedSideEffectImports`, and `skipLibCheck` — with every other option at its default. A file TypeScript compiles as CommonJS is outside this set: under it, TypeScript rejects that file's import declaration whatever the module declares. + - A file type-checks when the compiler reports no error for that program. +- **Covered files.** The type contract concerns a configuration file in 7's declarative form whose import names the module by a specifier spelling exactly `N`, whose path ends in `.ts`, `.mts`, `.cts`, or `.tsx` and is no declaration-file name (4.6's file-name rule), and which meets each of these conditions: + - It spells no `\` outside its comments: no identifier or string literal carries an escape sequence or line continuation, so every key, value, and the specifier read the same as spelled (2.4) and as TypeScript reads them. (Otherwise keys distinct as spelled, `"ab"` and `"a\x62"`, collide for TypeScript, and a key or value invalid as spelled, `"\x73pecs"` or `mode: "\x64irect"`, conforms for it.) + - It carries no comment TypeScript reads as a directive or pragma: a triple-slash directive (`/// <reference … />`), a comment directive in a line or block comment (`@ts-ignore`, `@ts-expect-error`), or a pragma (`@ts-nocheck`). Such comments suppress errors or raise their own. + - It imports `defineConfig` by that identifier, never by a string-literal import name (`{ "defineConfig" as d }`, a TypeScript error under `module` `es2015` and `es2020`), and binds it to a name strict module code admits as a binding — the first of 6.5's rules for an added import's identifiers: no ECMAScript reserved word (`await`, `yield`, `enum`, and `default` among them), and none of `let`, `static`, `implements`, `interface`, `package`, `private`, `protected`, `public`, `eval`, and `arguments` — and to neither `require` nor `exports`, which TypeScript reserves in a file it compiles as CommonJS. +- **Type contract.** In every covered setup: + - **Exports.** The module, as TypeScript resolves the covered file's import, exports exactly `defineConfig`, a value with no type or namespace meaning, and no other export, type-only or not. + - **Valid configurations.** A covered file valid under 7 type-checks with no errors. This holds for every spelling a covered file can carry: an aliased binding, string-literal keys, comments, and any group name, including one that spells a member of TypeScript's global `Object` interface or `__proto__`. + - **Shape violations.** A covered file in 7's declarative form holding one or more violations of the type-error class does not type-check: TypeScript reports at least one error in the file, its locations and messages unpinned, possibly fewer errors than violations. The type-error class is exactly: + - an unknown key (7) at any level; + - a missing required key: `specs`, `markdown`'s `emit`, and the keys 7.4 and 7.5 mark required for a profile and a rule; + - a value of a kind 7 does not admit in its position, a list's element included: a boolean, string, list, or object where 7 gives the position another kind; + - a string outside the values 7 enumerates for its position: `targets`, `boundaryKind`, `mode`, `type`, a selector's `kind`, an element of `edgeKinds` or `kinds`; + - a selector not in exactly one of its forms (7.5): one using more than one of `group`, `files`, and `tags`, one using none of them, or one carrying `kind` without `group`; + - an empty list where 7.4 or 7.5 forbids one: `targetTags`, `edgeKinds`, a rule's `kinds`, or a selector's `tags`. + - **Every other configuration error** (14.14) carries no type-level requirement either way: a covered file whose violations all lie outside the class may type-check or not. Among them: + - cross-references between names: a profile's `target` and `boundary`, a selector's `group`, a kind required because a name is ambiguous; + - the name and character rules: empty, duplicate, and U+FFFD-bearing names, `outDir`'s form; + - glob validity and globs outside the root; + - a key repeated within one object literal; + - the capture rules; + - a file matched by both a spec and a code group. +- **Runtime.** On every release of the Node.js 22 line and of every later line, Node.js run with no option, environment variable, or module customization hook that changes how modules are resolved or loaded — so with no user condition (`--conditions`, `-C`), no loader or customization hook (`--loader`, or one `--import` registers), and none of these through `NODE_OPTIONS` — and the module loaded through `import` or `require` as Reach describes: + - The module's exports are exactly `defineConfig`: an `import` namespace holds that one export, and a `require` result has that one own enumerable property, symbol-keyed properties counted as well as string-keyed ones. + - `defineConfig` returns its first argument and does nothing else: the very value passed, whatever it is, neither examined, copied, nor modified; `undefined` when called with none; any further arguments ignored. + - Beyond the runtime's own resolution of the specifier and loading of the package's files, neither loading the module nor calling `defineConfig` has any effect: no filesystem read outside the package, no filesystem write, no network access, no output on standard output or standard error, and no change to the global object or to any other state of the process. +- **xspec unchanged.** xspec still never executes or resolves the configuration, so no command's outcome depends on the module or on whether a project installed it. + +*Rationale, not carried into `SPEC.md`:* installation is defined as a placement so that the contract is blackbox-testable offline, the package installed under a name of a tester's choosing. The seam is ordinary installation, so it adds no tester-only option and no security exposure. The runtime contract covers every release of the Node.js 22 line, 22.0 included, so it rests on no behavior a later 22.x release introduced, such as `require` of an ES module, on by default only from 22.12. + +### 3. No package or distribution name + +No rule or example of `SPEC.md` names a package or distribution. The example in 7 keeps an import line, which the declarative form requires, with a specifier that names none; its spelling is settled in refinement. `SPEC.md` states the accepted form on its own terms, with no reference to a previously required specifier. + +## Interactions and compatibility + +- **Strict relaxation.** Every configuration valid today stays valid with identical results, one importing from `"xspec"` included. The only configurations whose validity changes are those that are well-formed TypeScript (14.20) and conform in every respect but their specifier, an escape spelling of `xspec` (read as spelled, 2.4) among them. + - Each moves from configuration error (14.14) to valid, and then behaves as any valid configuration does, change 1's exception included. Where such a file is a discovered code source whose specifier ends in `.xspec`, or is a relative one designating a derived-file path, its workspace fails with that source's invalid-import finding (14.15, exit 1) in place of the configuration error (exit 2). + - Likewise, a baseline whose configuration is such a file is no longer refused for its configuration (6.3). It reconstructs exactly when its content validates as a workspace, so not while that finding stands. +- **Generated modules.** They still carry no xspec runtime dependency (13.1). The product's module serves the configuration alone. +- **Nothing else.** No command gains a read, write, network access, or durable state, and the module has no effect of its own (change 2, Runtime). Determinism, JSON output, and the exit-code partition are unaffected beyond the relaxation. The machine-interface version (12.6) stays, since no JSON document form changes. + +## Documentation (outside `SPEC.md`) + +Per `DEVOPS.md`'s Docs rule, the release commit updates `docs/` and `README.md` for this change and meets the documentation goal recorded above. The configuration import is shown under the name the product is distributed as, and its type support is stated on `SPEC.md`'s authority. For a CommonJS project, where TypeScript under the initialized-project options (change 2) rejects a `.ts` configuration's import, the docs tell users to name the configuration file `.mts`, passing it with `--config` (7), or to declare `"type": "module"`. The alias install step is removed, and no instruction leads users to install or run the unrelated package that holds the bare name. diff --git a/src/core/code-analysis.ts b/src/core/code-analysis.ts index 866b1f1f..a103be6d 100644 --- a/src/core/code-analysis.ts +++ b/src/core/code-analysis.ts @@ -27,21 +27,27 @@ // module import's default and `text` bindings root chains and `text` // calls exactly as a valid import's do whatever other defect the // declaration carries (SPEC 4: the other binding is the invalid one; 11.2, -// 14: its 14.15 makes nothing about their uses undetectable); an invalid -// binding (a named binding other than `text`, a namespace binding) is no -// spec module reference, and a chain rooted at the binding of an `.xspec` -// require form — no spec module import (4) — is masked by that -// declaration's 14.15. A chain rooted at a shadowing local declaration or -// a type-only binding records no edge and falls under no condition (SPEC -// 4.5); its value-level misuse is the consumer's TypeScript error, outside -// xspec's validations. An identifier a spec module import binds that another -// import of the same scope, or a value-level declaration of that scope, -// also binds roots no resolving chain (SPEC 2.4, 4.5), whether or not -// either import is type-only: beside the collision's 14.15, its chains -// report as unresolved (14.7) and a call through it as `text` is a plain -// call. Imports binding one identifier in different scopes of the file -// collide all the same (14.15), each scope's own binding rooting its -// chains there. +// 14: its 14.15 makes nothing about their uses undetectable). A +// value-level binding of no permitted form (SPEC 4 → 14.15: a named +// binding of an export other than the default and `text`, a namespace +// binding) is neither a node nor a `text` binding, so 4.5 sanctions none +// of its value-level uses: each is 14.18 at the binding's identifier +// alone, beside the import's 14.15, which makes none of them undetectable +// (SPEC 14), whatever the specifier designates — a configuration file a +// code group discovers included (7: `defineConfig` of `import { +// defineConfig } from "./specs/A.xspec"`). A chain rooted at the binding +// of an `.xspec` require form — no spec module import (4) — is masked by +// that declaration's 14.15. A chain rooted at a shadowing local +// declaration or a type-only binding, of a permitted form or not, records +// no edge and falls under no condition (SPEC 4.5); its value-level misuse +// is the consumer's TypeScript error, outside xspec's validations. An +// identifier a spec module import binds that another import of the same +// scope, or a value-level declaration of that scope, also binds roots no +// resolving chain (SPEC 2.4, 4.5), whether or not either import is +// type-only: beside the collision's 14.15, its chains report as +// unresolved (14.7) and a call through it as `text` is a plain call. +// Imports binding one identifier in different scopes of the file collide +// all the same (14.15), each scope's own binding rooting its chains there. // // An import declaration is a spec module import by its specifier alone // (SPEC 4), wherever it stands: TypeScript parses one in any statement @@ -736,7 +742,10 @@ const UNDEFINED_TARGET_REASON = * binding, its uses judged as any other's (4.5, 14.18), but a chain * rooted at it — and a `text` call through it — names no target: no edge, * no occurrence (5.7, 11.2), unresolved (14.7) beside the import's 14.15, - * which makes nothing about the use undetectable (SPEC 14). + * which makes nothing about the use undetectable (SPEC 14). The invalid + * binding itself — of no permitted form — is `unpermitted` where it is + * value-level and `type-level` where introduced type-only, whatever the + * specifier designates. */ type TrackedBinding = | { @@ -759,6 +768,7 @@ type TrackedBinding = /** SPEC 4: a binding introduced type-only is a type-level name. */ readonly kind: "type-level"; } + | UnpermittedBinding | { /** * The binding of an `import X = require(…)` declaration whose @@ -772,6 +782,51 @@ type TrackedBinding = } | CollidingBinding; +/** + * SPEC 4, 4.5 → 14.18: a value-level binding of a spec module import that + * no permitted form gives — a named binding of an export other than the + * default and `text` (the export read as 2.4 reads it), or a namespace + * binding — whose import's 14.15 reports the binding itself. It is + * neither a node (a default-export binding or a chain of child property + * accesses from it) nor a `text` binding, so 4.5 sanctions none of its + * value-level uses: every one is 14.18 (14, condition 18), which the + * import's 14.15 leaves detectable (SPEC 14) — wherever the specifier + * points, a `.xspec` specifier designating nothing included, and in a + * configuration file a code group discovers too (SPEC 7: `defineConfig` + * of `import { defineConfig } from "./specs/A.xspec"`, its call in the + * default export a value-level use). As a `text` binding outside callee + * position (`visitTextBindingUse`), it roots no chain and names no node: + * SPEC 14 locates each use's 14.18 at the binding's identifier alone — a + * property chain extends a node binding's spelling only — and no use + * records an edge or an occurrence (5.7). + */ +interface UnpermittedBinding { + readonly kind: "unpermitted"; + /** The export a named binding names, as spelled; null for a namespace. */ + readonly imported: string | null; +} + +/** + * The 14.18 message for a use of `name`, a binding of no permitted form + * (SPEC 14: an actionable error stating the correction). + */ +function unpermittedUseMessage( + name: string, + binding: UnpermittedBinding, +): string { + const binds = + binding.imported === null + ? `is a namespace binding of a spec module` + : `binds the spec module's export ${JSON.stringify(binding.imported)}`; + return ( + `unsupported node usage: ${JSON.stringify(name)} ${binds}, a binding ` + + `no value-level use may take — bind the default export and the "text" ` + + `export instead, and use the default export's nodes as dependency ` + + `markers or "text" arguments and the "text" export as a callee ` + + `(SPEC 4, 4.5, 14.18)` + ); +} + /** * A `text` binding of a spec module import (SPEC 4, 4.5), the declaration * valid or carrying another 14.15 defect. @@ -1502,7 +1557,10 @@ class CodeAnalyzer { // and a removal deletes the declaration whole (6.5). Attributes are a // condition elsewhere only — in a spec source a parse failure, the MDX // edition lacking their syntax (14.20), and on the configuration's - // `xspec` import a configuration error (7, `checkImport` in config.ts). + // `defineConfig` import, read as configuration, a configuration error + // (7, `checkImport` in config.ts). A configuration file a code group + // discovers is also analyzed here as any source (7), its import judged + // by these rules alone. // Bindings (SPEC 4): the default export and the named `text` export, // each optionally aliased, optionally type-only. A side-effect-only @@ -1516,6 +1574,15 @@ class CodeAnalyzer { binding: CodeImportBinding; role: "node" | "text"; }[] = []; + /** + * The bindings of no permitted form (SPEC 4 → 14.15): declaration → + * the export a named binding names (null for a namespace binding). + */ + const unpermitted: { + declaration: tst.Node; + typeOnly: boolean; + imported: string | null; + }[] = []; if (clause !== undefined) { if (clause.name !== undefined) { const binding: CodeImportBinding = { @@ -1532,6 +1599,11 @@ class CodeAnalyzer { `it uses a namespace-import binding — the permitted bindings ` + `are the default export and the named "text" export`, ); + unpermitted.push({ + declaration: named, + typeOnly: clauseTypeOnly, + imported: null, + }); } else { for (const element of named.elements) { const imported = this.importedName(element); @@ -1552,6 +1624,11 @@ class CodeAnalyzer { `the permitted bindings are the default export and the ` + `named "text" export`, ); + unpermitted.push({ + declaration: element, + typeOnly: binding.typeOnly, + imported, + }); } } } @@ -1584,9 +1661,6 @@ class CodeAnalyzer { // (`target` set) their chains and calls resolve or report 14.7 as a // valid import's do; through a specifier designating nothing // (`target` null) they are unresolved (SPEC 2.1, 4, 11.2 → 14.7). - // An invalid binding (a named binding other than `text`, a - // namespace binding) is no role's: it is never tracked here, its - // uses no spec module reference. this.declarations.set( declaration, binding.typeOnly @@ -1594,6 +1668,21 @@ class CodeAnalyzer { : { kind: role, target, specifier, importIndex }, ); } + // SPEC 4, 4.5, 14: an invalid binding (a named binding of an export + // other than the default and `text`, a namespace binding) is no role's + // and roots no chain, but it is still this spec module import's + // binding: value-level, every use of it is unsanctioned (14.18, beside + // this declaration's 14.15, which makes no use undetectable), whatever + // the specifier designates; introduced type-only, a type-level name + // whose uses fall under no condition (4.5). Never in `importBindings`: + // no recorded chain is rooted at it (SPEC 6.5). A collision of its + // identifier (SPEC 2.4) replaces this entry in `scanModuleLinks`. + for (const { declaration, typeOnly, imported } of unpermitted) { + this.declarations.set( + declaration, + typeOnly ? { kind: "type-level" } : { kind: "unpermitted", imported }, + ); + } const quote = this.sourceFile.text[literal.getStart(this.sourceFile)]; this.imports.push({ @@ -2178,10 +2267,12 @@ class CodeAnalyzer { this.addFinding( 18, localName, - `unsupported node usage: ${JSON.stringify(local)} re-exports a ` + - `spec module binding — re-export is not a sanctioned value-level ` + - `use; consume nodes as dependency markers or "text" arguments in ` + - `this file instead (SPEC 4.5, 14.18)`, + binding.kind === "unpermitted" + ? unpermittedUseMessage(local, binding) + : `unsupported node usage: ${JSON.stringify(local)} re-exports a ` + + `spec module binding — re-export is not a sanctioned ` + + `value-level use; consume nodes as dependency markers or ` + + `"text" arguments in this file instead (SPEC 4.5, 14.18)`, ); } } @@ -2194,8 +2285,9 @@ class CodeAnalyzer { * name's leftmost identifier, extended for a node binding by the * longest static property chain (2.4) it roots there, the qualified * name's segments being non-computed accesses (`SPEC.a.b` of - * `export import X = SPEC.a.b;`), and for a `text` binding by nothing - * (`text` of `import t2 = text;`) — never the whole declaration. + * `export import X = SPEC.a.b;`), and for a `text` binding, or one of no + * permitted form, by nothing (`text` of `import t2 = text;`, `foo` of + * `import X = foo.a;`) — never the whole declaration. */ private visitImportEqualsUse(declaration: tst.ImportEqualsDeclaration): void { const reference = declaration.moduleReference; @@ -2215,6 +2307,11 @@ class CodeAnalyzer { ) { return; } + if (binding.kind === "unpermitted") { + // SPEC 4, 4.5, 14: no node binding, so no chain extends its spelling. + this.addFinding(18, name, unpermittedUseMessage(name.text, binding)); + return; + } // A colliding identifier's use here is a `text` binding's exactly // where its imports bind the `text` export and not the default one, // as visitIdentifier routes a use outside callee position (SPEC 2.4, @@ -2230,7 +2327,12 @@ class CodeAnalyzer { ); } - /** One identifier: a spec binding use, or nothing (SPEC 4.5). */ + /** + * One identifier: a spec module binding's value-level use, or nothing + * (SPEC 4.5) — an identifier TypeScript scoping resolves to no spec + * module import's binding (a shadowing local, a non-spec import, an + * undeclared name) is no spec module reference. + */ private visitIdentifier(identifier: tst.Identifier): void { if (!isValueUseSite(identifier)) return; const binding = this.bindingOfIdentifier(identifier); @@ -2242,6 +2344,13 @@ class CodeAnalyzer { // (SPEC 14). return; } + if (binding.kind === "unpermitted") { + // SPEC 4, 4.5 → 14.18: a binding of no permitted form has no + // sanctioned value-level use — every use the walk reaches is + // unsanctioned, located at the identifier alone (SPEC 14). + this.visitUnpermittedBindingUse(identifier, binding); + return; + } if (binding.kind === "colliding") { // SPEC 2.4, 4.5: the uses of the bindings its spec module imports // give it, naming no target — as a callee a `text` binding's where @@ -2265,6 +2374,33 @@ class CodeAnalyzer { this.visitNodeBindingUse(identifier, binding); } + /** + * SPEC 4, 4.5 → 14.18: one value-level use of a spec module import's + * binding of no permitted form (`UnpermittedBinding`) — as a callee + * (`foo(…)`, the configuration's `defineConfig({…})`, SPEC 7), an + * argument (of a `text` call too: `analyzeTextCall` records nothing for + * an argument rooted here), an initializer, a bare expression statement, + * a property access's or element access's root (`foo.a.b;`: never a + * marker, its chain no reference — no edge, no occurrence, no 14.7 or + * 14.8), a shorthand property, a class's `extends` expression, or an + * instantiation expression's expression. 4.5 sanctions none of them, so + * each is 14.18, located — as a `text` binding's outside callee position + * (`visitTextBindingUse`) — at the binding's identifier alone: SPEC 14 + * extends the spelling by a static property chain for a node binding + * only. Each use is reported once, here; a re-export and an import alias + * are reported by `visitExportSpecifiers` and `visitImportEqualsUse`. + */ + private visitUnpermittedBindingUse( + identifier: tst.Identifier, + binding: UnpermittedBinding, + ): void { + this.addFinding( + 18, + identifier, + unpermittedUseMessage(identifier.text, binding), + ); + } + /** * SPEC 4.5: a node binding appears only as a dependency marker — a bare * static chain in expression-statement position — or as the sole @@ -2404,7 +2540,10 @@ class CodeAnalyzer { // 14.15 already accounts for the whole call (SPEC 14). A spec module // import's `text` binding is a `text` callee whatever other defect its // declaration carries (SPEC 4, 11.2, 14). A colliding callee's call is - // no `text` call (SPEC 4.5): its arguments are ordinary uses. + // no `text` call (SPEC 4.5), nor is a call through a binding of no + // permitted form (`foo(A.a)`, even one aliased `text`: `import { foo + // as text }`), its callee 14.18 itself: their arguments are ordinary + // uses. return binding?.kind === "text" || binding?.kind === "poisoned"; } @@ -2533,16 +2672,19 @@ class CodeAnalyzer { } if ( rootBinding.kind === "text" || + rootBinding.kind === "unpermitted" || (rootBinding.kind === "colliding" && !rootBinding.node) ) { // SPEC 4.5: a `text` binding appears only as a `text` call's callee, - // so an argument rooted at one — directly, or through the accesses - // and wrappers `leftmostIdentifier` climbs — names no node and the - // call records nothing. Its use is 14.18, reported once, by the walk - // (visitIdentifier → visitTextBindingUse), which reaches every such - // root: SPEC 14 locates it at the binding's identifier alone — no - // property chain extends a `text` binding's spelling — never at the - // whole argument, and never twice. + // and a binding of no permitted form (SPEC 4 → 14.15) nowhere, so an + // argument rooted at either — directly, or through the accesses and + // wrappers `leftmostIdentifier` climbs — names no node and the call + // records nothing: no edge, no occurrence, no 14.7, 14.8, or 14.11. + // Its use is 14.18, reported once, by the walk (visitIdentifier → + // visitTextBindingUse, visitUnpermittedBindingUse), which reaches + // every such root: SPEC 14 locates it at the binding's identifier + // alone — no property chain extends either binding's spelling — + // never at the whole argument, and never twice. return; } const classified = classifyReference(argument, this.sourceFile); diff --git a/src/core/config.ts b/src/core/config.ts index f71f7c1e..60696947 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -1,22 +1,28 @@ // Project configuration: static parse and schema validation (SPEC 7). // // SPEC 7: `xspec.config.ts` is declarative — data, not executed code. The -// file MUST consist of exactly an import of `defineConfig` from the module -// specifier "xspec" (optionally aliased; no `type` or `defer` modifier and -// no import attributes) and a default export of one call -// to that binding, whose sole argument is statically literal: object -// literals with non-computed identifier or string-literal keys, array -// literals, static string literals (2.4), and the boolean literals `true` -// and `false` — no other statement or expression form, no spread, no -// computed value. Every string literal it holds, and every key, is read as +// file MUST consist of exactly an import of `defineConfig` (optionally +// aliased; no `type` or `defer` modifier and no import attributes) whose +// module specifier is any static string literal (2.4), and a default +// export of one call to that binding, whose sole argument is statically +// literal: object literals with non-computed identifier or string-literal +// keys, array literals, static string literals (2.4), and the boolean +// literals `true` and `false` — no other statement or expression form, no +// spread, no computed value. Every string literal read here — the +// argument's, and a string-literal import name — and every key is read as // spelled (SPEC 2.4: "every configuration literal (7)"; SPEC 7: a key is // repeated when two keys spell the same name) — no escape sequence is -// interpreted. IMPLEMENTATION (Key libraries): the file is parsed with -// the TypeScript compiler API as an AST reduced to data, never executed or -// imported. A file that is not well-formed TypeScript or does not conform, -// and every schema violation of SPEC 7.1–7.5, is a configuration error -// (14.14) — reported by every command at configuration load as a usage -// error (12.0, exit 2), preceding all source analysis. +// interpreted. The import's specifier is never read at all: wherever xspec +// reads a configuration, a baseline's (6.3) included, it never interprets, +// resolves, or loads the specifier, so the configuration's validity, and +// everything derived from it, are independent of what the specifier +// designates and of its spelling (SPEC 7). IMPLEMENTATION (Key +// libraries): the file is parsed with the TypeScript compiler API as an +// AST reduced to data, never executed or imported. A file that is not +// well-formed TypeScript or does not conform, and every schema violation +// of SPEC 7.1–7.5, is a configuration error (14.14) — reported by every +// command at configuration load as a usage error (12.0, exit 2), preceding +// all source analysis. // // This module is pure: it maps configuration text to a validated // `Configuration` or to condition-14 findings. Locating and reading the @@ -275,8 +281,8 @@ function checkSyntax( const FORM_EXPECTATION = `the configuration must consist of exactly an import of defineConfig ` + - `from "xspec" (optionally aliased) and a default export of one call to ` + - `that binding (SPEC 7)`; + `(optionally aliased) whose module specifier is any static string ` + + `literal, and a default export of one call to that binding (SPEC 7)`; /** * SPEC 7: the file MUST consist of exactly the `defineConfig` import and @@ -322,8 +328,9 @@ function checkForm( } /** - * SPEC 7: exactly an import of `defineConfig` from the module specifier - * "xspec", optionally aliased. Returns the local binding name, or null. + * SPEC 7: exactly an import of `defineConfig`, optionally aliased, whose + * module specifier is any static string literal (2.4) — never interpreted, + * resolved, or loaded. Returns the local binding name, or null. */ function checkImport( decl: tst.ImportDeclaration, @@ -332,16 +339,27 @@ function checkImport( ): string | null { let ok = true; const specifier = decl.moduleSpecifier; - // SPEC 2.4: the specifier is a configuration literal, its value the - // characters between its delimiters as spelled — an escape-spelled - // "xspec" is some other specifier. - if ( - !ts.isStringLiteral(specifier) || - stringLiteralValue(specifier, sourceFile) !== "xspec" - ) { + // SPEC 7: the module specifier is any static string literal (2.4: a + // plain single- or double-quoted string; a template literal is not + // static), whatever it spells and whatever, if anything, it designates — + // a bare or scoped package name, a relative or absolute path, a URL, or + // the empty string, in either quote style, with escape sequences, line + // continuations, or U+FFFD alike. Wherever xspec reads a configuration, a + // baseline's (6.3) included, the specifier is never interpreted, + // resolved, or loaded, so its value is never read: only its node kind is + // examined here. A spelling TypeScript's scanner rejects — an escape it + // refuses — leaves the file not well-formed (14.20), which `checkSyntax` + // reports before the form is read. TypeScript's parser takes any + // expression in the specifier's place, its checker alone requiring a + // string literal, so an identifier, a template literal, or a + // parenthesized string parses with no syntax diagnostic: such a file + // does not conform, refused here by 7's form (14.14). + if (!ts.isStringLiteral(specifier)) { findings.add( - `the import must be from the module specifier "xspec", read as ` + - `spelled with no escape sequence interpreted (SPEC 7, 2.4)`, + `the import's module specifier must be a static string literal — a ` + + `plain single- or double-quoted string, whatever it spells; a ` + + `template literal or any other expression is not static (SPEC 7, ` + + `2.4)`, lineOf(specifier, sourceFile), ); ok = false; @@ -374,7 +392,7 @@ function checkImport( ok = false; } // SPEC 7: "no `type` or `defer` modifier". TypeScript 5.9 parses - // `import defer { defineConfig } from "xspec"` with no syntax diagnostic + // `import defer { defineConfig } from "…"` with no syntax diagnostic // (a deferred import's namespace-only rule is a checker rule, which // configuration loading never runs), so the clause's phase modifier is // read here; the clause starts at the `defer` keyword. @@ -397,9 +415,9 @@ function checkImport( const named = clause.namedBindings; if (named === undefined || !ts.isNamedImports(named)) { findings.add( - `the import must be a named import of defineConfig ` + - `(\`import { defineConfig } from "xspec"\`, optionally aliased) ` + - `(SPEC 7)`, + `the import must be a named import of defineConfig — ` + + `import { defineConfig } from "…", optionally aliased, its ` + + `module specifier any static string literal (SPEC 7)`, lineOf(decl, sourceFile), ); return null; diff --git a/src/index.cts b/src/index.cts new file mode 100644 index 00000000..3bdb6543 --- /dev/null +++ b/src/index.cts @@ -0,0 +1,166 @@ +// The `defineConfig` module (SPEC 7.6) along the `require` route: the +// package's root entry as package.json's `exports["."].require` names it, +// compiled to dist/index.cjs and typed by dist/index.d.cts. Its twin, +// index.mts, is the same module along the `import` route (dist/index.mjs, +// typed by dist/index.d.mts): the two declare the same configuration type, +// alias for alias, and must not drift apart. The aliases below are copied +// from index.mts byte for byte, and that file's header gives their reasons +// (one export and no type; aliases, never interfaces; the type contract) and +// the runtime contract both entries keep. +// +// Why a CommonJS entry (SPEC 7.6, Reach and Runtime): the module must load +// through `require` in a CommonJS module, with no option, environment +// variable, or module customization hook, on every release of the Node.js 22 +// line and of every later line. On 22.0 to 22.11 `require` cannot load an ES +// module without a flag, so the `require` route names this CommonJS file. A +// `.cjs` file is CommonJS by its extension alone, whatever the manifest's +// `type` says and whether or not Node.js reads it (it reads none for the +// package installed as node_modules/node_modules). IMPLEMENTATION.md's "ES +// modules throughout" yields to 7.6 here, as that document's preamble rules +// wherever a choice it names cannot satisfy SPEC.md (the Liaison's ruling of +// 2026-10-29); every other module of the product stays an ES module. +// +// Why `export =`: tsc compiles a `.cts` source as CommonJS, and under +// tsconfig.base.json's `verbatimModuleSyntax` a CommonJS-format file cannot +// carry a top-level `export` modifier on a value (TS1287). `export =` of an +// object literal compiles to `module.exports = { defineConfig };` with no +// `__esModule` marker (tsc writes one only for ES-syntax exports), so the +// `require` result's one own property, string- or symbol-keyed, is +// `defineConfig` (SPEC 7.6, Runtime). In dist/index.d.cts tsc types the +// assignment as a constant of type `{ defineConfig: typeof defineConfig }`: +// its one member is the one export a named import of the module binds in a +// file TypeScript compiles as CommonJS under `node16` or `nodenext`, the +// setups that resolve the `require` entry (SPEC 7.6, Type contract), and +// the default import TypeScript admits there for interoperation with +// CommonJS is no export the module declares. + +/** + * A non-empty list (SPEC 7.4, 7.5): `targetTags`, `edgeKinds`, a rule's + * `kinds`, and a selector's `tags` must not be empty (14.14). Repeated + * elements are admitted, as 7.4 and 7.5 read these lists as sets. + */ +type NonEmpty<T> = [T, ...T[]]; + +/** + * A dependency edge kind a profile's `edgeKinds` and a rule's `kinds` admit + * (SPEC 7.4, 7.5) — not `"contains"`, the edge kind 5.2 also defines. + */ +type EdgeKind = "depends" | "embeds" | "references"; + +/** A group's kind: `boundaryKind` (SPEC 7.4) and a selector's `kind` (7.5). */ +type GroupKind = "spec" | "code"; + +/** + * Named groups, each a list of globs: `specs` (SPEC 7.1) and `code` (7.2). + * Any name is a group name, and a group's list may be empty (7). A plain + * `string[]`, never a tuple: TypeScript 5.9.3 types an object-literal key + * naming a member of the global `Object` interface (`constructor`, + * `toString`, and the like) by that member rather than by this index + * signature, so such a group's list would lose a tuple's contextual typing + * and fail to type-check though valid. + */ +type Groups = { [name: string]: string[] }; + +/** The `markdown` key (SPEC 7.3). */ +type Markdown = { + /** Whether pure Markdown files are emitted (SPEC 7.3). */ + emit: boolean; + /** + * A directory relative to the workspace root into which emitted files are + * redirected, preserving workspace-relative paths (SPEC 7.3). + */ + outDir?: string; +}; + +/** A named coverage profile (SPEC 7.4). */ +type Profile = { + /** The profile's unique name. */ + name: string; + /** The spec group whose requirements must be covered. */ + target: string; + /** Restricts the target set to nodes carrying at least one listed tag. */ + targetTags?: NonEmpty<string>; + /** `"leaves"` (the default) restricts the target set to childless nodes. */ + targets?: "leaves" | "all"; + /** The spec or code group that counts as the coverage boundary. */ + boundary: string; + /** Required exactly when `boundary` names both a spec and a code group. */ + boundaryKind?: GroupKind; + mode: "direct" | "transitive"; + /** The edge kinds coverage paths use; all three by default. */ + edgeKinds?: NonEmpty<EdgeKind>; +}; + +/** A group selector (SPEC 7.5). */ +type GroupSelector = { + group: string; + /** Required exactly when the name is both a spec and a code group. */ + kind?: GroupKind; + files?: never; + tags?: never; +}; + +/** A files selector (SPEC 7.5): a glob, with capture wildcards. */ +type FilesSelector = { + files: string; + group?: never; + kind?: never; + tags?: never; +}; + +/** A tags selector (SPEC 7.5): matches nodes carrying a listed tag. */ +type TagsSelector = { + tags: NonEmpty<string>; + group?: never; + kind?: never; + files?: never; +}; + +/** + * A policy selector (SPEC 7.5) matches by exactly one of `group`, `files`, + * and `tags`, and only a group selector carries `kind`. Each form declares the + * other forms' keys optional and `never`, so a selector using two or three + * forms, none (`{}`), or `kind` without `group` matches no member of this + * union, while an unknown key is excess in every member. + */ +type Selector = GroupSelector | FilesSelector | TagsSelector; + +/** A named policy rule constraining dependency edges (SPEC 7.5). */ +type Rule = { + /** The rule's unique name. */ + name: string; + type: "forbidden" | "allowedOnly"; + from: Selector; + to: Selector; + /** The edge kinds the rule constrains; all three by default. */ + kinds?: NonEmpty<EdgeKind>; +}; + +/** + * The `defineConfig` argument (SPEC 7): `specs` required; `code`, + * `markdown`, `coverage`, and `policy` optional, an empty `coverage` or + * `policy` list being valid. + */ +type Config = { + specs: Groups; + code?: Groups; + markdown?: Markdown; + coverage?: Profile[]; + policy?: Rule[]; +}; + +/** + * `xspec.config.ts` default-exports one call to this function (SPEC 7, 7.6). + * Not generic: its argument is checked against `Config` itself, so + * TypeScript's excess-property check reports an unknown key at every level, + * where inference into a type parameter would check none. At run time it is + * the identity: it returns the very value passed, never examined, copied, or + * modified (`undefined` when called with none; further arguments ignored), and + * does nothing else. + */ +function defineConfig(config: Config): Config { + return config; +} + +// The module's one export (SPEC 7.6): the `require` result is this object. +export = { defineConfig }; diff --git a/src/index.mts b/src/index.mts new file mode 100644 index 00000000..5675a569 --- /dev/null +++ b/src/index.mts @@ -0,0 +1,167 @@ +// The `defineConfig` module (SPEC 7.6) along the `import` route: the +// package's root entry as package.json's `exports["."].import` names it, +// compiled to dist/index.mjs and typed by dist/index.d.mts, which the +// top-level `types` also names for TypeScript's `node10` resolution (it reads +// no `exports`). Its twin, index.cts, is the same module along the `require` +// route (dist/index.cjs, typed by dist/index.d.cts): the two declare the same +// configuration type, alias for alias, and must not drift apart. +// +// One export and no type (SPEC 7.6): the module exports exactly one binding, +// `defineConfig`. The configuration type is therefore built from unexported +// type aliases alone, and this file's one `export` keeps them unexported in +// the declaration file too, which tsc closes with `export {}` (a declaration +// module with no export list exports every top-level declaration). Aliases, +// never interfaces: where a consumer's declaration emit is on, as under 7.6's +// initialized-project options, the declaration of the consumer's default +// export inlines an unexported alias's structure, while an unexported +// interface cannot be named there and fails a valid configuration (TS4082). +// +// The type contract (SPEC 7.6, over the configuration of 7 to 7.5): every +// configuration valid under 7 type-checks, and each member of 7.6's +// type-error class fails to — an unknown key at any level, a missing required +// key, a value of a kind 7 does not admit, a string outside 7's enumerations, +// a selector not in exactly one of its forms, and an empty `targetTags`, +// `edgeKinds`, rule `kinds`, or selector `tags`. Every other configuration +// error (14.14) is left to xspec's static validation, the authoritative one. +// +// The runtime contract (SPEC 7.6): `defineConfig` returns its first argument +// itself and does nothing else, and loading the module has no effect. xspec +// never executes or imports a configuration (SPEC 7); this module serves the +// consumer's type checking and editor support alone. +// +// Why an `.mjs` file: SPEC 7.6 covers every installation name, `node_modules` +// among them, on every release of the Node.js 22 line. Node.js's +// package-scope lookup, which reads a manifest's `type`, stops without +// reading a package.json that sits directly in a directory named +// node_modules, so for the package installed as node_modules/node_modules its +// own `"type": "module"` is never read: a `.js` entry would be read as +// CommonJS and, on releases predating module-syntax detection (22.0 among +// them), fail to load. An `.mjs` file is an ES module by its extension alone. + +/** + * A non-empty list (SPEC 7.4, 7.5): `targetTags`, `edgeKinds`, a rule's + * `kinds`, and a selector's `tags` must not be empty (14.14). Repeated + * elements are admitted, as 7.4 and 7.5 read these lists as sets. + */ +type NonEmpty<T> = [T, ...T[]]; + +/** + * A dependency edge kind a profile's `edgeKinds` and a rule's `kinds` admit + * (SPEC 7.4, 7.5) — not `"contains"`, the edge kind 5.2 also defines. + */ +type EdgeKind = "depends" | "embeds" | "references"; + +/** A group's kind: `boundaryKind` (SPEC 7.4) and a selector's `kind` (7.5). */ +type GroupKind = "spec" | "code"; + +/** + * Named groups, each a list of globs: `specs` (SPEC 7.1) and `code` (7.2). + * Any name is a group name, and a group's list may be empty (7). A plain + * `string[]`, never a tuple: TypeScript 5.9.3 types an object-literal key + * naming a member of the global `Object` interface (`constructor`, + * `toString`, and the like) by that member rather than by this index + * signature, so such a group's list would lose a tuple's contextual typing + * and fail to type-check though valid. + */ +type Groups = { [name: string]: string[] }; + +/** The `markdown` key (SPEC 7.3). */ +type Markdown = { + /** Whether pure Markdown files are emitted (SPEC 7.3). */ + emit: boolean; + /** + * A directory relative to the workspace root into which emitted files are + * redirected, preserving workspace-relative paths (SPEC 7.3). + */ + outDir?: string; +}; + +/** A named coverage profile (SPEC 7.4). */ +type Profile = { + /** The profile's unique name. */ + name: string; + /** The spec group whose requirements must be covered. */ + target: string; + /** Restricts the target set to nodes carrying at least one listed tag. */ + targetTags?: NonEmpty<string>; + /** `"leaves"` (the default) restricts the target set to childless nodes. */ + targets?: "leaves" | "all"; + /** The spec or code group that counts as the coverage boundary. */ + boundary: string; + /** Required exactly when `boundary` names both a spec and a code group. */ + boundaryKind?: GroupKind; + mode: "direct" | "transitive"; + /** The edge kinds coverage paths use; all three by default. */ + edgeKinds?: NonEmpty<EdgeKind>; +}; + +/** A group selector (SPEC 7.5). */ +type GroupSelector = { + group: string; + /** Required exactly when the name is both a spec and a code group. */ + kind?: GroupKind; + files?: never; + tags?: never; +}; + +/** A files selector (SPEC 7.5): a glob, with capture wildcards. */ +type FilesSelector = { + files: string; + group?: never; + kind?: never; + tags?: never; +}; + +/** A tags selector (SPEC 7.5): matches nodes carrying a listed tag. */ +type TagsSelector = { + tags: NonEmpty<string>; + group?: never; + kind?: never; + files?: never; +}; + +/** + * A policy selector (SPEC 7.5) matches by exactly one of `group`, `files`, + * and `tags`, and only a group selector carries `kind`. Each form declares the + * other forms' keys optional and `never`, so a selector using two or three + * forms, none (`{}`), or `kind` without `group` matches no member of this + * union, while an unknown key is excess in every member. + */ +type Selector = GroupSelector | FilesSelector | TagsSelector; + +/** A named policy rule constraining dependency edges (SPEC 7.5). */ +type Rule = { + /** The rule's unique name. */ + name: string; + type: "forbidden" | "allowedOnly"; + from: Selector; + to: Selector; + /** The edge kinds the rule constrains; all three by default. */ + kinds?: NonEmpty<EdgeKind>; +}; + +/** + * The `defineConfig` argument (SPEC 7): `specs` required; `code`, + * `markdown`, `coverage`, and `policy` optional, an empty `coverage` or + * `policy` list being valid. + */ +type Config = { + specs: Groups; + code?: Groups; + markdown?: Markdown; + coverage?: Profile[]; + policy?: Rule[]; +}; + +/** + * `xspec.config.ts` default-exports one call to this function (SPEC 7, 7.6). + * Not generic: its argument is checked against `Config` itself, so + * TypeScript's excess-property check reports an unknown key at every level, + * where inference into a type parameter would check none. At run time it is + * the identity: it returns the very value passed, never examined, copied, or + * modified (`undefined` when called with none; further arguments ignored), and + * does nothing else. + */ +export function defineConfig(config: Config): Config { + return config; +} diff --git a/src/index.ts b/src/index.ts deleted file mode 100644 index 8b58131b..00000000 --- a/src/index.ts +++ /dev/null @@ -1,80 +0,0 @@ -// The `xspec` package entry: the `defineConfig` export that -// `xspec.config.ts` imports (SPEC 7; IMPLEMENTATION Distribution). The -// configuration is declarative — the product parses `xspec.config.ts` -// statically and never executes or imports it (SPEC 7) — so `defineConfig` -// is an identity function: its value to consumers is the type checking and -// editor support they get while authoring the configuration. The types -// below mirror the SPEC 7 schema; the authoritative validation is the -// product's static one (14.14). - -/** SPEC 7.3: the `markdown` key. */ -export interface XspecMarkdownConfig { - /** Whether pure Markdown files are emitted (SPEC 7.3). */ - readonly emit: boolean; - /** - * Optional directory, relative to the workspace root and resolving - * within it, into which emitted files are redirected preserving - * workspace-relative paths (SPEC 7.3). - */ - readonly outDir?: string; -} - -/** SPEC 7.4: one named coverage profile. */ -export interface XspecCoverageProfile { - /** Unique profile name. */ - readonly name: string; - /** Spec group whose requirements must be covered. */ - readonly target: string; - /** When present, restricts the target set by tags; must not be empty. */ - readonly targetTags?: readonly string[]; - /** `"leaves"` (default) restricts the target set to childless nodes. */ - readonly targets?: "leaves" | "all"; - /** Spec or code group counting as the coverage boundary. */ - readonly boundary: string; - /** Required exactly when `boundary` names both a spec and a code group. */ - readonly boundaryKind?: "spec" | "code"; - readonly mode: "direct" | "transitive"; - /** Subset of the dependency edge kinds; defaults to all three. */ - readonly edgeKinds?: readonly ("depends" | "embeds" | "references")[]; -} - -/** SPEC 7.5: a selector matches by exactly one of group, files, or tags. */ -export type XspecPolicySelector = - | { - readonly group: string; - /** Required exactly when the name is both a spec and a code group. */ - readonly kind?: "spec" | "code"; - } - | { readonly files: string } - | { readonly tags: readonly string[] }; - -/** SPEC 7.5: one named policy rule constraining dependency edges. */ -export interface XspecPolicyRule { - /** Unique rule name. */ - readonly name: string; - readonly type: "forbidden" | "allowedOnly"; - readonly from: XspecPolicySelector; - readonly to: XspecPolicySelector; - /** Subset of the dependency edge kinds; defaults to all three. */ - readonly kinds?: readonly ("depends" | "embeds" | "references")[]; -} - -/** SPEC 7: the `defineConfig` argument. */ -export interface XspecConfig { - /** Named groups of xspec source files, each a list of globs (SPEC 7.1). */ - readonly specs: Readonly<Record<string, readonly string[]>>; - /** Named groups of TypeScript source files (SPEC 7.2). */ - readonly code?: Readonly<Record<string, readonly string[]>>; - readonly markdown?: XspecMarkdownConfig; - readonly coverage?: readonly XspecCoverageProfile[]; - readonly policy?: readonly XspecPolicyRule[]; -} - -/** - * SPEC 7: `xspec.config.ts` default-exports one call to this function, - * whose sole argument is statically literal. Identity at runtime; the - * configuration is only ever read statically by xspec. - */ -export function defineConfig<T extends XspecConfig>(config: T): T { - return config; -} diff --git a/src/tsconfig.json b/src/tsconfig.json index bb29f108..1b8725eb 100644 --- a/src/tsconfig.json +++ b/src/tsconfig.json @@ -1,6 +1,24 @@ { // The product program (`xspec`). Compiled by `npm run build` to dist/; // dist/cli/bin.js is the `xspec` executable declared in package.json. + // + // The defineConfig module (SPEC 7.6) is the package's root entry, one file + // per route that package.json's `exports` names: + // import the ES module dist/index.mjs, compiled from index.mts, typed + // by dist/index.d.mts (which the top-level `types` also names, + // for TypeScript's `node10` resolution, which reads no + // `exports`). An `.mjs` file is an ES module by its extension + // alone, as it must be: Node.js reads no `type` from the manifest + // of a package installed as node_modules/node_modules, an + // installation name 7.6 covers, and 22.0 predates module-syntax + // detection, so a `.js` entry would load as CommonJS there and + // fail; + // require the CommonJS module dist/index.cjs, compiled from index.cts, + // typed by dist/index.d.cts, so that the module loads through + // `require` with no option on every Node.js release 7.6 covers, + // 22.0 through 22.11 included, where `require` cannot load an ES + // module. Hence `.mts` and `.cts` sources are compiled too. + // // This project must never include files from test/ — the harness is a // separate program (TEST-SPEC H-2; IMPLEMENTATION.md). "extends": "../tsconfig.base.json", @@ -9,5 +27,5 @@ "outDir": "../dist", "declaration": true }, - "include": ["./**/*.ts"] + "include": ["./**/*.ts", "./**/*.mts", "./**/*.cts"] } diff --git a/test/fixtures/conf-avail/product.mjs b/test/fixtures/conf-avail/product.mjs index c3801c9b..e42bb435 100644 --- a/test/fixtures/conf-avail/product.mjs +++ b/test/fixtures/conf-avail/product.mjs @@ -305,18 +305,27 @@ async function findConfigPath(cwd, configFlag) { /** * Parse the declarative configuration (SPEC 7): exactly an import of - * `defineConfig` from "xspec" (optionally aliased) and a default export of - * one call whose sole argument is statically literal. Returns the argument - * as data. Any other form is a configuration error (SPEC 14.14, exit 2). + * `defineConfig` (optionally aliased) whose module specifier is any static + * string literal (2.4), and a default export of one call whose sole argument + * is statically literal. Returns the argument as data. Any other form is a + * configuration error (SPEC 14.14, exit 2). */ function parseConfigSource(text) { + // The module specifier is matched as spelled and never decoded, + // interpreted, resolved, or loaded (SPEC 7; CERTIFICATIONS.md preamble): + // a static string literal in either quote style, each of its characters + // any but its own quote, a backslash, U+000A, and U+000D, or a backslash + // with the character after it (CRLF taken whole): escape sequences and + // line continuations alike. An escape TypeScript's scanner rejects is + // accepted too: a conformer judges 14.20 on its accepting side alone + // (TEST-SPEC S-9). const importMatch = - /import\s*\{\s*defineConfig(?:\s+as\s+([A-Za-z_$][\w$]*))?\s*\}\s*from\s*(["'])xspec\2\s*;?/.exec( + /import\s*\{\s*defineConfig(?:\s+as\s+([A-Za-z_$][\w$]*))?\s*\}\s*from\s*(?:"(?:[^"\\\n\r]|\\(?:\r\n|[\s\S]))*"|'(?:[^'\\\n\r]|\\(?:\r\n|[\s\S]))*')\s*;?/.exec( text, ); if (!importMatch) { throw new UsageError( - 'configuration error: xspec.config.ts must import { defineConfig } from "xspec" (SPEC 7, 14.14)', + "configuration error: xspec.config.ts must import { defineConfig } from a static string literal (SPEC 7, 14.14)", ); } const binding = importMatch[1] ?? "defineConfig"; diff --git a/test/fixtures/conf-core/product.mjs b/test/fixtures/conf-core/product.mjs index 44e7369d..e34d0238 100644 --- a/test/fixtures/conf-core/product.mjs +++ b/test/fixtures/conf-core/product.mjs @@ -416,18 +416,27 @@ async function findConfigPath(cwd, configFlag) { /** * Parse the declarative configuration (SPEC 7): exactly an import of - * `defineConfig` from "xspec" (optionally aliased) and a default export of - * one call whose sole argument is statically literal. Returns the argument - * as data. Any other form is a configuration error (SPEC 14.14, exit 2). + * `defineConfig` (optionally aliased) whose module specifier is any static + * string literal (2.4), and a default export of one call whose sole argument + * is statically literal. Returns the argument as data. Any other form is a + * configuration error (SPEC 14.14, exit 2). */ function parseConfigSource(text) { + // The module specifier is matched as spelled and never decoded, + // interpreted, resolved, or loaded (SPEC 7; CERTIFICATIONS.md preamble): + // a static string literal in either quote style, each of its characters + // any but its own quote, a backslash, U+000A, and U+000D, or a backslash + // with the character after it (CRLF taken whole): escape sequences and + // line continuations alike. An escape TypeScript's scanner rejects is + // accepted too: a conformer judges 14.20 on its accepting side alone + // (TEST-SPEC S-9). const importMatch = - /import\s*\{\s*defineConfig(?:\s+as\s+([A-Za-z_$][\w$]*))?\s*\}\s*from\s*(["'])xspec\2\s*;?/.exec( + /import\s*\{\s*defineConfig(?:\s+as\s+([A-Za-z_$][\w$]*))?\s*\}\s*from\s*(?:"(?:[^"\\\n\r]|\\(?:\r\n|[\s\S]))*"|'(?:[^'\\\n\r]|\\(?:\r\n|[\s\S]))*')\s*;?/.exec( text, ); if (!importMatch) { throw new UsageError( - 'configuration error: xspec.config.ts must import { defineConfig } from "xspec" (SPEC 7, 14.14)', + "configuration error: xspec.config.ts must import { defineConfig } from a static string literal (SPEC 7, 14.14)", ); } const binding = importMatch[1] ?? "defineConfig"; diff --git a/test/fixtures/conf-disc/product.mjs b/test/fixtures/conf-disc/product.mjs index eea3b7fb..c8f35a46 100644 --- a/test/fixtures/conf-disc/product.mjs +++ b/test/fixtures/conf-disc/product.mjs @@ -399,18 +399,27 @@ async function findConfigPath(cwd, configFlag) { /** * Parse the declarative configuration (SPEC 7): exactly an import of - * `defineConfig` from "xspec" (optionally aliased) and a default export of - * one call whose sole argument is statically literal. Returns the argument - * as data. Any other form is a configuration error (SPEC 14.14, exit 2). + * `defineConfig` (optionally aliased) whose module specifier is any static + * string literal (2.4), and a default export of one call whose sole argument + * is statically literal. Returns the argument as data. Any other form is a + * configuration error (SPEC 14.14, exit 2). */ function parseConfigSource(text) { + // The module specifier is matched as spelled and never decoded, + // interpreted, resolved, or loaded (SPEC 7; CERTIFICATIONS.md preamble): + // a static string literal in either quote style, each of its characters + // any but its own quote, a backslash, U+000A, and U+000D, or a backslash + // with the character after it (CRLF taken whole): escape sequences and + // line continuations alike. An escape TypeScript's scanner rejects is + // accepted too: a conformer judges 14.20 on its accepting side alone + // (TEST-SPEC S-9). const importMatch = - /import\s*\{\s*defineConfig(?:\s+as\s+([A-Za-z_$][\w$]*))?\s*\}\s*from\s*(["'])xspec\2\s*;?/.exec( + /import\s*\{\s*defineConfig(?:\s+as\s+([A-Za-z_$][\w$]*))?\s*\}\s*from\s*(?:"(?:[^"\\\n\r]|\\(?:\r\n|[\s\S]))*"|'(?:[^'\\\n\r]|\\(?:\r\n|[\s\S]))*')\s*;?/.exec( text, ); if (!importMatch) { throw new UsageError( - 'configuration error: xspec.config.ts must import { defineConfig } from "xspec" (SPEC 7, 14.14)', + "configuration error: xspec.config.ts must import { defineConfig } from a static string literal (SPEC 7, 14.14)", ); } const binding = importMatch[1] ?? "defineConfig"; diff --git a/test/fixtures/conf-import/bin-braced.mjs b/test/fixtures/conf-import/bin-braced.mjs new file mode 100644 index 00000000..d45c14d6 --- /dev/null +++ b/test/fixtures/conf-import/bin-braced.mjs @@ -0,0 +1,27 @@ +#!/usr/bin/env node +// VIOL-IMPORT-BRACED violator executable (CERTIFICATIONS.md +// §VIOL-IMPORT-BRACED). The CONF-IMPORT conformer with exactly one +// behavioral deviation: the braced form of the Unicode escape sequence (a +// backslash, `u`, and a code point's hex digits in braces) is not recognized +// in the configuration's import specifier where its code point is at or +// below U+FFFF, leading zeros and surrogates included — a specifier spelling +// one is judged not well-formed TypeScript (14.20), so its configuration is +// a configuration error (14.14), every command exiting 2 with the 12.7 +// configuration-error document concerning `xspec.config.ts`. A braced escape +// begins where the grammar 14.20 fixes begins one — at a backslash that +// itself begins an escape sequence and is followed by `u{` — never at a +// backslash a preceding backslash escapes, after which `u{…}` is ordinary +// characters, read as the conformer reads them. A single deviation: one +// escape form of the grammar 14.20 fixes dropped, for the specifier and +// those code points alone, consumed at product.mjs's one hook +// (`specifierRefusal`); a braced escape above U+FFFF, the four-digit form, +// every other escape sequence, line continuations, either quote style, and +// every other spelling are the conformer's. Certifies P-19 (C-1): exactly it +// fails against this fixture, on each draw whose specifier spells such an +// escape — the §CONF-IMPORT in-scope set has no other test. +import { runXspec } from "./product.mjs"; + +const code = await runXspec(process.argv.slice(2), process.cwd(), { + refuseBracedEscapes: true, +}); +process.exit(code); diff --git a/test/fixtures/conf-import/bin-single.mjs b/test/fixtures/conf-import/bin-single.mjs new file mode 100644 index 00000000..08840600 --- /dev/null +++ b/test/fixtures/conf-import/bin-single.mjs @@ -0,0 +1,21 @@ +#!/usr/bin/env node +// VIOL-IMPORT-SINGLE violator executable (CERTIFICATIONS.md +// §VIOL-IMPORT-SINGLE). The CONF-IMPORT conformer with exactly one +// behavioral deviation: a single-quoted module specifier is refused — the +// configuration's import is read only where its specifier is double-quoted, +// a configuration whose specifier is single-quoted being a configuration +// error (14.14), every command exiting 2 with the 12.7 configuration-error +// document concerning `xspec.config.ts`. A single deviation: one quote style +// of the static string literal 2.4 defines dropped, for the specifier alone, +// consumed at product.mjs's one hook (`specifierRefusal`); a double-quoted +// specifier — whatever its text, escapes, line continuations, and code +// points — and every other literal of the configuration, single-quoted globs +// included, are the conformer's. Certifies P-19 (C-1): exactly it fails +// against this fixture, on each draw whose specifier is single-quoted — the +// §CONF-IMPORT in-scope set has no other test. +import { runXspec } from "./product.mjs"; + +const code = await runXspec(process.argv.slice(2), process.cwd(), { + refuseSingleQuotes: true, +}); +process.exit(code); diff --git a/test/fixtures/conf-import/bin.mjs b/test/fixtures/conf-import/bin.mjs new file mode 100644 index 00000000..236c22c2 --- /dev/null +++ b/test/fixtures/conf-import/bin.mjs @@ -0,0 +1,10 @@ +#!/usr/bin/env node +// CONF-IMPORT conformer executable (CERTIFICATIONS.md §CONF-IMPORT). The +// certification runner drives this file exactly as it drives the built +// product — an executable/workspace binding and nothing else (TEST-SPEC C-2). +// Violator fixtures (VIOL-IMPORT-*) reuse product.mjs with exactly one +// behavioral deviation each; this entry runs the conformer, deviation-free. +import { runXspec } from "./product.mjs"; + +const code = await runXspec(process.argv.slice(2), process.cwd(), {}); +process.exit(code); diff --git a/test/fixtures/conf-import/product.mjs b/test/fixtures/conf-import/product.mjs new file mode 100644 index 00000000..f5cc1823 --- /dev/null +++ b/test/fixtures/conf-import/product.mjs @@ -0,0 +1,2101 @@ +// CONF-IMPORT conformer fixture (CERTIFICATIONS.md §CONF-IMPORT; TEST-SPEC 17 +// C-1/C-2). A harness-owned executable product implementing §CONF-IMPORT's +// Scope with the simplest conforming behavior — driven only through the C-2 +// executable/workspace binding, never importing product code (the product and +// the harness are distinct programs; this fixture is part of the harness). +// +// Scope implemented (see CERTIFICATIONS.md §CONF-IMPORT): +// - T7-9's workspace outside its install stagings, as P-19 draws over it: +// configured spec groups of trivial single-section `.mdx` sources — one +// line holding an opening `<S id="…">` (or `<Spec id="…">`) tag, plain +// text, and the matching closing tag, with at most one final line +// terminator (T7-9(d)'s `specs/A.mdx`, `<S id="a">A</S>`) — and `markdown` +// with `emit: true`, emitting next to sources (7.3, 13.2); `emit: false`, +// an absent `markdown`, and an `outDir` are handled as 7.3 states. No code +// group (an empty `code` map aside), no `coverage` or `policy` rule (an +// empty list aside), no journal, no review sessions, no git. Anything +// outside that shape — another source form, a code group, a rule, a +// journal, a session directory, another command — is refused loudly with +// exit 70 (`xspec: fixture scope error: …` on stderr), outside SPEC 12.0's +// exit partition: a fixture-side condition, never a product verdict. +// - The configuration's import, read as 7 states (CERTIFICATIONS.md +// preamble): its module specifier is any static string literal (2.4), in +// either quote style — escape sequences of every form, line +// continuations, U+FFFD, and other non-ASCII code points included — whose +// characters are read as spelled and never decoded, interpreted, +// resolved, or loaded: nothing is read and no network access is made on +// its account, so the configuration's validity and every answer are +// independent of it. Well-formedness (14.20) is judged on its accepting +// side alone (TEST-SPEC S-9): the tokenizer takes a backslash together +// with the character after it (a carriage return and line feed pair +// whole), and ends a literal at its own quote alone, so a spelling +// TypeScript's scanner rejects is accepted too. The configuration file is +// a source only where a configured glob matches it (7). +// - Command surface: `build` (12.1), `check` (12.2), `ids` (12.3), and +// `inventory` (11.6) in its full 12.7 document form, each with `--json` +// and `--config` and behaving per 12.0 and 13.3 — `build` generating each +// source's module (13.1) and its Markdown (13.2) and writing graph data +// whose record lists the derived paths generated (13.3), the record +// `inventory` reports (11.6). None is mutating (13.5: `rename`, `move`, +// and the mutating `review` subcommands), so `--test-hold`, value-taking +// by name all the same, is an unknown flag of each: the usage error of +// 12.0. +// - Universal rules (CERTIFICATIONS.md preamble): the configuration is +// located by upward search for `xspec.config.ts` from the working +// directory, or at the path `--config` names, resolved against the +// working directory (7, 12.0); configured paths and globs resolve against +// the configuration file's directory, the workspace root; the arguments +// are read under 12.0's invocation grammar (`readInvocation`) — flag +// tokens anywhere, a value-taking flag taking the whole next token, arity +// fixed by name for every command, `--` ending flag reading, the remaining +// tokens matching the synopsis exactly — and, with JSON in effect, every +// usage or configuration error (exit 2) is the 12.7 error document. +// +// Key mechanisms: +// - Every syntax-class check (12.0) precedes configuration loading and +// every scope refusal: first the checks the arguments decide for every +// command alike (`readInvocation`: unknown, repeated, or valueless flags; +// malformed values), then the command word and `query`'s subcommand, then +// the served command's synopsis (`checkSynopsis`) and `ids --file`'s +// outside-root spelling. Only then are a command outside the surface, a +// `query` subcommand, and the flags `ids` names but this fixture does not +// serve (`--tree`, `--file`, `--unreferenced`) refused (exit 70). +// - Discovery (7, 13.4) lists a directory — the workspace root, or one +// reached from it through directories alone — exactly when a configured +// glob matches a path below it, `.xspec/` counting for none, and never +// follows or discovers a symbolic link; globs are byte-wise (`*`, `?`, +// `**` as a whole segment, the dot-segment rule); derived files — +// `.xspec.` names, `.xspec/` paths, and, while emission is enabled, the +// configured Markdown emit destinations, by configuration alone — are no +// sources. A `.mdx` source whose path holds `#`, U+FFFD, or a character +// 7.1 bars is one 14.19 finding beside its content's analysis; a spec +// match without `.mdx`, whose content 14.19 would leave to be analyzed as +// a spec source's, is outside the scope (exit 70) wherever sources are +// analyzed, and `inventory`, which parses none, lists it with its derived +// paths structurally absent. +// - `build` (12.1): validates (14.19, and 14.22 over its own write paths); +// on findings exits 1, modifying nothing. Otherwise it writes each +// source's module `NAME.xspec.ts` (13.1: fixed bytes naming the source, +// beginning with the generated-file header of 4 — content beyond the path +// is out of scope, and no companion is written) and, while emission is +// enabled, its Markdown per 3 (the two tags removed, the text and the +// line's terminator kept), replacing each path's occupant and never +// writing through a link (13.4); then removes every recorded path no +// longer generated (13.4); then writes graph data — the graph +// (`.xspec/graph.json`) and, last, the record of the derived paths +// generated (`.xspec/record.json`), a layout no consumer sees (13.3). +// - `check` (12.2): the same validations, then 14.10's forms: the per-file +// form (each generated path's occupant judged itself: a plain file +// holding exactly the generated bytes, or stale) and the graph-data unit +// form (the graph missing or mismatching), both on a workspace passing +// the validations alone; the unreadable-record unit form (14.23) and the +// recorded-file form on any workspace. It never refreshes; exits 1 on +// any finding. +// - `ids` (12.3, 13.3): the gate — `build`'s validations, their findings +// reported with exit 1, nothing evaluated or written past it — then the +// refresh: where the graph is missing or mismatches what `build` would +// now write, the graph alone is rewritten, no TypeScript or Markdown +// generated or removed and the record left as it stands; then the +// listing, one entry per discovered spec source in byte order of path, +// its IDs in document order. +// - `inventory` (11.6): JSON-only, the full 12.7 document — anchoring +// (physical paths, relative to the working directory), the resolved +// configuration view, the discovered sources with their groups, the +// derived-file map, the record (or, where recorded state exists that +// cannot be read as one, the unavailability marker with its 14.23 +// finding, exit 1), the graph-data area, the journal's occupancy, the +// (empty) session list, and the lock path — parsing no source and writing +// nothing. +// +// Determinism (SPEC 12.0): no wall clock, no randomness, no absolute paths in +// any output; paths in byte order; all JSON serialized with byte-sorted keys; +// graph data a function of the discovered sources and groups alone. Nothing +// written depends on the configuration's import, so a workspace whose +// specifier is spelled otherwise writes every module and Markdown file +// byte-identical to its twin's. +// +// This source holds no backslash: every special character is built from its +// code point (`BACKSLASH`, `LF`, `CR`, …), so no tool handling the file can +// decode an escape sequence out of it. +// +// Deviation seam: runXspec(argv, cwd, options) assigns `options` onto the +// module-level `deviations` switches (all off = this conformer). The +// configuration's specifier is read in one place, `parseConfigText`, which +// returns its quote character and its spelled characters and gives them no +// meaning; `loadConfig` hands them to `specifierRefusal`, the violators' one +// hook, which makes a configuration error (14.14) of the class of spellings +// a switch refuses — `refuseBracedEscapes` (VIOL-IMPORT-BRACED, +// `bin-braced.mjs`) and `refuseSingleQuotes` (VIOL-IMPORT-SINGLE, +// `bin-single.mjs`) — and of nothing while every switch is off. + +import { Buffer } from "node:buffer"; +import { createHash } from "node:crypto"; +import * as fsp from "node:fs/promises"; +import * as path from "node:path"; + +// --------------------------------------------------------------------------- +// Code points (this source spells no backslash; see the header) +// --------------------------------------------------------------------------- + +const cp = (code) => String.fromCodePoint(code); + +const BACKSLASH = cp(0x5c); +const LF = cp(0x0a); +const CR = cp(0x0d); +const LINE_SEPARATOR = cp(0x2028); +const PARAGRAPH_SEPARATOR = cp(0x2029); +const REPLACEMENT_CHARACTER = cp(0xfffd); +const BACKTICK = cp(0x60); + +/** + * ECMAScript's WhiteSpace and LineTerminator code points (14.20): tab, + * vertical tab, form feed, space, no-break space, the byte-order mark, the + * other space separators (Zs), line feed, carriage return, and U+2028 and + * U+2029 — what separates the configuration's tokens. + */ +const CONFIG_SPACE = new Set([ + 0x09, 0x0b, 0x0c, 0x20, 0xa0, 0xfeff, 0x1680, 0x2000, 0x2001, 0x2002, 0x2003, + 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a, 0x202f, 0x205f, + 0x3000, 0x0a, 0x0d, 0x2028, 0x2029, +]); + +/** SPEC 1.4's whitespace: tab, LF, vertical tab, form feed, CR, space. */ +const SPEC_WHITESPACE = new Set([0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x20]); + +// --------------------------------------------------------------------------- +// Outcome carriers +// --------------------------------------------------------------------------- + +/** + * Usage or configuration error (SPEC 12.0 exit 2): the message on stderr in + * both output forms, after the concerned path when one is set (14); with + * JSON output in effect the 12.7 error document is the entire stdout. + * `code`/`path` are the error finding's stable code and concerned path — + * set for a configuration error (14.14: `configuration-error` and the + * concerned path in the anchoring form), `null` for a plain usage error. + */ +class UsageError extends Error { + constructor(message, { code = null, path = null } = {}) { + super(message); + this.code = code; + this.path = path; + } +} + +/** Findings (SPEC 12.0 exit 1): the findings report on stdout. */ +class FindingsError extends Error { + constructor(findings) { + super("findings"); + this.findings = findings; + } +} + +/** + * An invocation or workspace outside this fixture's scope + * (CERTIFICATIONS.md §CONF-IMPORT) that a conforming product would answer: + * refused loudly with exit 70, outside the 12.0 partition, so a test reaching + * it fails on its exit-code assertion with the cause on stderr — never on a + * fabricated answer or a false usage error. + */ +class ScopeError extends Error {} + +// --------------------------------------------------------------------------- +// Canonical JSON (sorted keys, SPEC 12.0) and byte order +// --------------------------------------------------------------------------- + +/** Byte-wise comparison of two strings' UTF-8 encodings (SPEC 12.0). */ +function compareBytes(a, b) { + return Buffer.compare(Buffer.from(a, "utf8"), Buffer.from(b, "utf8")); +} + +function byteSorted(strings) { + return [...strings].sort(compareBytes); +} + +function sortKeysDeep(value) { + if (Array.isArray(value)) return value.map(sortKeysDeep); + if (value !== null && typeof value === "object") { + const sorted = {}; + for (const key of Object.keys(value).sort(compareBytes)) { + sorted[key] = sortKeysDeep(value[key]); + } + return sorted; + } + return value; +} + +/** One serializer for every JSON document: sorted keys, two-space indent. */ +function canonicalJson(value) { + return JSON.stringify(sortKeysDeep(value), null, 2); +} + +// --------------------------------------------------------------------------- +// Deviation switches, all off in the conformer; assigned by runXspec from +// each entry's options (module header). +// --------------------------------------------------------------------------- + +let deviations = {}; + +// --------------------------------------------------------------------------- +// Invocation grammar (SPEC 12.0) +// --------------------------------------------------------------------------- + +/** + * Every flag of every command with its arity, fixed by name (12.0): 1 for a + * flag taking the whole next token as its value, 0 for one taking none — the + * flags the synopses and defining sections name (6, 8, 9, 10.7, 11, 12, + * 13.5). A `--` token naming no flag of any command takes no value. + */ +const FLAG_ARITY = new Map([ + ["--json", 0], + ["--preview", 0], + ["--tree", 0], + ["--text", 0], + ["--check", 0], + ["--unreferenced", 0], + ["--config", 1], + ["--test-hold", 1], + ["--file", 1], + ["--to", 1], + ["--from", 1], + ["--kinds", 1], + ["--group", 1], + ["--tag", 1], + ["--coverage", 1], + ["--base", 1], + ["--strategy", 1], + ["--name", 1], + ["--status", 1], + ["--note", 1], +]); + +/** Every command of the product (12). */ +const PRODUCT_COMMANDS = new Set([ + "build", + "check", + "ids", + "show", + "coverage", + "impact", + "review", + "query", + "occurrences", + "view", + "at", + "inventory", + "rename", + "move", + "version", +]); + +/** + * The commands whose every surface is JSON-only (SPEC 12.0: 11's `query`, + * `occurrences`, `view`, `at`, and `inventory`; 12.6's `version`) — beside + * 10.7's `review export`, a subcommand's surface. + */ +const JSON_ONLY_COMMANDS = new Set([ + "query", + "occurrences", + "view", + "at", + "inventory", + "version", +]); + +/** + * Whether the invoked surface — the command word and, for `review`, its + * subcommand, both among the non-flag tokens (12.0) — is JSON-only, a single + * JSON document its only output form with or without `--json` (12.0). + */ +function isJsonOnlySurface(words) { + const [command, subcommand] = words; + return ( + JSON_ONLY_COMMANDS.has(command) || + (command === "review" && subcommand === "export") + ); +} + +/** + * The synopses this fixture judges (SPEC 11.1, 11.6, 12.1–12.3): for each + * served command and each `query` subcommand, the flags its synopsis or + * defining section names beside the globals `--json` and `--config` (12.0), + * the flags it requires, and its operand count; `unservedFlags` names the + * flags 12.3 gives `ids` that this fixture does not serve. A command outside + * this map and `query` (`show`, `view`, …) is refused once the checks the + * arguments decide for every command have passed, and every `query` + * subcommand once its synopsis has. + */ +const SYNOPSES = new Map([ + ["build", { flags: [], operands: 0 }], + ["check", { flags: [], operands: 0 }], + [ + "ids", + { + flags: ["--tree", "--file", "--unreferenced"], + operands: 0, + unservedFlags: ["--tree", "--file", "--unreferenced"], + }, + ], + ["inventory", { flags: [], operands: 0 }], +]); + +const QUERY_SYNOPSES = new Map([ + ["node", { flags: [], operands: 1 }], + [ + "nodes", + { flags: ["--group", "--file", "--tag", "--coverage"], operands: 0 }, + ], + ["edges", { flags: ["--from", "--to", "--kinds"], operands: 0 }], + ["subtree", { flags: [], operands: 1 }], + ["ancestors", { flags: [], operands: 1 }], + [ + "reachable", + { + flags: ["--from", "--to", "--kinds"], + required: ["--from", "--to"], + operands: 0, + }, + ], +]); + +/** + * An argument value is malformed when it is not valid UTF-8 or contains + * U+FFFD (SPEC 12.0); Node decodes argv lossily, an ill-formed byte arriving + * as U+FFFD, so the one test covers both. + */ +function isMalformedValue(value) { + return value.includes(REPLACEMENT_CHARACTER); +} + +/** + * Read the arguments under the grammar of SPEC 12.0: flag tokens anywhere — + * before the command word, between it and its operands, or after them — a + * value-taking flag taking the whole next token, whatever it looks like, and + * `--` ending flag reading (dropped; every later token a non-flag token). + * Returns the flags (name to value, `true` for a flag taking none), the + * remaining non-flag tokens in order — the command, `query`'s subcommand, + * then the operands — whether a `--json` token was read as a flag (never as + * another flag's value), and the first syntax-class error met that the + * arguments decide for every command alike, if any. + */ +function readInvocation(argv) { + const flags = new Map(); + const words = []; + let json = false; + let error = null; + const note = (message) => { + if (error === null) error = message; + }; + let flagsEnded = false; + for (let i = 0; i < argv.length; i += 1) { + const token = argv[i]; + if (!flagsEnded && token === "--") { + flagsEnded = true; + continue; + } + if (!flagsEnded && token.startsWith("--")) { + if (token === "--json") json = true; + if (flags.has(token)) { + note( + `repeated flag ${token}: a flag may be given at most once (SPEC 12.0)`, + ); + } + if (FLAG_ARITY.get(token) === 1) { + if (i + 1 >= argv.length) { + note(`flag ${token} lacks its value (SPEC 12.0)`); + flags.set(token, true); + } else { + i += 1; + const value = argv[i]; + if (isMalformedValue(value)) { + note( + `malformed value for ${token}: not valid UTF-8, or containing U+FFFD (SPEC 12.0)`, + ); + } + flags.set(token, value); + } + } else { + if (!FLAG_ARITY.has(token)) note(`unknown flag ${token} (SPEC 12.0)`); + flags.set(token, true); + } + continue; + } + if (isMalformedValue(token)) { + note( + "malformed argument: not valid UTF-8, or containing U+FFFD (SPEC 12.0)", + ); + } + words.push(token); + } + return { flags, words, json, error }; +} + +/** + * The synopsis checks of SPEC 12.0's syntax class for one command or `query` + * subcommand (`spelled`): every flag given is one it accepts — its + * synopsis's or defining section's, or the global `--json` and `--config` + * (`--test-hold` belongs to the mutating commands alone, 13.5, none of them + * served here) — the operands match its synopsis in number, and its + * required flags are given. + */ +function checkSynopsis(spelled, synopsis, flags, operands) { + for (const name of flags.keys()) { + if ( + name !== "--json" && + name !== "--config" && + !synopsis.flags.includes(name) + ) { + throw new UsageError(`unknown flag ${name} for ${spelled} (SPEC 12.0)`); + } + } + if (operands.length < synopsis.operands) { + throw new UsageError(`${spelled}: missing operand (SPEC 12.0)`); + } + if (operands.length > synopsis.operands) { + throw new UsageError( + `surplus operand ${operands[synopsis.operands]}: ${spelled} takes ${String(synopsis.operands)} operand(s) (SPEC 12.0)`, + ); + } + for (const name of synopsis.required ?? []) { + if (!flags.has(name)) { + throw new UsageError( + `${spelled}: missing required flag ${name} (SPEC 11.1, 12.0)`, + ); + } + } +} + +/** + * Whether a glob lies outside the workspace root, decided by its spelling + * alone (SPEC 7; for `--file`, 11 and 12.3): a leading `/`, or a depth + * falling below zero — `..` lowering it, `.`, an empty segment, and `**` + * leaving it, every other segment raising it. + */ +function globOutsideRoot(glob) { + if (glob.startsWith("/")) return true; + let depth = 0; + for (const segment of glob.split("/")) { + if (segment === "..") { + depth -= 1; + if (depth < 0) return true; + } else if (segment !== "." && segment !== "" && segment !== "**") { + depth += 1; + } + } + return false; +} + +/** + * `ids --file`'s outside-root rule (SPEC 7, 12.3, 12.0): an invalid flag + * value of the syntax class, decided by the pattern's spelling alone. + */ +function checkFileGlob(flag, value) { + if (globOutsideRoot(value)) { + throw new UsageError( + `invalid ${flag} value ${JSON.stringify(value)}: the pattern lies outside the workspace root (SPEC 7, 12.3, 12.0)`, + ); + } +} + +/** The four edge kinds (SPEC 5.2): `query edges --kinds`' vocabulary. */ +const EDGE_KINDS = new Set(["contains", "depends", "embeds", "references"]); + +/** The three dependency kinds (SPEC 5.2): `query reachable --kinds`'. */ +const DEPENDENCY_KINDS = new Set(["depends", "embeds", "references"]); + +/** + * A `<node>` or `<graph-node>` spelling's syntax (SPEC 1.5, 4.6, 12.0): at + * most one `#`, a non-empty path part, and, with a `#`, a non-empty part + * after it — judged from the argument alone, before configuration loads. + */ +function checkNodeSpelling(spelled, what, value) { + const parts = value.split("#"); + if (parts.length > 2 || parts[0] === "" || parts[1] === "") { + throw new UsageError( + `${spelled}: malformed ${what} ${JSON.stringify(value)} (SPEC 1.5, 12.0)`, + ); + } +} + +/** + * A `--kinds` list (SPEC 11.1, 12.0): comma-separated elements drawn from + * the subcommand's vocabulary; an empty element — a leading, trailing, or + * doubled comma — or one outside it is an invalid flag value. + */ +function checkKinds(spelled, value, vocabulary) { + for (const element of value.split(",")) { + if (!vocabulary.has(element)) { + throw new UsageError( + `${spelled}: invalid --kinds value ${JSON.stringify(value)} (SPEC 11.1, 12.0)`, + ); + } + } +} + +/** The names 1.4 bars as an ID segment or tag. */ +const BARRED_NAMES = new Set([ + "$", + "__proto__", + "prototype", + "constructor", + "then", +]); + +/** + * Whether a spelling is a well-formed tag (SPEC 1.4, 2.6): non-empty, no + * control character or whitespace, none of `#`, the quotes, the backslash, + * `&`, U+2028, U+2029, or U+FFFD, and no barred name (`.` is admitted). + */ +function isWellFormedTag(value) { + if (value === "" || BARRED_NAMES.has(value)) return false; + for (const char of value) { + const code = char.codePointAt(0); + if (code <= 0x20 || code === 0x7f) return false; + if ( + [ + "#", + '"', + "'", + BACKSLASH, + "&", + LINE_SEPARATOR, + PARAGRAPH_SEPARATOR, + ].includes(char) || + char === REPLACEMENT_CHARACTER + ) { + return false; + } + } + return true; +} + +/** + * The value spellings of `query`'s flags and operands that SPEC 12.0 puts in + * the syntax class (11.1): identities with at most one `#`, `--kinds` + * against its subcommand's vocabulary, `--coverage` against `required` and + * `none`, `--tag` as a well-formed tag, and `--file`'s outside-root rule. + */ +function checkQueryValues(spelled, subcommand, flags, operands) { + for (const operand of operands) checkNodeSpelling(spelled, "node", operand); + for (const name of ["--from", "--to"]) { + if (flags.has(name)) { + checkNodeSpelling(spelled, `${name} graph node`, flags.get(name)); + } + } + if (flags.has("--kinds")) { + checkKinds( + spelled, + flags.get("--kinds"), + subcommand === "reachable" ? DEPENDENCY_KINDS : EDGE_KINDS, + ); + } + if (flags.has("--coverage")) { + const value = flags.get("--coverage"); + if (value !== "required" && value !== "none") { + throw new UsageError( + `${spelled}: invalid --coverage value ${JSON.stringify(value)}: required or none (SPEC 11.1, 12.0)`, + ); + } + } + if (flags.has("--tag") && !isWellFormedTag(flags.get("--tag"))) { + throw new UsageError( + `${spelled}: malformed --tag value ${JSON.stringify(flags.get("--tag"))} (SPEC 1.4, 11.1, 12.0)`, + ); + } + if (flags.has("--file")) checkFileGlob("--file", flags.get("--file")); +} + +// --------------------------------------------------------------------------- +// Filesystem occupants (SPEC 13.4: judged at the path itself, never through +// a symbolic link) +// --------------------------------------------------------------------------- + +/** + * The kind of a path's occupant, read with lstat: "dir", "file", "symlink", + * "other", or "absent". A path below a non-directory component reads as + * absent (ENOTDIR); `occupantKind` walks a workspace path's components. + */ +async function lstatKind(absPath) { + try { + const stats = await fsp.lstat(absPath); + if (stats.isDirectory()) return "dir"; + if (stats.isFile()) return "file"; + if (stats.isSymbolicLink()) return "symlink"; + return "other"; + } catch (error) { + if (error.code === "ENOENT" || error.code === "ENOTDIR") return "absent"; + throw error; + } +} + +/** A workspace-relative path's absolute form under the root. */ +function absUnder(rootAbs, rel) { + return path.join(rootAbs, ...rel.split("/")); +} + +/** + * The occupant of a workspace-relative path as 13.4's reads judge it: below + * a workspace-relative directory component that is absent or occupied by + * anything other than a directory — a symbolic link included, whatever it + * targets — nothing is read, the path holding nothing ("absent"). + */ +async function occupantKind(rootAbs, rel) { + const segments = rel.split("/"); + for (let i = 1; i < segments.length; i += 1) { + const component = segments.slice(0, i).join("/"); + if ((await lstatKind(absUnder(rootAbs, component))) !== "dir") { + return "absent"; + } + } + return lstatKind(absUnder(rootAbs, rel)); +} + +/** + * A plain workspace-relative path (1.5, 7.3): one or more non-empty + * `/`-separated segments, none `.` or `..`. + */ +function isPlainRelativePath(value) { + return ( + typeof value === "string" && + value !== "" && + value.split("/").every((s) => s !== "" && s !== "." && s !== "..") + ); +} + +/** Valid UTF-8 text, or null; a byte-order mark is kept as a character. */ +function decodeUtf8(bytes) { + try { + return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode( + bytes, + ); + } catch { + return null; + } +} + +/** Whether the bytes begin with a UTF-8 byte-order mark (EF BB BF). */ +function beginsWithBom(bytes) { + return bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf; +} + +// --------------------------------------------------------------------------- +// Configuration (SPEC 7): location, declarative parse, validation +// --------------------------------------------------------------------------- + +const CONFIG_NAME = "xspec.config.ts"; + +/** + * The anchoring form of SPEC 11.6 and 14: `absPath` relative to the working + * directory, `/`-joined, `.` for the working directory itself — both + * entering as physical paths, which the caller resolves (11.6); where no + * relative path exists (roots on different Windows drives), the platform's + * absolute form as given. + */ +function anchoringPath(cwdReal, absPath) { + const rel = path.relative(cwdReal, absPath); + if (rel === "") return "."; + if (path.isAbsolute(rel)) return rel; + return rel.split(path.sep).join("/"); +} + +/** + * Locate, read, parse, and validate the configuration (SPEC 7, 14.14). The + * configuration file is the occupant of the path the upward search finds — + * the nearest directory, the working directory first, holding an entry named + * `xspec.config.ts`, whatever occupies it — or the path `--config` names, + * resolved against the working directory, and is read only when it is a + * plain file. Every defect is one configuration error concerning that path + * in the anchoring form; a `--config` path nothing occupies is reported as + * given, and missing configuration with no `--config` as `.` (14). + */ +async function loadConfig(cwd, configFlag) { + const cwdAbs = path.resolve(cwd); + let configPath; + if (configFlag !== undefined) { + configPath = path.resolve(cwdAbs, configFlag); + if ((await lstatKind(configPath)) === "absent") { + throw new UsageError( + `configuration error: --config ${configFlag} names nothing (SPEC 7, 14.14)`, + { code: "configuration-error", path: configFlag }, + ); + } + } else { + let dir = cwdAbs; + for (;;) { + const candidate = path.join(dir, CONFIG_NAME); + if ((await lstatKind(candidate)) !== "absent") { + configPath = candidate; + break; + } + const parent = path.dirname(dir); + if (parent === dir) { + throw new UsageError( + `configuration error: no ${CONFIG_NAME} found by upward search from the working directory (SPEC 7, 14.14)`, + { code: "configuration-error", path: "." }, + ); + } + dir = parent; + } + } + const cwdReal = await fsp.realpath(cwdAbs); + const rootReal = await fsp.realpath(path.dirname(configPath)); + const configAnchor = anchoringPath( + cwdReal, + path.join(rootReal, path.basename(configPath)), + ); + const configError = (what) => + new UsageError(`configuration error: ${what} (SPEC 7, 14.14)`, { + code: "configuration-error", + path: configAnchor, + }); + if ((await lstatKind(configPath)) !== "file") { + throw configError( + "the configuration path holds something other than a plain file", + ); + } + let bytes; + try { + bytes = await fsp.readFile(configPath); + } catch (error) { + if (error.code === "EACCES" || error.code === "EPERM") { + throw configError("the configuration file cannot be read (14.25)"); + } + throw error; + } + if (beginsWithBom(bytes)) { + throw configError("the file begins with a byte-order mark"); + } + const text = decodeUtf8(bytes); + if (text === null) throw configError("the file is not valid UTF-8"); + const { data, specifier } = parseConfigText(text, configError); + // The violators' one hook (module header): the specifier as read, judged + // by the deviation switches alone, before validation as well-formedness + // (14.20) precedes it. The conformer, every switch off, refuses nothing. + const refusal = specifierRefusal(specifier); + if (refusal !== null) throw configError(refusal); + return { + ...validateConfig(data, configError), + root: path.dirname(configPath), + rootAnchor: anchoringPath(cwdReal, rootReal), + configAnchor, + configError, + }; +} + +/** ECMAScript whitespace and line terminators, between tokens (14.20). */ +function isConfigSpace(c) { + return CONFIG_SPACE.has(c.codePointAt(0)); +} + +function isLineTerminator(c) { + return ( + c === LF || c === CR || c === LINE_SEPARATOR || c === PARAGRAPH_SEPARATOR + ); +} + +const WORD_PATTERN = /[A-Za-z_$][A-Za-z0-9_$]*/y; + +/** + * Tokens of the declarative configuration (SPEC 7): punctuators, identifier + * words, and static string literals, with whitespace and comments + * contributing nothing. A string literal runs from its quote character to + * the next same quote not taken by a backslash: a backslash takes the + * character after it with it — a carriage return and line feed pair whole, + * so a line continuation after any line terminator stays inside — and a raw + * line feed or carriage return ends no literal but is refused, as + * TypeScript refuses it. The token's value is the characters between the + * delimiters exactly as spelled, no escape sequence interpreted (2.4), and + * the token keeps its quote character. + */ +function tokenizeConfig(text, configError) { + const tokens = []; + let i = 0; + while (i < text.length) { + const c = text[i]; + if (isConfigSpace(c)) { + i += 1; + continue; + } + if (c === "/" && text[i + 1] === "/") { + i += 2; + while (i < text.length && !isLineTerminator(text[i])) i += 1; + continue; + } + if (c === "/" && text[i + 1] === "*") { + const end = text.indexOf("*/", i + 2); + if (end === -1) throw configError("an unterminated block comment"); + i = end + 2; + continue; + } + if ("{}[](),:;".includes(c)) { + tokens.push({ type: "punct", value: c }); + i += 1; + continue; + } + if (c === '"' || c === "'") { + let j = i + 1; + while (j < text.length && text[j] !== c) { + if (text[j] === LF || text[j] === CR) { + throw configError("a line break inside a string literal"); + } + if (text[j] === BACKSLASH) { + j += text[j + 1] === CR && text[j + 2] === LF ? 3 : 2; + } else { + j += 1; + } + } + if (j >= text.length) throw configError("an unterminated string literal"); + tokens.push({ type: "string", quote: c, value: text.slice(i + 1, j) }); + i = j + 1; + continue; + } + WORD_PATTERN.lastIndex = i; + const word = WORD_PATTERN.exec(text); + if (word !== null) { + tokens.push({ type: "word", value: word[0] }); + i += word[0].length; + continue; + } + throw configError( + `unexpected character at offset ${String(i)}: only the declarative form is admitted`, + ); + } + return tokens; +} + +/** + * Parse the declarative configuration (SPEC 7): exactly an import of + * `defineConfig` (optionally aliased; no `type` or `defer` modifier, no + * import attributes) whose module specifier is any static string literal + * (2.4), and a default export of one call to that binding whose sole + * argument is statically literal — object literals with non-computed + * identifier or string-literal keys (a key repeated within one object a + * configuration error), array literals, static string literals, and + * `true`/`false`. Objects are returned as Maps, in spelling order. The + * specifier is returned as read — its quote character and its spelled + * characters — and given no meaning (module header). + */ +function parseConfigText(text, configError) { + const tokens = tokenizeConfig(text, configError); + let i = 0; + const peekIs = (type, value) => + tokens[i] !== undefined && + tokens[i].type === type && + (value === undefined || tokens[i].value === value); + const take = (type, value, what) => { + if (!peekIs(type, value)) throw configError(`expected ${what}`); + const token = tokens[i]; + i += 1; + return token; + }; + take("word", "import", "the import of defineConfig"); + take("punct", "{", '"{" in the import of defineConfig'); + take("word", "defineConfig", "the name defineConfig"); + let binding = "defineConfig"; + if (peekIs("word", "as")) { + i += 1; + binding = take("word", undefined, "the import's alias").value; + } + if (peekIs("punct", ",")) i += 1; + take("punct", "}", '"}" in the import of defineConfig'); + take("word", "from", '"from"'); + // The module specifier: any static string literal token, read as spelled + // and never decoded, interpreted, resolved, or loaded (SPEC 7; + // CERTIFICATIONS.md preamble). A spelling TypeScript's scanner rejects is + // accepted too: 14.20 is judged on its accepting side alone (S-9). + const specifierToken = take( + "string", + undefined, + "the module specifier, a static string literal", + ); + if (peekIs("punct", ";")) i += 1; + take("word", "export", "the default export"); + take("word", "default", '"default"'); + take("word", binding, `a call of ${binding}`); + take("punct", "(", `"(" after ${binding}`); + const parseValue = () => { + if (peekIs("string")) return take("string", undefined, "a string").value; + if (peekIs("word", "true") || peekIs("word", "false")) { + return take("word", undefined, "a boolean").value === "true"; + } + if (peekIs("punct", "{")) { + i += 1; + const object = new Map(); + while (!peekIs("punct", "}")) { + const key = peekIs("string") + ? take("string", undefined, "a key").value + : take("word", undefined, "an object key").value; + if (object.has(key)) { + throw configError(`the key ${JSON.stringify(key)} is repeated`); + } + take("punct", ":", `":" after the key ${JSON.stringify(key)}`); + object.set(key, parseValue()); + if (!peekIs("punct", ",")) break; + i += 1; + } + take("punct", "}", '"}" closing an object literal'); + return object; + } + if (peekIs("punct", "[")) { + i += 1; + const array = []; + while (!peekIs("punct", "]")) { + array.push(parseValue()); + if (!peekIs("punct", ",")) break; + i += 1; + } + take("punct", "]", '"]" closing an array literal'); + return array; + } + throw configError( + "expected a static literal: an object, array, string, or boolean", + ); + }; + const value = parseValue(); + if (peekIs("punct", ",")) i += 1; + take("punct", ")", `")" closing the call of ${binding}`); + if (peekIs("punct", ";")) i += 1; + if (i !== tokens.length) { + throw configError("content after the default export"); + } + if (!(value instanceof Map)) { + throw configError("defineConfig takes one object literal"); + } + return { + data: value, + specifier: { quote: specifierToken.quote, spelled: specifierToken.value }, + }; +} + +/** A braced Unicode escape's code point digits: one or more hex digits. */ +const HEX_DIGITS = /^[0-9A-Fa-f]+$/; + +/** + * Whether a specifier's spelled characters hold a braced Unicode escape (a + * backslash, `u`, and a code point's hex digits in braces) of a code point + * at or below U+FFFF, leading zeros and surrogates included + * (VIOL-IMPORT-BRACED). The characters are read left to right as the grammar + * 14.20 fixes reads them, as the tokenizer does: a backslash begins an + * escape sequence and takes the character after it with it (a carriage + * return and line feed pair whole), so a braced escape begins only at a + * backslash that itself begins an escape and is followed by `u{` — never at + * one a preceding backslash escapes, after which `u{…}` is ordinary + * characters — and every other escape is passed over whole or read on as + * ordinary characters, which begin none. + */ +function spellsBracedEscapeAtOrBelowFfff(spelled) { + let i = 0; + while (i < spelled.length) { + if (spelled[i] !== BACKSLASH) { + i += 1; + continue; + } + if (spelled[i + 1] === "u" && spelled[i + 2] === "{") { + const close = spelled.indexOf("}", i + 3); + const digits = close === -1 ? "" : spelled.slice(i + 3, close); + if (HEX_DIGITS.test(digits) && Number.parseInt(digits, 16) <= 0xffff) { + return true; + } + } + i += spelled[i + 1] === CR && spelled[i + 2] === LF ? 3 : 2; + } + return false; +} + +/** + * The violators' one hook (module header): the configuration error (14.14) + * a deviation switch makes of the configuration's import specifier as read — + * its quote character and its spelled characters — or null, which the + * conformer, every switch off, always returns. + * - `refuseBracedEscapes` (VIOL-IMPORT-BRACED): a specifier spelling a + * braced Unicode escape of a code point at or below U+FFFF is judged not + * well-formed TypeScript (14.20); a braced escape above U+FFFF, the + * four-digit form, every other escape, line continuations, both quote + * styles, and every other spelling are read as the conformer reads them. + * - `refuseSingleQuotes` (VIOL-IMPORT-SINGLE): a single-quoted specifier is + * refused, the import read only where its specifier is double-quoted; a + * double-quoted specifier, whatever it holds, and every other literal of + * the configuration are read as the conformer reads them. + */ +function specifierRefusal(specifier) { + if ( + deviations.refuseBracedEscapes && + spellsBracedEscapeAtOrBelowFfff(specifier.spelled) + ) { + return "the module specifier is not a well-formed string literal: a braced Unicode escape of a code point at or below U+FFFF"; + } + if (deviations.refuseSingleQuotes && specifier.quote === "'") { + return "the module specifier must be a double-quoted string literal"; + } + return null; +} + +/** One group map (7.1, 7.2): named lists of globs, in configuration order. */ +function validatedGroups(value, section, configError) { + if (!(value instanceof Map)) { + throw configError(`${section} must be an object literal of named groups`); + } + const groups = []; + for (const [name, globs] of value) { + if (name === "") throw configError(`an empty ${section} group name`); + if (name.includes(REPLACEMENT_CHARACTER)) { + throw configError(`a ${section} group name containing U+FFFD`); + } + if (!Array.isArray(globs) || globs.some((g) => typeof g !== "string")) { + throw configError( + `the ${section} group ${JSON.stringify(name)} must be a list of glob strings`, + ); + } + for (const glob of globs) { + if (globOutsideRoot(glob)) { + throw configError( + `the glob ${JSON.stringify(glob)} lies outside the workspace root`, + ); + } + } + groups.push({ name, globs }); + } + return groups; +} + +/** + * Validate the parsed configuration (SPEC 7, 7.1–7.3): `specs` required; + * unknown keys anywhere a configuration error; `markdown.emit` a required + * boolean and `markdown.outDir` a plain workspace-relative path outside the + * graph-data area. A code group, a `coverage` profile, and a `policy` rule + * are outside this fixture's scope (an empty `code` map and empty lists + * equal omission, 7). + */ +function validateConfig(data, configError) { + const known = ["specs", "code", "markdown", "coverage", "policy"]; + for (const key of data.keys()) { + if (!known.includes(key)) { + throw configError(`the key ${JSON.stringify(key)} is unknown`); + } + } + if (!data.has("specs")) throw configError("`specs` is required"); + const specGroups = validatedGroups(data.get("specs"), "specs", configError); + if (data.has("code")) { + const codeGroups = validatedGroups(data.get("code"), "code", configError); + if (codeGroups.length > 0) { + throw new ScopeError( + "a code group is outside this fixture's scope (CERTIFICATIONS.md §CONF-IMPORT: no code group)", + ); + } + } + for (const key of ["coverage", "policy"]) { + if (!data.has(key)) continue; + const value = data.get(key); + if (!Array.isArray(value)) + throw configError(`the key ${key} must be a list`); + if (value.length > 0) { + throw new ScopeError( + `the configuration key ${key} is outside this fixture's scope (CERTIFICATIONS.md §CONF-IMPORT: no coverage or policy)`, + ); + } + } + let emit = false; + let outDir = null; + if (data.has("markdown")) { + const markdown = data.get("markdown"); + if (!(markdown instanceof Map)) { + throw configError("`markdown` must be an object literal"); + } + for (const key of markdown.keys()) { + if (key !== "emit" && key !== "outDir") { + throw configError(`the key markdown.${key} is unknown`); + } + } + if (typeof markdown.get("emit") !== "boolean") { + throw configError("markdown.emit is required and must be true or false"); + } + emit = markdown.get("emit"); + if (markdown.has("outDir")) { + const value = markdown.get("outDir"); + if (!isPlainRelativePath(value)) { + throw configError( + "markdown.outDir must be one or more non-empty segments, none . or .., with no leading /", + ); + } + if (value === ".xspec" || value.startsWith(".xspec/")) { + throw configError("markdown.outDir lies in the graph-data area .xspec"); + } + outDir = value; + } + } + return { specGroups, emit, outDir }; +} + +// --------------------------------------------------------------------------- +// Discovery (SPEC 7, 13.4) +// --------------------------------------------------------------------------- + +const DOT = 0x2e; +const STAR = 0x2a; +const QUESTION = 0x3f; + +/** One pattern segment against one path segment, byte-wise (SPEC 7). */ +function segmentMatches(pattern, name) { + const p = Buffer.from(pattern, "utf8"); + const s = Buffer.from(name, "utf8"); + // A path segment beginning with `.` is matched only by a pattern segment + // written with a leading `.` (SPEC 7). + if (s[0] === DOT && p[0] !== DOT) return false; + const match = (i, j) => { + if (i === p.length) return j === s.length; + if (p[i] === STAR) { + for (let k = j; k <= s.length; k += 1) { + if (match(i + 1, k)) return true; + } + return false; + } + if (j === s.length) return false; + if (p[i] === QUESTION || p[i] === s[j]) return match(i + 1, j + 1); + return false; + }; + return match(0, 0); +} + +/** + * Glob matching (SPEC 7): `*` any possibly empty byte run within a segment, + * `?` one byte, `**` — as a whole pattern segment only — any number of + * whole segments including none (never a dot-initial one), every other + * character a literal; `.`, `..`, and empty pattern segments match nothing, + * since no discovered path carries such a segment. + */ +function globMatches(glob, rel) { + const patterns = glob.split("/"); + const names = rel.split("/"); + const match = (i, j) => { + if (i === patterns.length) return j === names.length; + if (patterns[i] === "**") { + if (match(i + 1, j)) return true; + for (let k = j; k < names.length; k += 1) { + if (names[k].startsWith(".")) return false; + if (match(i + 1, k + 1)) return true; + } + return false; + } + if (j === names.length) return false; + return segmentMatches(patterns[i], names[j]) && match(i + 1, j + 1); + }; + return match(0, 0); +} + +/** Whether a pattern segment can match a path segment at all (SPEC 7). */ +function segmentSatisfiable(segment) { + return segment !== "" && segment !== "." && segment !== ".."; +} + +/** + * Whether `glob` matches some path below the directory `dirRel` (workspace- + * relative, `""` for the root): the condition under which discovery lists + * that directory (SPEC 7). + */ +function globReachesBelow(glob, dirRel) { + const patterns = glob.split("/"); + const names = dirRel === "" ? [] : dirRel.split("/"); + const below = (i, j) => { + if (j === names.length) { + const rest = patterns.slice(i); + return ( + rest.length > 0 && + rest.every((segment) => segment === "**" || segmentSatisfiable(segment)) + ); + } + if (i === patterns.length) return false; + if (patterns[i] === "**") { + if (below(i + 1, j)) return true; + if (names[j].startsWith(".")) return false; + return below(i, j + 1); + } + return segmentMatches(patterns[i], names[j]) && below(i + 1, j + 1); + }; + return below(0, 0); +} + +/** + * The plain files the configured globs match (SPEC 7), workspace-relative — + * the directory-entry names descending from the root, `/`-joined — in byte + * order. Discovery lists the root, and a directory reached from it through + * directories alone, exactly when a glob matches a path below it, `.xspec` + * counting for none (13.4); it examines the kind of exactly those entries a + * glob matches or that it would list were they directories, from the + * listing itself. A symbolic link — to a file or a directory, broken or not + * — is never discovered and never traversed, and no other non-plain kind is + * a source. + */ +async function matchedFiles(config) { + const globs = config.specGroups.flatMap((group) => group.globs); + const files = []; + const walk = async (dirRel) => { + const dirAbs = dirRel === "" ? config.root : absUnder(config.root, dirRel); + const entries = await fsp.readdir(dirAbs, { withFileTypes: true }); + for (const entry of entries) { + const rel = dirRel === "" ? entry.name : `${dirRel}/${entry.name}`; + if (rel === ".xspec") continue; + const matched = globs.some((glob) => globMatches(glob, rel)); + const reaches = globs.some((glob) => globReachesBelow(glob, rel)); + if (entry.isDirectory()) { + if (reaches) await walk(rel); + } else if (entry.isFile()) { + if (matched) files.push(rel); + } + } + }; + if (globs.some((glob) => globReachesBelow(glob, ""))) await walk(""); + return byteSorted(files); +} + +/** A spec source's generated module path (13.1): `NAME.xspec.ts`. */ +function modulePathOf(sourceRel) { + return `${sourceRel.slice(0, -".mdx".length)}.xspec.ts`; +} + +/** A spec source's Markdown emit destination (13.2, 7.3): `NAME.md`. */ +function markdownPathOf(config, sourceRel) { + const emitted = `${sourceRel.slice(0, -".mdx".length)}.md`; + return config.outDir === null ? emitted : `${config.outDir}/${emitted}`; +} + +/** + * Discover the configured spec sources (SPEC 7, 13.4): the matched plain + * files less the derived files — names containing `.xspec.`, paths under + * `.xspec/`, and, while emission is enabled, the configured Markdown emit + * destinations of the matched `.mdx` files (7.3), which exist by + * configuration alone — each with the groups matching it, in configuration + * order. + */ +async function discover(config) { + const matches = []; + for (const rel of await matchedFiles(config)) { + const name = rel.slice(rel.lastIndexOf("/") + 1); + if (name.includes(".xspec.") || rel.startsWith(".xspec/")) continue; + const groups = config.specGroups + .filter((group) => group.globs.some((glob) => globMatches(glob, rel))) + .map((group) => group.name); + matches.push({ rel, groups }); + } + const emitDestinations = new Set(); + if (config.emit) { + for (const match of matches) { + if (match.rel.endsWith(".mdx")) { + emitDestinations.add(markdownPathOf(config, match.rel)); + } + } + } + const specSources = matches.filter((m) => !emitDestinations.has(m.rel)); + return { + specSources, + discovered: new Set(specSources.map((m) => m.rel)), + }; +} + +// --------------------------------------------------------------------------- +// Sources in scope: trivial single-section `.mdx` on one line +// --------------------------------------------------------------------------- + +/** A source's bytes as text: valid UTF-8 with no byte-order mark (1.6). */ +function sourceText(rel, bytes) { + if (beginsWithBom(bytes)) { + throw new ScopeError( + `${rel} begins with a byte-order mark: an unparseable source (14.20) is outside this fixture's scope`, + ); + } + const text = decodeUtf8(bytes); + if (text === null) { + throw new ScopeError( + `${rel} is not valid UTF-8: an unparseable source (14.20) is outside this fixture's scope`, + ); + } + return text; +} + +/** An ID segment in this fixture's scope: a subset of 1.4's valid ones. */ +function isScopeSegment(id) { + return /^[A-Za-z][A-Za-z0-9_-]*$/.test(id) && !BARRED_NAMES.has(id); +} + +/** + * Plain text on one line, as the scope's sections hold it: no control + * character, no line terminator, none of `<`, `>`, `{`, `}`, `&`, the + * backslash, or the backtick, and at least one character outside 1.4's + * whitespace — so the line its tags stand on keeps content once they are + * removed (3). + */ +function isPlainText(body) { + let content = false; + for (const char of body) { + const code = char.codePointAt(0); + if (code < 0x20 || code === 0x7f) return false; + if (char === LINE_SEPARATOR || char === PARAGRAPH_SEPARATOR) return false; + if ("<>{}&".includes(char) || char === BACKSLASH || char === BACKTICK) { + return false; + } + if (!SPEC_WHITESPACE.has(code)) content = true; + } + return content; +} + +/** + * The scope's spec source shape: one line holding `<S id="X">` (or + * `<Spec id="X">`), plain text, and the matching closing tag, then at most + * one line terminator (CR LF, LF, or CR) ending the file. Returns the + * section's ID, its source range (1.7: the construct from its opening tag's + * first byte through its closing tag's last), and the compiled Markdown + * (3): both tags removed, the line keeping its text and its terminator. + */ +function parseTrivialSection(rel, bytes) { + const text = sourceText(rel, bytes); + const outOfScope = (why) => + new ScopeError( + `${rel}: ${why} — this fixture's sources are trivial single-section .mdx files, one line holding the opening tag, plain text, and the closing tag (CERTIFICATIONS.md §CONF-IMPORT)`, + ); + let terminator = ""; + for (const candidate of [CR + LF, LF, CR]) { + if (text.endsWith(candidate)) { + terminator = candidate; + break; + } + } + const line = text.slice(0, text.length - terminator.length); + const open = /^<(S|Spec) id="([^"]*)">/.exec(line); + if (open === null) throw outOfScope("no opening tag at the file's start"); + if (!isScopeSegment(open[2])) throw outOfScope(`the ID ${open[2]}`); + const closing = `</${open[1]}>`; + if ( + !line.endsWith(closing) || + line.length < open[0].length + closing.length + ) { + throw outOfScope("no matching closing tag ending the line"); + } + const body = line.slice(open[0].length, line.length - closing.length); + if (!isPlainText(body)) { + throw outOfScope(`the text ${JSON.stringify(body)} is no plain text`); + } + return { + id: open[2], + range: { start: 0, end: Buffer.byteLength(line, "utf8") }, + markdown: body + terminator, + }; +} + +function sha256Hex(bytes) { + return createHash("sha256").update(bytes).digest("hex"); +} + +/** + * The generated module's bytes (13.1): the generated-file header naming the + * source (4), and nothing the configuration spells — content beyond the + * path is out of scope. + */ +function moduleContent(sourceRel) { + return Buffer.from( + `// Generated by xspec from ${sourceRel} (CONF-IMPORT fixture: module content beyond its path is out of scope).${LF}export {};${LF}`, + "utf8", + ); +} + +// --------------------------------------------------------------------------- +// Findings (SPEC 14, 12.7) +// --------------------------------------------------------------------------- + +const CODE_TOKENS = new Map([ + [10, "stale-output"], + [19, "invalid-source-path"], + [22, "obstructed-write-path"], + [23, "unreadable-record"], +]); + +function finding(condition, concerned, message) { + return { condition, path: concerned, message }; +} + +/** + * The pinned findings order (12.7): by code — the numbered conditions in + * numeric order — then locations (empty for every condition here), then + * concerned path bytes, then identities (empty), then message; identical + * findings collapse to one. + */ +function compareFindings(a, b) { + if (a.condition !== b.condition) return a.condition - b.condition; + const byPath = compareBytes(a.path, b.path); + if (byPath !== 0) return byPath; + return compareBytes(a.message, b.message); +} + +/** The findings in the 12.7 finding form, ordered and collapsed. */ +function findingForms(findings) { + const sorted = [...findings].sort(compareFindings); + return sorted + .filter((f, i) => i === 0 || compareFindings(sorted[i - 1], f) !== 0) + .map((f) => ({ + code: CODE_TOKENS.get(f.condition), + message: f.message, + locations: [], + path: f.path, + identities: [], + })); +} + +/** + * A findings report (12.0, 12.7): with JSON output in effect the document + * `{"findings": […]}`; without it one line per finding naming the path it + * concerns, its code, and its message. + */ +function emitReport(io, json, findings) { + const forms = findingForms(findings); + if (json) { + io.stdout(canonicalJson({ findings: forms }) + LF); + } else { + for (const f of forms) io.stdout(`${f.path}: ${f.code}: ${f.message}${LF}`); + } +} + +// --------------------------------------------------------------------------- +// The workspace model: sources, derived files, graph data +// --------------------------------------------------------------------------- + +// The graph-data area (13.3), its durable paths (6.1, 10.1), and the lock +// path (13.5), as `inventory` reports them (11.6). +const GRAPH_DATA_AREA = ".xspec"; +const JOURNAL_PATH = ".xspec/journal"; +const SESSION_DIRECTORY = ".xspec/reviews"; +const LOCK_PATH = ".xspec/lock"; +// The fixture's graph-data layout, unenumerated to consumers (13.3): the +// graph, which a refresh rewrites, and the record of the derived paths +// generated, which only `build` writes. +const GRAPH_FILE = ".xspec/graph.json"; +const RECORD_FILE = ".xspec/record.json"; + +/** Characters 7.1 bars from a spec source's path, beside `#` and U+FFFD. */ +const SPEC_PATH_BARRED = [ + '"', + "'", + BACKSLASH, + LF, + CR, + LINE_SEPARATOR, + PARAGRAPH_SEPARATOR, +]; + +/** + * A journal (6.1) and review sessions (10.1) are outside this fixture's + * scope: a command whose answer would consult one refuses its presence. + */ +async function refuseDurableState(config, { sessions = false } = {}) { + if ((await occupantKind(config.root, JOURNAL_PATH)) !== "absent") { + throw new ScopeError( + `a journal (${JOURNAL_PATH}) is outside this fixture's scope (CERTIFICATIONS.md §CONF-IMPORT; SPEC 6.1)`, + ); + } + if ( + sessions && + (await occupantKind(config.root, SESSION_DIRECTORY)) !== "absent" + ) { + throw new ScopeError( + `review sessions (${SESSION_DIRECTORY}) are outside this fixture's scope (CERTIFICATIONS.md §CONF-IMPORT; SPEC 10.1)`, + ); + } +} + +/** + * Discover, validate, and analyze the workspace: the 14.19 findings, the + * derived files the current sources and configuration generate (each + * `.mdx` spec source's module and, while emission is enabled, its + * Markdown), and the graph as graph data holds it — the sources with their + * groups, content hashes, and sections, nothing the configuration's import + * spells. + */ +async function loadWorkspace(config) { + const discovery = await discover(config); + const findings = []; + const derived = []; + const sources = []; + for (const source of discovery.specSources) { + const rel = source.rel; + if (!rel.endsWith(".mdx")) { + // 14.19, but an invalid path masks nothing (14): the file's content + // would be analyzed as a spec source's, which this fixture's reader of + // one-line sections cannot do — refused, never answered in part. + throw new ScopeError( + `${rel} is in a spec group without the .mdx extension: such a source is outside this fixture's scope (CERTIFICATIONS.md §CONF-IMPORT; SPEC 7.1, 14.19)`, + ); + } + if ( + [REPLACEMENT_CHARACTER, "#", ...SPEC_PATH_BARRED].some((c) => + rel.includes(c), + ) + ) { + findings.push( + finding( + 19, + rel, + `${rel} contains a character a spec source's path may not hold; rename it (SPEC 7, 7.1)`, + ), + ); + } + const bytes = await fsp.readFile(absUnder(config.root, rel)); + const section = parseTrivialSection(rel, bytes); + derived.push({ rel: modulePathOf(rel), content: moduleContent(rel) }); + if (config.emit) { + derived.push({ + rel: markdownPathOf(config, rel), + content: Buffer.from(section.markdown, "utf8"), + }); + } + sources.push({ + path: rel, + kind: "spec", + groups: source.groups, + hash: sha256Hex(bytes), + sections: [{ id: section.id, range: section.range }], + }); + } + derived.sort((a, b) => compareBytes(a.rel, b.rel)); + sources.sort((a, b) => compareBytes(a.path, b.path)); + return { + findings, + derived, + generated: new Set(derived.map((d) => d.rel)), + discovered: discovery.discovered, + graph: { sources }, + }; +} + +/** + * 14.22 over `build`'s write paths (the derived files generated and graph + * data), as `build`, `check`, and the gate of 13.3 alike judge them: each + * workspace-relative directory component occupied by anything other than a + * directory, and each module or Markdown path that is a directory component + * of another write path or of a discovered source's path — one finding per + * offending path. + */ +async function obstructionFindings(config, ws) { + const writePaths = [...ws.derived.map((d) => d.rel), GRAPH_FILE, RECORD_FILE]; + const offending = new Set(); + for (const rel of writePaths) { + const segments = rel.split("/"); + for (let i = 1; i < segments.length; i += 1) { + const component = segments.slice(0, i).join("/"); + const kind = await lstatKind(absUnder(config.root, component)); + if (kind === "absent") break; + if (kind !== "dir") { + offending.add(component); + break; + } + } + } + const others = [...writePaths, ...ws.discovered]; + for (const item of ws.derived) { + if (others.some((o) => o.startsWith(`${item.rel}/`))) { + offending.add(item.rel); + } + } + return [...offending].map((rel) => + finding( + 22, + rel, + `${rel} obstructs a path xspec writes: a directory component must be a directory, and a derived path no other write's or source's directory; move or delete what occupies it (SPEC 13.4)`, + ), + ); +} + +/** The graph's bytes as graph data holds them (13.3). */ +function graphBytes(ws) { + return Buffer.from(canonicalJson(ws.graph) + LF, "utf8"); +} + +/** The record's bytes: the derived paths generated, in byte order (13.3). */ +function recordBytes(ws) { + return Buffer.from( + canonicalJson({ derivedFiles: byteSorted(ws.generated) }) + LF, + "utf8", + ); +} + +/** + * Whether the plain file at a workspace-relative path holds exactly + * `content`, judged at the path itself (13.4, 14.10): a symbolic link, a + * directory, any other occupant, a path below a non-directory component, + * and a file whose content the environment refuses are not. + */ +async function holdsExactly(config, rel, content) { + if ((await occupantKind(config.root, rel)) !== "file") return false; + try { + return ( + Buffer.compare( + await fsp.readFile(absUnder(config.root, rel)), + content, + ) === 0 + ); + } catch (error) { + if (error.code === "EACCES" || error.code === "EPERM") return false; + throw error; + } +} + +/** + * The recorded generation state (13.3, 14.23): "empty" where none exists — + * the area absent, or a directory holding no record; "unreadable" where + * state exists that cannot be read as a record — the area's own path held + * by a non-directory, a record that is no plain file, refuses its read, or + * does not decode; "readable" otherwise, with the recorded paths in byte + * order. + */ +async function readRecord(config) { + const areaKind = await lstatKind(absUnder(config.root, GRAPH_DATA_AREA)); + if (areaKind === "absent") return { state: "empty", paths: [] }; + if (areaKind !== "dir") return { state: "unreadable" }; + const recordAbs = absUnder(config.root, RECORD_FILE); + const recordKind = await lstatKind(recordAbs); + if (recordKind === "absent") return { state: "empty", paths: [] }; + if (recordKind !== "file") return { state: "unreadable" }; + let doc; + try { + const text = decodeUtf8(await fsp.readFile(recordAbs)); + doc = text === null ? null : JSON.parse(text); + } catch { + return { state: "unreadable" }; + } + if ( + doc === null || + typeof doc !== "object" || + Array.isArray(doc) || + !Array.isArray(doc.derivedFiles) || + !doc.derivedFiles.every(isPlainRelativePath) + ) { + return { state: "unreadable" }; + } + return { state: "readable", paths: byteSorted(new Set(doc.derivedFiles)) }; +} + +// --------------------------------------------------------------------------- +// Derived-file writes and 13.4's removal of recorded paths no longer +// generated +// --------------------------------------------------------------------------- + +/** + * The occupant 13.4's removal judges for a recorded path: below a + * workspace-relative directory component that is absent or occupied by + * anything other than a directory, nothing is read — the path holds + * nothing; otherwise the path's own occupant, judged itself (lstat). + */ +async function recordedOccupant(config, rel) { + return { + kind: await occupantKind(config.root, rel), + abs: absUnder(config.root, rel), + }; +} + +/** + * Whether the removal removes the occupant (13.4): anything but a directory + * or a discovered source; a path holding nothing is left as it is. + */ +function isRemovable(occupant, rel, ws) { + return ( + occupant.kind !== "absent" && + occupant.kind !== "dir" && + !ws.discovered.has(rel) + ); +} + +/** + * Remove a recorded path no longer generated (13.4): its occupant, where + * removable, unlinked — a symbolic link as the link itself, never its + * target; anything else left as it is, the removal making no write. + */ +async function removeRecorded(config, rel, ws) { + const occupant = await recordedOccupant(config, rel); + if (isRemovable(occupant, rel, ws)) await fsp.unlink(occupant.abs); +} + +/** + * A directory at a path `build` or a refresh writes: replacing it would + * remove everything it holds (13.4), which no staging in this fixture's + * scope calls for — refused loudly before any write. + */ +async function refuseDirectoryOccupants(config, rels) { + for (const rel of rels) { + if ((await occupantKind(config.root, rel)) === "dir") { + throw new ScopeError( + `a directory occupies the derived path ${rel}: replacing it is outside this fixture's scope (CERTIFICATIONS.md §CONF-IMPORT; SPEC 13.4)`, + ); + } + } +} + +/** + * Write one derived file (13.4): the path's occupant — a plain file, a + * symbolic link as the link itself, or any other non-directory — is + * replaced, missing directories are created, and nothing is written + * through a link (the exclusive create fails rather than follow anything + * left there). + */ +async function writeDerived(config, rel, content) { + const abs = absUnder(config.root, rel); + if ((await lstatKind(abs)) !== "absent") await fsp.unlink(abs); + await fsp.mkdir(path.dirname(abs), { recursive: true }); + await fsp.writeFile(abs, content, { flag: "wx" }); +} + +// --------------------------------------------------------------------------- +// Commands +// --------------------------------------------------------------------------- + +/** + * `xspec build` (12.1): on validation findings (14.19, 14.22) exit 1, + * modifying nothing; otherwise write every derived file, remove the + * recorded paths no longer generated (13.4; an unreadable or empty record + * names none — such orphans lie outside xspec's knowledge), then write + * graph data: the graph, and last the record of the paths generated (13.3). + */ +async function commandBuild(io, cwd, flags, json) { + const config = await loadConfig(cwd, flags.get("--config")); + await refuseDurableState(config); + const ws = await loadWorkspace(config); + const findings = [...ws.findings, ...(await obstructionFindings(config, ws))]; + if (findings.length > 0) throw new FindingsError(findings); + await refuseDirectoryOccupants(config, [ + ...ws.generated, + GRAPH_FILE, + RECORD_FILE, + ]); + const record = await readRecord(config); + for (const item of ws.derived) { + await writeDerived(config, item.rel, item.content); + } + if (record.state === "readable") { + for (const rel of record.paths) { + if (!ws.generated.has(rel)) await removeRecorded(config, rel, ws); + } + } + await writeDerived(config, GRAPH_FILE, graphBytes(ws)); + await writeDerived(config, RECORD_FILE, recordBytes(ws)); + if (json) emitReport(io, true, []); + return 0; +} + +/** + * `xspec check` (12.2): the build validations, then 14.10's forms — per + * file and graph data (the mismatch forms) on a workspace passing them, the + * unreadable-record unit form and the recorded-file form on any workspace. + * Never refreshes and writes nothing; exits 1 on any finding. + */ +async function commandCheck(io, cwd, flags, json) { + const config = await loadConfig(cwd, flags.get("--config")); + await refuseDurableState(config, { sessions: true }); + const ws = await loadWorkspace(config); + const findings = [...ws.findings, ...(await obstructionFindings(config, ws))]; + const passing = findings.length === 0; + const record = await readRecord(config); + if (record.state === "unreadable") { + findings.push( + finding( + 10, + GRAPH_DATA_AREA, + "the recorded generation state under .xspec cannot be read as a record; run xspec build to replace it (SPEC 14.10, 14.23)", + ), + ); + } else if ( + passing && + !(await holdsExactly(config, GRAPH_FILE, graphBytes(ws))) + ) { + findings.push( + finding( + 10, + GRAPH_DATA_AREA, + "graph data is missing or does not match the current sources and configuration; run xspec build (SPEC 14.10, 13.3)", + ), + ); + } + if (passing) { + for (const item of ws.derived) { + if (!(await holdsExactly(config, item.rel, item.content))) { + findings.push( + finding( + 10, + item.rel, + `${item.rel} is missing or does not match what the current sources and configuration generate; run xspec build (SPEC 14.10)`, + ), + ); + } + } + } + if (record.state === "readable") { + const writePaths = [...ws.generated, GRAPH_FILE, RECORD_FILE]; + for (const rel of record.paths) { + if (ws.generated.has(rel)) continue; + if (!isRemovable(await recordedOccupant(config, rel), rel, ws)) continue; + const obstructs = writePaths.some((w) => w.startsWith(`${rel}/`)); + findings.push( + finding( + 10, + rel, + obstructs + ? `${rel} is a recorded derived file no longer generated that obstructs a path the rebuild writes; delete it manually, then run xspec build (SPEC 14.10, 13.4)` + : `${rel} is a recorded derived file the current sources and configuration no longer generate; run xspec build to remove it (SPEC 14.10, 13.4)`, + ), + ); + } + } + if (findings.length > 0) throw new FindingsError(findings); + if (json) emitReport(io, true, []); + return 0; +} + +/** + * `xspec ids` (12.3, 13.3): the syntax class first — `--file`'s outside-root + * spelling — then the flags 12.3 names that this fixture does not serve, + * refused loudly; then the gate — the validations of `build`, whose + * findings it reports with exit 1, nothing evaluated or written past it — + * then the refresh, where the graph is missing or does not match what + * `build` would now write: the graph alone rewritten, no TypeScript or + * Markdown generated or removed, and the record left as it stands, absent, + * empty, or unreadable alike; then the listing, one entry per discovered + * spec source in byte order of path, its IDs in document order. + */ +async function commandIds(io, cwd, flags, json) { + if (flags.has("--file")) checkFileGlob("--file", flags.get("--file")); + for (const flag of SYNOPSES.get("ids").unservedFlags) { + if (flags.has(flag)) { + throw new ScopeError( + `ids ${flag} is outside this fixture's scope (CERTIFICATIONS.md §CONF-IMPORT: ids under --json alone)`, + ); + } + } + const config = await loadConfig(cwd, flags.get("--config")); + await refuseDurableState(config); + const ws = await loadWorkspace(config); + const findings = [...ws.findings, ...(await obstructionFindings(config, ws))]; + if (findings.length > 0) throw new FindingsError(findings); + const graph = graphBytes(ws); + if (!(await holdsExactly(config, GRAPH_FILE, graph))) { + await refuseDirectoryOccupants(config, [GRAPH_FILE]); + await writeDerived(config, GRAPH_FILE, graph); + } + const files = ws.graph.sources.map((source) => ({ + file: source.path, + ids: source.sections.map((section) => section.id), + })); + if (json) { + io.stdout(canonicalJson({ files }) + LF); + } else { + for (const entry of files) { + io.stdout(entry.file + LF); + for (const id of entry.ids) io.stdout(` ${id}${LF}`); + } + } + return 0; +} + +/** + * `xspec inventory` (11.6): JSON-only, the full 12.7 document the entire + * stdout with or without `--json` — the anchoring (the workspace root and + * the configuration file relative to the working directory, physical paths + * both), the resolved configuration view (groups with their globs exactly + * as configured, the emission state and `outDir`, and the empty code, + * coverage, and policy lists), every discovered source with its group + * memberships in configuration order, the derived-file map (the module + * and, while emission is enabled, the Markdown destination of each `.mdx` + * spec source; both structurally absent for a spec-group file without the + * extension, 13.1), the record, the graph-data area, the journal's + * occupancy, the session files, and the lock path. It parses no source and + * writes nothing. Recorded state that exists but cannot be read as a record + * is 14.23 met in the record-supplied datum: `recorded` the unavailability + * marker, its finding beside the answer, exit 1. A session directory is + * outside this fixture's scope. + */ +async function commandInventory(io, cwd, flags) { + const config = await loadConfig(cwd, flags.get("--config")); + const discovery = await discover(config); + if ((await occupantKind(config.root, SESSION_DIRECTORY)) === "dir") { + throw new ScopeError( + `a review-session directory (${SESSION_DIRECTORY}) is present: review sessions are outside this fixture's scope (CERTIFICATIONS.md §CONF-IMPORT; SPEC 10.1, 11.6)`, + ); + } + const specSources = [...discovery.specSources].sort((a, b) => + compareBytes(a.rel, b.rel), + ); + const sources = specSources.map((source) => ({ + path: source.rel, + groups: source.groups.map((name) => ({ name, kind: "spec" })), + })); + const derived = specSources.map((source) => { + if (!source.rel.endsWith(".mdx")) { + return { source: source.rel, module: null, markdown: null }; + } + return { + source: source.rel, + module: modulePathOf(source.rel), + markdown: config.emit ? markdownPathOf(config, source.rel) : null, + }; + }); + const record = await readRecord(config); + const findings = []; + if (record.state === "unreadable") { + findings.push( + finding( + 23, + GRAPH_DATA_AREA, + "the recorded generation state under .xspec cannot be read as a record, so the recorded derived-file paths are unavailable; run xspec build to replace it (SPEC 14.23, 11.6)", + ), + ); + } + const doc = { + findings: findingForms(findings), + root: config.rootAnchor, + config: config.configAnchor, + configuration: { + specs: config.specGroups.map((group) => ({ + name: group.name, + globs: [...group.globs], + })), + code: [], + markdown: { emit: config.emit, outDir: config.outDir }, + coverage: [], + policy: [], + }, + sources, + derived, + recorded: + record.state === "unreadable" ? { unavailable: true } : record.paths, + graphData: GRAPH_DATA_AREA, + journal: { + path: JOURNAL_PATH, + occupied: (await occupantKind(config.root, JOURNAL_PATH)) !== "absent", + }, + sessions: [], + lock: LOCK_PATH, + }; + io.stdout(canonicalJson(doc) + LF); + return findings.length > 0 ? 1 : 0; +} + +// --------------------------------------------------------------------------- +// Entry and dispatch (SPEC 12.0 exit partition) +// --------------------------------------------------------------------------- + +/** + * Run one invocation: `argv` without the executable, `cwd` the working + * directory, `options` the deviation switches (none for this conformer). + * Returns the exit code. + */ +export async function runXspec(argv, cwd, options = {}) { + deviations = { ...options }; + const io = { + stdout: (text) => process.stdout.write(text), + stderr: (text) => process.stderr.write(text), + }; + return await dispatchCommand(io, cwd, argv); +} + +/** + * Read one invocation under the grammar of SPEC 12.0, dispatch it, and map + * its outcome to 12.0's codes. Every syntax-class error is decided from the + * arguments alone, before configuration is loaded and before any of this + * fixture's scope refusals (12.0): first the checks the arguments decide for + * every command alike (`readInvocation`), then the command word and + * `query`'s subcommand, then the synopsis (`checkSynopsis`) and the value + * spellings 12.0 puts in the syntax class. + */ +async function dispatchCommand(io, cwd, argv) { + const invocation = readInvocation(argv); + const [command, ...operands] = invocation.words; + // JSON output is in effect when a `--json` token is read as a flag — not + // as another flag's value — or when the invoked surface is JSON-only + // (SPEC 12.0): `inventory` among the served ones (11), so its every answer + // and usage error is JSON, with or without `--json`. It governs error + // delivery even when the arguments are the error. + const jsonInEffect = invocation.json || isJsonOnlySurface(invocation.words); + try { + if (invocation.error !== null) throw new UsageError(invocation.error); + if (command === undefined) { + throw new UsageError("expected a command (SPEC 12.0)"); + } + if (!PRODUCT_COMMANDS.has(command)) { + throw new UsageError(`unknown command ${command} (SPEC 12.0)`); + } + if (command === "query") { + const [subcommand, ...rest] = operands; + if (subcommand === undefined) { + throw new UsageError("query: missing subcommand (SPEC 11.1, 12.0)"); + } + const synopsis = QUERY_SYNOPSES.get(subcommand); + if (synopsis === undefined) { + throw new UsageError( + `query: unknown subcommand ${subcommand} (SPEC 11.1, 12.0)`, + ); + } + const spelled = `query ${subcommand}`; + checkSynopsis(spelled, synopsis, invocation.flags, rest); + checkQueryValues(spelled, subcommand, invocation.flags, rest); + throw new ScopeError( + `${spelled} is outside this fixture's surface: build, check, ids, and inventory alone (CERTIFICATIONS.md §CONF-IMPORT)`, + ); + } + const synopsis = SYNOPSES.get(command); + if (synopsis === undefined) { + throw new ScopeError( + `the ${command} command is outside this fixture's surface: build, check, ids, and inventory alone (CERTIFICATIONS.md §CONF-IMPORT)`, + ); + } + checkSynopsis(command, synopsis, invocation.flags, operands); + const { flags } = invocation; + switch (command) { + case "build": + return await commandBuild(io, cwd, flags, jsonInEffect); + case "check": + return await commandCheck(io, cwd, flags, jsonInEffect); + case "ids": + return await commandIds(io, cwd, flags, jsonInEffect); + case "inventory": + return await commandInventory(io, cwd, flags); + default: + throw new Error(`no handler for the served command ${command}`); + } + } catch (error) { + if (error instanceof UsageError) { + // Usage and configuration errors (12.0): the message on stderr in both + // output forms, after the concerned path where the error has one (a + // configuration error's, in the anchoring form, 14); with JSON output + // in effect the single 12.7 error document — its stable code and + // concerned path for a configuration error, null and null for a plain + // usage error — is the entire stdout, and without it stdout stays + // empty. The output form never changes the exit code or stderr. + if (jsonInEffect) { + io.stdout( + canonicalJson({ + error: { + code: error.code, + message: error.message, + locations: [], + path: error.path, + identities: [], + }, + }) + LF, + ); + } + io.stderr( + error.path === null + ? `xspec: ${error.message}${LF}` + : `xspec: ${error.path}: ${error.message}${LF}`, + ); + return 2; + } + if (error instanceof FindingsError) { + emitReport(io, jsonInEffect, error.findings); + return 1; + } + if (error instanceof ScopeError) { + io.stderr(`xspec: fixture scope error: ${error.message}${LF}`); + return 70; + } + // A crash is a fixture bug: exit outside the 12.0 partition so every + // exit-code assertion fails loudly and the diagnosis carries the stack. + io.stderr( + `xspec: internal fixture error: ${error?.stack ?? String(error)}${LF}`, + ); + return 70; + } +} diff --git a/test/fixtures/conf-md/product.mjs b/test/fixtures/conf-md/product.mjs index bcd5fecd..14001a3e 100644 --- a/test/fixtures/conf-md/product.mjs +++ b/test/fixtures/conf-md/product.mjs @@ -288,18 +288,27 @@ async function findConfigPath(cwd, configFlag) { /** * Parse the declarative configuration (SPEC 7): exactly an import of - * `defineConfig` from "xspec" (optionally aliased) and a default export of - * one call whose sole argument is statically literal. Returns the argument - * as data. Any other form is a configuration error (SPEC 14.14, exit 2). + * `defineConfig` (optionally aliased) whose module specifier is any static + * string literal (2.4), and a default export of one call whose sole argument + * is statically literal. Returns the argument as data. Any other form is a + * configuration error (SPEC 14.14, exit 2). */ function parseConfigSource(text) { + // The module specifier is matched as spelled and never decoded, + // interpreted, resolved, or loaded (SPEC 7; CERTIFICATIONS.md preamble): + // a static string literal in either quote style, each of its characters + // any but its own quote, a backslash, U+000A, and U+000D, or a backslash + // with the character after it (CRLF taken whole): escape sequences and + // line continuations alike. An escape TypeScript's scanner rejects is + // accepted too: a conformer judges 14.20 on its accepting side alone + // (TEST-SPEC S-9). const importMatch = - /import\s*\{\s*defineConfig(?:\s+as\s+([A-Za-z_$][\w$]*))?\s*\}\s*from\s*(["'])xspec\2\s*;?/.exec( + /import\s*\{\s*defineConfig(?:\s+as\s+([A-Za-z_$][\w$]*))?\s*\}\s*from\s*(?:"(?:[^"\\\n\r]|\\(?:\r\n|[\s\S]))*"|'(?:[^'\\\n\r]|\\(?:\r\n|[\s\S]))*')\s*;?/.exec( text, ); if (!importMatch) { throw new UsageError( - 'configuration error: xspec.config.ts must import { defineConfig } from "xspec" (SPEC 7, 14.14)', + "configuration error: xspec.config.ts must import { defineConfig } from a static string literal (SPEC 7, 14.14)", ); } const binding = importMatch[1] ?? "defineConfig"; diff --git a/test/fixtures/conf-orphan/product.mjs b/test/fixtures/conf-orphan/product.mjs index eb48e412..baacf036 100644 --- a/test/fixtures/conf-orphan/product.mjs +++ b/test/fixtures/conf-orphan/product.mjs @@ -559,11 +559,12 @@ function tokenizeConfig(text, configError) { /** * Parse the declarative configuration (SPEC 7): exactly an import of - * `defineConfig` from "xspec" (optionally aliased; no `type` or `defer` - * modifier, no import attributes) and a default export of one call to that - * binding whose sole argument is statically literal — object literals with - * non-computed identifier or string-literal keys (a key repeated within one - * object a configuration error), array literals, static string literals, and + * `defineConfig` (optionally aliased; no `type` or `defer` modifier, no + * import attributes) whose module specifier is any static string literal + * (2.4), and a default export of one call to that binding whose sole + * argument is statically literal — object literals with non-computed + * identifier or string-literal keys (a key repeated within one object a + * configuration error), array literals, static string literals, and * `true`/`false`. Objects are returned as Maps, in spelling order. */ function parseConfigText(text, configError) { @@ -590,7 +591,12 @@ function parseConfigText(text, configError) { if (peekIs("punct", ",")) i += 1; take("punct", "}", '"}" in the import of defineConfig'); take("word", "from", '"from"'); - take("string", "xspec", 'the module specifier "xspec"'); + // The module specifier: any static string literal token, its value the + // characters between its delimiters as spelled (tokenizeConfig), never + // decoded, interpreted, resolved, or loaded (SPEC 7; CERTIFICATIONS.md + // preamble). An escape TypeScript's scanner rejects is accepted too: a + // conformer judges 14.20 on its accepting side alone (TEST-SPEC S-9). + take("string", undefined, "the module specifier, a static string literal"); if (peekIs("punct", ";")) i += 1; take("word", "export", "the default export"); take("word", "default", '"default"'); diff --git a/test/fixtures/conf-valid/product.mjs b/test/fixtures/conf-valid/product.mjs index 1dd88df5..1da89a72 100644 --- a/test/fixtures/conf-valid/product.mjs +++ b/test/fixtures/conf-valid/product.mjs @@ -283,18 +283,27 @@ async function findConfigPath(cwd, configFlag) { /** * Parse the declarative configuration (SPEC 7): exactly an import of - * `defineConfig` from "xspec" (optionally aliased) and a default export of - * one call whose sole argument is statically literal. Returns the argument - * as data. Any other form is a configuration error (SPEC 14.14, exit 2). + * `defineConfig` (optionally aliased) whose module specifier is any static + * string literal (2.4), and a default export of one call whose sole argument + * is statically literal. Returns the argument as data. Any other form is a + * configuration error (SPEC 14.14, exit 2). */ function parseConfigSource(text) { + // The module specifier is matched as spelled and never decoded, + // interpreted, resolved, or loaded (SPEC 7; CERTIFICATIONS.md preamble): + // a static string literal in either quote style, each of its characters + // any but its own quote, a backslash, U+000A, and U+000D, or a backslash + // with the character after it (CRLF taken whole): escape sequences and + // line continuations alike. An escape TypeScript's scanner rejects is + // accepted too: a conformer judges 14.20 on its accepting side alone + // (TEST-SPEC S-9). const importMatch = - /import\s*\{\s*defineConfig(?:\s+as\s+([A-Za-z_$][\w$]*))?\s*\}\s*from\s*(["'])xspec\2\s*;?/.exec( + /import\s*\{\s*defineConfig(?:\s+as\s+([A-Za-z_$][\w$]*))?\s*\}\s*from\s*(?:"(?:[^"\\\n\r]|\\(?:\r\n|[\s\S]))*"|'(?:[^'\\\n\r]|\\(?:\r\n|[\s\S]))*')\s*;?/.exec( text, ); if (!importMatch) { throw new UsageError( - 'configuration error: xspec.config.ts must import { defineConfig } from "xspec" (SPEC 7, 14.14)', + "configuration error: xspec.config.ts must import { defineConfig } from a static string literal (SPEC 7, 14.14)", ); } const binding = importMatch[1] ?? "defineConfig"; diff --git a/test/fixtures/empty-stub-package/package.json b/test/fixtures/empty-stub-package/package.json new file mode 100644 index 00000000..1ff44c52 --- /dev/null +++ b/test/fixtures/empty-stub-package/package.json @@ -0,0 +1,4 @@ +{ + "name": "xspec-empty-stub", + "version": "0.0.0" +} diff --git a/test/fixtures/module-channel-standin/index.d.ts b/test/fixtures/module-channel-standin/index.d.ts new file mode 100644 index 00000000..5d40ed53 --- /dev/null +++ b/test/fixtures/module-channel-standin/index.d.ts @@ -0,0 +1 @@ +export declare const answer: number; diff --git a/test/fixtures/module-channel-standin/index.js b/test/fixtures/module-channel-standin/index.js new file mode 100644 index 00000000..f60974a7 --- /dev/null +++ b/test/fixtures/module-channel-standin/index.js @@ -0,0 +1,3 @@ +"use strict"; + +exports.answer = 42; diff --git a/test/fixtures/module-channel-standin/lib/helper.js b/test/fixtures/module-channel-standin/lib/helper.js new file mode 100644 index 00000000..7ac7510c --- /dev/null +++ b/test/fixtures/module-channel-standin/lib/helper.js @@ -0,0 +1,5 @@ +"use strict"; + +module.exports = function helper() { + return "helper"; +}; diff --git a/test/fixtures/module-channel-standin/package.json b/test/fixtures/module-channel-standin/package.json new file mode 100644 index 00000000..19ced41b --- /dev/null +++ b/test/fixtures/module-channel-standin/package.json @@ -0,0 +1,6 @@ +{ + "name": "module-channel-standin", + "version": "1.0.0", + "main": "index.js", + "types": "index.d.ts" +} diff --git a/test/fixtures/module-channel-ts/conforming/index.cjs b/test/fixtures/module-channel-ts/conforming/index.cjs new file mode 100644 index 00000000..789dd5d5 --- /dev/null +++ b/test/fixtures/module-channel-ts/conforming/index.cjs @@ -0,0 +1,5 @@ +"use strict"; + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/module-channel-ts/conforming/index.d.cts b/test/fixtures/module-channel-ts/conforming/index.d.cts new file mode 100644 index 00000000..1b71fefa --- /dev/null +++ b/test/fixtures/module-channel-ts/conforming/index.d.cts @@ -0,0 +1,8 @@ +type Settings = { + groups: { [name: string]: string[] }; + output?: { enabled: boolean }; +}; + +export declare function defineConfig(settings: Settings): Settings; + +export {}; diff --git a/test/fixtures/module-channel-ts/conforming/index.d.ts b/test/fixtures/module-channel-ts/conforming/index.d.ts new file mode 100644 index 00000000..1b71fefa --- /dev/null +++ b/test/fixtures/module-channel-ts/conforming/index.d.ts @@ -0,0 +1,8 @@ +type Settings = { + groups: { [name: string]: string[] }; + output?: { enabled: boolean }; +}; + +export declare function defineConfig(settings: Settings): Settings; + +export {}; diff --git a/test/fixtures/module-channel-ts/conforming/index.js b/test/fixtures/module-channel-ts/conforming/index.js new file mode 100644 index 00000000..792a0664 --- /dev/null +++ b/test/fixtures/module-channel-ts/conforming/index.js @@ -0,0 +1,3 @@ +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/module-channel-ts/conforming/package.json b/test/fixtures/module-channel-ts/conforming/package.json new file mode 100644 index 00000000..fd3bee94 --- /dev/null +++ b/test/fixtures/module-channel-ts/conforming/package.json @@ -0,0 +1,19 @@ +{ + "name": "module-channel-ts-conforming", + "version": "1.0.0", + "type": "module", + "types": "./index.d.ts", + "main": "./index.cjs", + "exports": { + ".": { + "import": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "require": { + "types": "./index.d.cts", + "default": "./index.cjs" + } + } + } +} diff --git a/test/fixtures/module-channel-ts/declaration-error/index.cjs b/test/fixtures/module-channel-ts/declaration-error/index.cjs new file mode 100644 index 00000000..789dd5d5 --- /dev/null +++ b/test/fixtures/module-channel-ts/declaration-error/index.cjs @@ -0,0 +1,5 @@ +"use strict"; + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/module-channel-ts/declaration-error/index.d.cts b/test/fixtures/module-channel-ts/declaration-error/index.d.cts new file mode 100644 index 00000000..0c5b5bd4 --- /dev/null +++ b/test/fixtures/module-channel-ts/declaration-error/index.d.cts @@ -0,0 +1,10 @@ +type Settings = { + groups: { [name: string]: string[] }; + output?: { enabled: boolean }; +}; + +export declare function defineConfig(settings: Settings): Settings; + +declare const broken: MissingType; + +export {}; diff --git a/test/fixtures/module-channel-ts/declaration-error/index.d.ts b/test/fixtures/module-channel-ts/declaration-error/index.d.ts new file mode 100644 index 00000000..0c5b5bd4 --- /dev/null +++ b/test/fixtures/module-channel-ts/declaration-error/index.d.ts @@ -0,0 +1,10 @@ +type Settings = { + groups: { [name: string]: string[] }; + output?: { enabled: boolean }; +}; + +export declare function defineConfig(settings: Settings): Settings; + +declare const broken: MissingType; + +export {}; diff --git a/test/fixtures/module-channel-ts/declaration-error/index.js b/test/fixtures/module-channel-ts/declaration-error/index.js new file mode 100644 index 00000000..792a0664 --- /dev/null +++ b/test/fixtures/module-channel-ts/declaration-error/index.js @@ -0,0 +1,3 @@ +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/module-channel-ts/declaration-error/package.json b/test/fixtures/module-channel-ts/declaration-error/package.json new file mode 100644 index 00000000..1c017c52 --- /dev/null +++ b/test/fixtures/module-channel-ts/declaration-error/package.json @@ -0,0 +1,19 @@ +{ + "name": "module-channel-ts-declaration-error", + "version": "1.0.0", + "type": "module", + "types": "./index.d.ts", + "main": "./index.cjs", + "exports": { + ".": { + "import": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "require": { + "types": "./index.d.cts", + "default": "./index.cjs" + } + } + } +} diff --git a/test/fixtures/module-channel-ts/global-augmenting/index.cjs b/test/fixtures/module-channel-ts/global-augmenting/index.cjs new file mode 100644 index 00000000..789dd5d5 --- /dev/null +++ b/test/fixtures/module-channel-ts/global-augmenting/index.cjs @@ -0,0 +1,5 @@ +"use strict"; + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/module-channel-ts/global-augmenting/index.d.cts b/test/fixtures/module-channel-ts/global-augmenting/index.d.cts new file mode 100644 index 00000000..d268361f --- /dev/null +++ b/test/fixtures/module-channel-ts/global-augmenting/index.d.cts @@ -0,0 +1,14 @@ +type Settings = { + groups: { [name: string]: string[] }; + output?: { enabled: boolean }; +}; + +export declare function defineConfig(settings: Settings): Settings; + +declare global { + interface RangeError { + name: number; + } +} + +export {}; diff --git a/test/fixtures/module-channel-ts/global-augmenting/index.d.ts b/test/fixtures/module-channel-ts/global-augmenting/index.d.ts new file mode 100644 index 00000000..d268361f --- /dev/null +++ b/test/fixtures/module-channel-ts/global-augmenting/index.d.ts @@ -0,0 +1,14 @@ +type Settings = { + groups: { [name: string]: string[] }; + output?: { enabled: boolean }; +}; + +export declare function defineConfig(settings: Settings): Settings; + +declare global { + interface RangeError { + name: number; + } +} + +export {}; diff --git a/test/fixtures/module-channel-ts/global-augmenting/index.js b/test/fixtures/module-channel-ts/global-augmenting/index.js new file mode 100644 index 00000000..792a0664 --- /dev/null +++ b/test/fixtures/module-channel-ts/global-augmenting/index.js @@ -0,0 +1,3 @@ +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/module-channel-ts/global-augmenting/package.json b/test/fixtures/module-channel-ts/global-augmenting/package.json new file mode 100644 index 00000000..f040e31b --- /dev/null +++ b/test/fixtures/module-channel-ts/global-augmenting/package.json @@ -0,0 +1,19 @@ +{ + "name": "module-channel-ts-global-augmenting", + "version": "1.0.0", + "type": "module", + "types": "./index.d.ts", + "main": "./index.cjs", + "exports": { + ".": { + "import": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "require": { + "types": "./index.d.cts", + "default": "./index.cjs" + } + } + } +} diff --git a/test/fixtures/module-channel-ts/listing-instance/index.d.ts b/test/fixtures/module-channel-ts/listing-instance/index.d.ts new file mode 100644 index 00000000..915ea624 --- /dev/null +++ b/test/fixtures/module-channel-ts/listing-instance/index.d.ts @@ -0,0 +1,7 @@ +declare class Settings { + defineConfig<T>(value: T): T; +} + +declare const settings: Settings; + +export = settings; diff --git a/test/fixtures/module-channel-ts/listing-instance/index.js b/test/fixtures/module-channel-ts/listing-instance/index.js new file mode 100644 index 00000000..e9313894 --- /dev/null +++ b/test/fixtures/module-channel-ts/listing-instance/index.js @@ -0,0 +1,7 @@ +"use strict"; + +module.exports = { + defineConfig(value) { + return value; + }, +}; diff --git a/test/fixtures/module-channel-ts/listing-instance/package.json b/test/fixtures/module-channel-ts/listing-instance/package.json new file mode 100644 index 00000000..d825f3d7 --- /dev/null +++ b/test/fixtures/module-channel-ts/listing-instance/package.json @@ -0,0 +1,6 @@ +{ + "name": "module-channel-ts-listing-instance", + "version": "1.0.0", + "types": "./index.d.ts", + "main": "./index.js" +} diff --git a/test/fixtures/module-channel-ts/listing-meanings/index.cjs b/test/fixtures/module-channel-ts/listing-meanings/index.cjs new file mode 100644 index 00000000..e9313894 --- /dev/null +++ b/test/fixtures/module-channel-ts/listing-meanings/index.cjs @@ -0,0 +1,7 @@ +"use strict"; + +module.exports = { + defineConfig(value) { + return value; + }, +}; diff --git a/test/fixtures/module-channel-ts/listing-meanings/index.d.cts b/test/fixtures/module-channel-ts/listing-meanings/index.d.cts new file mode 100644 index 00000000..2fa4cff8 --- /dev/null +++ b/test/fixtures/module-channel-ts/listing-meanings/index.d.cts @@ -0,0 +1,15 @@ +declare const marker: unique symbol; + +declare const api: { + defineConfig<T>(value: T): T; + readonly [marker]: true; +}; + +declare namespace api { + type defineConfig = string; + interface Options { + readonly note: string; + } +} + +export = api; diff --git a/test/fixtures/module-channel-ts/listing-meanings/index.d.ts b/test/fixtures/module-channel-ts/listing-meanings/index.d.ts new file mode 100644 index 00000000..35ab00b4 --- /dev/null +++ b/test/fixtures/module-channel-ts/listing-meanings/index.d.ts @@ -0,0 +1,9 @@ +declare function defineConfig<T>(value: T): T; +declare namespace defineConfig { + const version: number; +} + +export { defineConfig }; +export type { defineConfig as typeOnlyFunction }; +export type * from "./star.js"; +export default function declaredDefault(): void; diff --git a/test/fixtures/module-channel-ts/listing-meanings/index.js b/test/fixtures/module-channel-ts/listing-meanings/index.js new file mode 100644 index 00000000..faf6f706 --- /dev/null +++ b/test/fixtures/module-channel-ts/listing-meanings/index.js @@ -0,0 +1,7 @@ +export function defineConfig(value) { + return value; +} + +defineConfig.version = 1; + +export default function declaredDefault() {} diff --git a/test/fixtures/module-channel-ts/listing-meanings/package.json b/test/fixtures/module-channel-ts/listing-meanings/package.json new file mode 100644 index 00000000..21e2f5ab --- /dev/null +++ b/test/fixtures/module-channel-ts/listing-meanings/package.json @@ -0,0 +1,19 @@ +{ + "name": "module-channel-ts-listing-meanings", + "version": "1.0.0", + "type": "module", + "types": "./index.d.ts", + "main": "./index.cjs", + "exports": { + ".": { + "import": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "require": { + "types": "./index.d.cts", + "default": "./index.cjs" + } + } + } +} diff --git a/test/fixtures/module-channel-ts/listing-meanings/star.d.ts b/test/fixtures/module-channel-ts/listing-meanings/star.d.ts new file mode 100644 index 00000000..5bf86c7e --- /dev/null +++ b/test/fixtures/module-channel-ts/listing-meanings/star.d.ts @@ -0,0 +1 @@ +export declare const starValue: number; diff --git a/test/fixtures/module-channel-ts/listing-meanings/star.js b/test/fixtures/module-channel-ts/listing-meanings/star.js new file mode 100644 index 00000000..6dbdf346 --- /dev/null +++ b/test/fixtures/module-channel-ts/listing-meanings/star.js @@ -0,0 +1 @@ +export const starValue = 1; diff --git a/test/fixtures/module-channel-ts/permissive/index.cjs b/test/fixtures/module-channel-ts/permissive/index.cjs new file mode 100644 index 00000000..789dd5d5 --- /dev/null +++ b/test/fixtures/module-channel-ts/permissive/index.cjs @@ -0,0 +1,5 @@ +"use strict"; + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/module-channel-ts/permissive/index.d.cts b/test/fixtures/module-channel-ts/permissive/index.d.cts new file mode 100644 index 00000000..39f377e3 --- /dev/null +++ b/test/fixtures/module-channel-ts/permissive/index.d.cts @@ -0,0 +1,3 @@ +export declare function defineConfig(settings: any): any; + +export {}; diff --git a/test/fixtures/module-channel-ts/permissive/index.d.ts b/test/fixtures/module-channel-ts/permissive/index.d.ts new file mode 100644 index 00000000..39f377e3 --- /dev/null +++ b/test/fixtures/module-channel-ts/permissive/index.d.ts @@ -0,0 +1,3 @@ +export declare function defineConfig(settings: any): any; + +export {}; diff --git a/test/fixtures/module-channel-ts/permissive/index.js b/test/fixtures/module-channel-ts/permissive/index.js new file mode 100644 index 00000000..792a0664 --- /dev/null +++ b/test/fixtures/module-channel-ts/permissive/index.js @@ -0,0 +1,3 @@ +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/module-channel-ts/permissive/package.json b/test/fixtures/module-channel-ts/permissive/package.json new file mode 100644 index 00000000..2169dbfd --- /dev/null +++ b/test/fixtures/module-channel-ts/permissive/package.json @@ -0,0 +1,19 @@ +{ + "name": "module-channel-ts-permissive", + "version": "1.0.0", + "type": "module", + "types": "./index.d.ts", + "main": "./index.cjs", + "exports": { + ".": { + "import": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "require": { + "types": "./index.d.cts", + "default": "./index.cjs" + } + } + } +} diff --git a/test/fixtures/s10-stand-ins/adds-array-property/index.cjs b/test/fixtures/s10-stand-ins/adds-array-property/index.cjs new file mode 100644 index 00000000..667d5fda --- /dev/null +++ b/test/fixtures/s10-stand-ins/adds-array-property/index.cjs @@ -0,0 +1,7 @@ +"use strict"; + +Array.xspecS10Property = "added"; + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/adds-array-property/index.mjs b/test/fixtures/s10-stand-ins/adds-array-property/index.mjs new file mode 100644 index 00000000..27d0eeef --- /dev/null +++ b/test/fixtures/s10-stand-ins/adds-array-property/index.mjs @@ -0,0 +1,5 @@ +Array.xspecS10Property = "added"; + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/adds-array-property/package.json b/test/fixtures/s10-stand-ins/adds-array-property/package.json new file mode 100644 index 00000000..acf679b8 --- /dev/null +++ b/test/fixtures/s10-stand-ins/adds-array-property/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-adds-array-property-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/adds-global/index.cjs b/test/fixtures/s10-stand-ins/adds-global/index.cjs new file mode 100644 index 00000000..208df4a9 --- /dev/null +++ b/test/fixtures/s10-stand-ins/adds-global/index.cjs @@ -0,0 +1,7 @@ +"use strict"; + +globalThis.xspecS10Global = "added"; + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/adds-global/index.mjs b/test/fixtures/s10-stand-ins/adds-global/index.mjs new file mode 100644 index 00000000..02cecb68 --- /dev/null +++ b/test/fixtures/s10-stand-ins/adds-global/index.mjs @@ -0,0 +1,5 @@ +globalThis.xspecS10Global = "added"; + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/adds-global/package.json b/test/fixtures/s10-stand-ins/adds-global/package.json new file mode 100644 index 00000000..3dd0691e --- /dev/null +++ b/test/fixtures/s10-stand-ins/adds-global/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-adds-global-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/adds-listener/index.cjs b/test/fixtures/s10-stand-ins/adds-listener/index.cjs new file mode 100644 index 00000000..cc3e10ac --- /dev/null +++ b/test/fixtures/s10-stand-ins/adds-listener/index.cjs @@ -0,0 +1,7 @@ +"use strict"; + +process.on("exit", function xspecS10Exit() {}); + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/adds-listener/index.mjs b/test/fixtures/s10-stand-ins/adds-listener/index.mjs new file mode 100644 index 00000000..dca40845 --- /dev/null +++ b/test/fixtures/s10-stand-ins/adds-listener/index.mjs @@ -0,0 +1,5 @@ +process.on("exit", function xspecS10Exit() {}); + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/adds-listener/package.json b/test/fixtures/s10-stand-ins/adds-listener/package.json new file mode 100644 index 00000000..78dbeb57 --- /dev/null +++ b/test/fixtures/s10-stand-ins/adds-listener/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-adds-listener-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/adds-math-property/index.cjs b/test/fixtures/s10-stand-ins/adds-math-property/index.cjs new file mode 100644 index 00000000..ff909c91 --- /dev/null +++ b/test/fixtures/s10-stand-ins/adds-math-property/index.cjs @@ -0,0 +1,7 @@ +"use strict"; + +Math.xspecS10Property = "added"; + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/adds-math-property/index.mjs b/test/fixtures/s10-stand-ins/adds-math-property/index.mjs new file mode 100644 index 00000000..a1c687a6 --- /dev/null +++ b/test/fixtures/s10-stand-ins/adds-math-property/index.mjs @@ -0,0 +1,5 @@ +Math.xspecS10Property = "added"; + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/adds-math-property/package.json b/test/fixtures/s10-stand-ins/adds-math-property/package.json new file mode 100644 index 00000000..b48a71f6 --- /dev/null +++ b/test/fixtures/s10-stand-ins/adds-math-property/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-adds-math-property-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/alters-prototype/index.cjs b/test/fixtures/s10-stand-ins/alters-prototype/index.cjs new file mode 100644 index 00000000..a5b721f8 --- /dev/null +++ b/test/fixtures/s10-stand-ins/alters-prototype/index.cjs @@ -0,0 +1,10 @@ +"use strict"; + +const trim = String.prototype.trim; +String.prototype.trim = function xspecS10Trim() { + return Reflect.apply(trim, this, []); +}; + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/alters-prototype/index.mjs b/test/fixtures/s10-stand-ins/alters-prototype/index.mjs new file mode 100644 index 00000000..c16a0739 --- /dev/null +++ b/test/fixtures/s10-stand-ins/alters-prototype/index.mjs @@ -0,0 +1,8 @@ +const trim = String.prototype.trim; +String.prototype.trim = function xspecS10Trim() { + return Reflect.apply(trim, this, []); +}; + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/alters-prototype/package.json b/test/fixtures/s10-stand-ins/alters-prototype/package.json new file mode 100644 index 00000000..54d8c204 --- /dev/null +++ b/test/fixtures/s10-stand-ins/alters-prototype/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-alters-prototype-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/changes-directory/index.cjs b/test/fixtures/s10-stand-ins/changes-directory/index.cjs new file mode 100644 index 00000000..9d52cf5f --- /dev/null +++ b/test/fixtures/s10-stand-ins/changes-directory/index.cjs @@ -0,0 +1,7 @@ +"use strict"; + +process.chdir(".."); + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/changes-directory/index.mjs b/test/fixtures/s10-stand-ins/changes-directory/index.mjs new file mode 100644 index 00000000..80967790 --- /dev/null +++ b/test/fixtures/s10-stand-ins/changes-directory/index.mjs @@ -0,0 +1,5 @@ +process.chdir(".."); + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/changes-directory/package.json b/test/fixtures/s10-stand-ins/changes-directory/package.json new file mode 100644 index 00000000..a9d12147 --- /dev/null +++ b/test/fixtures/s10-stand-ins/changes-directory/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-changes-directory-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/commonjs/index.js b/test/fixtures/s10-stand-ins/commonjs/index.js new file mode 100644 index 00000000..789dd5d5 --- /dev/null +++ b/test/fixtures/s10-stand-ins/commonjs/index.js @@ -0,0 +1,5 @@ +"use strict"; + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/commonjs/package.json b/test/fixtures/s10-stand-ins/commonjs/package.json new file mode 100644 index 00000000..fe9cc91e --- /dev/null +++ b/test/fixtures/s10-stand-ins/commonjs/package.json @@ -0,0 +1,5 @@ +{ + "name": "s10-commonjs-standin", + "version": "1.0.0", + "main": "./index.js" +} diff --git a/test/fixtures/s10-stand-ins/copies-argument/index.cjs b/test/fixtures/s10-stand-ins/copies-argument/index.cjs new file mode 100644 index 00000000..10e3d5bf --- /dev/null +++ b/test/fixtures/s10-stand-ins/copies-argument/index.cjs @@ -0,0 +1,9 @@ +"use strict"; + +exports.defineConfig = function defineConfig(settings) { + if (Array.isArray(settings)) return settings.slice(); + if (typeof settings === "object" && settings !== null) { + return Object.assign({}, settings); + } + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/copies-argument/index.mjs b/test/fixtures/s10-stand-ins/copies-argument/index.mjs new file mode 100644 index 00000000..f6dfb8cb --- /dev/null +++ b/test/fixtures/s10-stand-ins/copies-argument/index.mjs @@ -0,0 +1,7 @@ +export function defineConfig(settings) { + if (Array.isArray(settings)) return settings.slice(); + if (typeof settings === "object" && settings !== null) { + return Object.assign({}, settings); + } + return settings; +} diff --git a/test/fixtures/s10-stand-ins/copies-argument/package.json b/test/fixtures/s10-stand-ins/copies-argument/package.json new file mode 100644 index 00000000..cef4d838 --- /dev/null +++ b/test/fixtures/s10-stand-ins/copies-argument/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-copies-argument-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/dual/condition.cjs b/test/fixtures/s10-stand-ins/dual/condition.cjs new file mode 100644 index 00000000..f81c4eb8 --- /dev/null +++ b/test/fixtures/s10-stand-ins/dual/condition.cjs @@ -0,0 +1,8 @@ +"use strict"; + +const kind = this === undefined ? "an ES module" : "a CommonJS module"; +process.stdout.write(`condition.cjs: ${kind}${String.fromCharCode(10)}`); + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/dual/index.cjs b/test/fixtures/s10-stand-ins/dual/index.cjs new file mode 100644 index 00000000..b732188b --- /dev/null +++ b/test/fixtures/s10-stand-ins/dual/index.cjs @@ -0,0 +1,8 @@ +"use strict"; + +const kind = this === undefined ? "an ES module" : "a CommonJS module"; +process.stdout.write(`index.cjs: ${kind}${String.fromCharCode(10)}`); + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/dual/index.mjs b/test/fixtures/s10-stand-ins/dual/index.mjs new file mode 100644 index 00000000..21be9ad1 --- /dev/null +++ b/test/fixtures/s10-stand-ins/dual/index.mjs @@ -0,0 +1,6 @@ +const kind = this === undefined ? "an ES module" : "a CommonJS module"; +process.stdout.write(`index.mjs: ${kind}${String.fromCharCode(10)}`); + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/dual/package.json b/test/fixtures/s10-stand-ins/dual/package.json new file mode 100644 index 00000000..238465a2 --- /dev/null +++ b/test/fixtures/s10-stand-ins/dual/package.json @@ -0,0 +1,11 @@ +{ + "name": "s10-dual-standin", + "version": "1.0.0", + "exports": { + ".": { + "xspec-s10-user-condition": "./condition.cjs", + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/emits-warning/index.cjs b/test/fixtures/s10-stand-ins/emits-warning/index.cjs new file mode 100644 index 00000000..bc190f9a --- /dev/null +++ b/test/fixtures/s10-stand-ins/emits-warning/index.cjs @@ -0,0 +1,10 @@ +"use strict"; + +process.emitWarning("a warning the module emits while it loads", { + type: "XspecS10Warning", + code: "XSPEC_S10_EMITTED", +}); + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/emits-warning/index.mjs b/test/fixtures/s10-stand-ins/emits-warning/index.mjs new file mode 100644 index 00000000..0732e9c6 --- /dev/null +++ b/test/fixtures/s10-stand-ins/emits-warning/index.mjs @@ -0,0 +1,8 @@ +process.emitWarning("a warning the module emits while it loads", { + type: "XspecS10Warning", + code: "XSPEC_S10_EMITTED", +}); + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/emits-warning/package.json b/test/fixtures/s10-stand-ins/emits-warning/package.json new file mode 100644 index 00000000..1de5e2d6 --- /dev/null +++ b/test/fixtures/s10-stand-ins/emits-warning/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-emits-warning-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/invalid-main/index.js b/test/fixtures/s10-stand-ins/invalid-main/index.js new file mode 100644 index 00000000..789dd5d5 --- /dev/null +++ b/test/fixtures/s10-stand-ins/invalid-main/index.js @@ -0,0 +1,5 @@ +"use strict"; + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/invalid-main/package.json b/test/fixtures/s10-stand-ins/invalid-main/package.json new file mode 100644 index 00000000..d2658d32 --- /dev/null +++ b/test/fixtures/s10-stand-ins/invalid-main/package.json @@ -0,0 +1,5 @@ +{ + "name": "s10-invalid-main-standin", + "version": "1.0.0", + "main": "./missing.js" +} diff --git a/test/fixtures/s10-stand-ins/main-lookup/lib/index.js b/test/fixtures/s10-stand-ins/main-lookup/lib/index.js new file mode 100644 index 00000000..792a0664 --- /dev/null +++ b/test/fixtures/s10-stand-ins/main-lookup/lib/index.js @@ -0,0 +1,3 @@ +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/main-lookup/package.json b/test/fixtures/s10-stand-ins/main-lookup/package.json new file mode 100644 index 00000000..6caa9f8a --- /dev/null +++ b/test/fixtures/s10-stand-ins/main-lookup/package.json @@ -0,0 +1,6 @@ +{ + "name": "s10-main-lookup-standin", + "version": "1.0.0", + "type": "module", + "main": "./lib" +} diff --git a/test/fixtures/s10-stand-ins/module-only/index.js b/test/fixtures/s10-stand-ins/module-only/index.js new file mode 100644 index 00000000..792a0664 --- /dev/null +++ b/test/fixtures/s10-stand-ins/module-only/index.js @@ -0,0 +1,3 @@ +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/module-only/package.json b/test/fixtures/s10-stand-ins/module-only/package.json new file mode 100644 index 00000000..4d457362 --- /dev/null +++ b/test/fixtures/s10-stand-ins/module-only/package.json @@ -0,0 +1,6 @@ +{ + "name": "s10-module-only-standin", + "version": "1.0.0", + "type": "module", + "exports": "./index.js" +} diff --git a/test/fixtures/s10-stand-ins/opens-fifos/index.cjs b/test/fixtures/s10-stand-ins/opens-fifos/index.cjs new file mode 100644 index 00000000..0ffa21cc --- /dev/null +++ b/test/fixtures/s10-stand-ins/opens-fifos/index.cjs @@ -0,0 +1,26 @@ +"use strict"; + +const { open } = require("node:fs"); +const { homedir } = require("node:os"); +const { join, sep } = require("node:path"); + +const ownDirectory = __dirname; +const LF = String.fromCharCode(10); +const nodeModules = `${sep}node_modules${sep}`; +const importingDirectory = ownDirectory.slice( + 0, + ownDirectory.lastIndexOf(nodeModules), +); +for (const directory of [process.cwd(), importingDirectory, homedir()]) { + const fifo = join(directory, "xspec.config.ts"); + process.stdout.write(`opens-fifos: opening ${fifo}${LF}`); + open(fifo, "r", (error) => { + const outcome = + error === null ? "opened" : `failed to open (${String(error.code)})`; + process.stdout.write(`opens-fifos: ${outcome} ${fifo}${LF}`); + }); +} + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/opens-fifos/index.mjs b/test/fixtures/s10-stand-ins/opens-fifos/index.mjs new file mode 100644 index 00000000..4a1f0f3c --- /dev/null +++ b/test/fixtures/s10-stand-ins/opens-fifos/index.mjs @@ -0,0 +1,25 @@ +import { open } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join, sep } from "node:path"; +import { fileURLToPath } from "node:url"; + +const ownDirectory = dirname(fileURLToPath(import.meta.url)); +const LF = String.fromCharCode(10); +const nodeModules = `${sep}node_modules${sep}`; +const importingDirectory = ownDirectory.slice( + 0, + ownDirectory.lastIndexOf(nodeModules), +); +for (const directory of [process.cwd(), importingDirectory, homedir()]) { + const fifo = join(directory, "xspec.config.ts"); + process.stdout.write(`opens-fifos: opening ${fifo}${LF}`); + open(fifo, "r", (error) => { + const outcome = + error === null ? "opened" : `failed to open (${String(error.code)})`; + process.stdout.write(`opens-fifos: ${outcome} ${fifo}${LF}`); + }); +} + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/opens-fifos/package.json b/test/fixtures/s10-stand-ins/opens-fifos/package.json new file mode 100644 index 00000000..679d848e --- /dev/null +++ b/test/fixtures/s10-stand-ins/opens-fifos/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-opens-fifos-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/prevents-global-extensions/index.cjs b/test/fixtures/s10-stand-ins/prevents-global-extensions/index.cjs new file mode 100644 index 00000000..af6b4358 --- /dev/null +++ b/test/fixtures/s10-stand-ins/prevents-global-extensions/index.cjs @@ -0,0 +1,7 @@ +"use strict"; + +Object.preventExtensions(globalThis); + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/prevents-global-extensions/index.mjs b/test/fixtures/s10-stand-ins/prevents-global-extensions/index.mjs new file mode 100644 index 00000000..63c53c04 --- /dev/null +++ b/test/fixtures/s10-stand-ins/prevents-global-extensions/index.mjs @@ -0,0 +1,5 @@ +Object.preventExtensions(globalThis); + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/prevents-global-extensions/package.json b/test/fixtures/s10-stand-ins/prevents-global-extensions/package.json new file mode 100644 index 00000000..f9976da6 --- /dev/null +++ b/test/fixtures/s10-stand-ins/prevents-global-extensions/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-prevents-global-extensions-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/prints-after-dep0128/index.js b/test/fixtures/s10-stand-ins/prints-after-dep0128/index.js new file mode 100644 index 00000000..efa56cd5 --- /dev/null +++ b/test/fixtures/s10-stand-ins/prints-after-dep0128/index.js @@ -0,0 +1,13 @@ +"use strict"; + +const LF = String.fromCharCode(10); +process.nextTick(() => { + process.stderr.write( + `(node:${process.pid}) [XSPEC_S10_FORGED] Warning: a line the module ` + + `writes after the release's own warning${LF}`, + ); +}); + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/prints-after-dep0128/package.json b/test/fixtures/s10-stand-ins/prints-after-dep0128/package.json new file mode 100644 index 00000000..4e444282 --- /dev/null +++ b/test/fixtures/s10-stand-ins/prints-after-dep0128/package.json @@ -0,0 +1,5 @@ +{ + "name": "s10-prints-after-dep0128-standin", + "version": "1.0.0", + "main": "./missing.js" +} diff --git a/test/fixtures/s10-stand-ins/prints-after-dep0151/lib/index.js b/test/fixtures/s10-stand-ins/prints-after-dep0151/lib/index.js new file mode 100644 index 00000000..52bd9dff --- /dev/null +++ b/test/fixtures/s10-stand-ins/prints-after-dep0151/lib/index.js @@ -0,0 +1,11 @@ +const LF = String.fromCharCode(10); +process.nextTick(() => { + process.stderr.write( + `(node:${process.pid}) [XSPEC_S10_FORGED] Warning: a line the module ` + + `writes after the release's own warning${LF}`, + ); +}); + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/prints-after-dep0151/package.json b/test/fixtures/s10-stand-ins/prints-after-dep0151/package.json new file mode 100644 index 00000000..a2a981e6 --- /dev/null +++ b/test/fixtures/s10-stand-ins/prints-after-dep0151/package.json @@ -0,0 +1,6 @@ +{ + "name": "s10-prints-after-dep0151-standin", + "version": "1.0.0", + "type": "module", + "main": "./lib" +} diff --git a/test/fixtures/s10-stand-ins/prints-stderr/index.cjs b/test/fixtures/s10-stand-ins/prints-stderr/index.cjs new file mode 100644 index 00000000..363e0b58 --- /dev/null +++ b/test/fixtures/s10-stand-ins/prints-stderr/index.cjs @@ -0,0 +1,9 @@ +"use strict"; + +process.stderr.write( + `prints-stderr: a line the module writes${String.fromCharCode(10)}`, +); + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/prints-stderr/index.mjs b/test/fixtures/s10-stand-ins/prints-stderr/index.mjs new file mode 100644 index 00000000..68aca582 --- /dev/null +++ b/test/fixtures/s10-stand-ins/prints-stderr/index.mjs @@ -0,0 +1,7 @@ +process.stderr.write( + `prints-stderr: a line the module writes${String.fromCharCode(10)}`, +); + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/prints-stderr/package.json b/test/fixtures/s10-stand-ins/prints-stderr/package.json new file mode 100644 index 00000000..9f1f366b --- /dev/null +++ b/test/fixtures/s10-stand-ins/prints-stderr/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-prints-stderr-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/prints-stdout/index.cjs b/test/fixtures/s10-stand-ins/prints-stdout/index.cjs new file mode 100644 index 00000000..fa56ff3e --- /dev/null +++ b/test/fixtures/s10-stand-ins/prints-stdout/index.cjs @@ -0,0 +1,9 @@ +"use strict"; + +process.stdout.write( + `prints-stdout: a line the module writes${String.fromCharCode(10)}`, +); + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/prints-stdout/index.mjs b/test/fixtures/s10-stand-ins/prints-stdout/index.mjs new file mode 100644 index 00000000..d532ceed --- /dev/null +++ b/test/fixtures/s10-stand-ins/prints-stdout/index.mjs @@ -0,0 +1,7 @@ +process.stdout.write( + `prints-stdout: a line the module writes${String.fromCharCode(10)}`, +); + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/prints-stdout/package.json b/test/fixtures/s10-stand-ins/prints-stdout/package.json new file mode 100644 index 00000000..d1f877ca --- /dev/null +++ b/test/fixtures/s10-stand-ins/prints-stdout/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-prints-stdout-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/prints-warning-form/index.cjs b/test/fixtures/s10-stand-ins/prints-warning-form/index.cjs new file mode 100644 index 00000000..4b738100 --- /dev/null +++ b/test/fixtures/s10-stand-ins/prints-warning-form/index.cjs @@ -0,0 +1,17 @@ +"use strict"; + +const { basename } = require("node:path"); + +const LF = String.fromCharCode(10); +const hint = + "(Use `" + + basename(process.argv0 || "node", ".exe") + + " --trace-warnings ...` to show where the warning was created)"; +process.stderr.write( + `(node:${process.pid}) [XSPEC_S10_FORGED] Warning: a line the module ` + + `writes in the warning form${LF}${hint}${LF}`, +); + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/prints-warning-form/index.mjs b/test/fixtures/s10-stand-ins/prints-warning-form/index.mjs new file mode 100644 index 00000000..d2a33180 --- /dev/null +++ b/test/fixtures/s10-stand-ins/prints-warning-form/index.mjs @@ -0,0 +1,15 @@ +import { basename } from "node:path"; + +const LF = String.fromCharCode(10); +const hint = + "(Use `" + + basename(process.argv0 || "node", ".exe") + + " --trace-warnings ...` to show where the warning was created)"; +process.stderr.write( + `(node:${process.pid}) [XSPEC_S10_FORGED] Warning: a line the module ` + + `writes in the warning form${LF}${hint}${LF}`, +); + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/prints-warning-form/package.json b/test/fixtures/s10-stand-ins/prints-warning-form/package.json new file mode 100644 index 00000000..999ef3bd --- /dev/null +++ b/test/fixtures/s10-stand-ins/prints-warning-form/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-prints-warning-form-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/reparents-prototype/index.cjs b/test/fixtures/s10-stand-ins/reparents-prototype/index.cjs new file mode 100644 index 00000000..ea2a402c --- /dev/null +++ b/test/fixtures/s10-stand-ins/reparents-prototype/index.cjs @@ -0,0 +1,10 @@ +"use strict"; + +Object.setPrototypeOf( + Date.prototype, + Object.create(Object.getPrototypeOf(Date.prototype)), +); + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/reparents-prototype/index.mjs b/test/fixtures/s10-stand-ins/reparents-prototype/index.mjs new file mode 100644 index 00000000..03c5f082 --- /dev/null +++ b/test/fixtures/s10-stand-ins/reparents-prototype/index.mjs @@ -0,0 +1,8 @@ +Object.setPrototypeOf( + Date.prototype, + Object.create(Object.getPrototypeOf(Date.prototype)), +); + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/reparents-prototype/package.json b/test/fixtures/s10-stand-ins/reparents-prototype/package.json new file mode 100644 index 00000000..51a30c26 --- /dev/null +++ b/test/fixtures/s10-stand-ins/reparents-prototype/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-reparents-prototype-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/replaces-emit-warning/index.cjs b/test/fixtures/s10-stand-ins/replaces-emit-warning/index.cjs new file mode 100644 index 00000000..aeab0d4e --- /dev/null +++ b/test/fixtures/s10-stand-ins/replaces-emit-warning/index.cjs @@ -0,0 +1,10 @@ +"use strict"; + +const emitWarning = process.emitWarning; +process.emitWarning = function xspecS10EmitWarning(...args) { + return Reflect.apply(emitWarning, this, args); +}; + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/replaces-emit-warning/index.mjs b/test/fixtures/s10-stand-ins/replaces-emit-warning/index.mjs new file mode 100644 index 00000000..a0dcf0c5 --- /dev/null +++ b/test/fixtures/s10-stand-ins/replaces-emit-warning/index.mjs @@ -0,0 +1,8 @@ +const emitWarning = process.emitWarning; +process.emitWarning = function xspecS10EmitWarning(...args) { + return Reflect.apply(emitWarning, this, args); +}; + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/replaces-emit-warning/package.json b/test/fixtures/s10-stand-ins/replaces-emit-warning/package.json new file mode 100644 index 00000000..77b07804 --- /dev/null +++ b/test/fixtures/s10-stand-ins/replaces-emit-warning/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-replaces-emit-warning-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/replaces-write/index.cjs b/test/fixtures/s10-stand-ins/replaces-write/index.cjs new file mode 100644 index 00000000..3c82b619 --- /dev/null +++ b/test/fixtures/s10-stand-ins/replaces-write/index.cjs @@ -0,0 +1,12 @@ +"use strict"; + +for (const stream of [process.stdout, process.stderr]) { + const write = stream.write; + stream.write = function xspecS10Write(...args) { + return Reflect.apply(write, this, args); + }; +} + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/replaces-write/index.mjs b/test/fixtures/s10-stand-ins/replaces-write/index.mjs new file mode 100644 index 00000000..4092b86a --- /dev/null +++ b/test/fixtures/s10-stand-ins/replaces-write/index.mjs @@ -0,0 +1,10 @@ +for (const stream of [process.stdout, process.stderr]) { + const write = stream.write; + stream.write = function xspecS10Write(...args) { + return Reflect.apply(write, this, args); + }; +} + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/replaces-write/package.json b/test/fixtures/s10-stand-ins/replaces-write/package.json new file mode 100644 index 00000000..7e1eb51a --- /dev/null +++ b/test/fixtures/s10-stand-ins/replaces-write/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-replaces-write-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/sets-env/index.cjs b/test/fixtures/s10-stand-ins/sets-env/index.cjs new file mode 100644 index 00000000..ce73ccab --- /dev/null +++ b/test/fixtures/s10-stand-ins/sets-env/index.cjs @@ -0,0 +1,7 @@ +"use strict"; + +process.env.XSPEC_S10_VARIABLE = "set"; + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/sets-env/index.mjs b/test/fixtures/s10-stand-ins/sets-env/index.mjs new file mode 100644 index 00000000..460cea30 --- /dev/null +++ b/test/fixtures/s10-stand-ins/sets-env/index.mjs @@ -0,0 +1,5 @@ +process.env.XSPEC_S10_VARIABLE = "set"; + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/sets-env/package.json b/test/fixtures/s10-stand-ins/sets-env/package.json new file mode 100644 index 00000000..4ab6c716 --- /dev/null +++ b/test/fixtures/s10-stand-ins/sets-env/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-sets-env-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/sets-exit-code/index.cjs b/test/fixtures/s10-stand-ins/sets-exit-code/index.cjs new file mode 100644 index 00000000..5c8cae6b --- /dev/null +++ b/test/fixtures/s10-stand-ins/sets-exit-code/index.cjs @@ -0,0 +1,7 @@ +"use strict"; + +process.exitCode = 0; + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/sets-exit-code/index.mjs b/test/fixtures/s10-stand-ins/sets-exit-code/index.mjs new file mode 100644 index 00000000..57e24c37 --- /dev/null +++ b/test/fixtures/s10-stand-ins/sets-exit-code/index.mjs @@ -0,0 +1,5 @@ +process.exitCode = 0; + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/sets-exit-code/package.json b/test/fixtures/s10-stand-ins/sets-exit-code/package.json new file mode 100644 index 00000000..70188f9a --- /dev/null +++ b/test/fixtures/s10-stand-ins/sets-exit-code/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-sets-exit-code-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/sets-title/index.cjs b/test/fixtures/s10-stand-ins/sets-title/index.cjs new file mode 100644 index 00000000..de74880b --- /dev/null +++ b/test/fixtures/s10-stand-ins/sets-title/index.cjs @@ -0,0 +1,7 @@ +"use strict"; + +process.title = "xspec-s10-title"; + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/sets-title/index.mjs b/test/fixtures/s10-stand-ins/sets-title/index.mjs new file mode 100644 index 00000000..26cef293 --- /dev/null +++ b/test/fixtures/s10-stand-ins/sets-title/index.mjs @@ -0,0 +1,5 @@ +process.title = "xspec-s10-title"; + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/sets-title/package.json b/test/fixtures/s10-stand-ins/sets-title/package.json new file mode 100644 index 00000000..ab4d0224 --- /dev/null +++ b/test/fixtures/s10-stand-ins/sets-title/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-sets-title-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/starts-timer/index.cjs b/test/fixtures/s10-stand-ins/starts-timer/index.cjs new file mode 100644 index 00000000..ef8d81bc --- /dev/null +++ b/test/fixtures/s10-stand-ins/starts-timer/index.cjs @@ -0,0 +1,7 @@ +"use strict"; + +setTimeout(function xspecS10Timer() {}, 100); + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/starts-timer/index.mjs b/test/fixtures/s10-stand-ins/starts-timer/index.mjs new file mode 100644 index 00000000..73611448 --- /dev/null +++ b/test/fixtures/s10-stand-ins/starts-timer/index.mjs @@ -0,0 +1,5 @@ +setTimeout(function xspecS10Timer() {}, 100); + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/starts-timer/package.json b/test/fixtures/s10-stand-ins/starts-timer/package.json new file mode 100644 index 00000000..300e217d --- /dev/null +++ b/test/fixtures/s10-stand-ins/starts-timer/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-starts-timer-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/touches-proxy/index.cjs b/test/fixtures/s10-stand-ins/touches-proxy/index.cjs new file mode 100644 index 00000000..5d68899a --- /dev/null +++ b/test/fixtures/s10-stand-ins/touches-proxy/index.cjs @@ -0,0 +1,6 @@ +"use strict"; + +exports.defineConfig = function defineConfig(settings) { + if (typeof settings === "function") void settings.xspecS10Property; + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/touches-proxy/index.mjs b/test/fixtures/s10-stand-ins/touches-proxy/index.mjs new file mode 100644 index 00000000..bc29bdd3 --- /dev/null +++ b/test/fixtures/s10-stand-ins/touches-proxy/index.mjs @@ -0,0 +1,4 @@ +export function defineConfig(settings) { + if (typeof settings === "function") void settings.xspecS10Property; + return settings; +} diff --git a/test/fixtures/s10-stand-ins/touches-proxy/package.json b/test/fixtures/s10-stand-ins/touches-proxy/package.json new file mode 100644 index 00000000..63367eaa --- /dev/null +++ b/test/fixtures/s10-stand-ins/touches-proxy/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-touches-proxy-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s10-stand-ins/writes-file/index.cjs b/test/fixtures/s10-stand-ins/writes-file/index.cjs new file mode 100644 index 00000000..6e49ed90 --- /dev/null +++ b/test/fixtures/s10-stand-ins/writes-file/index.cjs @@ -0,0 +1,15 @@ +"use strict"; + +const { writeFileSync } = require("node:fs"); +const { homedir, tmpdir } = require("node:os"); +const { join } = require("node:path"); + +const ownDirectory = __dirname; +const name = `writes-file-${process.pid}-${process.hrtime.bigint()}`; +for (const directory of [process.cwd(), homedir(), tmpdir(), ownDirectory]) { + writeFileSync(join(directory, name), "written", { flag: "wx" }); +} + +exports.defineConfig = function defineConfig(settings) { + return settings; +}; diff --git a/test/fixtures/s10-stand-ins/writes-file/index.mjs b/test/fixtures/s10-stand-ins/writes-file/index.mjs new file mode 100644 index 00000000..51c9f16d --- /dev/null +++ b/test/fixtures/s10-stand-ins/writes-file/index.mjs @@ -0,0 +1,14 @@ +import { writeFileSync } from "node:fs"; +import { homedir, tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const ownDirectory = dirname(fileURLToPath(import.meta.url)); +const name = `writes-file-${process.pid}-${process.hrtime.bigint()}`; +for (const directory of [process.cwd(), homedir(), tmpdir(), ownDirectory]) { + writeFileSync(join(directory, name), "written", { flag: "wx" }); +} + +export function defineConfig(settings) { + return settings; +} diff --git a/test/fixtures/s10-stand-ins/writes-file/package.json b/test/fixtures/s10-stand-ins/writes-file/package.json new file mode 100644 index 00000000..c5f51d24 --- /dev/null +++ b/test/fixtures/s10-stand-ins/writes-file/package.json @@ -0,0 +1,10 @@ +{ + "name": "s10-writes-file-standin", + "version": "1.0.0", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.cjs" + } + } +} diff --git a/test/fixtures/s4-module-channel/ambient-types/index.d.ts b/test/fixtures/s4-module-channel/ambient-types/index.d.ts new file mode 100644 index 00000000..539c0188 --- /dev/null +++ b/test/fixtures/s4-module-channel/ambient-types/index.d.ts @@ -0,0 +1 @@ +declare var s4AmbientGlobal: number; diff --git a/test/fixtures/s4-module-channel/ambient-types/package.json b/test/fixtures/s4-module-channel/ambient-types/package.json new file mode 100644 index 00000000..c51df1e7 --- /dev/null +++ b/test/fixtures/s4-module-channel/ambient-types/package.json @@ -0,0 +1,5 @@ +{ + "name": "@types/s4-ambient", + "version": "1.0.0", + "types": "./index.d.ts" +} diff --git a/test/fixtures/s4-module-channel/declaration-error/index.cjs b/test/fixtures/s4-module-channel/declaration-error/index.cjs new file mode 100644 index 00000000..491c6258 --- /dev/null +++ b/test/fixtures/s4-module-channel/declaration-error/index.cjs @@ -0,0 +1,5 @@ +"use strict"; + +exports.defineConfig = function defineConfig(value) { + return value; +}; diff --git a/test/fixtures/s4-module-channel/declaration-error/index.d.cts b/test/fixtures/s4-module-channel/declaration-error/index.d.cts new file mode 100644 index 00000000..93c4635b --- /dev/null +++ b/test/fixtures/s4-module-channel/declaration-error/index.d.cts @@ -0,0 +1,5 @@ +export declare function defineConfig<T>(value: T): T; + +declare const unresolved: UndeclaredType; + +export {}; diff --git a/test/fixtures/s4-module-channel/declaration-error/index.d.ts b/test/fixtures/s4-module-channel/declaration-error/index.d.ts new file mode 100644 index 00000000..93c4635b --- /dev/null +++ b/test/fixtures/s4-module-channel/declaration-error/index.d.ts @@ -0,0 +1,5 @@ +export declare function defineConfig<T>(value: T): T; + +declare const unresolved: UndeclaredType; + +export {}; diff --git a/test/fixtures/s4-module-channel/declaration-error/index.js b/test/fixtures/s4-module-channel/declaration-error/index.js new file mode 100644 index 00000000..07d41a1f --- /dev/null +++ b/test/fixtures/s4-module-channel/declaration-error/index.js @@ -0,0 +1,3 @@ +export function defineConfig(value) { + return value; +} diff --git a/test/fixtures/s4-module-channel/declaration-error/package.json b/test/fixtures/s4-module-channel/declaration-error/package.json new file mode 100644 index 00000000..86e7ca06 --- /dev/null +++ b/test/fixtures/s4-module-channel/declaration-error/package.json @@ -0,0 +1,19 @@ +{ + "name": "s4-module-channel-declaration-error", + "version": "1.0.0", + "type": "module", + "types": "./index.d.ts", + "main": "./index.cjs", + "exports": { + ".": { + "import": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "require": { + "types": "./index.d.cts", + "default": "./index.cjs" + } + } + } +} diff --git a/test/fixtures/s4-module-channel/dual/index.cjs b/test/fixtures/s4-module-channel/dual/index.cjs new file mode 100644 index 00000000..491c6258 --- /dev/null +++ b/test/fixtures/s4-module-channel/dual/index.cjs @@ -0,0 +1,5 @@ +"use strict"; + +exports.defineConfig = function defineConfig(value) { + return value; +}; diff --git a/test/fixtures/s4-module-channel/dual/index.d.cts b/test/fixtures/s4-module-channel/dual/index.d.cts new file mode 100644 index 00000000..d675b442 --- /dev/null +++ b/test/fixtures/s4-module-channel/dual/index.d.cts @@ -0,0 +1 @@ +export declare function defineConfig<T>(value: T): T; diff --git a/test/fixtures/s4-module-channel/dual/index.d.ts b/test/fixtures/s4-module-channel/dual/index.d.ts new file mode 100644 index 00000000..d675b442 --- /dev/null +++ b/test/fixtures/s4-module-channel/dual/index.d.ts @@ -0,0 +1 @@ +export declare function defineConfig<T>(value: T): T; diff --git a/test/fixtures/s4-module-channel/dual/index.js b/test/fixtures/s4-module-channel/dual/index.js new file mode 100644 index 00000000..07d41a1f --- /dev/null +++ b/test/fixtures/s4-module-channel/dual/index.js @@ -0,0 +1,3 @@ +export function defineConfig(value) { + return value; +} diff --git a/test/fixtures/s4-module-channel/dual/package.json b/test/fixtures/s4-module-channel/dual/package.json new file mode 100644 index 00000000..aab6c36c --- /dev/null +++ b/test/fixtures/s4-module-channel/dual/package.json @@ -0,0 +1,19 @@ +{ + "name": "s4-module-channel-dual", + "version": "1.0.0", + "type": "module", + "types": "./index.d.ts", + "main": "./index.cjs", + "exports": { + ".": { + "import": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "require": { + "types": "./index.d.cts", + "default": "./index.cjs" + } + } + } +} diff --git a/test/fixtures/s4-module-channel/esm-only/index.d.ts b/test/fixtures/s4-module-channel/esm-only/index.d.ts new file mode 100644 index 00000000..d675b442 --- /dev/null +++ b/test/fixtures/s4-module-channel/esm-only/index.d.ts @@ -0,0 +1 @@ +export declare function defineConfig<T>(value: T): T; diff --git a/test/fixtures/s4-module-channel/esm-only/index.js b/test/fixtures/s4-module-channel/esm-only/index.js new file mode 100644 index 00000000..07d41a1f --- /dev/null +++ b/test/fixtures/s4-module-channel/esm-only/index.js @@ -0,0 +1,3 @@ +export function defineConfig(value) { + return value; +} diff --git a/test/fixtures/s4-module-channel/esm-only/package.json b/test/fixtures/s4-module-channel/esm-only/package.json new file mode 100644 index 00000000..1f1645a1 --- /dev/null +++ b/test/fixtures/s4-module-channel/esm-only/package.json @@ -0,0 +1,11 @@ +{ + "name": "s4-module-channel-esm-only", + "version": "1.0.0", + "type": "module", + "exports": { + ".": { + "types": "./index.d.ts", + "default": "./index.js" + } + } +} diff --git a/test/fixtures/s4-module-channel/export-assignment/index.d.ts b/test/fixtures/s4-module-channel/export-assignment/index.d.ts new file mode 100644 index 00000000..ab14b41c --- /dev/null +++ b/test/fixtures/s4-module-channel/export-assignment/index.d.ts @@ -0,0 +1,6 @@ +declare const api: { + defineConfig<T>(value: T): T; + readonly other: number; +}; + +export = api; diff --git a/test/fixtures/s4-module-channel/export-assignment/index.js b/test/fixtures/s4-module-channel/export-assignment/index.js new file mode 100644 index 00000000..2ba4b4dd --- /dev/null +++ b/test/fixtures/s4-module-channel/export-assignment/index.js @@ -0,0 +1,8 @@ +"use strict"; + +module.exports = { + defineConfig(value) { + return value; + }, + other: 1, +}; diff --git a/test/fixtures/s4-module-channel/export-assignment/package.json b/test/fixtures/s4-module-channel/export-assignment/package.json new file mode 100644 index 00000000..5bdb04fa --- /dev/null +++ b/test/fixtures/s4-module-channel/export-assignment/package.json @@ -0,0 +1,6 @@ +{ + "name": "s4-module-channel-export-assignment", + "version": "1.0.0", + "types": "./index.d.ts", + "main": "./index.js" +} diff --git a/test/fixtures/s4-module-channel/exports-only/entry.cjs b/test/fixtures/s4-module-channel/exports-only/entry.cjs new file mode 100644 index 00000000..491c6258 --- /dev/null +++ b/test/fixtures/s4-module-channel/exports-only/entry.cjs @@ -0,0 +1,5 @@ +"use strict"; + +exports.defineConfig = function defineConfig(value) { + return value; +}; diff --git a/test/fixtures/s4-module-channel/exports-only/entry.d.cts b/test/fixtures/s4-module-channel/exports-only/entry.d.cts new file mode 100644 index 00000000..d675b442 --- /dev/null +++ b/test/fixtures/s4-module-channel/exports-only/entry.d.cts @@ -0,0 +1 @@ +export declare function defineConfig<T>(value: T): T; diff --git a/test/fixtures/s4-module-channel/exports-only/entry.d.ts b/test/fixtures/s4-module-channel/exports-only/entry.d.ts new file mode 100644 index 00000000..d675b442 --- /dev/null +++ b/test/fixtures/s4-module-channel/exports-only/entry.d.ts @@ -0,0 +1 @@ +export declare function defineConfig<T>(value: T): T; diff --git a/test/fixtures/s4-module-channel/exports-only/entry.js b/test/fixtures/s4-module-channel/exports-only/entry.js new file mode 100644 index 00000000..07d41a1f --- /dev/null +++ b/test/fixtures/s4-module-channel/exports-only/entry.js @@ -0,0 +1,3 @@ +export function defineConfig(value) { + return value; +} diff --git a/test/fixtures/s4-module-channel/exports-only/package.json b/test/fixtures/s4-module-channel/exports-only/package.json new file mode 100644 index 00000000..71d545f7 --- /dev/null +++ b/test/fixtures/s4-module-channel/exports-only/package.json @@ -0,0 +1,17 @@ +{ + "name": "s4-module-channel-exports-only", + "version": "1.0.0", + "type": "module", + "exports": { + ".": { + "import": { + "types": "./entry.d.ts", + "default": "./entry.js" + }, + "require": { + "types": "./entry.d.cts", + "default": "./entry.cjs" + } + } + } +} diff --git a/test/fixtures/s4-module-channel/implicit-any/index.cjs b/test/fixtures/s4-module-channel/implicit-any/index.cjs new file mode 100644 index 00000000..fd3fddd5 --- /dev/null +++ b/test/fixtures/s4-module-channel/implicit-any/index.cjs @@ -0,0 +1,7 @@ +"use strict"; + +exports.defineConfig = function defineConfig(value) { + return value; +}; + +exports.loosely = function loosely() {}; diff --git a/test/fixtures/s4-module-channel/implicit-any/index.d.cts b/test/fixtures/s4-module-channel/implicit-any/index.d.cts new file mode 100644 index 00000000..ec473e19 --- /dev/null +++ b/test/fixtures/s4-module-channel/implicit-any/index.d.cts @@ -0,0 +1,3 @@ +export declare function defineConfig<T>(value: T): T; + +export declare function loosely(untyped): void; diff --git a/test/fixtures/s4-module-channel/implicit-any/index.d.ts b/test/fixtures/s4-module-channel/implicit-any/index.d.ts new file mode 100644 index 00000000..ec473e19 --- /dev/null +++ b/test/fixtures/s4-module-channel/implicit-any/index.d.ts @@ -0,0 +1,3 @@ +export declare function defineConfig<T>(value: T): T; + +export declare function loosely(untyped): void; diff --git a/test/fixtures/s4-module-channel/implicit-any/index.js b/test/fixtures/s4-module-channel/implicit-any/index.js new file mode 100644 index 00000000..825cb60c --- /dev/null +++ b/test/fixtures/s4-module-channel/implicit-any/index.js @@ -0,0 +1,5 @@ +export function defineConfig(value) { + return value; +} + +export function loosely() {} diff --git a/test/fixtures/s4-module-channel/implicit-any/package.json b/test/fixtures/s4-module-channel/implicit-any/package.json new file mode 100644 index 00000000..7200bda4 --- /dev/null +++ b/test/fixtures/s4-module-channel/implicit-any/package.json @@ -0,0 +1,19 @@ +{ + "name": "s4-module-channel-implicit-any", + "version": "1.0.0", + "type": "module", + "types": "./index.d.ts", + "main": "./index.cjs", + "exports": { + ".": { + "import": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "require": { + "types": "./index.d.cts", + "default": "./index.cjs" + } + } + } +} diff --git a/test/fixtures/s4-module-channel/implicit-export/index.cjs b/test/fixtures/s4-module-channel/implicit-export/index.cjs new file mode 100644 index 00000000..491c6258 --- /dev/null +++ b/test/fixtures/s4-module-channel/implicit-export/index.cjs @@ -0,0 +1,5 @@ +"use strict"; + +exports.defineConfig = function defineConfig(value) { + return value; +}; diff --git a/test/fixtures/s4-module-channel/implicit-export/index.d.cts b/test/fixtures/s4-module-channel/implicit-export/index.d.cts new file mode 100644 index 00000000..c3fb2475 --- /dev/null +++ b/test/fixtures/s4-module-channel/implicit-export/index.d.cts @@ -0,0 +1,5 @@ +export declare function defineConfig<T>(value: T): T; + +interface RequireEntryInterface { + readonly note: string; +} diff --git a/test/fixtures/s4-module-channel/implicit-export/index.d.ts b/test/fixtures/s4-module-channel/implicit-export/index.d.ts new file mode 100644 index 00000000..faab4ee4 --- /dev/null +++ b/test/fixtures/s4-module-channel/implicit-export/index.d.ts @@ -0,0 +1,5 @@ +export declare function defineConfig<T>(value: T): T; + +interface ImportEntryInterface { + readonly note: string; +} diff --git a/test/fixtures/s4-module-channel/implicit-export/index.js b/test/fixtures/s4-module-channel/implicit-export/index.js new file mode 100644 index 00000000..07d41a1f --- /dev/null +++ b/test/fixtures/s4-module-channel/implicit-export/index.js @@ -0,0 +1,3 @@ +export function defineConfig(value) { + return value; +} diff --git a/test/fixtures/s4-module-channel/implicit-export/package.json b/test/fixtures/s4-module-channel/implicit-export/package.json new file mode 100644 index 00000000..be1cdb5e --- /dev/null +++ b/test/fixtures/s4-module-channel/implicit-export/package.json @@ -0,0 +1,19 @@ +{ + "name": "s4-module-channel-implicit-export", + "version": "1.0.0", + "type": "module", + "types": "./index.d.ts", + "main": "./index.cjs", + "exports": { + ".": { + "import": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "require": { + "types": "./index.d.cts", + "default": "./index.cjs" + } + } + } +} diff --git a/test/fixtures/s4-module-channel/typed/index.cjs b/test/fixtures/s4-module-channel/typed/index.cjs new file mode 100644 index 00000000..491c6258 --- /dev/null +++ b/test/fixtures/s4-module-channel/typed/index.cjs @@ -0,0 +1,5 @@ +"use strict"; + +exports.defineConfig = function defineConfig(value) { + return value; +}; diff --git a/test/fixtures/s4-module-channel/typed/index.d.cts b/test/fixtures/s4-module-channel/typed/index.d.cts new file mode 100644 index 00000000..9de329fb --- /dev/null +++ b/test/fixtures/s4-module-channel/typed/index.d.cts @@ -0,0 +1,5 @@ +export interface Settings { + readonly checked: boolean; +} + +export declare function defineConfig<T>(value: T): T; diff --git a/test/fixtures/s4-module-channel/typed/index.d.ts b/test/fixtures/s4-module-channel/typed/index.d.ts new file mode 100644 index 00000000..9de329fb --- /dev/null +++ b/test/fixtures/s4-module-channel/typed/index.d.ts @@ -0,0 +1,5 @@ +export interface Settings { + readonly checked: boolean; +} + +export declare function defineConfig<T>(value: T): T; diff --git a/test/fixtures/s4-module-channel/typed/index.js b/test/fixtures/s4-module-channel/typed/index.js new file mode 100644 index 00000000..07d41a1f --- /dev/null +++ b/test/fixtures/s4-module-channel/typed/index.js @@ -0,0 +1,3 @@ +export function defineConfig(value) { + return value; +} diff --git a/test/fixtures/s4-module-channel/typed/package.json b/test/fixtures/s4-module-channel/typed/package.json new file mode 100644 index 00000000..5c8e9b77 --- /dev/null +++ b/test/fixtures/s4-module-channel/typed/package.json @@ -0,0 +1,19 @@ +{ + "name": "s4-module-channel-typed", + "version": "1.0.0", + "type": "module", + "types": "./index.d.ts", + "main": "./index.cjs", + "exports": { + ".": { + "import": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "require": { + "types": "./index.d.cts", + "default": "./index.cjs" + } + } + } +} diff --git a/test/fixtures/s4-module-channel/unexported-return/index.cjs b/test/fixtures/s4-module-channel/unexported-return/index.cjs new file mode 100644 index 00000000..8a25a6a3 --- /dev/null +++ b/test/fixtures/s4-module-channel/unexported-return/index.cjs @@ -0,0 +1,9 @@ +"use strict"; + +exports.defineConfig = function defineConfig(value) { + return value; +}; + +exports.defineVisible = function defineVisible(value) { + return value; +}; diff --git a/test/fixtures/s4-module-channel/unexported-return/index.d.cts b/test/fixtures/s4-module-channel/unexported-return/index.d.cts new file mode 100644 index 00000000..c67f3cca --- /dev/null +++ b/test/fixtures/s4-module-channel/unexported-return/index.d.cts @@ -0,0 +1,13 @@ +interface Hidden { + readonly checked: boolean; +} + +export interface Visible { + readonly checked: boolean; +} + +export declare function defineConfig(value: Hidden): Hidden; + +export declare function defineVisible(value: Visible): Visible; + +export {}; diff --git a/test/fixtures/s4-module-channel/unexported-return/index.d.ts b/test/fixtures/s4-module-channel/unexported-return/index.d.ts new file mode 100644 index 00000000..c67f3cca --- /dev/null +++ b/test/fixtures/s4-module-channel/unexported-return/index.d.ts @@ -0,0 +1,13 @@ +interface Hidden { + readonly checked: boolean; +} + +export interface Visible { + readonly checked: boolean; +} + +export declare function defineConfig(value: Hidden): Hidden; + +export declare function defineVisible(value: Visible): Visible; + +export {}; diff --git a/test/fixtures/s4-module-channel/unexported-return/index.js b/test/fixtures/s4-module-channel/unexported-return/index.js new file mode 100644 index 00000000..a1b2df99 --- /dev/null +++ b/test/fixtures/s4-module-channel/unexported-return/index.js @@ -0,0 +1,7 @@ +export function defineConfig(value) { + return value; +} + +export function defineVisible(value) { + return value; +} diff --git a/test/fixtures/s4-module-channel/unexported-return/package.json b/test/fixtures/s4-module-channel/unexported-return/package.json new file mode 100644 index 00000000..9df1bc6a --- /dev/null +++ b/test/fixtures/s4-module-channel/unexported-return/package.json @@ -0,0 +1,19 @@ +{ + "name": "s4-module-channel-unexported-return", + "version": "1.0.0", + "type": "module", + "types": "./index.d.ts", + "main": "./index.cjs", + "exports": { + ".": { + "import": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "require": { + "types": "./index.d.cts", + "default": "./index.cjs" + } + } + } +} diff --git a/test/helpers/config-import.ts b/test/helpers/config-import.ts new file mode 100644 index 00000000..d0fb744f --- /dev/null +++ b/test/helpers/config-import.ts @@ -0,0 +1,118 @@ +// The configuration import's spelling (TEST-SPEC T7-9, §16 P-19; SPEC 7, +// 2.4; CERTIFICATIONS.md §CONF-IMPORT and its Exclusions bullet "T7-9 and +// T7-10") — the one path by which the harness stages a configuration whose +// import's module specifier is a given static string literal. Harness +// machinery only: no product imports, no test-framework dependence. +// +// SPEC 7 reads the specifier as spelled (2.4): any static string literal, +// in either quote style, escape sequences, line continuations, and U+FFFD +// included, never interpreted, resolved, or loaded. A test of that rule is +// worth only what reaches the file: tooling that handles the literal as its +// value — a code printer (`JSON.stringify` among them) serializing a drawn +// value, text whose escape sequences were decoded on their way into the +// harness — stages another spelling of the same value, and a formatter +// normalizing quotes stages the single-quoted form as a double-quoted one; +// S-9 accepts either, and the class P-19 searches goes silently unreached +// (CONF-IMPORT's two staging hazards). So the literal is handed over exactly +// as it is to appear in the file, its quotes included, and reaches the +// file's text by concatenation alone: `configImportText` joins three +// strings and nothing else — no printer, no decoding, no formatter, no +// re-quoting — and the workspace builder writes that text's UTF-8 bytes as +// they stand (test/self/p19-fixed-seed-draws.test.ts reads each fixed-seed +// draw's staged file back and pins its bytes). P-19's draws +// (test/suite/registry/section-16-p19.ts) and every configuration of T7-9's +// (a) and (b) (test/suite/registry/section-7-import.ts, which pins each of +// its records' bytes at module load) are staged through this module, so +// that (a)'s escape-spelled, line-continuation, single-quoted, and +// raw-U+FFFD arms ride VIOL-IMPORT-BRACED's and VIOL-IMPORT-SINGLE's +// certification of P-19 representatively (CERTIFICATIONS.md, Exclusions). +// T7-10's configurations (the same module) are composed from this module's +// head, `configImportText` for its undiscovered arms and its baselines, and +// stage its `specs/A.mdx` record; their literals spell no escape but one +// baseline's, T7-9(b)'s hexadecimal escape with one hex digit, built from +// BACKSLASH. +// A literal holding a backslash is built by its caller from code point +// U+005C (the BACKSLASH constant below), never spelled in harness source, +// where a string or template literal would itself interpret an escape. +// +// The workspace (T7-9's opening; CONF-IMPORT's scope and staging +// constraints): `xspec.config.ts` with one spec group, `main`, globbing +// `specs/*.mdx`, and `markdown` with `emit: true`, emitting next to sources +// (7.3, 13.2) — no code group at all, and no `coverage` or `policy`, so that +// no configured group discovers the configuration file — over `specs/A.mdx` +// and `specs/B.mdx`, each a trivial single-section source whose one section +// carries an `id` alone around plain text (`<S id="a">A</S>`, T7-9(d)'s +// `specs/A.mdx`); no git repository and no `node_modules`. + +import { stagedMdx } from "./staged-mdx.js"; +import type { StagedMdx } from "./staged-mdx.js"; +import { stagedTs } from "./staged-ts.js"; +import type { StagedTs } from "./staged-ts.js"; + +/** U+005C, the escape character, built from its code point. */ +export const BACKSLASH = String.fromCodePoint(0x5c); + +/** The configuration file's workspace-relative path (SPEC 7). */ +export const CONFIG_IMPORT_CONFIG_PATH = "xspec.config.ts"; + +/** + * The configuration's text before its import's specifier: the import of + * `defineConfig`, unaliased, with no modifier and no attributes (SPEC 7). + */ +export const CONFIG_IMPORT_HEAD = "import { defineConfig } from "; + +/** + * The configuration's text after its import's specifier: the line's end, a + * blank line, and the default export — the one spec group `main` over + * `specs/*.mdx` and Markdown emission next to sources (module header). + */ +export const CONFIG_IMPORT_TAIL = ` + +export default defineConfig({ + specs: { + main: ["specs/*.mdx"] + }, + markdown: { emit: true } +}) +`; + +/** The twin's specifier (T7-9, P-19): the double-quoted name `xspec`. */ +export const CONFIG_IMPORT_TWIN_LITERAL = '"xspec"'; + +/** + * The configuration whose import's module specifier is `literal`, spelled + * exactly as it is to appear in the file, its quotes included: the three + * strings joined, nothing printed, decoded, or re-quoted (module header). + * The caller guarantees `literal` is one static string literal TypeScript + * 5.9.3's scanner accepts; S-9 judges the result before any product sees it. + */ +export function configImportText(literal: string): string { + return CONFIG_IMPORT_HEAD + literal + CONFIG_IMPORT_TAIL; +} + +/** + * The twin's configuration, a staged-source record (S-9's timing clause: + * every twin workspace T7-9 and P-19 stage is created at module load's + * bytes). + */ +export const CONFIG_IMPORT_TWIN_CONFIG: StagedTs = stagedTs( + 'T7-9/P-19 xspec.config.ts (the twin: the specifier "xspec", one spec group main over specs/*.mdx, Markdown emitted next to sources)', + configImportText(CONFIG_IMPORT_TWIN_LITERAL), +); + +/** + * The workspace's two sources, staged-source records (module header): T7-9 + * and P-19 stage them in workspaces created after a product invocation. + */ +export const CONFIG_IMPORT_SOURCES: Readonly<Record<string, StagedMdx>> = { + "specs/A.mdx": stagedMdx( + `T7-9/P-19 specs/A.mdx (one section, its id alone around plain text: <S id="a">A</S>)`, + `<S id="a">A</S> +`, + ), + "specs/B.mdx": stagedMdx( + `T7-9/P-19 specs/B.mdx (one section, its id alone around plain text: <S id="b">B</S>)`, + `<S id="b">B</S> +`, + ), +}; diff --git a/test/helpers/module-channel-bootstrap.cjs b/test/helpers/module-channel-bootstrap.cjs new file mode 100644 index 00000000..e53f32dc --- /dev/null +++ b/test/helpers/module-channel-bootstrap.cjs @@ -0,0 +1,1202 @@ +// The module channel's bootstrap on a Node.js release (TEST-SPEC T7.6-6, +// T7.6-7, S-10, H-2; SPEC 7.6 Runtime). Harness code, never product code, +// and it imports none: helpers/module-channel-node.ts copies these bytes +// into each run's own directory — outside the staging, the run's working +// directory, its HOME, and its TMPDIR — and runs +// +// <release>/bin/node <this file> <importing module> <report> <route> +// +// with no option before this file and an explicit minimal environment, +// through the subprocess driver under the run's own hang guard. +// +// Before anything of the package loads, in this order: +// 1. It captures every built-in it calls once loading has begun, so that +// what the loaded module does to the global object, a built-in +// prototype, or `process` does not reach the report; and from then on it +// neither iterates an array through its prototype (no array +// destructuring, spread, or `for...of`) nor assigns a property it has +// not defined, so nothing the module installs there runs either, but +// for a `toJSON` the report's serialization looks up. +// 2. It reads the run's conditions — its arguments, the release's version, +// executable, and options (`process.execArgv`), the process identifier, +// the environment, and the working directory — which the driver checks +// against those it set (TEST-SPEC T7.6-6's run conditions, S-10). +// 3. It makes T7.6-6's call values (below): the identity values, the two +// recording Proxies, and the frozen object. +// 4. It registers a `warning` listener on `process`, recording each warning +// the runtime delivers, in order (TEST-SPEC T7.6-7(a)), and an `exit` +// listener writing the report as the process exits. +// 5. It reads T7.6-7(c)'s process state (below) twice: once to settle it — +// the runtime materializes some of the global object's properties on +// their first read (lazy data properties: on 22.23.4 and later, reading +// `FormData`'s descriptor loads the runtime's own fetch implementation, +// which adds a symbol-keyed global), and creates `process.stdout` and +// `process.stderr` on theirs — and then as the baseline the run's state +// is compared against, the listeners of step 4 among it. +// Only then does it load the importing module, by the physical path the +// driver gives: `import()` of its file URL for an ES module (`.mjs`), +// `require` for a CommonJS module (`.cjs`). The importing module performs +// its route's load of the package and hands back what it loaded — a +// namespace, the promise of one, or a `require` result — beside a note of +// its own kind (its top-level `this`) and location (`import.meta.url`, or +// `__filename`). +// +// What the load handed back is then observed inside the run (TEST-SPEC +// T7.6-6), through the built-ins captured in step 1: +// - (a) Its own keys, each with its kind (a string, or a symbol named by its +// description), and its enumerability read from its descriptor, never +// invoking an accessor. The driver reads the route's listing from them: +// an `import` namespace's string-keyed properties, a `require` result's +// enumerable ones. +// - (b) and (c) `defineConfig`, read from it once, then called as a plain +// function once per case, in the order of the driver's `CALL_CASES`: an +// object, an array, a function, a symbol, `null`, `undefined` passed +// explicitly, a string, a boolean, a bigint, `0`, `-0`, and `NaN`; no +// argument; a further argument; the two Proxies; the frozen object. Each +// call's verdict is `Object.is` of what it returned and what it must +// return — its (first) argument, or `undefined` with no argument: +// `returned-argument`, `returned-other` (the value described by its type +// and, for a primitive or a harness value, its text), or `threw` (the +// thrown value read as the report reads one). +// - Each trap either Proxy's handler runs, in order, from the moment the +// Proxies exist to the run's end. Each Proxy's target is a function, and +// its handler carries all thirteen traps, each recording its invocation +// and then forwarding to the captured `Reflect` method. Nothing of the +// bootstrap's own touches a Proxy once it is made: a returned or thrown +// Proxy is named by identity alone. +// +// Once the calls are made, the process state is read again and compared, +// in the run, with the baseline (TEST-SPEC T7.6-7(c): unchanged across the +// load and the calls), each difference recorded under the observation that +// found it — the names the driver's `STATE_OBSERVATIONS` lists: +// - `global-object`: the global object's own properties, string- and +// symbol-keyed, with their descriptors, read without invoking an accessor +// (a property added, removed, or changed in its kind, value, getter, +// setter, or attributes, each value compared by `Object.is`); +// - `built-ins`: likewise, the own properties of the global built-in +// constructors and namespace objects and of those constructors' +// prototypes — here every string-keyed own data property of the global +// object, as the baseline reads it, holding an object or a function (the +// global object itself and `process` aside: ECMAScript's constructors and +// namespace objects, the runtime's own, and the other built-in objects +// and functions the global object holds, a superset of TEST-SPEC's), +// each labeled by its key, and each such function's own `prototype` data +// property holding an object or a function, labeled `<key>.prototype`, +// each object observed once, under its first label; +// - `extensibility` and `prototype`: the extensibility and the prototype of +// each of these objects, the global object and `process` included; +// - `process`: `process`'s own properties with their descriptors, read +// likewise; +// - `environment`: `process.env`'s variables and their values; +// - `title`: the process title; `working-directory`: the working directory +// (`process.cwd()`, called as captured in step 1); `exit-code`: +// `process.exitCode`; +// - `stream-write`: the `write` each of `process.stdout` and +// `process.stderr` resolves to, compared by identity; +// - `listeners`: the listeners registered on `process`, each event's in +// order, compared by identity — the `warning` and `exit` listeners of +// step 4 among them; +// - `timers-and-handles`: the pending timers and handles the runtime +// reports — its active handles (`process._getActiveHandles()`), compared +// by identity, and its pending timers and immediates +// (`process.getActiveResourcesInfo()`'s `Timeout` and `Immediate` +// entries), counted — never its pending requests, which its own loading +// leaves in flight (an ES module's file handle still closing on 22.0 to +// 22.12, say). +// A read the module makes fail is a difference too. The objects compared +// are those the baseline found (a global replaced is a change of the global +// object's, the replaced object still observed); values are named by their +// type, a primitive's text, or an observed object's label, so nothing of +// the package's runs while they are described. At most `STATE_CHANGE_LIMIT` +// differences are listed, the rest counted. +// +// The report is one JSON document, whose members the driver's decoder +// (`decodeModuleRunReport`) reads exactly, written to the path the driver +// names: once the load and the calls have completed, or the load has +// failed, and again as the process exits, then holding the exit code and +// every warning delivered and trap invoked by then. Its phase is `loading` +// until the load hands back a value or throws, `calling` while the calls +// run and the state is compared — so a process ending inside a call is +// reported as such — and `completed` after, the comparison (`state`: the +// labels of the objects observed, the differences, and how many more were +// left unlisted) set with it where the module loaded, and null otherwise. +// Each write goes to a sibling `.partial` file renamed +// over the report, so the driver reads a whole document or none. A process +// ending before both writes — killed by a signal, or exiting without +// running its `exit` listeners while still loading — leaves none, which +// the driver reports as such. Nothing here writes to standard output or +// standard error, sets a timer, or keeps the process alive. + +"use strict"; + +const fs = require("node:fs"); +const url = require("node:url"); +const events = require("node:events"); + +// 1. The built-ins called once loading has begun. +const writeFileSync = fs.writeFileSync; +const renameSync = fs.renameSync; +const pathToFileURL = url.pathToFileURL; +const stringify = JSON.stringify; +const defineProperty = Reflect.defineProperty; +const apply = Reflect.apply; +const ownKeys = Reflect.ownKeys; +const getOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor; +const getPrototypeOf = Reflect.getPrototypeOf; +const isExtensible = Reflect.isExtensible; +const hasOwn = Object.hasOwn; +const objectKeys = Object.keys; +const is = Object.is; +const freeze = Object.freeze; +const promiseThen = Promise.prototype.then; +const stringSlice = String.prototype.slice; +const arraySort = Array.prototype.sort; +const toText = String; +const ProxyConstructor = Proxy; +const MapConstructor = Map; +const mapGet = Map.prototype.get; +const mapSet = Map.prototype.set; +const mapHas = Map.prototype.has; +const symbolDescription = getOwnPropertyDescriptor( + Symbol.prototype, + "description", +).get; +const eventNames = events.EventEmitter.prototype.eventNames; +const rawListeners = events.EventEmitter.prototype.rawListeners; +const processCwd = process.cwd; +const getActiveResourcesInfo = process.getActiveResourcesInfo; +const getActiveHandles = process._getActiveHandles; +const globalObject = globalThis; + +/** The report's protocol, which the driver's decoder requires. */ +const PROTOCOL = "xspec-module-run/3"; + +/** How much of a returned string a call's description keeps. */ +const RETURNED_TEXT_LIMIT = 200; + +/** The most differences in process state a report lists (header). */ +const STATE_CHANGE_LIMIT = 100; + +/** How much of a string a difference's description keeps. */ +const DESCRIBED_TEXT_LIMIT = 80; + +/** + * Every trap a Proxy handler can carry (the driver's `PROXY_TRAPS`), each + * forwarded to its `Reflect` method, captured here. + */ +const TRAPS = [ + "apply", + "construct", + "defineProperty", + "deleteProperty", + "get", + "getOwnPropertyDescriptor", + "getPrototypeOf", + "has", + "isExtensible", + "ownKeys", + "preventExtensions", + "set", + "setPrototypeOf", +]; +const forwards = { __proto__: null }; +for (let index = 0; index < TRAPS.length; index += 1) { + forwards[TRAPS[index]] = Reflect[TRAPS[index]]; +} + +// 2. The run's conditions: this file's path, the importing module's, the +// report's, and the route, as the driver passed them. +const argv = process.argv.slice(1); +const importingModule = argv[1]; +const reportPath = argv[2]; +const route = argv[3]; +const partialPath = `${reportPath}.partial`; + +const environment = {}; +const environmentNames = Object.keys(process.env); +for (let index = 0; index < environmentNames.length; index += 1) { + const name = environmentNames[index]; + defineProperty(environment, name, { + value: process.env[name], + writable: true, + enumerable: true, + configurable: true, + }); +} + +// 3. T7.6-6's call values. +const trapLog = []; +const firstProxy = recordingProxy("first"); +const secondProxy = recordingProxy("second"); +const firstArgument = { xspecArgument: "first" }; +const secondArgument = { xspecArgument: "second" }; +const frozenObject = freeze({ xspecFrozen: true }); + +/** The harness values a call may hand back in place of its own, by name. */ +const KNOWN_VALUES = [ + [firstProxy, "the first Proxy"], + [secondProxy, "the second Proxy"], + [firstArgument, "the first of two arguments"], + [secondArgument, "the second of two arguments"], + [frozenObject, "the frozen object"], +]; + +/** + * T7.6-6's calls, in the order of the driver's `CALL_CASES`: each case's + * arguments, and the value the call must return. + */ +const CALLS = [ + identityCall("object", { xspecIdentity: "object" }), + identityCall("array", ["xspec", "identity"]), + identityCall("function", function xspecIdentity() {}), + identityCall("symbol", Symbol("xspec identity")), + identityCall("null", null), + identityCall("undefined", undefined), + identityCall("string", "xspec identity"), + identityCall("boolean", false), + identityCall("bigint", 10n), + identityCall("zero", 0), + identityCall("negative-zero", -0), + identityCall("nan", NaN), + { label: "no-argument", args: [], expected: undefined }, + { + label: "further-arguments", + args: [firstArgument, secondArgument], + expected: firstArgument, + }, + { label: "proxies", args: [firstProxy, secondProxy], expected: firstProxy }, + { label: "frozen", args: [frozenObject], expected: frozenObject }, +]; + +const warnings = []; +const report = { + protocol: PROTOCOL, + argv, + release: { + version: process.version, + execPath: process.execPath, + execArgv: process.execArgv.slice(), + }, + pid: process.pid, + environment, + cwd: process.cwd(), + phase: "loading", + importingModule: null, + load: null, + calls: null, + state: null, + bootstrapError: null, + warnings, + exit: null, +}; + +// 4. The listeners, registered before the importing module's own loading +// begins. +process.on("warning", (warning) => { + append(warnings, describeWarning(warning)); +}); +process.on("exit", (code) => { + report.exit = { code: typeof code === "number" ? code : null }; + writeReport(); +}); + +apply(promiseThen, load(), [ + () => { + writeReport(); + }, + (error) => { + report.bootstrapError = describeThrown(error); + writeReport(); + }, +]); + +/** + * Load the importing module along the route, and record what its load + * handed back and what T7.6-6's calls observed of it, or what the load + * threw, and, where it loaded, how the process state compares with the + * baseline once the calls are made (header). Each phase's members are set + * together, with no code of the package's between them, so a report written + * at any exit is consistent. + */ +async function load() { + const asModule = + route === "static-import" || route === "dynamic-import-from-module"; + const asCommonJs = + route === "dynamic-import-from-commonjs" || route === "require"; + if (!asModule && !asCommonJs) { + throw new TypeError(`no route is named ${stringify(route)}`); + } + // 5. The state settled, then read as the baseline, before the importing + // module's own loading begins. + readState(listSubjects()); + const baseline = readState(listSubjects()); + requireReadable(baseline); + let importer; + let loaded; + try { + importer = asModule + ? await import(pathToFileURL(importingModule).href) + : require(importingModule); + loaded = + route === "dynamic-import-from-commonjs" + ? await importer.loaded + : importer.loaded; + } catch (error) { + report.load = { outcome: "failed", error: describeThrown(error) }; + report.phase = "completed"; + return; + } + const note = { + topLevelThis: readText(importer.kind, "topLevelThis"), + location: readText(importer.kind, "location"), + }; + const value = describeLoaded(loaded); + const calls = { reading: null, results: [], traps: trapLog }; + report.importingModule = note; + report.load = { outcome: "loaded", value }; + report.calls = calls; + report.phase = "calling"; + makeCalls(loaded, calls); + const state = compareStates(baseline, readState(baseline.subjects)); + report.state = state; + report.phase = "completed"; +} + +/** What the loaded value is: its type and, for an object, its own keys. */ +function describeLoaded(value) { + const type = typeOf(value); + return { + type, + ownKeys: + type === "object" || type === "function" ? listOwnKeys(value) : null, + }; +} + +/** + * Each own key of `value`, in its own order: its kind, its name (a + * symbol's description), and its enumerability (null where its descriptor + * cannot be read); null where the keys cannot be listed. + */ +function listOwnKeys(value) { + let keys; + try { + keys = ownKeys(value); + } catch { + return null; + } + const listing = []; + for (let index = 0; index < keys.length; index += 1) { + const key = keys[index]; + const symbol = typeof key === "symbol"; + append(listing, { + kind: symbol ? "symbol" : "string", + name: symbol ? describeSymbol(key) : key, + enumerable: readEnumerable(value, key), + }); + } + return listing; +} + +/** Whether `value`'s own property `key` is enumerable; null if unreadable. */ +function readEnumerable(value, key) { + try { + const descriptor = getOwnPropertyDescriptor(value, key); + return descriptor === undefined ? null : descriptor.enumerable === true; + } catch { + return null; + } +} + +/** A symbol's description, or null where it has none. */ +function describeSymbol(symbol) { + try { + const description = apply(symbolDescription, symbol, []); + return typeof description === "string" ? description : null; + } catch { + return null; + } +} + +/** + * Read `defineConfig` from what the load handed back, once, and make each + * of T7.6-6's calls with it, recording each verdict as it is reached. + */ +function makeCalls(loaded, calls) { + let defineConfig; + try { + defineConfig = loaded.defineConfig; + } catch (error) { + calls.reading = { type: null, thrown: describeThrown(error) }; + return; + } + calls.reading = { type: typeOf(defineConfig), thrown: null }; + if (typeof defineConfig !== "function") return; + for (let index = 0; index < CALLS.length; index += 1) { + append(calls.results, makeCall(defineConfig, CALLS[index])); + } +} + +/** One call, as a plain function, and its verdict. */ +function makeCall(defineConfig, call) { + let returned; + try { + returned = apply(defineConfig, undefined, call.args); + } catch (error) { + return { + case: call.label, + outcome: "threw", + returned: null, + thrown: describeThrown(error), + }; + } + return is(returned, call.expected) + ? { + case: call.label, + outcome: "returned-argument", + returned: null, + thrown: null, + } + : { + case: call.label, + outcome: "returned-other", + returned: describeReturned(returned), + thrown: null, + }; +} + +/** A case whose one argument is the value it must return. */ +function identityCall(label, value) { + return { label, args: [value], expected: value }; +} + +/** + * A value a call returned in place of its own: its type and, for a + * primitive, its text, or, for a harness value, its name; never touching a + * Proxy. + */ +function describeReturned(value) { + const type = typeOf(value); + let text; + if (type === "object" || type === "function") { + text = knownName(value); + } else if (type === "number") { + text = is(value, -0) ? "-0" : toText(value); + } else if (type === "bigint") { + text = `${toText(value)}n`; + } else if (type === "string") { + text = + value.length > RETURNED_TEXT_LIMIT + ? `${apply(stringSlice, value, [0, RETURNED_TEXT_LIMIT])}...` + : value; + } else { + text = toText(value); + } + return { type, text }; +} + +/** The name of a harness value `value` is, or null. */ +function knownName(value) { + for (let index = 0; index < KNOWN_VALUES.length; index += 1) { + if (is(value, KNOWN_VALUES[index][0])) return KNOWN_VALUES[index][1]; + } + return null; +} + +/** Whether `value` is one of the two recording Proxies. */ +function isArgumentProxy(value) { + return is(value, firstProxy) || is(value, secondProxy); +} + +/** + * A Proxy over a function whose handler carries every trap, each recording + * its invocation in `trapLog` and then forwarding to `Reflect`. + */ +function recordingProxy(label) { + const handler = { __proto__: null }; + for (let index = 0; index < TRAPS.length; index += 1) { + const trap = TRAPS[index]; + const forward = forwards[trap]; + handler[trap] = (...args) => { + append(trapLog, { proxy: label, trap }); + return apply(forward, undefined, args); + }; + } + return new ProxyConstructor(function xspecProxyTarget() {}, handler); +} + +// T7.6-7(c): the process state (header). + +/** + * The objects the state reads (header), each `{ label, object, observation + * }`: the global object; the built-ins — each string-keyed own data + * property of the global object holding an object or a function, the + * global object and `process` aside, and each such function's own + * `prototype` data property holding one, each object once, under its first + * label; and `process`. + */ +function listSubjects() { + const subjects = [ + { + label: "the global object", + object: globalObject, + observation: "global-object", + }, + ]; + const seen = new MapConstructor(); + apply(mapSet, seen, [globalObject, true]); + apply(mapSet, seen, [process, true]); + const keys = ownKeys(globalObject); + for (let index = 0; index < keys.length; index += 1) { + const key = keys[index]; + if (typeof key !== "string") continue; + const value = dataValue(globalObject, key); + if (!isObjectLike(value) || apply(mapHas, seen, [value])) continue; + apply(mapSet, seen, [value, true]); + append(subjects, { label: key, object: value, observation: "built-ins" }); + if (typeof value !== "function") continue; + const prototype = dataValue(value, "prototype"); + if (!isObjectLike(prototype) || apply(mapHas, seen, [prototype])) continue; + apply(mapSet, seen, [prototype, true]); + append(subjects, { + label: `${key}.prototype`, + object: prototype, + observation: "built-ins", + }); + } + append(subjects, { + label: "process", + object: process, + observation: "process", + }); + return subjects; +} + +/** `object`'s own data property `key`'s value; undefined where it has none. */ +function dataValue(object, key) { + const descriptor = getOwnPropertyDescriptor(object, key); + return descriptor !== undefined && hasOwn(descriptor, "value") + ? descriptor.value + : undefined; +} + +/** Whether `value` is an object or a function. */ +function isObjectLike(value) { + return ( + (typeof value === "object" && value !== null) || typeof value === "function" + ); +} + +/** + * The process state as (c) reads it (header): each subject's own + * properties, extensibility, and prototype, and each other observation's + * reading, every one `{ ok: true, value }`, or `{ ok: false, error }` where + * the read threw. + */ +function readState(subjects) { + const objects = []; + for (let index = 0; index < subjects.length; index += 1) { + const object = subjects[index].object; + append( + objects, + attempt(() => readObject(object)), + ); + } + return { + subjects, + objects, + environment: attempt(readEnvironment), + title: attempt(() => process.title), + workingDirectory: attempt(() => apply(processCwd, process, [])), + exitCode: attempt(() => process.exitCode), + stdoutWrite: attempt(() => process.stdout.write), + stderrWrite: attempt(() => process.stderr.write), + listeners: attempt(readListeners), + pending: attempt(readPending), + }; +} + +/** + * `object`'s own properties, in its own order, each with its descriptor, + * and its extensibility and prototype. + */ +function readObject(object) { + const keys = ownKeys(object); + const order = []; + const properties = new MapConstructor(); + for (let index = 0; index < keys.length; index += 1) { + const descriptor = readDescriptor(object, keys[index]); + if (descriptor === null) continue; + append(order, keys[index]); + apply(mapSet, properties, [keys[index], descriptor]); + } + return { + order, + properties, + extensible: isExtensible(object), + prototype: getPrototypeOf(object), + }; +} + +/** + * `object`'s own property `key`'s descriptor, its members read as its own, + * so no accessor is invoked and nothing inherited consulted; null where it + * has none. + */ +function readDescriptor(object, key) { + const descriptor = getOwnPropertyDescriptor(object, key); + if (descriptor === undefined) return null; + if (hasOwn(descriptor, "get")) { + return { + accessor: true, + value: undefined, + writable: false, + get: descriptor.get, + set: descriptor.set, + enumerable: descriptor.enumerable, + configurable: descriptor.configurable, + }; + } + return { + accessor: false, + value: descriptor.value, + writable: descriptor.writable, + get: undefined, + set: undefined, + enumerable: descriptor.enumerable, + configurable: descriptor.configurable, + }; +} + +/** `process.env`'s variables, by name, each `[name, value]`. */ +function readEnvironment() { + const environment = process.env; + const names = apply(arraySort, objectKeys(environment), []); + const entries = []; + for (let index = 0; index < names.length; index += 1) { + append(entries, [names[index], toText(environment[names[index]])]); + } + return entries; +} + +/** The listeners registered on `process`: each event's `[name, listeners]`. */ +function readListeners() { + const names = apply(eventNames, process, []); + const listing = []; + for (let index = 0; index < names.length; index += 1) { + append(listing, [ + names[index], + apply(rawListeners, process, [names[index]]), + ]); + } + return listing; +} + +/** + * The pending timers and handles the runtime reports (header): its active + * handles, and its pending timers and immediates, counted. + */ +function readPending() { + const resources = apply(getActiveResourcesInfo, process, []); + let timeouts = 0; + let immediates = 0; + for (let index = 0; index < resources.length; index += 1) { + if (resources[index] === "Timeout") timeouts += 1; + else if (resources[index] === "Immediate") immediates += 1; + } + return { + handles: apply(getActiveHandles, process, []), + timeouts, + immediates, + }; +} + +/** `read()`'s value, `{ ok: true, value }`, or what it threw. */ +function attempt(read) { + try { + return { ok: true, value: read(), error: null }; + } catch (error) { + return { ok: false, value: undefined, error: describeThrown(error) }; + } +} + +/** Throw where the baseline could not read a part of the state. */ +function requireReadable(state) { + for (let index = 0; index < state.objects.length; index += 1) { + const reading = state.objects[index]; + if (!reading.ok) { + throw new TypeError( + `the baseline could not read ${state.subjects[index].label}: ` + + describeError(reading.error), + ); + } + } + const readings = [ + ["process.env", state.environment], + ["the process title", state.title], + ["the working directory", state.workingDirectory], + ["process.exitCode", state.exitCode], + ["process.stdout.write", state.stdoutWrite], + ["process.stderr.write", state.stderrWrite], + ["the listeners registered on process", state.listeners], + ["the pending timers and handles", state.pending], + ]; + for (let index = 0; index < readings.length; index += 1) { + if (!readings[index][1].ok) { + throw new TypeError( + `the baseline could not read ${readings[index][0]}: ` + + describeError(readings[index][1].error), + ); + } + } +} + +/** + * How `after` differs from `baseline` (header): `{ subjects, changes, + * omitted }` — the labels of the objects observed, each difference `{ + * observation, subject, detail }`, at most `STATE_CHANGE_LIMIT` of them, and + * how many more were found. + */ +function compareStates(baseline, after) { + const labels = new MapConstructor(); + const subjectLabels = []; + for (let index = 0; index < baseline.subjects.length; index += 1) { + const subject = baseline.subjects[index]; + apply(mapSet, labels, [subject.object, subject.label]); + append(subjectLabels, subject.label); + } + const result = { subjects: subjectLabels, changes: [], omitted: 0 }; + const record = (observation, subject, detail) => { + if (result.changes.length < STATE_CHANGE_LIMIT) { + append(result.changes, { observation, subject, detail }); + } else { + result.omitted += 1; + } + }; + for (let index = 0; index < baseline.subjects.length; index += 1) { + const subject = baseline.subjects[index]; + const reading = after.objects[index]; + if (!reading.ok) { + record( + subject.observation, + subject.label, + `its own properties could not be read afterwards: ` + + describeError(reading.error), + ); + continue; + } + compareObject( + subject, + baseline.objects[index].value, + reading.value, + labels, + record, + ); + } + const compareValue = (before, now, add) => { + if (!is(before, now)) { + add( + `it changed from ${describeValue(before, labels)} to ` + + describeValue(now, labels), + ); + } + }; + const compareWrite = (before, now, add) => { + if (!is(before, now)) { + add( + `it now resolves to ` + + (typeof now === "function" + ? "another function" + : describeValue(now, labels)) + + `, no longer to the one it resolved to before`, + ); + } + }; + const readings = [ + ["environment", "process.env", "environment", compareEnvironment], + ["title", "the process title", "title", compareValue], + [ + "working-directory", + "the working directory", + "workingDirectory", + compareValue, + ], + ["exit-code", "process.exitCode", "exitCode", compareValue], + ["stream-write", "process.stdout.write", "stdoutWrite", compareWrite], + ["stream-write", "process.stderr.write", "stderrWrite", compareWrite], + [ + "listeners", + "the listeners registered on process", + "listeners", + compareListeners, + ], + [ + "timers-and-handles", + "the pending timers and handles", + "pending", + comparePending, + ], + ]; + for (let index = 0; index < readings.length; index += 1) { + const reading = readings[index]; + const observation = reading[0]; + const subject = reading[1]; + const part = reading[2]; + const compare = reading[3]; + const now = after[part]; + const add = (detail) => { + record(observation, subject, detail); + }; + if (!now.ok) { + add(`it could not be read afterwards: ${describeError(now.error)}`); + } else { + compare(baseline[part].value, now.value, add); + } + } + return result; +} + +/** + * Each difference in one subject's own properties, its extensibility, and + * its prototype, recorded under its observation. + */ +function compareObject(subject, before, after, labels, record) { + const label = subject.label; + const observation = subject.observation; + for (let index = 0; index < before.order.length; index += 1) { + const key = before.order[index]; + const was = apply(mapGet, before.properties, [key]); + if (!apply(mapHas, after.properties, [key])) { + record( + observation, + label, + `its own property ${describeKey(key)} was removed: it was ` + + describeDescriptor(was, labels), + ); + continue; + } + const now = apply(mapGet, after.properties, [key]); + if (!sameDescriptor(was, now)) { + record( + observation, + label, + `its own property ${describeKey(key)} changed from ` + + `${describeDescriptor(was, labels)} to ` + + describeDescriptor(now, labels), + ); + } + } + for (let index = 0; index < after.order.length; index += 1) { + const key = after.order[index]; + if (!apply(mapHas, before.properties, [key])) { + record( + observation, + label, + `an own property ${describeKey(key)} was added: ` + + describeDescriptor(apply(mapGet, after.properties, [key]), labels), + ); + } + } + if (before.extensible !== after.extensible) { + record( + "extensibility", + label, + before.extensible + ? "it was extensible and no longer is" + : "it was not extensible and now is", + ); + } + if (!is(before.prototype, after.prototype)) { + record( + "prototype", + label, + `its prototype changed from ${describeValue(before.prototype, labels)} ` + + `to ${describeValue(after.prototype, labels)}`, + ); + } +} + +/** Whether two descriptors are alike, each value compared by `Object.is`. */ +function sameDescriptor(left, right) { + return ( + left.accessor === right.accessor && + is(left.value, right.value) && + is(left.get, right.get) && + is(left.set, right.set) && + left.writable === right.writable && + left.enumerable === right.enumerable && + left.configurable === right.configurable + ); +} + +/** Each variable of `process.env` set, removed, or changed. */ +function compareEnvironment(before, after, add) { + const was = new MapConstructor(); + const now = new MapConstructor(); + for (let index = 0; index < before.length; index += 1) { + apply(mapSet, was, [before[index][0], before[index][1]]); + } + for (let index = 0; index < after.length; index += 1) { + apply(mapSet, now, [after[index][0], after[index][1]]); + } + for (let index = 0; index < before.length; index += 1) { + const name = before[index][0]; + const value = before[index][1]; + if (!apply(mapHas, now, [name])) { + add( + `its variable ${stringify(name)} was removed: it held ` + + describePrimitive(value, "string"), + ); + } else if (apply(mapGet, now, [name]) !== value) { + add( + `its variable ${stringify(name)} changed from ` + + `${describePrimitive(value, "string")} to ` + + describePrimitive(apply(mapGet, now, [name]), "string"), + ); + } + } + for (let index = 0; index < after.length; index += 1) { + const name = after[index][0]; + const value = after[index][1]; + if (!apply(mapHas, was, [name])) { + add( + `a variable ${stringify(name)} was set to ` + + describePrimitive(value, "string"), + ); + } + } +} + +/** Each event whose listeners on `process` differ, by identity and order. */ +function compareListeners(before, after, add) { + const was = new MapConstructor(); + const now = new MapConstructor(); + for (let index = 0; index < before.length; index += 1) { + apply(mapSet, was, [before[index][0], before[index][1]]); + } + for (let index = 0; index < after.length; index += 1) { + apply(mapSet, now, [after[index][0], after[index][1]]); + } + const names = []; + for (let index = 0; index < before.length; index += 1) { + append(names, before[index][0]); + } + for (let index = 0; index < after.length; index += 1) { + if (!apply(mapHas, was, [after[index][0]])) append(names, after[index][0]); + } + for (let index = 0; index < names.length; index += 1) { + const name = names[index]; + const listenersBefore = apply(mapHas, was, [name]) + ? apply(mapGet, was, [name]) + : []; + const listenersAfter = apply(mapHas, now, [name]) + ? apply(mapGet, now, [name]) + : []; + let alike = listenersBefore.length === listenersAfter.length; + for (let at = 0; alike && at < listenersBefore.length; at += 1) { + alike = is(listenersBefore[at], listenersAfter[at]); + } + if (!alike) { + add( + `the event ${describeKey(name)} had ` + + `${toText(listenersBefore.length)} listener(s) and has ` + + `${toText(listenersAfter.length)}` + + (listenersBefore.length === listenersAfter.length + ? ", not the same ones in the same order" + : ""), + ); + } + } +} + +/** Each change in the active handles and the pending timers and immediates. */ +function comparePending(before, after, add) { + if (before.timeouts !== after.timeouts) { + add( + `${toText(before.timeouts)} timer(s) were pending (Timeout), and ` + + `${toText(after.timeouts)} are`, + ); + } + if (before.immediates !== after.immediates) { + add( + `${toText(before.immediates)} immediate(s) were pending (Immediate), ` + + `and ${toText(after.immediates)} are`, + ); + } + const was = new MapConstructor(); + const now = new MapConstructor(); + for (let index = 0; index < before.handles.length; index += 1) { + apply(mapSet, was, [before.handles[index], true]); + } + for (let index = 0; index < after.handles.length; index += 1) { + apply(mapSet, now, [after.handles[index], true]); + } + for (let index = 0; index < after.handles.length; index += 1) { + if (!apply(mapHas, was, [after.handles[index]])) { + add( + `a handle (${describeHandle(after.handles[index])}) is active that ` + + `was not`, + ); + } + } + for (let index = 0; index < before.handles.length; index += 1) { + if (!apply(mapHas, now, [before.handles[index]])) { + add( + `a handle (${describeHandle(before.handles[index])}) is no longer ` + + `active`, + ); + } + } +} + +/** An active handle, by its constructor's name, read from descriptors. */ +function describeHandle(handle) { + try { + const prototype = isObjectLike(handle) ? getPrototypeOf(handle) : null; + const constructor = isObjectLike(prototype) + ? dataValue(prototype, "constructor") + : undefined; + const name = + typeof constructor === "function" + ? dataValue(constructor, "name") + : undefined; + return typeof name === "string" && name !== "" ? name : typeOf(handle); + } catch { + return typeOf(handle); + } +} + +/** A property key, in words: a string as JSON, a symbol by its description. */ +function describeKey(key) { + return typeof key === "symbol" + ? `Symbol(${describeSymbol(key) ?? ""})` + : stringify(key); +} + +/** A descriptor, in words: its kind, attributes, and value or functions. */ +function describeDescriptor(descriptor, labels) { + const attributes = + `${descriptor.enumerable ? "enumerable" : "not enumerable"}, ` + + (descriptor.configurable ? "configurable" : "not configurable"); + return descriptor.accessor + ? `an accessor property (${attributes}) whose getter is ` + + `${describeValue(descriptor.get, labels)} and setter ` + + describeValue(descriptor.set, labels) + : `a data property (${descriptor.writable ? "writable" : "not writable"}, ` + + `${attributes}) holding ${describeValue(descriptor.value, labels)}`; +} + +/** + * A value, in words, without running anything of the package's: an observed + * object by its label, any other object or function by its type, a + * primitive by its text. + */ +function describeValue(value, labels) { + const type = typeOf(value); + if (type === "object" || type === "function") { + if (apply(mapHas, labels, [value])) return apply(mapGet, labels, [value]); + return type === "function" ? "a function" : "an object"; + } + return describePrimitive(value, type); +} + +/** A primitive of type `type`, in words. */ +function describePrimitive(value, type) { + switch (type) { + case "number": + return is(value, -0) ? "-0" : toText(value); + case "bigint": + return `${toText(value)}n`; + case "string": + return stringify( + value.length > DESCRIBED_TEXT_LIMIT + ? `${apply(stringSlice, value, [0, DESCRIBED_TEXT_LIMIT])}...` + : value, + ); + case "symbol": + return `Symbol(${describeSymbol(value) ?? ""})`; + default: + return toText(value); + } +} + +/** A thrown value's description (`describeThrown`), in words. */ +function describeError(thrown) { + const head = thrown.name ?? `a value of type ${thrown.type}`; + return thrown.message === null + ? head + : `${head}: ${describePrimitive(thrown.message, "string")}`; +} + +/** `typeof value`, null reading as "null". */ +function typeOf(value) { + return value === null ? "null" : typeof value; +} + +/** + * A thrown value's type, and its name, code, message, and stack; a + * recording Proxy by its type alone, never read. + */ +function describeThrown(thrown) { + const type = typeOf(thrown); + const readable = + (type === "object" || type === "function") && !isArgumentProxy(thrown); + let message = null; + if (readable) { + message = readText(thrown, "message"); + } else if (type === "string") { + message = thrown; + } + return { + type, + name: readable ? readText(thrown, "name") : null, + code: readable ? readText(thrown, "code") : null, + message, + stack: readable ? readText(thrown, "stack") : null, + }; +} + +/** A delivered warning, read as a thrown value is, and its detail. */ +function describeWarning(warning) { + const described = describeThrown(warning); + const readable = + (described.type === "object" || described.type === "function") && + !isArgumentProxy(warning); + return { + type: described.type, + name: described.name, + code: described.code, + message: described.message, + detail: readable ? readText(warning, "detail") : null, + stack: described.stack, + }; +} + +/** `object[key]` where it is a string; null otherwise, or where it throws. */ +function readText(object, key) { + try { + const value = object[key]; + return typeof value === "string" ? value : null; + } catch { + return null; + } +} + +/** Append `value` to `array`, through no method the package can replace. */ +function append(array, value) { + defineProperty(array, array.length, { + value, + writable: true, + enumerable: true, + configurable: true, + }); +} + +/** Write the report whole: to a sibling file, renamed over it. */ +function writeReport() { + try { + writeFileSync(partialPath, stringify(report)); + renameSync(partialPath, reportPath); + } catch { + // The report's absence is then all the driver can be told (header). + } +} diff --git a/test/helpers/module-channel-node.ts b/test/helpers/module-channel-node.ts new file mode 100644 index 00000000..1dfd4a6f --- /dev/null +++ b/test/helpers/module-channel-node.ts @@ -0,0 +1,3505 @@ +// The module channel's Node.js release driver (TEST-SPEC H-2, T7.6-6's run +// conditions, T7.6-7, §7.6 Pairing, H-1, S-3, E-1, S-10; SPEC 7.6 Reach, +// Runtime). Harness machinery only: this module never imports product code +// and never loads a file of a package in its own process. It loads the +// `defineConfig` module, placed in a staging of the module channel +// (helpers/module-channel.ts), on a Node.js release E-1 provisions +// (helpers/node-releases.ts) along one of Node.js's routes, and reads back +// what that process observed. +// +// TEST-SPEC T7.6-6: on each release, run with no option, no environment +// variable (`NODE_OPTIONS` and `NODE_PATH` among them), no user condition, +// and no loader or customization hook, the module is loaded along each of +// Node.js's routes from a harness-written importing module in the importing +// file's place — a static `import` from an ES module (`.mjs`), a dynamic +// `import()` from an ES module and from a CommonJS module (`.cjs`), and +// `require` from a CommonJS module. T7.6-7: each run is given a fresh `HOME` +// and `TMPDIR`; the importing module reports its observations outside both +// streams and every compared path; harness-written code registers a +// `warning` listener on `process` and only then loads the importing module, +// by its physical path. +// +// - The routes (`MODULE_ROUTES`): each route's importing module is a file +// whose kind its extension fixes — `.mjs` an ES module, `.cjs` a CommonJS +// one, whatever any `package.json` says — named for its route +// (`importingModuleName`) and written into the importing file's place +// (`importingModuleText`): the directory the caller names, the +// placement's holding directory unless it names another. It holds the +// route's load of a specifier spelling exactly N, the placement's name, +// and nothing else of the package's, and hands back what it loaded — the +// namespace (static `import`), the namespace awaited at its top level +// (dynamic `import()` from an ES module), the promise `import()` returns +// (from a CommonJS module), or the `require` result — beside a note of +// its own kind, its top-level `this` (`undefined` in an ES module, its +// `module.exports` in a CommonJS one), and its location (`import.meta.url`, +// `__filename`). The four can stand side by side in one directory, each +// written once and found byte-equal by a later run; any other occupant of +// such a path is a `HarnessStagingError`. +// - The bootstrap (helpers/module-channel-bootstrap.cjs, harness code that +// imports none): a CommonJS file, which Node.js runs as one without +// reading any `package.json`, copied byte for byte into the run's own +// directory and run there as `<release>/bin/node <bootstrap> +// <importing module> <report> <route>` — no option before the script — +// through the subprocess driver (`runProduct`) under the run's own hang +// guard (`MODULE_RUN_TIMEOUT_MS`; S-3). In order, it captures the +// built-ins it calls once loading has begun, reads the run's conditions, +// registers a `warning` listener on `process` (recording each warning the +// runtime delivers, in order) and an `exit` listener, and only then loads +// the importing module by its physical path: `import()` of its file URL +// for an `.mjs`, `require` for a `.cjs`. It never awaits the loaded value +// itself, so a `then` export is never called by the harness. +// - The run's own directory (`PreparedModuleRun`): a fresh directory under +// the OS temporary directory, at its physical path, outside the staging, +// holding the bootstrap, the report, and three fresh, empty directories — +// the run's `HOME`, its `TMPDIR`, and its working directory, `work`, which +// is never the importing module's directory, so that T7.6-7(e) can stage +// a FIFO named `xspec.config.ts` in each of the three places it names, +// and which T7.6-7(b) compares before and after the run with the staging, +// `HOME`, and `TMPDIR` (a run asked to observe its effects, below). The +// report lies outside all four. The directory is removed when the run is +// disposed of; a caller staging more for a run does so between +// `prepareModuleRun` and `PreparedModuleRun.launch`, then disposes of it. +// - The environment (`moduleRunEnvironment`): explicit and minimal, never +// the ambient one filtered — `HOME` and `TMPDIR`, the run's fresh +// directories, and `PATH`, the harness's own where it has one (kept as +// every process environment carries it; Node.js resolves and loads no +// module through it). Nothing else is passed: no `NODE_OPTIONS` (no +// option, condition, loader, or hook through it), no `NODE_PATH` (no +// global module folder beyond those H-1 verifies empty), and none of the +// other variables bearing on module loading or the run's output +// (`NODE_PRESERVE_SYMLINKS`, `NODE_NO_WARNINGS`, `NODE_PENDING_DEPRECATION`, +// `NODE_REDIRECT_WARNINGS`, `NODE_COMPILE_CACHE`, `NODE_V8_COVERAGE`, +// `NODE_DEBUG`, `FORCE_COLOR`, among them). The run is spawned with the +// subprocess driver's environment overridden to exactly that +// (`productEnvironment` with every other variable removed), and the +// bootstrap's own reading of its environment must equal it. +// - Before each run (`launch`): Reach for the importing module on the +// finished staging (`ModuleStaging.verifyReach`: physical naming, the +// placement in place, nothing nearer, no self-reference, well-formed +// manifests, and, where declared, the project kind and nothing else +// installed), and H-1 under the run's exact environment, working +// directory, and executable (`ModuleStaging.verifyIsolation`) — each a +// `HarnessStagingError` when unmet. +// - The report (`decodeModuleRunReport`): one JSON document the bootstrap +// writes to a path the driver names, outside both streams — once the load +// and T7.6-6's calls have completed, or the load has failed, and again as +// the process exits, each time whole (a sibling file renamed over it). +// Its members are read exactly: the protocol, the arguments as the run +// saw them, the release's version, executable, and options, the process +// identifier, the environment, the working directory, the phase reached +// (`loading`, `calling`, `completed`), the importing module's note of its +// kind and location, the load's outcome (the loaded value's type and own +// keys — each key's kind, name, and enumerability — or the error the load +// threw: its type, name, code, message, and stack), T7.6-6's calls +// (below), T7.6-7(c)'s comparison of the process state (below; present +// exactly where the module loaded and the phase completed), a failure of +// the bootstrap's own, each warning delivered (its type, name, code, +// message, detail, and stack), and the exit code the `exit` listener saw. +// Anything else — absent members, an extra one, a value of another kind, +// members inconsistent with the phase, calls out of `CALL_CASES`' order, +// an observation of its own, bytes that are no UTF-8 JSON — is a +// malformed report: H-3's rule, failing loudly, never a pass. +// - The run's conditions, checked on every report that decodes (S-10 pins +// them on stand-ins): the arguments round-trip exactly as passed; the +// release in effect is the one provisioned (`process.version` and +// `process.execPath`, the executable's physical path); the run carries no +// option (`process.execArgv` empty); its environment is exactly the one +// set; its working directory is the run's; where the module loaded, the +// importing module ran as its route's kind, from its physical path; and, +// where the state was compared, it observed the global object, `process`, +// and ECMAScript's global constructors and namespace objects with each +// constructor's prototype (`REQUIRED_STATE_SUBJECTS`), so that no +// comparison passes over an empty set. A breach is a harness error +// (H-11): the harness sets every one of them before anything of the +// package loads. +// - Outcomes (`ModuleRunOutcome`): `loaded`, the route's load handed back a +// value; `load-failed`, it threw (a stub package's missing entry, an +// ES-module-only package along `require` on a release before 22.12.0); +// `incomplete`, the process exited before the load completed or failed +// (`process.exit` while loading, an uncaught exception, an unsettled +// top-level `await`) or during T7.6-6's calls, or the bootstrap's own +// flow failed; `no-report`, +// the process left no report (killed by a signal, or exiting without its +// `exit` listeners while loading); `malformed-report`. The run's exit +// code, signal, and both streams are reported beside the outcome. +// - Attribution (`assertModuleLoaded`): a run that loads nothing, crashes, +// or ends otherwise than on its own with exit code 0 is reported as such — +// for a test, a diagnosed failure (`HarnessAssertionError`, H-8), the +// module channel counting as part of the product, as S-7's stub package +// requires; for a stand-in the harness expected to load, a harness error +// (a plain `Error`), never a verdict. The run's hang-guard kill +// (`ProductRunTimeoutError`) propagates unchanged — a hang ends its test +// (S-3) — and so does every other rejection of the run's spawn, which +// for a release E-1 provisioned is a harness error. +// - T7.6-6's observations, made inside the run by the bootstrap once the +// load has handed back a value (its header), and read here as problems +// in words, each led by the run's description, none thrown, so that a +// test may run every arm and fail once naming each: +// (a) `exportsProblems`: the route's listing from the loaded value's own +// keys — an `import` namespace's string-keyed properties exactly +// `defineConfig` (a CommonJS-only entry's namespace, carrying +// `default`, fails), a `require` result's enumerable properties, +// string- and symbol-keyed alike, exactly `defineConfig` (an +// enumerable `__esModule` fails); +// (b) `identityProblems`: `defineConfig`, read once from the loaded +// value, a function, and each identity case of `CALL_CASES` — every +// value T7.6-6 names, no argument, a further argument — returning +// what it must, compared by `Object.is` inside the run; +// (c) `examinationProblems`: the call with two recording Proxies over +// functions returning the first, no trap of either invoked through +// the run's end, and the call with a frozen object returning it +// without a throw. +// - Pairing (§7.6; `pairingProblem`): each absence a runtime arm asserts +// counts only where the same run loaded the module and saw `defineConfig` +// return its argument — here, in every one of T7.6-6's calls, the +// conservative reading — so a missing or stub package fails every arm. +// - The output oracle (T7.6-7(a); `outputProblems`, `runtimeOutputProblems`): +// standard output empty, and standard error, byte for byte, exactly the +// release's printed forms of the warnings the bootstrap's listener +// captured, in order (`renderWarnings`): each `(node:<pid>) `, its +// bracketed code and a space where it carries a non-empty one, its type +// and message as the release joins them (`<type>: <message>`, either +// alone where the other is empty), a line feed and its detail where it +// carries one, the first warning followed by a line feed and the hint +// line the release appends to it, and each ended by a line feed; and no +// captured warning's stack beginning in the package's files, its first +// frame (`warningFirstFrame`: the first line after the stack's head that +// is a frame) naming a path under the placement or its copy, by path or +// file URL (`packageFrame`). A warning the oracle cannot render — no +// object whose name and message are strings, which the runtime's own +// warnings always are — fails it. Each release's printed form is learned +// from the release itself (`learnWarningForm`, once per release in a +// process): a calibration script (helpers/module-channel-warning- +// calibration.cjs, harness code beside the bootstrap) run on the release +// as a module run is — copied into a fresh directory of its own, through +// the subprocess driver under the run's guard, with a fresh `HOME` and +// `TMPDIR`, the harness's `PATH`, and no option — emits known warnings +// through `process.emitWarning` in three runs, a warning of a type of +// its own first, a `DeprecationWarning` first, and an +// `ExperimentalWarning` first, which between them carry and lack a code +// and a detail and span lines in their messages and details. The hint +// lines are read off the release's standard error after the first +// warning's form (the release appends one hint to a first deprecation +// and another to any other first warning), and the whole of each run's +// standard error must then render exactly from its captured warnings, so +// a release printing a warning in any other form — the separators and +// the line structure above included — fails the calibration as a harness +// error naming the release, never a verdict. +// - T7.6-7(c), process state (`stateProblems`): observed in every run, by +// the bootstrap (its header) — the state read once to settle what the +// runtime materializes on a first read, then as the baseline, both after +// the `warning` and `exit` listeners are registered and before the +// importing module's own loading begins, and again once T7.6-6's calls +// are made, compared in the run, each difference recorded under the +// observation that found it (`STATE_OBSERVATIONS`): the global object's +// own properties with their descriptors, read without invoking accessors +// (`global-object`); the own properties of the built-ins — every +// string-keyed own data property of the global object holding an object +// or a function, ECMAScript's constructors and namespace objects and the +// runtime's own among them, a superset of TEST-SPEC's "global built-in +// constructors and namespace objects", and each such function's own +// prototype (`built-ins`); the extensibility and the prototype of each of +// them, the global object and `process` included (`extensibility`, +// `prototype`); `process`'s own properties with their descriptors +// (`process`); `process.env` (`environment`); the process title +// (`title`); the working directory (`working-directory`); +// `process.exitCode` (`exit-code`); the `write` each of `process.stdout` +// and `process.stderr` resolves to (`stream-write`); the listeners +// registered on `process` (`listeners`); and the runtime's active handles +// and pending timers and immediates — never its pending requests, which +// its own loading leaves in flight (`timers-and-handles`). None may +// differ. No probe found the runtime's own loading changing any of them, +// on any of E-1's releases and routes, its own warnings printed included +// (S-10 pins it on stand-ins). +// - T7.6-7(b) and (e), writes and FIFOs (`writeProblems`, `fifoProblems`): +// observed in a run asked to (`ModuleRunRequest.effects`). Before it is +// launched, a FIFO named `xspec.config.ts` is staged in the run's working +// directory, in the importing module's directory (in the staging, staged +// once and found there by a later run), and in its `HOME` +// (helpers/lock-staging.ts `stageFifo`: `mkfifo` beside, then a hard link, +// read back as a FIFO of its mode, never opened); then each of the four +// places — the staging, the placement included, the working directory, +// `HOME`, and `TMPDIR` — is snapshotted (`snapshotPlace`): every entry +// under it and the place itself, by its kind — a plain file with its +// bytes, a directory, a symbolic link with its target, never followed, +// and a FIFO, a socket, or a device by its kind alone, never opened (S-3) +// — a read the entry's mode refuses recorded as such. Once the run ends, +// each place is snapshotted again and compared entry by entry +// (`comparePlaceSnapshots`: an entry created, removed, or modified — its +// kind, a plain file's bytes, a link's target), and each FIFO's path is +// read back, still a FIFO or not. A dedicated walk, not +// helpers/snapshot.ts's, names every kind (a FIFO turned into a socket is +// a change there) and records a refused read instead of throwing, and no +// lock path is left out: no product command runs here. That a FIFO stayed +// unopened is observed by the run's promptness — a reader opening a FIFO +// no writer holds blocks, so a run that opens one ends at its guard +// (S-3), its kill propagating unchanged — as the rest of the harness +// observes it (helpers/lock-staging.ts); no test observes a system call. +// Such a run compares the whole staging: while it is launched, the +// driver refuses to write into that staging for another run (an +// importing module, a FIFO) as a usage error, so prepare every run of a +// staging before launching one that observes its effects, or run them +// one after another. +// - T7.6-7(d), network: every run is network-denied by the environment it +// inherits, as every product invocation is — CI's Linux jobs run inside +// `.github/scripts/run-without-network.sh` (E-1) — so an attempted access +// fails rather than reaching a network; nothing here observes it. +// - Each of T7.6-7's absences counts only under the pairing above: +// `stateProblems`, `writeProblems`, and `fifoProblems` each report +// `pairingProblem` first, as `outputProblems` does. +// - Every examination and write here is a harness step under its own guard +// (helpers/step-guards.ts); the run itself is a product invocation under +// its own (S-3). E-1 exercises the releases on the Linux leg alone, and +// this driver serves POSIX paths alone. + +import { Buffer } from "node:buffer"; +import type { Stats } from "node:fs"; +import * as fsp from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { bytesEqual, describeByteDifference, fail } from "./assertions.js"; +import { stageFifo } from "./lock-staging.js"; +import type { + CommonJsTypeMember, + ModuleStaging, + Placement, + ProjectKind, + ReachStaging, +} from "./module-channel.js"; +import { moduleNameGrammarProblem } from "./module-channel.js"; +import type { NodeRelease } from "./node-releases.js"; +import type { StagingMode } from "./permissions.js"; +import { HarnessStagingError } from "./permissions.js"; +import { displaySnapshotPath } from "./snapshot.js"; +import { guardStep, guardSyncStep } from "./step-guards.js"; +import type { ProductBinding, RunGuards, RunResult } from "./subprocess.js"; +import { + DEFAULT_TIMEOUT_MS, + productEnvironment, + runProduct, +} from "./subprocess.js"; + +/** The staging mode every refusal of this module names. */ +const MODE: StagingMode = "module-channel"; + +/** The prefix of each run's own directory under the OS temporary one. */ +export const MODULE_RUN_PREFIX = "xspec-module-run-"; + +/** The protocol the bootstrap's report names, which the decoder requires. */ +export const MODULE_RUN_PROTOCOL = "xspec-module-run/3"; + +/** The name of each of T7.6-7(e)'s FIFOs (module header). */ +export const RUN_FIFO_NAME = "xspec.config.ts"; + +/** The prefix of each warning calibration's directory (module header). */ +export const WARNING_CALIBRATION_PREFIX = "xspec-warning-calibration-"; + +/** The protocol the calibration's report names, which its decoder requires. */ +export const WARNING_CALIBRATION_PROTOCOL = "xspec-warning-calibration/1"; + +/** + * Each run's own hang guard (TEST-SPEC S-3): the subprocess driver's + * default, sized for invocations whose call sites size none of their own. + * A run starts a release and loads one small package: about 40 ms + * unloaded here, staging checks included (AGENTS.md), so the guard is far + * more than ten times the run, loaded runs included, and a run blocking on + * a FIFO or kept alive by a timer ends at it, ending its test. + */ +export const MODULE_RUN_TIMEOUT_MS = DEFAULT_TIMEOUT_MS; + +/** The bootstrap, harness code beside this module (module header). */ +const BOOTSTRAP_SOURCE = fileURLToPath( + new URL("./module-channel-bootstrap.cjs", import.meta.url), +); + +/** The warning calibration, harness code beside this module (module header). */ +const CALIBRATION_SOURCE = fileURLToPath( + new URL("./module-channel-warning-calibration.cjs", import.meta.url), +); + +/** The names in a run's own directory (module header). */ +const CALIBRATION_NAME = "calibration.cjs"; +const BOOTSTRAP_NAME = "bootstrap.cjs"; +const REPORT_NAME = "report.json"; +const HOME_NAME = "home"; +const TMPDIR_NAME = "tmp"; +const WORK_NAME = "work"; + +const LF = String.fromCodePoint(0x0a); + +/** `/`, joining the names of a snapshot key's path (module header). */ +const SLASH_BYTES = Buffer.from([0x2f]); + +/** How much of a stream a diagnosis quotes. */ +const QUOTED_STREAM_LIMIT = 800; + +// --------------------------------------------------------------------------- +// Routes and importing modules +// --------------------------------------------------------------------------- + +/** + * Node.js's routes (TEST-SPEC T7.6-6; SPEC 7.6 Reach): a static `import` + * from an ES module, a dynamic `import()` from an ES module and from a + * CommonJS module, and `require` from a CommonJS module. + */ +export type ModuleRoute = + | "static-import" + | "dynamic-import-from-module" + | "dynamic-import-from-commonjs" + | "require"; + +/** Every route, in TEST-SPEC T7.6-6's order. */ +export const MODULE_ROUTES: readonly ModuleRoute[] = Object.freeze([ + "static-import", + "dynamic-import-from-module", + "dynamic-import-from-commonjs", + "require", +]); + +/** An importing module's kind, which its extension fixes. */ +export type ImportingModuleKind = "module" | "commonjs"; + +interface RouteShape { + readonly kind: ImportingModuleKind; + readonly extension: ".mjs" | ".cjs"; + readonly description: string; +} + +const ROUTE_SHAPES: Readonly<Record<ModuleRoute, RouteShape>> = { + "static-import": { + kind: "module", + extension: ".mjs", + description: "a static import from an ES module (.mjs)", + }, + "dynamic-import-from-module": { + kind: "module", + extension: ".mjs", + description: "a dynamic import() from an ES module (.mjs)", + }, + "dynamic-import-from-commonjs": { + kind: "commonjs", + extension: ".cjs", + description: "a dynamic import() from a CommonJS module (.cjs)", + }, + require: { + kind: "commonjs", + extension: ".cjs", + description: "require from a CommonJS module (.cjs)", + }, +}; + +/** The kind of `route`'s importing module. */ +export function importingModuleKind(route: ModuleRoute): ImportingModuleKind { + return ROUTE_SHAPES[route].kind; +} + +/** `route`, in words, for diagnoses. */ +export function describeRoute(route: ModuleRoute): string { + return ROUTE_SHAPES[route].description; +} + +/** The file name of `route`'s importing module (module header). */ +export function importingModuleName(route: ModuleRoute): string { + return `importing-module-${route}${ROUTE_SHAPES[route].extension}`; +} + +/** + * The text of `route`'s importing module loading `specifier` (module + * header): the route's load of a specifier spelling exactly `specifier`, a + * name of 7.6's grammar (spelled as a JSON string literal, which for such a + * name holds no escape), handed back as `loaded`, beside its kind note, + * `kind`. A specifier outside the grammar is a usage error. + */ +export function importingModuleText( + route: ModuleRoute, + specifier: string, +): string { + const problem = moduleNameGrammarProblem(specifier); + if (problem !== null) { + throw new Error( + `module channel: the specifier ${JSON.stringify(specifier)} ` + + `${problem}; an importing module names a placement by N, a name of ` + + `7.6's grammar`, + ); + } + const literal = JSON.stringify(specifier); + const header = + `// Harness-written importing module (xspec test harness, TEST-SPEC ` + + `T7.6-6): ${describeRoute(route)}.`; + const kindNote = (location: string): string[] => [ + " topLevelThis: typeof this,", + ` location: ${location},`, + ]; + let lines: string[]; + switch (route) { + case "static-import": + lines = [ + header, + `import * as loaded from ${literal};`, + "", + "export { loaded };", + "export const kind = {", + ...kindNote("import.meta.url"), + "};", + ]; + break; + case "dynamic-import-from-module": + lines = [ + header, + "export const kind = {", + ...kindNote("import.meta.url"), + "};", + `export const loaded = await import(${literal});`, + ]; + break; + case "dynamic-import-from-commonjs": + lines = [ + header, + "exports.kind = {", + ...kindNote("__filename"), + "};", + `exports.loaded = import(${literal});`, + ]; + break; + case "require": + lines = [ + header, + "exports.kind = {", + ...kindNote("__filename"), + "};", + `exports.loaded = require(${literal});`, + ]; + break; + } + return `${lines.join(LF)}${LF}`; +} + +// --------------------------------------------------------------------------- +// The environment +// --------------------------------------------------------------------------- + +/** + * A run's environment (module header): `HOME` and `TMPDIR` the run's fresh + * directories, and `PATH` the harness's own (`ambient`'s, `process.env` + * unless given) where it has a non-empty one; nothing else. + */ +export function moduleRunEnvironment( + home: string, + tmp: string, + ambient: Readonly<Record<string, string | undefined>> = process.env, +): Readonly<Record<string, string>> { + const environment: Record<string, string> = { HOME: home, TMPDIR: tmp }; + const searchPath = ambient["PATH"]; + if (searchPath !== undefined && searchPath !== "") { + environment["PATH"] = searchPath; + } + return Object.freeze(environment); +} + +/** The binding a release runs through (module header). */ +function releaseBinding(release: NodeRelease): ProductBinding { + return { + label: + `the Node.js release ${release.version} (${release.executable}), ` + + `loading the defineConfig module through the module channel`, + command: release.executable, + requiredFiles: [release.executable], + }; +} + +/** + * The subprocess driver's overrides giving a run of `binding` exactly + * `wanted`: every variable its environment would otherwise carry removed, + * then `wanted`'s set. + */ +function exactEnvironmentOverrides( + binding: ProductBinding, + wanted: Readonly<Record<string, string>>, +): Readonly<Record<string, string | undefined>> { + const entries: [string, string | undefined][] = Object.keys( + productEnvironment(binding), + ).map((name) => [name, undefined]); + for (const [name, value] of Object.entries(wanted)) { + entries.push([name, value]); + } + return Object.fromEntries(entries); +} + +/** Whether two environments hold the same variables, each the same value. */ +function sameEnvironment( + left: Readonly<Record<string, string>>, + right: Readonly<Record<string, string>>, +): boolean { + const leftNames = Object.keys(left).sort(); + const rightNames = Object.keys(right).sort(); + return ( + leftNames.length === rightNames.length && + leftNames.every( + (name, index) => name === rightNames[index] && left[name] === right[name], + ) + ); +} + +/** An environment, for a diagnosis: its variables, sorted. */ +function describeEnvironment( + environment: Readonly<Record<string, string>>, +): string { + return JSON.stringify( + Object.fromEntries( + Object.keys(environment) + .sort() + .map((name) => [name, environment[name]]), + ), + ); +} + +// --------------------------------------------------------------------------- +// The report +// --------------------------------------------------------------------------- + +/** A thrown value as the bootstrap reads it: its type, then strings where it has them. */ +export interface ThrownDescription { + /** `typeof` the value, `null` reading as "null". */ + readonly type: string; + readonly name: string | null; + readonly code: string | null; + readonly message: string | null; + readonly stack: string | null; +} + +/** A warning the runtime delivered to the bootstrap's `warning` listener. */ +export interface CapturedWarning extends ThrownDescription { + readonly detail: string | null; +} + +/** One own key of a loaded value, as the bootstrap lists it. */ +export interface OwnKey { + readonly kind: "string" | "symbol"; + /** The key itself, or a symbol's description (null where it has none). */ + readonly name: string | null; + /** Whether its descriptor is enumerable; null where none could be read. */ + readonly enumerable: boolean | null; +} + +/** What the route's load handed back, or what it threw. */ +export type LoadObservation = + | { + readonly outcome: "loaded"; + readonly value: { + /** `typeof` the loaded value, `null` reading as "null". */ + readonly type: string; + /** + * Its own keys in their own order, where it is an object or a + * function whose keys could be listed; null otherwise. + */ + readonly ownKeys: readonly OwnKey[] | null; + }; + } + | { readonly outcome: "failed"; readonly error: ThrownDescription }; + +/** + * T7.6-6's calls, in the order the bootstrap makes them (its header): an + * object, an array, a function, a symbol, `null`, `undefined` passed + * explicitly, a string, a boolean, a bigint, `0`, `-0`, and `NaN`, each + * returning itself; no argument, returning `undefined`; a further + * argument, returning the first; two recording Proxies, returning the + * first; and a frozen object, returning itself. + */ +export const CALL_CASES = Object.freeze([ + "object", + "array", + "function", + "symbol", + "null", + "undefined", + "string", + "boolean", + "bigint", + "zero", + "negative-zero", + "nan", + "no-argument", + "further-arguments", + "proxies", + "frozen", +] as const); + +/** One of T7.6-6's calls. */ +export type CallCase = (typeof CALL_CASES)[number]; + +/** T7.6-6(b)'s calls: each but (c)'s Proxies and frozen object. */ +export const IDENTITY_CASES: readonly CallCase[] = Object.freeze( + CALL_CASES.filter((name) => name !== "proxies" && name !== "frozen"), +); + +/** Every trap a Proxy handler can carry, each recorded by the bootstrap's. */ +export const PROXY_TRAPS = Object.freeze([ + "apply", + "construct", + "defineProperty", + "deleteProperty", + "get", + "getOwnPropertyDescriptor", + "getPrototypeOf", + "has", + "isExtensible", + "ownKeys", + "preventExtensions", + "set", + "setPrototypeOf", +] as const); + +/** One trap a Proxy handler can carry. */ +export type ProxyTrap = (typeof PROXY_TRAPS)[number]; + +/** A value a call returned in place of its own. */ +export interface ReturnedValue { + /** `typeof` it, `null` reading as "null". */ + readonly type: string; + /** A primitive's text, or a harness value's name; null otherwise. */ + readonly text: string | null; +} + +/** The verdict of one of T7.6-6's calls, reached by `Object.is` in the run. */ +export type CallOutcome = "returned-argument" | "returned-other" | "threw"; + +/** One of T7.6-6's calls, as the bootstrap made it. */ +export interface CallResult { + readonly case: CallCase; + readonly outcome: CallOutcome; + /** For `returned-other`, what it returned; null otherwise. */ + readonly returned: ReturnedValue | null; + /** For `threw`, what it threw; null otherwise. */ + readonly thrown: ThrownDescription | null; +} + +/** One trap a recording Proxy's handler ran. */ +export interface TrapInvocation { + readonly proxy: "first" | "second"; + readonly trap: ProxyTrap; +} + +/** How reading `defineConfig` from the loaded value went: one of the two. */ +export interface DefineConfigReading { + /** `typeof` the value read, `null` reading as "null"; null if it threw. */ + readonly type: string | null; + readonly thrown: ThrownDescription | null; +} + +/** T7.6-6's calls, as the bootstrap made them (its header). */ +export interface CallsObservation { + /** The read of `defineConfig`; null while it was unfinished. */ + readonly reading: DefineConfigReading | null; + /** Each call made, in `CALL_CASES`' order: all of them, once completed. */ + readonly results: readonly CallResult[]; + /** Each trap either Proxy's handler ran, in order, through the run's end. */ + readonly traps: readonly TrapInvocation[]; +} + +/** The importing module's note of its own kind and location. */ +export interface ImportingModuleNote { + /** `typeof this` at its top level: "undefined" in an ES module. */ + readonly topLevelThis: string | null; + /** `import.meta.url` in an ES module, `__filename` in a CommonJS one. */ + readonly location: string | null; +} + +/** + * T7.6-7(c)'s observations (module header; the bootstrap's header), each + * the name the bootstrap records a difference under. + */ +export const STATE_OBSERVATIONS = Object.freeze([ + "global-object", + "built-ins", + "extensibility", + "prototype", + "process", + "environment", + "title", + "working-directory", + "exit-code", + "stream-write", + "listeners", + "timers-and-handles", +] as const); + +/** One of T7.6-7(c)'s observations. */ +export type StateObservationName = (typeof STATE_OBSERVATIONS)[number]; + +/** One difference the bootstrap found in the process state. */ +export interface StateChange { + /** The observation that found it. */ + readonly observation: StateObservationName; + /** + * What differs: an observed object by its label ("the global object", + * "Array", "Array.prototype", "process"), or another observation's + * subject ("process.env", "process.stdout.write", ...). + */ + readonly subject: string; + /** How it differs, in words. */ + readonly detail: string; +} + +/** T7.6-7(c)'s comparison, as the bootstrap made it (its header). */ +export interface StateObservation { + /** The labels of the objects observed: the global object, each built-in, `process`. */ + readonly subjects: readonly string[]; + /** Each difference listed, at most the bootstrap's limit. */ + readonly changes: readonly StateChange[]; + /** How many differences were found beyond those listed. */ + readonly omitted: number; +} + +/** ECMAScript's global namespace objects: ECMA-262's, and ECMA-402's `Intl`. */ +const ECMASCRIPT_NAMESPACES = ["Atomics", "Intl", "JSON", "Math", "Reflect"]; + +/** + * ECMAScript's global constructors (ECMA-262's, `Iterator` among them), + * each of which every one of E-1's releases holds as a data property. + */ +const ECMASCRIPT_CONSTRUCTORS = [ + "AggregateError", + "Array", + "ArrayBuffer", + "BigInt", + "BigInt64Array", + "BigUint64Array", + "Boolean", + "DataView", + "Date", + "Error", + "EvalError", + "FinalizationRegistry", + "Float32Array", + "Float64Array", + "Function", + "Int8Array", + "Int16Array", + "Int32Array", + "Iterator", + "Map", + "Number", + "Object", + "Promise", + "Proxy", + "RangeError", + "ReferenceError", + "RegExp", + "Set", + "SharedArrayBuffer", + "String", + "Symbol", + "SyntaxError", + "TypeError", + "Uint8Array", + "Uint8ClampedArray", + "Uint16Array", + "Uint32Array", + "URIError", + "WeakMap", + "WeakRef", + "WeakSet", +]; + +/** + * The labels every compared state must have observed (module header): the + * global object, `process`, ECMAScript's global namespace objects and + * constructors, and each constructor's prototype, `Proxy` (which has none) + * aside. + */ +export const REQUIRED_STATE_SUBJECTS: readonly string[] = Object.freeze([ + "the global object", + "process", + ...ECMASCRIPT_NAMESPACES, + ...ECMASCRIPT_CONSTRUCTORS, + ...ECMASCRIPT_CONSTRUCTORS.filter((name) => name !== "Proxy").map( + (name) => `${name}.prototype`, + ), +]); + +/** How far a run got (module header). */ +export type ModuleRunPhase = "loading" | "calling" | "completed"; + +/** A decoded report (module header), its members read exactly. */ +export interface ModuleRunReport { + /** The bootstrap's path and the arguments after it, as the run saw them. */ + readonly argv: readonly string[]; + readonly release: { + /** `process.version`: `v` and the release's version. */ + readonly version: string; + /** `process.execPath`: the executable's physical path. */ + readonly execPath: string; + /** `process.execArgv`: the options before the script. */ + readonly execArgv: readonly string[]; + }; + /** `process.pid`. */ + readonly pid: number; + /** `process.env`, read before anything of the package loaded. */ + readonly environment: Readonly<Record<string, string>>; + /** `process.cwd()`, read likewise. */ + readonly cwd: string; + /** + * `loading` until the load handed back a value or threw; `calling` while + * T7.6-6's calls ran; `completed` once they, or a failed load, ended. + */ + readonly phase: ModuleRunPhase; + /** Where the module loaded: the importing module's note; null otherwise. */ + readonly importingModule: ImportingModuleNote | null; + /** The load's outcome from the phase `calling` on; null before. */ + readonly load: LoadObservation | null; + /** Where the module loaded: T7.6-6's calls; null otherwise. */ + readonly calls: CallsObservation | null; + /** + * Where the module loaded and the phase completed: T7.6-7(c)'s + * comparison of the process state; null otherwise. + */ + readonly state: StateObservation | null; + /** A failure of the bootstrap's own flow, if any. */ + readonly bootstrapError: ThrownDescription | null; + /** Each warning delivered to the `warning` listener, in order. */ + readonly warnings: readonly CapturedWarning[]; + /** The exit code the `exit` listener saw; null where it never ran. */ + readonly exit: { readonly code: number | null } | null; +} + +/** A report's decoding: the report, or what makes it malformed. */ +export type ReportDecoding = + | { readonly ok: true; readonly report: ModuleRunReport } + | { readonly ok: false; readonly problem: string }; + +/** A shape problem, thrown by the readers below and caught by the decoder. */ +class ReportShapeError extends Error {} + +const REPORT_MEMBERS = [ + "argv", + "bootstrapError", + "calls", + "cwd", + "environment", + "exit", + "importingModule", + "load", + "phase", + "pid", + "protocol", + "release", + "state", + "warnings", +]; +const RELEASE_MEMBERS = ["execArgv", "execPath", "version"]; +const STATE_MEMBERS = ["changes", "omitted", "subjects"]; +const STATE_CHANGE_MEMBERS = ["detail", "observation", "subject"]; +const THROWN_MEMBERS = ["code", "message", "name", "stack", "type"]; +const WARNING_MEMBERS = [...THROWN_MEMBERS, "detail"]; +const NOTE_MEMBERS = ["location", "topLevelThis"]; +const OWN_KEY_MEMBERS = ["enumerable", "kind", "name"]; +const CALLS_MEMBERS = ["reading", "results", "traps"]; +const READING_MEMBERS = ["thrown", "type"]; +const RESULT_MEMBERS = ["case", "outcome", "returned", "thrown"]; +const RETURNED_MEMBERS = ["text", "type"]; +const TRAP_MEMBERS = ["proxy", "trap"]; +const CALL_OUTCOMES: readonly CallOutcome[] = [ + "returned-argument", + "returned-other", + "threw", +]; + +/** + * Decode a report's bytes (module header): UTF-8 JSON holding exactly the + * bootstrap's members, each of its kind, consistent with the phase. Never + * throws for a malformed report: it says what makes it so. + */ +export function decodeModuleRunReport(bytes: Uint8Array): ReportDecoding { + let parsed: unknown; + try { + parsed = JSON.parse( + new TextDecoder("utf-8", { fatal: true }).decode(bytes), + ); + } catch (error) { + return { + ok: false, + problem: `its bytes are no UTF-8 JSON (${describeError(error)})`, + }; + } + try { + return { ok: true, report: readReport(parsed) }; + } catch (error) { + if (error instanceof ReportShapeError) { + return { ok: false, problem: error.message }; + } + throw error; + } +} + +function readReport(value: unknown): ModuleRunReport { + const record = readRecord(value, "the report", REPORT_MEMBERS); + if (record["protocol"] !== MODULE_RUN_PROTOCOL) { + throw new ReportShapeError( + `its protocol is ${JSON.stringify(record["protocol"])}, not ` + + `${JSON.stringify(MODULE_RUN_PROTOCOL)}`, + ); + } + const release = readRecord(record["release"], "release", RELEASE_MEMBERS); + const pid = record["pid"]; + if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0) { + throw new ReportShapeError( + `its pid ${JSON.stringify(pid)} is no positive integer`, + ); + } + const phase = record["phase"]; + if (phase !== "loading" && phase !== "calling" && phase !== "completed") { + throw new ReportShapeError( + `its phase ${JSON.stringify(phase)} is none of "loading", "calling", ` + + `and "completed"`, + ); + } + const report: ModuleRunReport = { + argv: readStrings(record["argv"], "argv"), + release: { + version: readString(release["version"], "release.version"), + execPath: readString(release["execPath"], "release.execPath"), + execArgv: readStrings(release["execArgv"], "release.execArgv"), + }, + pid, + environment: readEnvironment(record["environment"]), + cwd: readString(record["cwd"], "cwd"), + phase, + importingModule: + record["importingModule"] === null + ? null + : readNote(record["importingModule"]), + load: record["load"] === null ? null : readLoad(record["load"]), + calls: record["calls"] === null ? null : readCalls(record["calls"]), + state: record["state"] === null ? null : readState(record["state"]), + bootstrapError: + record["bootstrapError"] === null + ? null + : readThrown(record["bootstrapError"], "bootstrapError"), + warnings: readArray(record["warnings"], "warnings").map((warning, index) => + readWarning(warning, `warnings[${String(index)}]`), + ), + exit: record["exit"] === null ? null : readExit(record["exit"]), + }; + checkPhase(report); + if ( + (report.importingModule !== null) !== + (report.load?.outcome === "loaded") + ) { + throw new ReportShapeError( + "it holds the importing module's note without a loaded module, or a " + + "loaded module without the note", + ); + } + return report; +} + +/** + * The members each phase holds (module header): `loading`, neither a load + * outcome, calls, nor a state compared; `calling`, a loaded module and its + * calls so far, no state compared yet; `completed`, a load outcome, no + * failure of the bootstrap's own, and, for a loaded module, the state + * compared, `defineConfig` read, and every call made where it is a + * function, none otherwise. + */ +function checkPhase(report: ModuleRunReport): void { + const loaded = report.load?.outcome === "loaded"; + switch (report.phase) { + case "loading": + if ( + report.load !== null || + report.calls !== null || + report.state !== null + ) { + throw new ReportShapeError( + "it holds a load outcome, calls, or a state compared while still " + + "in the phase loading", + ); + } + return; + case "calling": + if (!loaded || report.calls === null || report.state !== null) { + throw new ReportShapeError( + "it reached the phase calling without a loaded module and its " + + "calls, or with a state compared", + ); + } + return; + case "completed": { + if (report.load === null || report.bootstrapError !== null) { + throw new ReportShapeError( + "it reached the phase completed without a load outcome, or with a " + + "failure of the bootstrap's own", + ); + } + const calls = report.calls; + if ((calls !== null) !== loaded) { + throw new ReportShapeError( + "it holds calls without a loaded module, or a loaded module " + + "without calls", + ); + } + if ((report.state !== null) !== loaded) { + throw new ReportShapeError( + "it holds a state compared without a loaded module, or a loaded " + + "module whose state was not compared", + ); + } + if (calls === null) return; + const callable = calls.reading?.type === "function"; + if ( + calls.reading === null || + calls.results.length !== (callable ? CALL_CASES.length : 0) + ) { + throw new ReportShapeError( + `it reached the phase completed with defineConfig unread, or with ` + + `${String(calls.results.length)} calls made where ` + + `${callable ? "all of them" : "none"} must be`, + ); + } + return; + } + } +} + +function readCalls(value: unknown): CallsObservation { + const record = readRecord(value, "calls", CALLS_MEMBERS); + const reading = + record["reading"] === null ? null : readReading(record["reading"]); + const results = readArray(record["results"], "calls.results").map( + (entry, index) => readCallResult(entry, `calls.results[${String(index)}]`), + ); + const traps = readArray(record["traps"], "calls.traps").map((entry, index) => + readTrap(entry, `calls.traps[${String(index)}]`), + ); + results.forEach((result, index) => { + if (result.case !== CALL_CASES[index]) { + throw new ReportShapeError( + `calls.results[${String(index)}] is the call ` + + `${JSON.stringify(result.case)}, where the bootstrap's order ` + + `(CALL_CASES) puts ${JSON.stringify(CALL_CASES[index] ?? null)}`, + ); + } + }); + if (results.length > 0 && reading?.type !== "function") { + throw new ReportShapeError( + "calls.results holds calls made with no function read as defineConfig", + ); + } + return { reading, results, traps }; +} + +function readState(value: unknown): StateObservation { + const record = readRecord(value, "state", STATE_MEMBERS); + const omitted = record["omitted"]; + if ( + typeof omitted !== "number" || + !Number.isSafeInteger(omitted) || + omitted < 0 + ) { + throw new ReportShapeError( + `state.omitted ${JSON.stringify(omitted)} is no non-negative integer`, + ); + } + return { + subjects: readStrings(record["subjects"], "state.subjects"), + changes: readArray(record["changes"], "state.changes").map((entry, index) => + readStateChange(entry, `state.changes[${String(index)}]`), + ), + omitted, + }; +} + +function readStateChange(value: unknown, where: string): StateChange { + const record = readRecord(value, where, STATE_CHANGE_MEMBERS); + const observation = record["observation"]; + if (!STATE_OBSERVATIONS.some((name) => name === observation)) { + throw new ReportShapeError( + `${where}.observation ${JSON.stringify(observation)} is none of ` + + "STATE_OBSERVATIONS", + ); + } + return { + observation: observation as StateObservationName, + subject: readString(record["subject"], `${where}.subject`), + detail: readString(record["detail"], `${where}.detail`), + }; +} + +function readReading(value: unknown): DefineConfigReading { + const record = readRecord(value, "calls.reading", READING_MEMBERS); + const type = readNullableString(record["type"], "calls.reading.type"); + const thrown = + record["thrown"] === null + ? null + : readThrown(record["thrown"], "calls.reading.thrown"); + if ((type === null) === (thrown === null)) { + throw new ReportShapeError( + "calls.reading holds both a type and a thrown value, or neither", + ); + } + return { type, thrown }; +} + +function readCallResult(value: unknown, where: string): CallResult { + const record = readRecord(value, where, RESULT_MEMBERS); + const callCase = record["case"]; + if (!CALL_CASES.some((name) => name === callCase)) { + throw new ReportShapeError( + `${where}.case ${JSON.stringify(callCase)} is none of CALL_CASES`, + ); + } + const outcome = record["outcome"]; + if (!CALL_OUTCOMES.some((name) => name === outcome)) { + throw new ReportShapeError( + `${where}.outcome ${JSON.stringify(outcome)} is none of ` + + JSON.stringify(CALL_OUTCOMES), + ); + } + const returned = + record["returned"] === null + ? null + : readReturned(record["returned"], `${where}.returned`); + const thrown = + record["thrown"] === null + ? null + : readThrown(record["thrown"], `${where}.thrown`); + if ( + (returned !== null) !== (outcome === "returned-other") || + (thrown !== null) !== (outcome === "threw") + ) { + throw new ReportShapeError( + `${where} holds a returned or thrown value its outcome ` + + `${JSON.stringify(outcome)} does not, or lacks one it does`, + ); + } + return { + case: callCase as CallCase, + outcome: outcome as CallOutcome, + returned, + thrown, + }; +} + +function readReturned(value: unknown, where: string): ReturnedValue { + const record = readRecord(value, where, RETURNED_MEMBERS); + return { + type: readString(record["type"], `${where}.type`), + text: readNullableString(record["text"], `${where}.text`), + }; +} + +function readTrap(value: unknown, where: string): TrapInvocation { + const record = readRecord(value, where, TRAP_MEMBERS); + const proxy = record["proxy"]; + const trap = record["trap"]; + if (proxy !== "first" && proxy !== "second") { + throw new ReportShapeError( + `${where}.proxy ${JSON.stringify(proxy)} is neither "first" nor "second"`, + ); + } + if (!PROXY_TRAPS.some((name) => name === trap)) { + throw new ReportShapeError( + `${where}.trap ${JSON.stringify(trap)} is none of PROXY_TRAPS`, + ); + } + return { proxy, trap: trap as ProxyTrap }; +} + +function readOwnKey(value: unknown, where: string): OwnKey { + const record = readRecord(value, where, OWN_KEY_MEMBERS); + const kind = record["kind"]; + if (kind !== "string" && kind !== "symbol") { + throw new ReportShapeError( + `${where}.kind ${JSON.stringify(kind)} is neither "string" nor "symbol"`, + ); + } + const name = + kind === "string" + ? readString(record["name"], `${where}.name`) + : readNullableString(record["name"], `${where}.name`); + const enumerable = record["enumerable"]; + if (enumerable !== null && typeof enumerable !== "boolean") { + throw new ReportShapeError( + `${where}.enumerable ${JSON.stringify(enumerable)} is no boolean`, + ); + } + return { kind, name, enumerable }; +} + +function readRecord( + value: unknown, + where: string, + members: readonly string[], +): Record<string, unknown> { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + throw new ReportShapeError(`${where} is no JSON object`); + } + const record = value as Record<string, unknown>; + const found = Object.keys(record).sort(); + const wanted = [...members].sort(); + if ( + found.length !== wanted.length || + found.some((name, index) => name !== wanted[index]) + ) { + throw new ReportShapeError( + `${where} holds the members ${JSON.stringify(found)}, not exactly ` + + JSON.stringify(wanted), + ); + } + return record; +} + +function readArray(value: unknown, where: string): readonly unknown[] { + if (!Array.isArray(value)) { + throw new ReportShapeError(`${where} is no JSON array`); + } + return value as readonly unknown[]; +} + +function readString(value: unknown, where: string): string { + if (typeof value !== "string") { + throw new ReportShapeError(`${where} is no string`); + } + return value; +} + +function readNullableString(value: unknown, where: string): string | null { + return value === null ? null : readString(value, where); +} + +function readStrings(value: unknown, where: string): readonly string[] { + return readArray(value, where).map((entry, index) => + readString(entry, `${where}[${String(index)}]`), + ); +} + +function readEnvironment(value: unknown): Readonly<Record<string, string>> { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + throw new ReportShapeError("environment is no JSON object"); + } + const entries = Object.entries(value as Record<string, unknown>).map( + ([name, entry]): [string, string] => [ + name, + readString(entry, `environment[${JSON.stringify(name)}]`), + ], + ); + return Object.freeze(Object.fromEntries(entries)); +} + +function readNote(value: unknown): ImportingModuleNote { + const record = readRecord(value, "importingModule", NOTE_MEMBERS); + return { + topLevelThis: readNullableString( + record["topLevelThis"], + "importingModule.topLevelThis", + ), + location: readNullableString( + record["location"], + "importingModule.location", + ), + }; +} + +function readThrown(value: unknown, where: string): ThrownDescription { + const record = readRecord(value, where, THROWN_MEMBERS); + return { + type: readString(record["type"], `${where}.type`), + name: readNullableString(record["name"], `${where}.name`), + code: readNullableString(record["code"], `${where}.code`), + message: readNullableString(record["message"], `${where}.message`), + stack: readNullableString(record["stack"], `${where}.stack`), + }; +} + +function readWarning(value: unknown, where: string): CapturedWarning { + const record = readRecord(value, where, WARNING_MEMBERS); + return { + type: readString(record["type"], `${where}.type`), + name: readNullableString(record["name"], `${where}.name`), + code: readNullableString(record["code"], `${where}.code`), + message: readNullableString(record["message"], `${where}.message`), + detail: readNullableString(record["detail"], `${where}.detail`), + stack: readNullableString(record["stack"], `${where}.stack`), + }; +} + +function readLoad(value: unknown): LoadObservation { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + throw new ReportShapeError("load is no JSON object"); + } + const outcome = (value as Record<string, unknown>)["outcome"]; + if (outcome === "loaded") { + const record = readRecord(value, "load", ["outcome", "value"]); + const loaded = readRecord(record["value"], "load.value", [ + "ownKeys", + "type", + ]); + return { + outcome, + value: { + type: readString(loaded["type"], "load.value.type"), + ownKeys: + loaded["ownKeys"] === null + ? null + : readArray(loaded["ownKeys"], "load.value.ownKeys").map( + (key, index) => + readOwnKey(key, `load.value.ownKeys[${String(index)}]`), + ), + }, + }; + } + if (outcome === "failed") { + const record = readRecord(value, "load", ["error", "outcome"]); + return { outcome, error: readThrown(record["error"], "load.error") }; + } + throw new ReportShapeError( + `load's outcome ${JSON.stringify(outcome)} is neither "loaded" nor ` + + `"failed"`, + ); +} + +function readExit(value: unknown): { readonly code: number | null } { + const record = readRecord(value, "exit", ["code"]); + const code = record["code"]; + if (code !== null && (typeof code !== "number" || !Number.isInteger(code))) { + throw new ReportShapeError( + `exit.code ${JSON.stringify(code)} is no integer`, + ); + } + return { code }; +} + +// --------------------------------------------------------------------------- +// Runs +// --------------------------------------------------------------------------- + +/** One run asked of the driver ({@link prepareModuleRun}). */ +export interface ModuleRunRequest { + /** The staging, placements made (helpers/module-channel.ts). */ + readonly staging: ModuleStaging; + /** The placement the importing module's specifier reaches: N its name. */ + readonly placement: Placement; + /** The route the run loads the module along. */ + readonly route: ModuleRoute; + /** The release the run loads it on (helpers/node-releases.ts). */ + readonly release: NodeRelease; + /** + * The importing file's place: a staging-relative directory, along its + * physical path — the placement's holding directory unless given. + */ + readonly importingDir?: string; + /** The project kind the staging declares, confirmed by Reach where given. */ + readonly project?: ProjectKind; + /** + * For a CommonJS project whose nearest `package.json` holds the `type` + * `"commonjs"` (T7.6-5(c)): that member, confirmed by Reach with the + * project kind (helpers/module-channel.ts `ReachStaging.nearestType`). + */ + readonly nearestType?: CommonJsTypeMember; + /** Whether nothing but the placement is installed, confirmed where set. */ + readonly alone?: boolean; + /** + * Whether the run also observes T7.6-7(b) and (e) (module header): its + * FIFOs staged before it, and the staging, its working directory, `HOME`, + * and `TMPDIR` snapshotted around it ({@link ModuleRun.effects}). Such a + * run compares the whole staging, so the driver refuses to prepare + * another run into that staging while it is launched. + */ + readonly effects?: boolean; + /** + * The run's guards: {@link MODULE_RUN_TIMEOUT_MS} and the subprocess + * driver's capture limit unless given. Registered bodies never pass them; + * a self-test's stand-in may lower them. + */ + readonly guards?: RunGuards; + /** Leads every diagnosis: the arm the run serves. */ + readonly context: string; +} + +/** + * What a run came to (module header): the route's load handed back a value + * (`loaded`) or threw (`load-failed`); the process exited before either, or + * the bootstrap's own flow failed (`incomplete`); it left no report + * (`no-report`); or its report is malformed (`malformed-report`). + */ +export type ModuleRunOutcome = + "loaded" | "load-failed" | "incomplete" | "no-report" | "malformed-report"; + +/** A finished run ({@link PreparedModuleRun.launch}). */ +export interface ModuleRun { + /** The run, in words, leading its diagnoses. */ + readonly description: string; + readonly route: ModuleRoute; + readonly release: NodeRelease; + /** The placement its importing module's specifier reached. */ + readonly placement: Placement; + /** The importing module, absolute and physical. */ + readonly importingModule: string; + /** The run's working directory, `HOME`, and `TMPDIR`. */ + readonly cwd: string; + readonly home: string; + readonly tmp: string; + /** The environment the run was given, exactly. */ + readonly environment: Readonly<Record<string, string>>; + /** The process's exit code, signal, and both streams. */ + readonly result: RunResult; + readonly outcome: ModuleRunOutcome; + /** The decoded report; undefined for `no-report` and `malformed-report`. */ + readonly report: ModuleRunReport | undefined; + /** What makes the report malformed, for `malformed-report`. */ + readonly reportProblem: string | undefined; + /** + * T7.6-7(b) and (e)'s observations, for a run asked for them + * ({@link ModuleRunRequest.effects}); undefined otherwise. + */ + readonly effects: RunEffects | undefined; +} + +/** A run whose module loaded and whose process exited 0 on its own. */ +export interface LoadedModuleRun extends ModuleRun { + readonly outcome: "loaded"; + readonly report: ModuleRunReport & { + readonly load: Extract<LoadObservation, { readonly outcome: "loaded" }>; + readonly importingModule: ImportingModuleNote; + readonly calls: CallsObservation & { + readonly reading: DefineConfigReading; + }; + readonly state: StateObservation; + }; +} + +/** The places T7.6-7(b) compares around a run (module header). */ +export type RunPlace = "staging" | "working directory" | "HOME" | "TMPDIR"; + +/** An entry's kind, by name (T7.6-7(b): a FIFO compared by its kind alone). */ +export type PlaceEntryKind = + | "plain file" + | "directory" + | "symbolic link" + | "FIFO" + | "socket" + | "character device" + | "block device" + | "entry of another kind"; + +/** One entry of a place, as {@link snapshotPlace} records it. */ +export type PlaceEntry = + | { + readonly kind: "plain file"; + /** Its bytes; null where its mode refused the read. */ + readonly bytes: Uint8Array | null; + } + | { + readonly kind: "directory"; + /** Whether it could be listed (its entries recorded). */ + readonly listed: boolean; + } + | { readonly kind: "symbolic link"; readonly target: Uint8Array } + | { readonly kind: OtherPlaceEntryKind }; + +/** The kinds of entry compared by their kind alone: never opened. */ +export type OtherPlaceEntryKind = Exclude< + PlaceEntryKind, + "plain file" | "directory" | "symbolic link" +>; + +/** + * A place's entries (module header), each keyed by its path's bytes + * relative to the place, latin1-encoded and `/`-separated (helpers/ + * snapshot.ts's keys), the place itself under `""`. + */ +export type PlaceSnapshot = ReadonlyMap<string, PlaceEntry>; + +/** One entry created, modified, or removed in a place. */ +export interface PlaceChange { + /** Its path in the place, for a diagnosis: `.` for the place itself. */ + readonly path: string; + readonly change: "created" | "modified" | "removed"; + /** What it was, is, or became, in words. */ + readonly detail: string; +} + +/** One place T7.6-7(b) compared, and what changed in it. */ +export interface PlaceWrites { + readonly place: RunPlace; + /** The place's root, absolute and physical. */ + readonly root: string; + readonly changes: readonly PlaceChange[]; +} + +/** One of T7.6-7(e)'s FIFOs, read back after the run. */ +export interface FifoAfter { + /** Its absolute path. */ + readonly path: string; + /** What occupies the path afterwards: its kind, or null for nothing. */ + readonly found: PlaceEntryKind | null; +} + +/** T7.6-7(b) and (e)'s observations of a run (module header). */ +export interface RunEffects { + /** (b): each of the four places, and what changed in it. */ + readonly writes: readonly PlaceWrites[]; + /** (e): each FIFO staged, and what its path holds afterwards. */ + readonly fifos: readonly FifoAfter[]; +} + +/** + * Whom a run's failure to load is charged to (module header): the product, + * for a test's run — a diagnosed failure — or the harness, for a stand-in + * it expected to load — a harness error. + */ +export type RunAttribution = "product" | "stand-in"; + +/** + * Prepare one run (module header): the importing module written in its + * place (or found byte-equal there), and the run's own directory made — + * its bootstrap, and its fresh `HOME`, `TMPDIR`, and working directory — + * and, for a run observing its effects, T7.6-7(e)'s FIFOs staged. Nothing + * runs yet: a caller may stage more in those directories before + * {@link PreparedModuleRun.launch}, and disposes of the run once done. + */ +export async function prepareModuleRun( + request: ModuleRunRequest, +): Promise<PreparedModuleRun> { + return PreparedModuleRun.prepare(request); +} + +/** + * One run, start to end ({@link prepareModuleRun}, then + * {@link PreparedModuleRun.launch}), its own directory removed afterwards + * however it ended. + */ +export async function runModuleRoute( + request: ModuleRunRequest, +): Promise<ModuleRun> { + const prepared = await prepareModuleRun(request); + try { + return await prepared.launch(); + } finally { + await prepared.dispose(); + } +} + +/** A prepared run ({@link prepareModuleRun}): launched once, then disposed of. */ +export class PreparedModuleRun { + readonly staging: ModuleStaging; + readonly placement: Placement; + readonly route: ModuleRoute; + readonly release: NodeRelease; + /** The importing module, staging-relative. */ + readonly importingFile: string; + /** The importing module, absolute and physical. */ + readonly importingModule: string; + /** The run's own directory, absolute and physical. */ + readonly root: string; + /** The run's fresh `HOME`, `TMPDIR`, and working directory. */ + readonly home: string; + readonly tmp: string; + readonly cwd: string; + /** The bootstrap's copy, and the report's path. */ + readonly bootstrap: string; + readonly reportPath: string; + /** The run's environment, exactly ({@link moduleRunEnvironment}). */ + readonly environment: Readonly<Record<string, string>>; + /** The run, in words, leading its diagnoses. */ + readonly description: string; + readonly #reach: ReachStaging; + readonly #guards: RunGuards; + /** Whether it observes T7.6-7(b) and (e) ({@link ModuleRunRequest.effects}). */ + readonly #effects: boolean; + readonly #fifos: string[] = []; + #launched = false; + #disposed = false; + + private constructor( + request: ModuleRunRequest, + importingFile: string, + root: string, + ) { + this.staging = request.staging; + this.placement = request.placement; + this.route = request.route; + this.release = request.release; + this.importingFile = importingFile; + this.importingModule = request.staging.path(importingFile); + this.root = root; + this.home = path.join(root, HOME_NAME); + this.tmp = path.join(root, TMPDIR_NAME); + this.cwd = path.join(root, WORK_NAME); + this.bootstrap = path.join(root, BOOTSTRAP_NAME); + this.reportPath = path.join(root, REPORT_NAME); + this.environment = moduleRunEnvironment(this.home, this.tmp); + this.description = + `${request.context}: the Node.js release ${request.release.version} ` + + `loading ${request.placement.name} along ` + + `${describeRoute(request.route)} from ${this.importingModule}`; + this.#reach = { + importingFile, + placement: request.placement, + ...(request.project === undefined ? {} : { project: request.project }), + ...(request.nearestType === undefined + ? {} + : { nearestType: request.nearestType }), + ...(request.alone === undefined ? {} : { alone: request.alone }), + }; + this.#guards = request.guards ?? {}; + this.#effects = request.effects === true; + } + + /** + * T7.6-7(e)'s FIFOs, absolute — in the working directory, in the + * importing module's directory, and in `HOME` — for a run observing its + * effects; none otherwise. + */ + get fifos(): readonly string[] { + return this.#fifos; + } + + /** See {@link prepareModuleRun}. */ + static async prepare(request: ModuleRunRequest): Promise<PreparedModuleRun> { + const { staging, placement, route } = request; + const importingDir = + request.importingDir ?? + path + .relative(staging.root, placement.holdingDir) + .split(path.sep) + .join("/"); + const name = importingModuleName(route); + const importingFile = + importingDir === "" || importingDir === "." + ? name + : `${importingDir}/${name}`; + await writeImportingModule( + staging, + importingFile, + importingModuleText(route, placement.name), + request.context, + ); + const root = await makeScratchDirectory(MODULE_RUN_PREFIX, request.context); + try { + const prepared = new PreparedModuleRun(request, importingFile, root); + await guardStep( + `making the run directories and the bootstrap under ${root} ` + + `(${request.context})`, + async () => { + for (const directory of [prepared.home, prepared.tmp, prepared.cwd]) { + await fsp.mkdir(directory); + } + await fsp.writeFile( + prepared.bootstrap, + await fsp.readFile(BOOTSTRAP_SOURCE), + { + flag: "wx", + }, + ); + }, + ); + if (prepared.#effects) await prepared.#stageFifos(importingDir); + return prepared; + } catch (error) { + await removeRunDirectory(root, request.context); + throw error; + } + } + + /** + * Run it (module header): Reach and H-1 verified first, under the run's + * exact environment, working directory, and executable; then the release + * run through the subprocess driver under the run's own guard — for a run + * observing its effects, its four places snapshotted just before and + * just after, and its FIFOs read back; then its report read, decoded, and + * its conditions checked. Resolves with the run whatever its outcome; + * rejects with the hang-guard kill, any other rejection of the run's + * spawn, an unmet staging precondition (`HarnessStagingError`), or a + * breach of the run's conditions (a harness error). + */ + async launch(): Promise<ModuleRun> { + if (this.#launched || this.#disposed) { + throw new Error( + `module channel: a prepared run launches once, before it is ` + + `disposed of (${this.description})`, + ); + } + this.#launched = true; + await this.staging.verifyReach(this.#reach); + const binding = releaseBinding(this.release); + const overrides = exactEnvironmentOverrides(binding, this.environment); + const spawnedWith = productEnvironment(binding, overrides); + if (!sameEnvironment(spawnedWith, this.environment)) { + throw new Error( + `harness error (H-11): ${this.description}: the run would be ` + + `spawned with the environment ${describeEnvironment(spawnedWith)}, ` + + `not exactly ${describeEnvironment(this.environment)}`, + ); + } + await this.staging.verifyIsolation({ + environment: spawnedWith, + cwd: this.cwd, + executables: [this.release.executable], + }); + const executable = await guardStep( + `reading the physical path of ${this.release.executable} ` + + `(${this.description})`, + () => fsp.realpath(this.release.executable), + ); + if ((await readReportBytes(this.reportPath, this.description)) !== null) { + throw new Error( + `harness error (H-11): ${this.description}: the report path ` + + `${this.reportPath} is occupied before the run`, + ); + } + const spawn = (): Promise<RunResult> => + runProduct(binding, { + cwd: this.cwd, + argv: [ + this.bootstrap, + this.importingModule, + this.reportPath, + this.route, + ], + env: overrides, + timeoutMs: this.#guards.timeoutMs ?? MODULE_RUN_TIMEOUT_MS, + ...(this.#guards.maxOutputBytes === undefined + ? {} + : { maxOutputBytes: this.#guards.maxOutputBytes }), + }); + const { result, effects } = this.#effects + ? await this.#observeEffects(spawn) + : { result: await spawn(), effects: undefined }; + const bytes = await readReportBytes(this.reportPath, this.description); + const decoding = + bytes === null + ? null + : guardSyncStep(`decoding the report of ${this.description}`, () => + decodeModuleRunReport(bytes), + ); + const base = { + description: this.description, + route: this.route, + release: this.release, + placement: this.placement, + importingModule: this.importingModule, + cwd: this.cwd, + home: this.home, + tmp: this.tmp, + environment: this.environment, + result, + effects, + }; + if (decoding === null) { + return { + ...base, + outcome: "no-report", + report: undefined, + reportProblem: undefined, + }; + } + if (!decoding.ok) { + return { + ...base, + outcome: "malformed-report", + report: undefined, + reportProblem: decoding.problem, + }; + } + const report = decoding.report; + this.#confirmConditions(report, executable); + let outcome: ModuleRunOutcome; + if (report.phase !== "completed" || report.load === null) { + outcome = "incomplete"; + } else { + outcome = report.load.outcome === "loaded" ? "loaded" : "load-failed"; + } + return { ...base, outcome, report, reportProblem: undefined }; + } + + /** Remove the run's own directory; idempotent. */ + async dispose(): Promise<void> { + if (this.#disposed) return; + this.#disposed = true; + await removeRunDirectory(this.root, this.description); + } + + /** + * Stage T7.6-7(e)'s FIFOs (module header): `xspec.config.ts` in the + * working directory and in `HOME`, fresh for the run, and in the + * importing module's directory, `importingDir` in the staging — found + * there already as a FIFO, staged by an earlier run, or staged now; any + * other occupant a `HarnessStagingError`. + */ + async #stageFifos(importingDir: string): Promise<void> { + const inStaging = + importingDir === "" || importingDir === "." + ? RUN_FIFO_NAME + : `${importingDir}/${RUN_FIFO_NAME}`; + const stagingFifo = this.staging.path(inStaging); + const occupant = await guardStep( + `reading what occupies ${stagingFifo} (${this.description})`, + () => readEntryKind(stagingFifo), + ); + if (occupant === null) { + refuseWhileObserved( + this.staging, + `the FIFO ${stagingFifo}`, + this.description, + ); + await guardStep( + `staging the FIFO ${stagingFifo} (${this.description})`, + () => + stageFifo( + { root: this.staging.root, tempRoot: this.root }, + inStaging, + ), + ); + } else if (occupant !== "FIFO") { + throw new HarnessStagingError( + MODE, + stagingFifo, + `${this.description}: the place of T7.6-7(e)'s FIFO in the ` + + `importing module's directory, ${stagingFifo}, is occupied by ` + + `${withArticle(occupant)} (TEST-SPEC T7.6-7(e): a FIFO named ` + + `${RUN_FIFO_NAME} in the importing module's directory)`, + ); + } + for (const directory of [this.cwd, this.home]) { + await guardStep( + `staging the FIFO ${path.join(directory, RUN_FIFO_NAME)} ` + + `(${this.description})`, + () => + stageFifo({ root: directory, tempRoot: this.root }, RUN_FIFO_NAME), + ); + } + this.#fifos.push( + path.join(this.cwd, RUN_FIFO_NAME), + stagingFifo, + path.join(this.home, RUN_FIFO_NAME), + ); + } + + /** + * Spawn the run observing T7.6-7(b) and (e) (module header): the four + * places snapshotted just before it and just after, compared, and each + * FIFO read back; the staging held as observed meanwhile, so that no + * other run is prepared into it. + */ + async #observeEffects( + spawn: () => Promise<RunResult>, + ): Promise<{ result: RunResult; effects: RunEffects }> { + const places: readonly (readonly [RunPlace, string])[] = [ + ["staging", this.staging.root], + ["working directory", this.cwd], + ["HOME", this.home], + ["TMPDIR", this.tmp], + ]; + observedLaunches.set( + this.staging, + (observedLaunches.get(this.staging) ?? 0) + 1, + ); + try { + const before: PlaceSnapshot[] = []; + for (const [, root] of places) { + before.push(await snapshotPlace(root, this.description)); + } + const result = await spawn(); + const writes: PlaceWrites[] = []; + for (const [index, [place, root]] of places.entries()) { + writes.push({ + place, + root, + changes: comparePlaceSnapshots( + before[index] ?? new Map(), + await snapshotPlace(root, this.description), + ), + }); + } + const fifos: FifoAfter[] = []; + for (const fifo of this.#fifos) { + fifos.push({ + path: fifo, + found: await guardStep( + `reading back the FIFO ${fifo} (${this.description})`, + () => readEntryKind(fifo), + ), + }); + } + return { result, effects: { writes, fifos } }; + } finally { + const count = (observedLaunches.get(this.staging) ?? 1) - 1; + if (count > 0) observedLaunches.set(this.staging, count); + else observedLaunches.delete(this.staging); + } + } + + /** + * The run's conditions (module header), on a report that decodes: a + * breach is a harness error, every one of them set before anything of + * the package loaded. + */ + #confirmConditions(report: ModuleRunReport, executable: string): void { + const breaches: string[] = []; + const argv = [ + this.bootstrap, + this.importingModule, + this.reportPath, + this.route, + ]; + if ( + report.argv.length !== argv.length || + report.argv.some((argument, index) => argument !== argv[index]) + ) { + breaches.push( + `its arguments ${JSON.stringify(report.argv)} are not those passed, ` + + JSON.stringify(argv), + ); + } + if (report.release.version !== `v${this.release.version}`) { + breaches.push( + `the release in effect reports ${report.release.version}, not ` + + `v${this.release.version} (TEST-SPEC E-1, S-10)`, + ); + } + if (report.release.execPath !== executable) { + breaches.push( + `the running executable is ${report.release.execPath}, not ` + + `${executable}, the provisioned release's physical path`, + ); + } + if (report.release.execArgv.length > 0) { + breaches.push( + `the run carries the options ${JSON.stringify(report.release.execArgv)}` + + ` (TEST-SPEC T7.6-6: run with no option)`, + ); + } + if (!sameEnvironment(report.environment, this.environment)) { + breaches.push( + `the run's environment is ${describeEnvironment(report.environment)}, ` + + `not exactly ${describeEnvironment(this.environment)} (TEST-SPEC ` + + `T7.6-6: no environment variable, NODE_OPTIONS and NODE_PATH among ` + + `them; T7.6-7: a fresh HOME and TMPDIR)`, + ); + } + if (report.cwd !== this.cwd) { + breaches.push( + `the run's working directory is ${report.cwd}, not ${this.cwd}`, + ); + } + const note = report.importingModule; + if (note !== null) { + const kind = importingModuleKind(this.route); + const topLevelThis = kind === "module" ? "undefined" : "object"; + const location = + kind === "module" + ? pathToFileURL(this.importingModule).href + : this.importingModule; + if (note.topLevelThis !== topLevelThis || note.location !== location) { + breaches.push( + `the importing module reports its top-level this as ` + + `${JSON.stringify(note.topLevelThis)} and its location as ` + + `${JSON.stringify(note.location)}, where ${describeRoute(this.route)} ` + + `runs one whose top-level this is ${JSON.stringify(topLevelThis)}, ` + + `at ${JSON.stringify(location)}`, + ); + } + } + const state = report.state; + if (state !== null) { + const missing = REQUIRED_STATE_SUBJECTS.filter( + (label) => !state.subjects.includes(label), + ); + if (missing.length > 0) { + breaches.push( + `its comparison of the process state observed none of ` + + `${JSON.stringify(missing)} (TEST-SPEC T7.6-7(c): the global ` + + `object, process, and the global built-in constructors and ` + + `namespace objects with those constructors' prototypes)`, + ); + } + } + if (breaches.length > 0) { + throw new Error( + `harness error (H-11): ${this.description}: the run's conditions ` + + `were not those the harness set — ${breaches.join("; ")}`, + ); + } + } +} + +// --------------------------------------------------------------------------- +// Attribution +// --------------------------------------------------------------------------- + +/** + * What keeps `run` from being a loaded run that exited 0 on its own, in + * words, or null where nothing does. + */ +export function moduleRunProblem(run: ModuleRun): string | null { + const ended = describeEnding(run.result); + switch (run.outcome) { + case "no-report": + return `left no report: the process ${ended}`; + case "malformed-report": + return ( + `left a malformed report (${run.reportProblem ?? "unknown"}): the ` + + `process ${ended}` + ); + case "incomplete": { + const own = run.report?.bootstrapError; + if (own !== null && own !== undefined) { + return ( + `failed in the harness's own bootstrap (${describeThrown(own)}): ` + + `the process ${ended}` + ); + } + const calls = run.report?.calls; + if ( + run.report?.phase === "calling" && + calls !== null && + calls !== undefined + ) { + const next = CALL_CASES[calls.results.length]; + const during = + calls.reading === null + ? "while reading defineConfig from what the route loaded" + : next === undefined + ? "after T7.6-6's calls to defineConfig" + : `during T7.6-6's call ${describeCallCase(next)}`; + return `loaded the module, but ended ${during}: the process ${ended}`; + } + return `ended before the load completed or failed: the process ${ended}`; + } + case "load-failed": { + const load = run.report?.load; + const thrown = + load !== undefined && load !== null && load.outcome === "failed" + ? describeThrown(load.error) + : "unknown"; + return `did not load the module — the load threw ${thrown}; the process ${ended}`; + } + case "loaded": + return run.result.exitCode === 0 && run.result.signal === null + ? null + : `loaded the module, but the process ${ended}, not with exit code 0 ` + + `on its own`; + } +} + +/** + * Require `run` to have loaded the module and exited 0 on its own (module + * header): otherwise a diagnosed failure for `"product"`, a harness error + * for `"stand-in"`, naming the run, what it came to, and its streams. + */ +export function assertModuleLoaded( + run: ModuleRun, + attribution: RunAttribution, +): LoadedModuleRun { + const problem = moduleRunProblem(run); + if (problem === null) return run as LoadedModuleRun; + const diagnosis = `${run.description} ${problem}; ${describeStreams(run.result)}`; + if (attribution === "product") { + fail( + `${diagnosis} (SPEC 7.6 Reach, Runtime: with the package installed ` + + `under N, a specifier spelling exactly N designates the module along ` + + `each of Node.js's routes, on every release, and loading it has no ` + + `effect; TEST-SPEC T7.6-6, H-8)`, + ); + } + throw new Error( + `harness error (H-11): ${diagnosis} — a stand-in the harness expected ` + + `to load did not, so the driver's runs are not what they claim`, + ); +} + +/** How a run's process ended, in words. */ +function describeEnding(result: RunResult): string { + return result.signal === null + ? `exited with code ${String(result.exitCode)}` + : `was killed by ${result.signal}`; +} + +/** A run's streams, quoted for a diagnosis. */ +function describeStreams(result: RunResult): string { + return ( + `standard output ${quoteStream(result.stdout)}, standard error ` + + quoteStream(result.stderr) + ); +} + +function quoteStream(text: string): string { + return text.length > QUOTED_STREAM_LIMIT + ? `${JSON.stringify(text.slice(0, QUOTED_STREAM_LIMIT))} (truncated)` + : JSON.stringify(text); +} + +/** A thrown value as the report gives it, in words. */ +export function describeThrown(thrown: ThrownDescription): string { + const parts: string[] = []; + if (thrown.name !== null) parts.push(thrown.name); + if (thrown.code !== null) parts.push(`[${thrown.code}]`); + const head = + parts.length === 0 ? `a value of type ${thrown.type}` : parts.join(" "); + return thrown.message === null + ? head + : `${head}: ${JSON.stringify(thrown.message)}`; +} + +// --------------------------------------------------------------------------- +// T7.6-6's observations, and pairing +// --------------------------------------------------------------------------- + +/** SPEC 7.6 Runtime's export clause, which T7.6-6(a)'s problems cite. */ +const EXPORTS_CITATION = + "(TEST-SPEC T7.6-6(a); SPEC 7.6 Runtime: the module's exports are " + + "exactly defineConfig — an import namespace holds that one export, and a " + + "require result has that one own enumerable property, symbol-keyed " + + "properties counted as well as string-keyed ones)"; + +/** SPEC 7.6 Runtime's return clause, which T7.6-6(b)'s problems cite. */ +const IDENTITY_CITATION = + "(TEST-SPEC T7.6-6(b); SPEC 7.6 Runtime: defineConfig returns its first " + + "argument, the very value passed, whatever it is; undefined when called " + + "with none; any further arguments ignored)"; + +/** SPEC 7.6 Runtime's return clause, which T7.6-6(c)'s problems cite. */ +const EXAMINATION_CITATION = + "(TEST-SPEC T7.6-6(c); SPEC 7.6 Runtime: defineConfig returns its first " + + "argument and does nothing else, that value neither examined, copied, nor " + + "modified)"; + +/** SPEC 7.6 Runtime's effect clause, which T7.6-7(a)'s problems cite. */ +const OUTPUT_CITATION = + "(TEST-SPEC T7.6-7(a); SPEC 7.6 Runtime: beyond the runtime's own " + + "resolution of the specifier and loading of the package's files, neither " + + "loading the module nor calling defineConfig has any effect — no output " + + "on standard output or standard error)"; + +const CALL_CASE_DESCRIPTIONS: Readonly<Record<CallCase, string>> = { + object: "defineConfig(v) with v an object", + array: "defineConfig(v) with v an array", + function: "defineConfig(v) with v a function", + symbol: "defineConfig(v) with v a symbol", + null: "defineConfig(null)", + undefined: "defineConfig(undefined), undefined passed explicitly", + string: "defineConfig(v) with v a string", + boolean: "defineConfig(false)", + bigint: "defineConfig(10n)", + zero: "defineConfig(0)", + "negative-zero": "defineConfig(-0)", + nan: "defineConfig(NaN)", + "no-argument": "defineConfig() with no argument, which returns undefined", + "further-arguments": + "defineConfig(a, b) with a further argument, which returns a", + proxies: + "defineConfig(p, q) with p and q Proxies over functions whose every " + + "trap records its invocation, which returns p itself", + frozen: "defineConfig(f) with f a frozen object", +}; + +/** One of T7.6-6's calls, in words. */ +export function describeCallCase(name: CallCase): string { + return CALL_CASE_DESCRIPTIONS[name]; +} + +/** One of T7.6-6's calls and what it came to, in words. */ +function describeCallResult(result: CallResult): string { + const call = describeCallCase(result.case); + switch (result.outcome) { + case "returned-argument": + return `${call}: it returned its argument`; + case "threw": + return ( + `${call}: it threw ` + + (result.thrown === null ? "a value" : describeThrown(result.thrown)) + ); + case "returned-other": + return `${call}: it returned ${describeReturned(result.returned)} instead`; + } +} + +/** A value a call returned in place of its own, in words. */ +function describeReturned(returned: ReturnedValue | null): string { + if (returned === null) return "another value"; + if (returned.text === null) return `another ${returned.type}`; + return returned.type === "string" + ? `the string ${JSON.stringify(returned.text)}` + : `${returned.text} (${returned.type})`; +} + +/** A loaded value's type, in words. */ +function describeValueType(type: string): string { + return type === "null" || type === "undefined" + ? type + : `a value of type ${type}`; +} + +/** Own keys, in words. */ +function describeKeys(keys: readonly OwnKey[]): string { + const described = keys.map((key) => + key.kind === "symbol" + ? `Symbol(${key.name ?? ""})` + : JSON.stringify(key.name), + ); + return `[${described.join(", ")}]`; +} + +/** + * What keeps T7.6-6's calls from having been made — `defineConfig`'s read + * threw, or read no function — in words, or null where nothing does. + */ +function readingFault(run: LoadedModuleRun): string | null { + const { reading } = run.report.calls; + if (reading.thrown !== null) { + return ( + `reading defineConfig from what the route loaded threw ` + + `${describeThrown(reading.thrown)}, so none of T7.6-6's calls was made` + ); + } + if (reading.type !== "function") { + return ( + `defineConfig, read from what the route loaded, is ` + + `${describeValueType(reading.type ?? "undefined")}, no function, so ` + + `none of T7.6-6's calls was made` + ); + } + return null; +} + +/** + * T7.6-6(a) on `run` (module header): the route's listing of the loaded + * value's own keys exactly `defineConfig`. Each problem in words, led by + * the run's description; none where it holds. + */ +export function exportsProblems(run: LoadedModuleRun): string[] { + const { value } = run.report.load; + if (run.route === "require") { + if (value.ownKeys === null) { + return [ + `${run.description}: the require result is ` + + `${describeValueType(value.type)} whose own keys could not be ` + + `listed, not one whose own enumerable properties are exactly ` + + `"defineConfig" ${EXPORTS_CITATION}`, + ]; + } + const problems: string[] = []; + const unread = value.ownKeys.filter((key) => key.enumerable === null); + if (unread.length > 0) { + problems.push( + `${run.description}: whether the require result's own properties ` + + `${describeKeys(unread)} are enumerable could not be read ` + + EXPORTS_CITATION, + ); + } + const enumerable = value.ownKeys.filter((key) => key.enumerable === true); + const [only] = enumerable; + if ( + enumerable.length !== 1 || + only?.kind !== "string" || + only.name !== "defineConfig" + ) { + problems.push( + `${run.description}: the require result's own enumerable ` + + `properties, string- and symbol-keyed alike, are ` + + `${describeKeys(enumerable)}, not exactly "defineConfig" ` + + EXPORTS_CITATION, + ); + } + return problems; + } + if (value.ownKeys === null) { + return [ + `${run.description}: the import namespace is ` + + `${describeValueType(value.type)} whose own keys could not be listed ` + + EXPORTS_CITATION, + ]; + } + const strings = value.ownKeys.filter((key) => key.kind === "string"); + const [only] = strings; + return strings.length === 1 && only?.name === "defineConfig" + ? [] + : [ + `${run.description}: the import namespace's own string-keyed ` + + `properties are ${describeKeys(strings)}, not exactly ` + + `"defineConfig" ${EXPORTS_CITATION}`, + ]; +} + +/** + * T7.6-6(b) on `run` (module header): `defineConfig` a function, and each + * identity case returning what it must by SameValue. Each problem in words, + * led by the run's description; none where it holds. + */ +export function identityProblems(run: LoadedModuleRun): string[] { + const fault = readingFault(run); + if (fault !== null) { + return [`${run.description}: ${fault} ${IDENTITY_CITATION}`]; + } + return run.report.calls.results + .filter( + (result) => + IDENTITY_CASES.includes(result.case) && + result.outcome !== "returned-argument", + ) + .map( + (result) => + `${run.description}: ${describeCallResult(result)}, compared by ` + + `SameValue ${IDENTITY_CITATION}`, + ); +} + +/** + * T7.6-6(c) on `run` (module header): the call with the two recording + * Proxies returning the first, no trap of either invoked through the run's + * end, and the call with a frozen object returning it without a throw. Each + * problem in words, led by the run's description; none where it holds. + */ +export function examinationProblems(run: LoadedModuleRun): string[] { + const fault = readingFault(run); + if (fault !== null) { + return [`${run.description}: ${fault} ${EXAMINATION_CITATION}`]; + } + const problems = run.report.calls.results + .filter( + (result) => + !IDENTITY_CASES.includes(result.case) && + result.outcome !== "returned-argument", + ) + .map( + (result) => + `${run.description}: ${describeCallResult(result)} ` + + EXAMINATION_CITATION, + ); + const { traps } = run.report.calls; + if (traps.length > 0) { + const invoked = traps.map( + (invocation) => `${invocation.trap} on the ${invocation.proxy} Proxy`, + ); + problems.push( + `${run.description}: ${describeCallCase("proxies")}, yet its Proxies' ` + + `handlers ran ${String(traps.length)} trap(s) through the run's end ` + + `— ${invoked.join(", ")} — where none may run ${EXAMINATION_CITATION}`, + ); + } + return problems; +} + +/** + * §7.6 Pairing on `run` (module header): an absence a runtime arm asserts + * counts only where the run loaded the module and saw `defineConfig` return + * its argument, here in every one of T7.6-6's calls. The problem in words, + * led by the run's description, or null where the pairing holds. + */ +export function pairingProblem(run: LoadedModuleRun): string | null { + const fault = readingFault(run); + const unmet = + fault === null + ? run.report.calls.results + .filter((result) => result.outcome !== "returned-argument") + .map((result) => describeCallResult(result)) + : [fault]; + if (unmet.length === 0) return null; + return ( + `${run.description}: no absence counts in this run, which never saw ` + + `defineConfig return its argument in every one of T7.6-6's calls — ` + + `${unmet.join("; ")} (TEST-SPEC §7.6 Pairing: an absence a runtime arm ` + + `asserts counts only where the same run loaded the module and saw ` + + `defineConfig return its argument)` + ); +} + +// --------------------------------------------------------------------------- +// The output oracle (T7.6-7(a)) +// --------------------------------------------------------------------------- + +/** A release's printed form of warnings (module header), learned from it. */ +export interface WarningForm { + /** The release whose form this is. */ + readonly version: string; + /** + * The hint line the release appends to the first warning it prints: to a + * `DeprecationWarning`, and to any other. + */ + readonly hints: { readonly deprecation: string; readonly other: string }; +} + +/** A rendering of a run's warnings, or why the oracle cannot render them. */ +export type WarningRendering = + | { readonly ok: true; readonly text: string } + | { readonly ok: false; readonly problem: string }; + +/** A warning's type and message as the release joins them (module header). */ +function joinedText(name: string, message: string): string { + if (name === "") return message; + if (message === "") return name; + return `${name}: ${message}`; +} + +/** + * The head of `warning`'s printed form (module header) — all of it but the + * hint line and the closing line feed — or null where the oracle cannot + * render it. + */ +function printedHead(warning: CapturedWarning, pid: number): string | null { + if ( + warning.type !== "object" || + warning.name === null || + warning.message === null + ) { + return null; + } + const code = + warning.code !== null && warning.code !== "" ? `[${warning.code}] ` : ""; + const detail = warning.detail === null ? "" : `${LF}${warning.detail}`; + return ( + `(node:${String(pid)}) ${code}` + + `${joinedText(warning.name, warning.message)}${detail}` + ); +} + +/** A captured warning, in words. */ +function describeCapturedWarning(warning: CapturedWarning): string { + const code = warning.code === null ? "" : `[${warning.code}] `; + const name = warning.name ?? `a value of type ${warning.type}`; + return warning.message === null + ? `${code}${name}` + : `${code}${name}: ${JSON.stringify(warning.message)}`; +} + +/** + * The release's printed forms of `warnings`, in order, as a process `pid` + * prints them under `form` (module header). + */ +export function renderWarnings( + warnings: readonly CapturedWarning[], + pid: number, + form: WarningForm, +): WarningRendering { + let text = ""; + for (const [index, warning] of warnings.entries()) { + const head = printedHead(warning, pid); + if (head === null) { + return { + ok: false, + problem: + `the run's warning ${String(index + 1)}, ` + + `${describeCapturedWarning(warning)}, is no object whose name and ` + + `message are strings, as the runtime's own warnings are, so the ` + + `oracle knows no printed form of it`, + }; + } + const hint = + index === 0 + ? `${LF}${warning.name === "DeprecationWarning" ? form.hints.deprecation : form.hints.other}` + : ""; + text += `${head}${hint}${LF}`; + } + return { ok: true, text }; +} + +/** + * The first frame of `warning`'s stack (module header): the first line after + * the stack's head — its type and message as the release joins them — that + * is a frame, an indented line beginning `at `; after the first line where + * the stack begins otherwise; null where there is none. + */ +export function warningFirstFrame(warning: CapturedWarning): string | null { + const { stack } = warning; + if (stack === null) return null; + const head = + warning.name !== null && warning.message !== null + ? joinedText(warning.name, warning.message) + : null; + let rest: string; + if ( + head !== null && + stack.startsWith(head) && + (stack.length === head.length || stack.charAt(head.length) === LF) + ) { + rest = stack.slice(head.length); + } else { + const firstBreak = stack.indexOf(LF); + rest = firstBreak === -1 ? "" : stack.slice(firstBreak); + } + for (const line of rest.split(LF)) { + const trimmed = line.trimStart(); + if (trimmed.length < line.length && trimmed.startsWith("at ")) { + return line; + } + } + return null; +} + +/** + * `warning`'s first frame where it names one of the package's files — a + * path under the placement or the copy it reaches, by path or file URL — + * or null. + */ +export function packageFrame( + warning: CapturedWarning, + placement: Placement, +): string | null { + const frame = warningFirstFrame(warning); + if (frame === null) return null; + for (const root of new Set([placement.path, placement.copy])) { + if ( + frame.includes(`${root}${path.sep}`) || + frame.includes(`${pathToFileURL(root).href}/`) + ) { + return frame; + } + } + return null; +} + +/** + * T7.6-7(a) on `run` under its release's `form` (module header): the + * pairing; standard output empty; standard error exactly the release's + * printed forms of the warnings the run emits, in order; and no warning's + * stack beginning in the package's files. Each problem in words, led by + * the run's description; none where it holds. + */ +export function outputProblems( + run: LoadedModuleRun, + form: WarningForm, +): string[] { + if (form.version !== run.release.version) { + throw new Error( + `module channel: the printed form learned from the Node.js release ` + + `${form.version} judges no run on ${run.release.version} ` + + `(${run.description})`, + ); + } + const problems: string[] = []; + const pairing = pairingProblem(run); + if (pairing !== null) problems.push(pairing); + if (run.result.stdoutBytes.length > 0) { + problems.push( + `${run.description}: standard output is not empty: ` + + `${quoteStream(run.result.stdout)} ${OUTPUT_CITATION}`, + ); + } + const { warnings, pid } = run.report; + const rendering = renderWarnings(warnings, pid, form); + if (!rendering.ok) { + problems.push( + `${run.description}: ${rendering.problem}; standard error ` + + `${quoteStream(run.result.stderr)} ${OUTPUT_CITATION}`, + ); + } else if (!bytesEqual(run.result.stderrBytes, rendering.text)) { + problems.push( + `${run.description}: standard error is not exactly the release's ` + + `printed forms of the ${String(warnings.length)} warning(s) the run ` + + `emits, in order — ` + + describeByteDifference( + run.result.stderrBytes, + Buffer.from(rendering.text, "utf8"), + "standard error", + "printed forms", + ) + + ` — standard error ${quoteStream(run.result.stderr)}, the printed ` + + `forms ${quoteStream(rendering.text)} ${OUTPUT_CITATION}`, + ); + } + warnings.forEach((warning, index) => { + const frame = packageFrame(warning, run.placement); + if (frame !== null) { + problems.push( + `${run.description}: the run's warning ${String(index + 1)}, ` + + `${describeCapturedWarning(warning)}, begins its stack in the ` + + `package's files, its first frame ${JSON.stringify(frame)}: a ` + + `warning the module emits, which the runtime's own loading never ` + + `does ${OUTPUT_CITATION}`, + ); + } + }); + return problems; +} + +/** + * {@link outputProblems} under the form learned from `run`'s release + * ({@link learnWarningForm}). + */ +export async function runtimeOutputProblems( + run: LoadedModuleRun, +): Promise<string[]> { + return outputProblems(run, await learnWarningForm(run.release)); +} + +// --------------------------------------------------------------------------- +// T7.6-7(b), (c), and (e) +// --------------------------------------------------------------------------- + +/** SPEC 7.6 Runtime's effect clause, which T7.6-7(c)'s problems cite. */ +const STATE_CITATION = + "(TEST-SPEC T7.6-7(c); SPEC 7.6 Runtime: beyond the runtime's own " + + "resolution of the specifier and loading of the package's files, neither " + + "loading the module nor calling defineConfig has any effect — no change " + + "to the global object or to any other state of the process)"; + +/** SPEC 7.6 Runtime's effect clause, which T7.6-7(b)'s problems cite. */ +const WRITES_CITATION = + "(TEST-SPEC T7.6-7(b); SPEC 7.6 Runtime: beyond the runtime's own " + + "resolution of the specifier and loading of the package's files, neither " + + "loading the module nor calling defineConfig has any effect — no " + + "filesystem write)"; + +/** SPEC 7.6 Runtime's effect clause, which T7.6-7(e)'s problems cite. */ +const FIFOS_CITATION = + "(TEST-SPEC T7.6-7(e), S-3; SPEC 7.6 Runtime: beyond the runtime's own " + + "resolution of the specifier and loading of the package's files, neither " + + "loading the module nor calling defineConfig has any effect — no " + + "filesystem read outside the package)"; + +const STATE_OBSERVATION_DESCRIPTIONS: Readonly< + Record<StateObservationName, string> +> = { + "global-object": "the global object's own properties", + "built-ins": "a global built-in object's own properties", + extensibility: "an observed object's extensibility", + prototype: "an observed object's prototype", + process: "process's own properties", + environment: "process.env", + title: "the process title", + "working-directory": "the working directory", + "exit-code": "process.exitCode", + "stream-write": "the write a standard stream resolves to", + listeners: "the listeners registered on process", + "timers-and-handles": "the pending timers and handles", +}; + +/** One of T7.6-7(c)'s observations, in words. */ +export function describeStateObservation(name: StateObservationName): string { + return STATE_OBSERVATION_DESCRIPTIONS[name]; +} + +/** + * T7.6-7(c) on `run` (module header): the pairing, and the process state + * unchanged across the load and the calls, as the bootstrap compared it. + * Each problem in words, led by the run's description; none where it + * holds. + */ +export function stateProblems(run: LoadedModuleRun): string[] { + const problems: string[] = []; + const pairing = pairingProblem(run); + if (pairing !== null) problems.push(pairing); + const { changes, omitted } = run.report.state; + for (const change of changes) { + problems.push( + `${run.description}: ${describeStateObservation(change.observation)} ` + + `changed across the load and the calls — ${change.subject}: ` + + `${change.detail} ${STATE_CITATION}`, + ); + } + if (omitted > 0) { + problems.push( + `${run.description}: the process state differs in ${String(omitted)} ` + + `more way(s) beyond those listed ${STATE_CITATION}`, + ); + } + return problems; +} + +/** `run`'s effects, which a run must have been asked to observe. */ +function requireEffects(run: ModuleRun, reader: string): RunEffects { + if (run.effects === undefined) { + throw new Error( + `module channel: ${reader} reads T7.6-7(b) and (e)'s observations, ` + + `which ${run.description} was not asked to make ` + + `(ModuleRunRequest.effects)`, + ); + } + return run.effects; +} + +/** A place, in words, with its root. */ +function describePlace(writes: PlaceWrites): string { + return writes.place === "staging" + ? `the staging (${writes.root})` + : writes.place === "working directory" + ? `the run's working directory (${writes.root})` + : `the run's ${writes.place} (${writes.root})`; +} + +/** + * T7.6-7(b) on `run`, a run observing its effects (module header): the + * pairing, and no entry created, modified, or removed in the staging, the + * working directory, `HOME`, or `TMPDIR`. Each problem in words, led by + * the run's description; none where it holds. + */ +export function writeProblems(run: LoadedModuleRun): string[] { + const effects = requireEffects(run, "writeProblems"); + const problems: string[] = []; + const pairing = pairingProblem(run); + if (pairing !== null) problems.push(pairing); + for (const writes of effects.writes) { + for (const change of writes.changes) { + problems.push( + `${run.description}: in ${describePlace(writes)}, ` + + `${JSON.stringify(change.path)} was ${change.change}: ` + + `${change.detail} ${WRITES_CITATION}`, + ); + } + } + return problems; +} + +/** + * T7.6-7(e) on `run`, a run observing its effects (module header): the + * pairing, and each FIFO still a FIFO in place — and, the run having ended + * within its guard, unopened. Each problem in words, led by the run's + * description; none where it holds. + */ +export function fifoProblems(run: LoadedModuleRun): string[] { + const effects = requireEffects(run, "fifoProblems"); + const problems: string[] = []; + const pairing = pairingProblem(run); + if (pairing !== null) problems.push(pairing); + for (const fifo of effects.fifos) { + if (fifo.found === "FIFO") continue; + problems.push( + `${run.description}: the FIFO ${fifo.path} is ` + + (fifo.found === null ? "gone" : `now ${withArticle(fifo.found)}`) + + `, no longer a FIFO in place ${FIFOS_CITATION}`, + ); + } + return problems; +} + +// --------------------------------------------------------------------------- +// Learning each release's printed form (module header) +// --------------------------------------------------------------------------- + +/** One warning a calibration run emits through `process.emitWarning`. */ +export interface CalibrationWarning { + /** Its type, the `type` option. */ + readonly type: string; + /** Its code, the `code` option; null for none. */ + readonly code: string | null; + readonly message: string; + /** Its detail, the `detail` option; null for none. */ + readonly detail: string | null; +} + +/** Which kind of warning a calibration run emits first (module header). */ +export type CalibrationKind = "other" | "deprecation" | "experimental"; + +/** The warnings each calibration run emits, in order (module header). */ +export const WARNING_CALIBRATIONS: Readonly< + Record<CalibrationKind, readonly CalibrationWarning[]> +> = Object.freeze({ + other: Object.freeze([ + { + type: "XspecCalibrationWarning", + code: "XSPEC_CALIBRATION", + message: `xspec calibration: a message${LF}over two lines`, + detail: `its detail${LF}over two lines`, + }, + { + type: "Warning", + code: null, + message: "xspec calibration: a warning with no code and no detail", + detail: null, + }, + { + type: "DeprecationWarning", + code: "XSPEC_CALIBRATION_DEPRECATION", + message: "xspec calibration: a later deprecation", + detail: null, + }, + ]), + deprecation: Object.freeze([ + { + type: "DeprecationWarning", + code: "XSPEC_CALIBRATION_DEPRECATION", + message: "xspec calibration: a first deprecation", + detail: "its detail", + }, + { + type: "ExperimentalWarning", + code: null, + message: `xspec calibration: a later experimental feature${LF}over two lines`, + detail: null, + }, + ]), + experimental: Object.freeze([ + { + type: "ExperimentalWarning", + code: null, + message: `xspec calibration: a first experimental feature${LF}over two lines`, + detail: null, + }, + { + type: "XspecCalibrationWarning", + code: "XSPEC_CALIBRATION", + message: "xspec calibration: a later warning", + detail: `its detail${LF}over two lines`, + }, + ]), +}); + +/** The forms learned in this process, by release (module header). */ +const warningForms = new Map<string, Promise<WarningForm>>(); + +/** + * The printed form of warnings on `release`, learned from the release + * itself (module header): once per release in a process, a learning that + * fails being forgotten. Rejects with a harness error where the release + * prints a warning in a form the oracle does not know. + */ +export function learnWarningForm(release: NodeRelease): Promise<WarningForm> { + const key = `${release.version}${LF}${release.executable}`; + const known = warningForms.get(key); + if (known !== undefined) return known; + const learning = calibrateWarningForm(release); + warningForms.set(key, learning); + learning.catch(() => { + if (warningForms.get(key) === learning) warningForms.delete(key); + }); + return learning; +} + +/** One calibration run's observations. */ +interface CalibrationRun { + /** The run, in words, leading its harness errors. */ + readonly context: string; + readonly pid: number; + /** The warnings delivered to its listener: exactly those it emitted. */ + readonly warnings: readonly CapturedWarning[]; + /** Its standard error, as UTF-8. */ + readonly stderr: string; +} + +async function calibrateWarningForm( + release: NodeRelease, +): Promise<WarningForm> { + const other = await runCalibration(release, "other"); + const deprecation = await runCalibration(release, "deprecation"); + const experimental = await runCalibration(release, "experimental"); + const form: WarningForm = Object.freeze({ + version: release.version, + hints: Object.freeze({ + deprecation: learnHint(deprecation), + other: learnHint(other), + }), + }); + for (const calibration of [other, deprecation, experimental]) { + confirmCalibration(form, calibration); + } + return form; +} + +/** + * Run the calibration script on `release` (module header), emitting + * `kind`'s warnings, and read what it printed and what its listener was + * delivered. Every departure from a clean run is a harness error. + */ +async function runCalibration( + release: NodeRelease, + kind: CalibrationKind, +): Promise<CalibrationRun> { + const context = + `learning how the Node.js release ${release.version} prints warnings ` + + `(the calibration emitting ${kind === "other" ? "a warning of its own type" : `a ${kind} warning`} first)`; + const root = await makeScratchDirectory(WARNING_CALIBRATION_PREFIX, context); + try { + const script = path.join(root, CALIBRATION_NAME); + const reportPath = path.join(root, REPORT_NAME); + const home = path.join(root, HOME_NAME); + const tmp = path.join(root, TMPDIR_NAME); + const cwd = path.join(root, WORK_NAME); + await guardStep( + `making the calibration's directories and script under ${root} ` + + `(${context})`, + async () => { + for (const directory of [home, tmp, cwd]) { + await fsp.mkdir(directory); + } + await fsp.writeFile(script, await fsp.readFile(CALIBRATION_SOURCE), { + flag: "wx", + }); + }, + ); + const binding = releaseBinding(release); + const emitted = WARNING_CALIBRATIONS[kind]; + const result = await runProduct(binding, { + cwd, + argv: [script, reportPath, JSON.stringify(emitted)], + env: exactEnvironmentOverrides(binding, moduleRunEnvironment(home, tmp)), + timeoutMs: MODULE_RUN_TIMEOUT_MS, + }); + const harnessError = (problem: string): Error => + new Error( + `harness error (H-11): ${context}: ${problem}; the process ` + + `${describeEnding(result)}, ${describeStreams(result)}`, + ); + if (result.exitCode !== 0 || result.signal !== null) { + throw harnessError("the calibration did not exit with code 0 on its own"); + } + if (result.stdoutBytes.length > 0) { + throw harnessError("the calibration wrote to standard output"); + } + const bytes = await readReportBytes(reportPath, context); + if (bytes === null) throw harnessError("the calibration left no report"); + const decoding = guardSyncStep( + `decoding the calibration's report (${context})`, + () => decodeCalibrationReport(bytes), + ); + if (!decoding.ok) { + throw harnessError(`its report is malformed (${decoding.problem})`); + } + const { pid, warnings } = decoding; + const delivered = warnings.map((warning) => ({ + type: warning.name, + code: warning.code, + message: warning.message, + detail: warning.detail, + })); + const asEmitted = + warnings.length === emitted.length && + warnings.every((warning, index) => { + const wanted = emitted[index]; + return ( + wanted !== undefined && + warning.type === "object" && + warning.name === wanted.type && + warning.code === wanted.code && + warning.message === wanted.message && + warning.detail === wanted.detail + ); + }); + if (!asEmitted) { + throw harnessError( + `the warnings its listener was delivered, ` + + `${JSON.stringify(delivered)}, are not those it emitted, ` + + JSON.stringify(emitted), + ); + } + const stderr = guardSyncStep( + `decoding the calibration's standard error (${context})`, + () => { + try { + return new TextDecoder("utf-8", { fatal: true }).decode( + result.stderrBytes, + ); + } catch { + return null; + } + }, + ); + if (stderr === null) throw harnessError("its standard error is no UTF-8"); + return { context, pid, warnings, stderr }; + } finally { + await removeRunDirectory(root, context); + } +} + +/** A calibration report's decoding: its members, or what makes it malformed. */ +type CalibrationDecoding = + | { + readonly ok: true; + readonly pid: number; + readonly warnings: readonly CapturedWarning[]; + } + | { readonly ok: false; readonly problem: string }; + +/** + * Decode a calibration report's bytes: UTF-8 JSON holding exactly the + * protocol, the process identifier, and the warnings delivered, each read + * as a module run's report reads one. + */ +function decodeCalibrationReport(bytes: Uint8Array): CalibrationDecoding { + let parsed: unknown; + try { + parsed = JSON.parse( + new TextDecoder("utf-8", { fatal: true }).decode(bytes), + ); + } catch (error) { + return { + ok: false, + problem: `its bytes are no UTF-8 JSON (${describeError(error)})`, + }; + } + try { + const record = readRecord(parsed, "the calibration's report", [ + "pid", + "protocol", + "warnings", + ]); + if (record["protocol"] !== WARNING_CALIBRATION_PROTOCOL) { + throw new ReportShapeError( + `its protocol is ${JSON.stringify(record["protocol"])}, not ` + + JSON.stringify(WARNING_CALIBRATION_PROTOCOL), + ); + } + const pid = record["pid"]; + if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0) { + throw new ReportShapeError( + `its pid ${JSON.stringify(pid)} is no positive integer`, + ); + } + const warnings = readArray(record["warnings"], "warnings").map( + (warning, index) => readWarning(warning, `warnings[${String(index)}]`), + ); + return { ok: true, pid, warnings }; + } catch (error) { + if (error instanceof ReportShapeError) { + return { ok: false, problem: error.message }; + } + throw error; + } +} + +/** + * The hint line `calibration`'s release appends to its first warning: the + * line after that warning's form at the head of its standard error. + */ +function learnHint(calibration: CalibrationRun): string { + const [first] = calibration.warnings; + const head = first === undefined ? null : printedHead(first, calibration.pid); + if (head === null) { + throw calibrationError(calibration, "its first warning cannot be rendered"); + } + const lead = `${head}${LF}`; + const { stderr } = calibration; + if (!stderr.startsWith(lead)) { + throw calibrationError( + calibration, + `its standard error does not begin with the first warning's form ` + + `${JSON.stringify(lead)}, so the release prints warnings in a form ` + + `the oracle does not know`, + ); + } + const end = stderr.indexOf(LF, lead.length); + if (end <= lead.length) { + throw calibrationError( + calibration, + "no hint line follows the first warning's form", + ); + } + return stderr.slice(lead.length, end); +} + +/** + * Require `calibration`'s whole standard error to be what `form` renders + * from the warnings its listener was delivered. + */ +function confirmCalibration( + form: WarningForm, + calibration: CalibrationRun, +): void { + const rendering = renderWarnings(calibration.warnings, calibration.pid, form); + if (!rendering.ok) throw calibrationError(calibration, rendering.problem); + if (rendering.text !== calibration.stderr) { + throw calibrationError( + calibration, + `its standard error is not what the learned form renders from its ` + + `warnings, so the release prints warnings in a form the oracle does ` + + `not know — ` + + describeByteDifference( + Buffer.from(calibration.stderr, "utf8"), + Buffer.from(rendering.text, "utf8"), + "standard error", + "rendered", + ), + ); + } +} + +function calibrationError(calibration: CalibrationRun, problem: string): Error { + return new Error( + `harness error (H-11): ${calibration.context}: ${problem}; standard ` + + `error ${quoteStream(calibration.stderr)}`, + ); +} + +// --------------------------------------------------------------------------- +// Files +// --------------------------------------------------------------------------- + +/** + * Write the importing module at `importingFile`, or find it there already, + * byte-equal (module header); any other occupant is a `HarnessStagingError`. + * A preparation writing the same file meanwhile is found byte-equal + * likewise once its write is whole; one caught mid-write is refused, so + * the runs of one route in one directory are prepared one after another + * (their launches may overlap). + */ +async function writeImportingModule( + staging: ModuleStaging, + importingFile: string, + text: string, + context: string, +): Promise<void> { + const target = staging.path(importingFile); + if ((await readImportingModule(target, context)) === "absent") { + refuseWhileObserved(staging, `the importing module ${target}`, context); + try { + await staging.writeFile(importingFile, text); + return; + } catch (error) { + if ((error as NodeJS.ErrnoException | undefined)?.code !== "EEXIST") { + throw error; + } + } + } + const existing = await readImportingModule(target, context); + if ( + existing === "absent" || + existing === "other" || + !existing.equals(Buffer.from(text)) + ) { + throw new HarnessStagingError( + MODE, + target, + `${context}: the importing module's place ${target} is occupied by ` + + `something other than the importing module its route writes there ` + + `(TEST-SPEC T7.6-6: a harness-written importing module in the ` + + `importing file's place)`, + ); + } +} + +/** + * The launches observing their effects in flight, by staging (module + * header): while one is, nothing is written into its staging for another + * run. + */ +const observedLaunches = new WeakMap<ModuleStaging, number>(); + +/** + * Refuse, as a usage error, to write `what` into `staging` while a run + * observing its effects is launched on it (module header): that run's + * comparison of the staging would charge the write to its module. + */ +function refuseWhileObserved( + staging: ModuleStaging, + what: string, + context: string, +): void { + if ((observedLaunches.get(staging) ?? 0) === 0) return; + throw new Error( + `module channel: ${what} would be written into the staging ` + + `${staging.root} while a run observing its effects is launched on it, ` + + `whose comparison of the staging would charge the write to its module ` + + `(TEST-SPEC T7.6-7(b)); prepare every run of a staging before ` + + `launching one that observes its effects, or run them one after ` + + `another (${context})`, + ); +} + +/** What occupies an importing module's place: its bytes, if a plain file. */ +async function readImportingModule( + target: string, + context: string, +): Promise<Buffer | "absent" | "other"> { + return guardStep( + `reading what occupies ${target} (${context})`, + async (): Promise<Buffer | "absent" | "other"> => { + try { + const stats = await fsp.lstat(target); + return stats.isFile() ? await fsp.readFile(target) : "other"; + } catch (error) { + if (isAbsence(error)) return "absent"; + throw error; + } + }, + ); +} + +/** + * A fresh directory named with `prefix` under the OS temporary directory, + * physical: a run's own, or a warning calibration's. + */ +async function makeScratchDirectory( + prefix: string, + context: string, +): Promise<string> { + const made = await guardStep( + `creating a directory under ${os.tmpdir()} (${context})`, + () => fsp.mkdtemp(path.join(os.tmpdir(), prefix)), + ); + try { + return await guardStep( + `reading the physical path of the run directory ${made} (${context})`, + () => fsp.realpath(made), + ); + } catch (error) { + await removeRunDirectory(made, context); + throw error; + } +} + +/** Remove a run directory, a directory the run made unwritable first made writable. */ +async function removeRunDirectory( + directory: string, + context: string, +): Promise<void> { + await guardStep( + `removing the run directory ${directory} (${context})`, + async () => { + try { + await fsp.rm(directory, { + recursive: true, + force: true, + maxRetries: 2, + }); + } catch { + await makeDirectoriesWritable(directory); + await fsp.rm(directory, { + recursive: true, + force: true, + maxRetries: 2, + }); + } + }, + ); +} + +/** Best-effort: give every directory under `directory` owner access. */ +async function makeDirectoriesWritable(directory: string): Promise<void> { + await fsp.chmod(directory, 0o700).catch(() => undefined); + const entries = await fsp + .readdir(directory, { withFileTypes: true }) + .catch(() => []); + for (const entry of entries) { + if (entry.isDirectory()) { + await makeDirectoriesWritable(path.join(directory, entry.name)); + } + } +} + +/** + * A place's entries (module header): `root` itself, under `""`, and every + * entry under it, each by its kind — a plain file with its bytes (null + * where its mode refuses the read), a directory (whether it lists), a + * symbolic link with its target, never followed, and a FIFO, a socket, or a + * device by its kind alone, never opened (TEST-SPEC T7.6-7(b), S-3). An + * absent root yields no entry. One harness step under its own guard. + */ +export async function snapshotPlace( + root: string, + context: string, +): Promise<PlaceSnapshot> { + return guardStep(`snapshotting ${root} (${context})`, async () => { + const entries = new Map<string, PlaceEntry>(); + await recordPlaceEntry(Buffer.from(root), null, entries); + return entries; + }); +} + +/** Record the entry at `abs` (`rel` in the place; null for its root), and those under it. */ +async function recordPlaceEntry( + abs: Buffer, + rel: Buffer | null, + entries: Map<string, PlaceEntry>, +): Promise<void> { + let stats: Stats; + try { + stats = await fsp.lstat(abs); + } catch (error) { + if (isAbsence(error)) return; + throw error; + } + const key = rel === null ? "" : rel.toString("latin1"); + if (stats.isFile()) { + let bytes: Buffer | null; + try { + bytes = await fsp.readFile(abs); + } catch (error) { + if (!isRefusal(error)) throw error; + bytes = null; + } + entries.set(key, { kind: "plain file", bytes }); + return; + } + if (stats.isSymbolicLink()) { + entries.set(key, { + kind: "symbolic link", + target: await fsp.readlink(abs, { encoding: "buffer" }), + }); + return; + } + if (!stats.isDirectory()) { + entries.set(key, { kind: otherKind(stats) }); + return; + } + let names: Buffer[] | null; + try { + names = (await fsp.readdir(abs, { encoding: "buffer" })).sort( + Buffer.compare, + ); + } catch (error) { + if (!isRefusal(error)) throw error; + names = null; + } + entries.set(key, { kind: "directory", listed: names !== null }); + for (const name of names ?? []) { + await recordPlaceEntry( + Buffer.concat([abs, SLASH_BYTES, name]), + rel === null ? name : Buffer.concat([rel, SLASH_BYTES, name]), + entries, + ); + } +} + +/** + * How a place changed between two snapshots (module header), entry by + * entry in bytewise path order: an entry created, removed, or modified — + * its kind, a plain file's bytes, a symbolic link's target, or whether a + * plain file reads or a directory lists. + */ +export function comparePlaceSnapshots( + before: PlaceSnapshot, + after: PlaceSnapshot, +): PlaceChange[] { + const keys = [...new Set([...before.keys(), ...after.keys()])].sort(); + const changes: PlaceChange[] = []; + for (const key of keys) { + const was = before.get(key); + const now = after.get(key); + const shown = key === "" ? "." : displaySnapshotPath(key); + if (was === undefined && now !== undefined) { + changes.push({ + path: shown, + change: "created", + detail: `it is ${describePlaceEntry(now)}`, + }); + } else if (was !== undefined && now === undefined) { + changes.push({ + path: shown, + change: "removed", + detail: `it was ${describePlaceEntry(was)}`, + }); + } else if (was !== undefined && now !== undefined) { + const detail = placeEntryDifference(was, now); + if (detail !== null) { + changes.push({ path: shown, change: "modified", detail }); + } + } + } + return changes; +} + +/** An entry of a place, in words. */ +function describePlaceEntry(entry: PlaceEntry): string { + switch (entry.kind) { + case "plain file": + return entry.bytes === null + ? "a plain file whose bytes could not be read" + : `a plain file of ${String(entry.bytes.length)} byte(s)`; + case "directory": + return entry.listed + ? "a directory" + : "a directory whose listing was refused"; + case "symbolic link": + return ( + `a symbolic link to ` + + JSON.stringify(Buffer.from(entry.target).toString("utf8")) + ); + default: + return withArticle(entry.kind); + } +} + +/** How two entries at one path differ, in words; null where they do not. */ +function placeEntryDifference(was: PlaceEntry, now: PlaceEntry): string | null { + if (was.kind !== now.kind) { + return `${describePlaceEntry(was)} became ${describePlaceEntry(now)}`; + } + if (was.kind === "plain file" && now.kind === "plain file") { + if (was.bytes === null || now.bytes === null) { + if (was.bytes === now.bytes) return null; + return was.bytes === null + ? "its bytes, which could not be read before, now can be" + : "its bytes can no longer be read"; + } + return bytesEqual(was.bytes, now.bytes) + ? null + : `its bytes changed — ${describeByteDifference(was.bytes, now.bytes, "before", "after")}`; + } + if (was.kind === "directory" && now.kind === "directory") { + if (was.listed === now.listed) return null; + return now.listed + ? "its listing, refused before, now succeeds" + : "its listing is now refused"; + } + if (was.kind === "symbolic link" && now.kind === "symbolic link") { + return bytesEqual(was.target, now.target) + ? null + : `its target changed from ` + + `${JSON.stringify(Buffer.from(was.target).toString("utf8"))} to ` + + JSON.stringify(Buffer.from(now.target).toString("utf8")); + } + return null; +} + +/** What occupies `abs`, by its kind, read without following or opening it; null for nothing. */ +async function readEntryKind(abs: string): Promise<PlaceEntryKind | null> { + try { + return entryKind(await fsp.lstat(abs)); + } catch (error) { + if (isAbsence(error)) return null; + throw error; + } +} + +/** An entry's kind, from its `lstat`. */ +function entryKind(stats: Stats): PlaceEntryKind { + if (stats.isFile()) return "plain file"; + if (stats.isDirectory()) return "directory"; + if (stats.isSymbolicLink()) return "symbolic link"; + return otherKind(stats); +} + +/** The kind of an entry that is no plain file, directory, or symbolic link. */ +function otherKind(stats: Stats): OtherPlaceEntryKind { + if (stats.isFIFO()) return "FIFO"; + if (stats.isSocket()) return "socket"; + if (stats.isCharacterDevice()) return "character device"; + if (stats.isBlockDevice()) return "block device"; + return "entry of another kind"; +} + +/** An entry's kind with its indefinite article. */ +function withArticle(kind: PlaceEntryKind): string { + return kind === "entry of another kind" ? `an ${kind}` : `a ${kind}`; +} + +/** + * The report's bytes, or null where none was written. Anything at the path + * but a plain file is no report either: it is never opened. + */ +async function readReportBytes( + reportPath: string, + description: string, +): Promise<Buffer | null> { + return guardStep(`reading the report of ${description}`, async () => { + try { + const stats = await fsp.lstat(reportPath); + return stats.isFile() ? await fsp.readFile(reportPath) : null; + } catch (error) { + if (isAbsence(error)) return null; + throw error; + } + }); +} + +function isAbsence(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException | undefined)?.code; + return code === "ENOENT"; +} + +/** Whether `error` is an entry's mode refusing a read or a listing. */ +function isRefusal(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException | undefined)?.code; + return code === "EACCES" || code === "EPERM"; +} + +function describeError(error: unknown): string { + if (error instanceof Error) { + const code = (error as NodeJS.ErrnoException).code; + return typeof code === "string" + ? `${code}: ${error.message}` + : `${error.name}: ${error.message}`; + } + return String(error); +} diff --git a/test/helpers/module-channel-ts.ts b/test/helpers/module-channel-ts.ts new file mode 100644 index 00000000..16f9ad1f --- /dev/null +++ b/test/helpers/module-channel-ts.ts @@ -0,0 +1,1841 @@ +// The module channel's TypeScript driver (TEST-SPEC §7.6 *Covered setups*, +// *Verdict*, *Pairing*, *Placement*, H-1, H-2, S-3; SPEC 7.6 *Covered +// setups*, *Type contract*). Harness machinery only: this module never +// imports product code and starts no process. It type-checks files a test +// writes into the module channel's stagings (helpers/module-channel.ts) +// with the harness's own TypeScript 5.9.3 (`typescript-5.9.3`, the release +// SPEC 14.20 names). It is separate from H-2's consumer tooling +// (helpers/tooling.ts), whose two fixed configurations S-4 pins and which +// this module never serves: 7.6's setups are not H-2's. +// +// The matrix (`COVERED_SETUPS`, TEST-SPEC §7.6 Covered setups): the +// configuration file, the program's one root, named with each of `.ts`, +// `.mts`, `.cts`, and `.tsx` in each of the three projects +// (helpers/module-channel.ts `PROJECT_KINDS`), judged under each option set +// covering it — the fourteen strict defaults (`strict` on, with +// `moduleResolution` `node10` and `module` at its default; `node16` and +// `nodenext`, each with `module` `node16`, `node18`, `node20`, and +// `nodenext`; `bundler` with `module` `es2015`, `es2020`, `es2022`, +// `esnext`, and `preserve`) for every file, and the initialized-project set +// (exactly the options SPEC 7.6 lists, which release 5.9.3's `tsc --init` +// writes) for each file TypeScript compiles as an ES module (`.mts` in every +// project, `.ts` and `.tsx` in the ES-module one): 173 setups. Each set is +// spelled as a `tsconfig.json` spells it and converted by TypeScript's own +// option parser, and nothing else is set: every option a set does not name +// stays at the release's default for that set — `target`, which the release +// derives from `module`, included, and `skipLibCheck` off under the strict +// defaults — and no option of the driver's own is added (no `noEmit`, no +// `types`, no `lib`). A module-load self-check confirms the composition. +// +// Programs. A test stages its files through `stageCoveredFiles`, which +// writes each file's bytes once per extension its setups name, into the +// directory the caller names (for the canonical placement, the project +// directory holding `node_modules/N`), each under a fresh name, and, where +// the caller names the placement the files' imports reach, verifies Reach +// for each written file against it and the project kind +// (`ModuleStaging.verifyReach`) before any program exists. Each program +// takes the files by their physical paths as its roots; its compiler host +// is TypeScript's own (`ts.createCompilerHost`, as `tsc` uses), its current +// directory a directory inside the staging (the files' own unless the caller +// names another), and it writes nothing: no emit is ever asked for +// (declaration diagnostics need none), and the host's `writeFile` refuses. +// +// The program condition (SPEC 7.6 Covered setups, Program; TEST-SPEC §7.6 +// Placement): nothing enters the program but the root, TypeScript's +// libraries for the option set, and what the root's import declaration +// brings in — files of any kind, and the libraries they reference. It is +// read from TypeScript's own record of why each file is in the program (its +// include reasons, an internal of release 5.9.3 that +// test/self/module-channel-ts.test.ts pins): every file is a root the driver +// named; a library — the program's default library, or one a library or a +// brought-in file references — that is TypeScript's own, a file of the +// release's library directory, never one an installed package replaces +// (`@typescript/lib-es5`); or a file a root's real import brings in, and +// then any file such a file imports or references. Neither an automatic +// type directive (an `@types` package included automatically) nor an +// import TypeScript synthesizes (`react/jsx-runtime` under `jsx` +// `react-jsx`) admits a file. A violation is a `HarnessStagingError` (mode +// `module-channel`) raised before any verdict: where the condition fails, +// 7.6 promises nothing, and no arm asserts anything there. +// +// The verdicts (TEST-SPEC §7.6 Verdict). Every error-category diagnostic +// TypeScript reports for a file's program counts, in any of its files: +// options, global, syntactic, semantic, and — wherever the set turns +// `declaration` on, as the initialized set does — declaration diagnostics, +// all computed whatever the others hold (tsc's short-circuit aside). A file +// type-checks when there is none (`assertTypeChecks`); it fails to +// type-check when at least one is located in the configuration file, the +// program's other files aside. Pairing (TEST-SPEC §7.6 Pairing): a +// shape-violation arm passes only where its valid twin type-checks in the +// same setup and placement (`assertShapeViolation`), so a missing or stub +// package fails every arm and a permissive one the shape-violation arms. +// Verdict failures are diagnosed (`HarnessAssertionError`, H-8), naming the +// setup, the file, and every error. +// +// The export listing (TEST-SPEC T7.6-1, S-4), where a request asks for it +// (`listExports`): each verdict then carries the listing of the module +// TypeScript resolves the file's one import declaration to, read from that +// file's own program, so each setup through its own resolution (a package +// serving different declaration files to `import` and to `require`, or to +// different modes, read through each), and never probed by names the +// harness chooses: +// - the module: `checker.getSymbolAtLocation` on the import's specifier. +// Where TypeScript resolves the import to no module it reads declarations +// from (a stub package, a JavaScript file without declarations), the +// listing names no module and no export. +// - the compiler's listing of its exports (`checker.getExportsOfModule`): a +// declaration module holding neither an export list nor an export +// assignment exports each of its top-level declarations, an interface it +// never marks `export` among them, which this listing sees; export stars +// are followed; TypeScript's synthetic default is never among them, a +// declared default export (`default`) is. +// - where the module declares an export assignment (`export =`), the +// members of the assigned value that a named import binds: the +// properties of that value's type (`checker.getPropertiesOfType` over +// `checker.getTypeOfSymbol` of the assignment), the type TypeScript's +// named-import resolution reads each imported name from — a member keyed +// by a symbol or a private name aside, which no import name spells. Not +// the checker's internal `getExportsAndPropertiesOfModule`, which lists +// no member of a value typed as a class instance, a primitive, an array, +// or a tuple, though a named import binds them: a value typed by a class +// declaring `defineConfig` imports it by name. +// - each name's meanings, merged where both lists hold it: value, type, and +// namespace, as TypeScript's symbol flags give them through aliases (an +// alias TypeScript cannot resolve carrying every meaning, as TypeScript +// reads it). A value meaning reached only through `export type`, `import +// type`, or `export type *`, which no import may use as a value, is no +// value meaning (`value` false) and is reported as such +// (`typeOnlyValue`): for a module without an export assignment, read as +// TypeScript reads the module object's value members (the module type's +// `checker.getPropertyOfType` returning that very export); for an export +// assignment's members, never; and for the exports of its assigned value, +// from the declarations along each alias +// (`ts.isTypeOnlyImportOrExportDeclaration`). +// Each listing is computed once the program's diagnostics are all read, so +// it changes no verdict. +// +// Sharing, and why each kind is sound for what a case checks (TEST-SPEC +// §7.6 Covered setups: how the harness reaches each verdict is open wherever +// it drops no pairing and stays sound): +// - Parsed libraries serve many programs, as TEST-SPEC allows: each file of +// TypeScript's library directory is parsed once per target, module +// format, and JSDoc mode, and its bound tree reused. For a declaration +// file the binder reads no option but the target (its strict mode follows +// the file's own module indicator; its unreachable-code, fallthrough, +// label, and const-enum readings concern executable statements, which a +// library holds none of), and each program's checker keeps its own links. +// No other file is cached: a staging's files are read afresh by each +// program. +// - Batching: `judge` checks all of a setup's files in one program, whose +// roots they all are, and reads each file's verdict from the program's +// options and global diagnostics, its shared files' diagnostics, and its +// own diagnostics. Each case's own program holds exactly that root and +// those shared files, so the batch is sound wherever no root reaches past +// its own module — checked on the program, not assumed: every root is an +// external module declaring nothing global (no global augmentation, no +// UMD export) and augmenting no module (a `declare module "…"`, which +// changes that module, its exports included, for every file of the +// program), every root's import brings in the same files (its closure +// over TypeScript's include reasons), and no root's check raises a global +// diagnostic, which could belong to any of them. Where a check fails, each +// file is judged in a program of its own instead. Within one program +// TypeScript's diagnostics for a file do not depend on which other files +// were checked first: the language service checks files in any order. +// Each root's export listing reads its own import's resolution, which +// every root of a batch shares. +// - The libraries' own diagnostics are read once per option set and library +// list, wherever no file of the program but the libraries contributes to +// the global scope (every other file an external module declaring nothing +// global): a library declares only globals and refers only to globals, so +// its diagnostics are then a function of the option set and the library +// list alone. Where some file does contribute — a package declaring +// `declare global { … }`, whose errors can land inside a library — the +// libraries are checked in that program. Libraries are checked first, as +// tsc checks them, then the program's other shared files, then the roots. +// - `judgeUnshared` is the reference reading the self-test compares against: +// one root, nothing shared but parsed libraries, every diagnostic read as +// `ts.getPreEmitDiagnostics` reads it. +// +// TEST-SPEC S-3: each program's creation and check is one synchronous +// harness step under its own guard (`guardSyncStep`, the default step guard +// — measured costs in AGENTS.md), each program of its own beside a batch its +// own step; writing and Reach are asynchronous steps under theirs. A misuse +// of this module (an unknown setup, an empty file list, a duplicate label, +// an export listing asked of a file holding other than one import +// declaration) is a plain `Error`. + +import * as fs from "node:fs"; +import * as fsp from "node:fs/promises"; +import * as path from "node:path"; +import ts from "typescript-5.9.3"; +import { fail } from "./assertions.js"; +import type { + CommonJsTypeMember, + ModuleStaging, + Placement, + ProjectKind, +} from "./module-channel.js"; +import { PROJECT_KINDS } from "./module-channel.js"; +import type { StagingMode } from "./permissions.js"; +import { HarnessStagingError } from "./permissions.js"; +import { guardStep, guardSyncStep } from "./step-guards.js"; + +/** The staging mode every refusal of this module names. */ +const MODE: StagingMode = "module-channel"; + +const LF = String.fromCodePoint(0x0a); + +/** The extensions a covered configuration file is named with. */ +export type CoveredExtension = ".ts" | ".mts" | ".cts" | ".tsx"; + +/** Every covered extension, in TEST-SPEC §7.6's order. */ +export const COVERED_EXTENSIONS: readonly CoveredExtension[] = Object.freeze([ + ".ts", + ".mts", + ".cts", + ".tsx", +]); + +/** The two kinds of option set SPEC 7.6 names. */ +export type OptionSetKind = "strict defaults" | "initialized-project options"; + +/** A `tsconfig.json` option value, as a set spells it. */ +export type TsconfigValue = boolean | string | readonly string[]; + +/** One of 7.6's option sets (module header). */ +export interface CoveredOptionSet { + /** How every diagnosis names the set. */ + readonly name: string; + readonly kind: OptionSetKind; + /** The set exactly as `tsconfig.json` spells it: these options, no other. */ + readonly tsconfig: Readonly<Record<string, TsconfigValue>>; + /** The same options, converted by TypeScript 5.9.3's option parser. */ + readonly compilerOptions: Readonly<ts.CompilerOptions>; +} + +/** The base directory option conversion resolves path options against. */ +const CONVERSION_BASE = path.parse(process.cwd()).root; + +/** A diagnostic's message, its chain flattened. */ +function flatten(diagnostic: ts.Diagnostic): string { + return ts.flattenDiagnosticMessageText(diagnostic.messageText, LF); +} + +/** + * An option set from its `tsconfig.json` spelling, converted by TypeScript's + * own parser; a spelling it rejects, or one converting to options other + * than those spelled, throws at module load. + */ +function optionSet( + name: string, + kind: OptionSetKind, + tsconfig: Record<string, TsconfigValue>, +): CoveredOptionSet { + const { options, errors } = ts.convertCompilerOptionsFromJson( + tsconfig, + CONVERSION_BASE, + ); + if (errors.length > 0) { + throw new Error( + `module channel's TypeScript driver: TypeScript 5.9.3 rejects ${name} ` + + `(${errors.map(flatten).join("; ")})`, + ); + } + const spelled = Object.keys(tsconfig).sort(); + const converted = Object.keys(options).sort(); + if (spelled.join(",") !== converted.join(",")) { + throw new Error( + `module channel's TypeScript driver: ${name}, spelled with ` + + `${spelled.join(", ")}, converts to the options ` + + `${converted.join(", ")}: nothing but the set's own options is set`, + ); + } + return Object.freeze({ + name, + kind, + tsconfig: Object.freeze({ ...tsconfig }), + compilerOptions: Object.freeze(options), + }); +} + +/** + * The strict defaults' modes (SPEC 7.6 Covered setups): each + * `moduleResolution` value that finds installed packages, with every + * `module` value the mode requires — `undefined` for `module` at its + * default under `node10`. + */ +const STRICT_DEFAULT_MODES: readonly (readonly [ + string, + readonly (string | undefined)[], +])[] = [ + ["node10", [undefined]], + ["node16", ["node16", "node18", "node20", "nodenext"]], + ["nodenext", ["node16", "node18", "node20", "nodenext"]], + ["bundler", ["es2015", "es2020", "es2022", "esnext", "preserve"]], +]; + +/** The fourteen strict defaults, in TEST-SPEC §7.6's order. */ +export const STRICT_DEFAULT_OPTION_SETS: readonly CoveredOptionSet[] = + Object.freeze( + STRICT_DEFAULT_MODES.flatMap(([moduleResolution, modules]) => + modules.map((module) => + module === undefined + ? optionSet( + `the strict defaults with moduleResolution ${moduleResolution} ` + + `and module at its default`, + "strict defaults", + { strict: true, moduleResolution }, + ) + : optionSet( + `the strict defaults with moduleResolution ${moduleResolution} ` + + `and module ${module}`, + "strict defaults", + { strict: true, moduleResolution, module }, + ), + ), + ), + ); + +/** + * The initialized-project options (SPEC 7.6 Covered setups): exactly the + * set release 5.9.3's `tsc --init` writes. + */ +export const INITIALIZED_PROJECT_OPTION_SET: CoveredOptionSet = optionSet( + "the initialized-project options", + "initialized-project options", + { + module: "nodenext", + target: "esnext", + types: [], + jsx: "react-jsx", + moduleDetection: "force", + strict: true, + declaration: true, + declarationMap: true, + sourceMap: true, + verbatimModuleSyntax: true, + isolatedModules: true, + exactOptionalPropertyTypes: true, + noUncheckedIndexedAccess: true, + noUncheckedSideEffectImports: true, + skipLibCheck: true, + }, +); + +/** Every option set: the strict defaults, then the initialized-project set. */ +export const COVERED_OPTION_SETS: readonly CoveredOptionSet[] = Object.freeze([ + ...STRICT_DEFAULT_OPTION_SETS, + INITIALIZED_PROJECT_OPTION_SET, +]); + +/** + * Whether TypeScript compiles a file so named in a project of `project`'s + * kind as an ES module (SPEC 7.6: a name ending in `.mts`, or in `.ts` or + * `.tsx` in an ES-module project) — the files the initialized-project set + * covers. + */ +export function compilesAsEsModule( + project: ProjectKind, + extension: CoveredExtension, +): boolean { + return ( + extension === ".mts" || + (project === "es-module" && (extension === ".ts" || extension === ".tsx")) + ); +} + +/** One covered setup: a project kind, an extension, and an option set. */ +export interface CoveredSetup { + readonly project: ProjectKind; + readonly extension: CoveredExtension; + readonly optionSet: CoveredOptionSet; + /** How every diagnosis names the setup. */ + readonly label: string; +} + +/** How a diagnosis names a project kind. */ +const PROJECT_LABELS: Readonly<Record<ProjectKind, string>> = { + "es-module": + 'the ES-module project (its package.json holding "type": "module")', + commonjs: "the CommonJS project whose package.json holds no type", + "no-manifest": "the CommonJS project with no package.json", +}; + +/** The number of covered setups TEST-SPEC §7.6 counts: 173 programs per arm. */ +export const COVERED_SETUP_COUNT = 173; + +/** + * Every covered setup (module header): by project kind, then option set, + * then extension, the initialized-project set only where it covers the file. + */ +export const COVERED_SETUPS: readonly CoveredSetup[] = Object.freeze( + PROJECT_KINDS.flatMap((project) => + COVERED_OPTION_SETS.flatMap((set) => + COVERED_EXTENSIONS.filter( + (extension) => + set.kind === "strict defaults" || + compilesAsEsModule(project, extension), + ).map((extension) => + Object.freeze({ + project, + extension, + optionSet: set, + label: + `a ${extension} configuration file in ` + + `${PROJECT_LABELS[project]} under ${set.name}`, + }), + ), + ), + ), +); + +/** The covered setups of one project kind, in {@link COVERED_SETUPS} order. */ +export function coveredSetupsOf(project: ProjectKind): readonly CoveredSetup[] { + return COVERED_SETUPS.filter((setup) => setup.project === project); +} + +/** + * The matrix's composition (module header), confirmed at module load: a + * table drifting from TEST-SPEC §7.6 fails every test importing it. + */ +function checkMatrixComposition(): void { + const problems: string[] = []; + if (STRICT_DEFAULT_OPTION_SETS.length !== 14) { + problems.push( + `${String(STRICT_DEFAULT_OPTION_SETS.length)} strict defaults, not 14`, + ); + } + const names = new Set(COVERED_OPTION_SETS.map((set) => set.name)); + if (names.size !== COVERED_OPTION_SETS.length) { + problems.push("two option sets share a name"); + } + for (const set of STRICT_DEFAULT_OPTION_SETS) { + const keys = Object.keys(set.tsconfig); + if ( + set.tsconfig["strict"] !== true || + keys.some( + (key) => !["strict", "moduleResolution", "module"].includes(key), + ) + ) { + problems.push(`${set.name} sets ${keys.join(", ")}`); + } + } + if (Object.keys(INITIALIZED_PROJECT_OPTION_SET.tsconfig).length !== 15) { + problems.push("the initialized-project set does not name 15 options"); + } + if (COVERED_SETUPS.length !== COVERED_SETUP_COUNT) { + problems.push( + `${String(COVERED_SETUPS.length)} setups, not ${String(COVERED_SETUP_COUNT)}`, + ); + } + if ( + new Set(COVERED_SETUPS.map((setup) => setup.label)).size !== + COVERED_SETUPS.length + ) { + problems.push("two setups share a label"); + } + let esModuleFiles = 0; + for (const project of PROJECT_KINDS) { + for (const extension of COVERED_EXTENSIONS) { + const esModule = compilesAsEsModule(project, extension); + if (esModule) esModuleFiles += 1; + const count = COVERED_SETUPS.filter( + (setup) => setup.project === project && setup.extension === extension, + ).length; + if (count !== 14 + (esModule ? 1 : 0)) { + problems.push( + `${String(count)} setups for a ${extension} file in the ${project} project`, + ); + } + } + } + if (esModuleFiles !== 5) { + problems.push( + `${String(esModuleFiles)} file kinds compiled as ES modules, not 5`, + ); + } + if (problems.length > 0) { + throw new Error( + `module channel's TypeScript driver: the covered setups drift from ` + + `TEST-SPEC §7.6 Covered setups: ${problems.join("; ")}`, + ); + } +} + +checkMatrixComposition(); + +/** A path with `/` separators, as TypeScript spells file names. */ +function slashed(file: string): string { + return file.split(path.sep).join("/"); +} + +/** + * TypeScript 5.9.3's library directory, by its physical path: where its + * compiler host finds every library it ships. + */ +const TYPESCRIPT_LIBRARY_DIRECTORY: string = guardSyncStep( + "reading the physical path of TypeScript 5.9.3's library directory", + () => slashed(fs.realpathSync(path.dirname(ts.getDefaultLibFilePath({})))), +); + +/** Whether `fileName` is a file of TypeScript's own library directory. */ +function isTypeScriptLibrary(fileName: string): boolean { + return path.posix.dirname(fileName) === TYPESCRIPT_LIBRARY_DIRECTORY; +} + +/** + * Parsed libraries (module header): each file of TypeScript's library + * directory once per target, module format, and JSDoc mode, keyed so. + */ +const parsedLibraries = new Map<string, ts.SourceFile>(); + +/** {@link parsedLibraries}'s key for a library parse request. */ +function libraryKey( + fileName: string, + request: ts.ScriptTarget | ts.CreateSourceFileOptions, +): string { + const options = + typeof request === "object" ? request : { languageVersion: request }; + return [ + String(options.languageVersion), + String(options.impliedNodeFormat), + String(options.jsDocParsingMode), + fileName, + ].join("|"); +} + +/** + * A program's compiler host (module header): TypeScript's own, with the + * current directory given, parsed libraries reused, and no write allowed. + */ +function compilerHost( + options: ts.CompilerOptions, + currentDirectory: string, + context: string, +): ts.CompilerHost { + const base = ts.createCompilerHost(options); + return { + ...base, + getCurrentDirectory: () => currentDirectory, + getSourceFile: (fileName, request, onError, shouldCreateNewSourceFile) => { + if ( + shouldCreateNewSourceFile === true || + !isTypeScriptLibrary(fileName) + ) { + return base.getSourceFile( + fileName, + request, + onError, + shouldCreateNewSourceFile, + ); + } + const key = libraryKey(fileName, request); + const parsed = parsedLibraries.get(key); + if (parsed !== undefined) return parsed; + const made = base.getSourceFile(fileName, request, onError); + if (made !== undefined) parsedLibraries.set(key, made); + return made; + }, + writeFile: (fileName) => { + throw new Error( + `module channel's TypeScript driver: a program asked to write ` + + `${fileName}; the driver never emits (${context})`, + ); + }, + }; +} + +/** A fresh copy of a set's options for one program, arrays copied too. */ +function programOptions(set: CoveredOptionSet): ts.CompilerOptions { + const options: ts.CompilerOptions = {}; + for (const [key, value] of Object.entries(set.compilerOptions)) { + options[key] = Array.isArray(value) ? [...(value as string[])] : value; + } + return options; +} + +/** Whether a program's options turn declaration diagnostics on. */ +function emitsDeclarations(options: ts.CompilerOptions): boolean { + return options.declaration === true || options.composite === true; +} + +// TypeScript 5.9.3's internals this module reads (module header), absent +// from its public declarations and pinned by +// test/self/module-channel-ts.test.ts: a program's include reasons, each +// source file's canonical path and import list, and the reasons' kinds. + +/** One reason TypeScript records for a file's presence in a program. */ +interface FileIncludeReason { + readonly kind: number; + /** The referencing file's canonical path, for a reference's reasons. */ + readonly file?: string; + /** The reference's index in the referencing file's list of its kind. */ + readonly index?: number; + /** The type reference an automatic type directive names. */ + readonly typeReference?: string; +} + +/** The internal program member this module reads. */ +interface IncludeReasonsProgram { + getFileIncludeReasons(): { + get(path: string): readonly FileIncludeReason[] | undefined; + }; +} + +/** The internal source file members this module reads. */ +interface InternalSourceFile { + readonly path: string; + readonly imports?: readonly ts.StringLiteralLike[]; +} + +/** The include-reason kinds this module distinguishes, read from TypeScript. */ +interface IncludeKinds { + readonly RootFile: number; + readonly Import: number; + readonly ReferenceFile: number; + readonly TypeReferenceDirective: number; + readonly LibFile: number; + readonly LibReferenceDirective: number; + readonly AutomaticTypeDirectiveFile: number; +} + +/** {@link IncludeKinds}, read from TypeScript's own enumeration at load. */ +const INCLUDE_KINDS: IncludeKinds = ((): IncludeKinds => { + const table = (ts as unknown as { FileIncludeKind?: Record<string, unknown> }) + .FileIncludeKind; + const names = [ + "RootFile", + "Import", + "ReferenceFile", + "TypeReferenceDirective", + "LibFile", + "LibReferenceDirective", + "AutomaticTypeDirectiveFile", + ] as const; + const kinds: Record<string, number> = {}; + for (const name of names) { + const value = table?.[name]; + if (typeof value !== "number") { + throw new Error( + `module channel's TypeScript driver: TypeScript 5.9.3 exposes no ` + + `include-reason kind ${name} (ts.FileIncludeKind); the program ` + + `condition is read from these internals (module header)`, + ); + } + kinds[name] = value; + } + return Object.freeze(kinds as unknown as IncludeKinds); +})(); + +/** The reference kinds through which a brought-in file brings in another. */ +const REFERENCE_KINDS: ReadonlySet<number> = new Set([ + INCLUDE_KINDS.Import, + INCLUDE_KINDS.ReferenceFile, + INCLUDE_KINDS.TypeReferenceDirective, + INCLUDE_KINDS.LibReferenceDirective, +]); + +/** How a diagnosis names an include reason. */ +function describeReason( + program: ts.Program, + reason: FileIncludeReason, +): string { + const kind = + Object.entries(INCLUDE_KINDS).find( + ([, value]) => value === reason.kind, + )?.[0] ?? `kind ${String(reason.kind)}`; + if (reason.kind === INCLUDE_KINDS.AutomaticTypeDirectiveFile) { + return `included automatically as the type package ${String(reason.typeReference)}`; + } + if (reason.file === undefined) return kind; + const from = program.getSourceFileByPath(reason.file as ts.Path); + const fromName = from?.fileName ?? reason.file; + if (reason.kind === INCLUDE_KINDS.Import && from !== undefined) { + const node = (from as unknown as InternalSourceFile).imports?.[ + reason.index ?? -1 + ]; + if (node !== undefined && node.pos < 0) { + return `imported by an import TypeScript synthesizes in ${fromName} (${JSON.stringify(node.text)})`; + } + } + return `${kind} from ${fromName}`; +} + +/** Whether a source file contributes to the global scope (module header). */ +function contributesGlobals(file: ts.SourceFile): boolean { + if (!ts.isExternalModule(file)) return true; + const reaches = (statements: readonly ts.Statement[]): boolean => + statements.some((statement) => { + if (ts.isNamespaceExportDeclaration(statement)) return true; + if (!ts.isModuleDeclaration(statement)) return false; + if ((statement.flags & ts.NodeFlags.GlobalAugmentation) !== 0) + return true; + let body = statement.body; + while (body !== undefined && ts.isModuleDeclaration(body)) { + if ((body.flags & ts.NodeFlags.GlobalAugmentation) !== 0) return true; + body = body.body; + } + return body !== undefined && ts.isModuleBlock(body) + ? reaches(body.statements) + : false; + }); + return reaches(file.statements); +} + +/** + * Whether an external module augments another module (module header): a + * `declare module "…"` among its statements, which changes that module for + * every file of the program. + */ +function augmentsModules(file: ts.SourceFile): boolean { + return ( + ts.isExternalModule(file) && + file.statements.some( + (statement) => + ts.isModuleDeclaration(statement) && ts.isStringLiteral(statement.name), + ) + ); +} + +/** A program's files, classified (module header). */ +interface ProgramFiles { + /** The files of TypeScript's library directory, in program order. */ + readonly libraries: readonly ts.SourceFile[]; + /** Every other file but the roots, in program order. */ + readonly others: readonly ts.SourceFile[]; + /** Each root's own program: the root, what it brings in, the libraries. */ + readonly ownPrograms: readonly ReadonlySet<ts.SourceFile>[]; + /** Why the roots cannot share one program, or undefined where they can. */ + readonly unbatchable: string | undefined; + /** Whether no file but the libraries contributes to the global scope. */ + readonly librariesAlone: boolean; +} + +/** + * Classify a program's files and check SPEC 7.6's program condition on them + * (module header), throwing `HarnessStagingError` where a file entered the + * program otherwise. + */ +function classifyProgram( + program: ts.Program, + roots: readonly ts.SourceFile[], + context: string, +): ProgramFiles { + const reasons = ( + program as unknown as Partial<IncludeReasonsProgram> + ).getFileIncludeReasons?.(); + if (reasons === undefined) { + throw new Error( + `module channel's TypeScript driver: TypeScript 5.9.3's program has no ` + + `getFileIncludeReasons; the program condition is read from it ` + + `(module header; ${context})`, + ); + } + const files = program.getSourceFiles(); + const rootSet = new Set(roots); + const edges = new Map<ts.SourceFile, ts.SourceFile[]>(); + const defaultLibraries: ts.SourceFile[] = []; + const refused: string[] = []; + const reasonsOf = (file: ts.SourceFile): readonly FileIncludeReason[] => + reasons.get((file as unknown as InternalSourceFile).path) ?? []; + for (const file of files) { + for (const reason of reasonsOf(file)) { + if (reason.kind === INCLUDE_KINDS.RootFile && !rootSet.has(file)) { + refused.push(`${file.fileName} is a root the driver did not name`); + } + if (reason.kind === INCLUDE_KINDS.LibFile) defaultLibraries.push(file); + if ( + (reason.kind === INCLUDE_KINDS.LibFile || + reason.kind === INCLUDE_KINDS.LibReferenceDirective) && + !isTypeScriptLibrary(file.fileName) + ) { + refused.push( + `${file.fileName} is a library of the program (${describeReason(program, reason)}) ` + + `that is no file of TypeScript's own library directory ` + + `${TYPESCRIPT_LIBRARY_DIRECTORY}: an installed package replaces it`, + ); + } + if (!REFERENCE_KINDS.has(reason.kind) || reason.file === undefined) { + continue; + } + const from = program.getSourceFileByPath(reason.file as ts.Path); + if (from === undefined) { + refused.push( + `${file.fileName} is referenced from ${reason.file}, which is no ` + + `file of the program`, + ); + continue; + } + if (reason.kind === INCLUDE_KINDS.Import) { + const node = (from as unknown as InternalSourceFile).imports?.[ + reason.index ?? -1 + ]; + if (node === undefined) { + throw new Error( + `module channel's TypeScript driver: TypeScript records an ` + + `import of ${file.fileName} at index ${String(reason.index)} ` + + `of ${from.fileName}, which lists no such import (module ` + + `header; ${context})`, + ); + } + if (node.pos < 0) continue; + } + const list = edges.get(from) ?? []; + list.push(file); + edges.set(from, list); + } + } + const closure = (starts: readonly ts.SourceFile[]): Set<ts.SourceFile> => { + const seen = new Set<ts.SourceFile>(starts); + const queue = [...starts]; + for (let next = queue.shift(); next !== undefined; next = queue.shift()) { + for (const reached of edges.get(next) ?? []) { + if (!seen.has(reached)) { + seen.add(reached); + queue.push(reached); + } + } + } + return seen; + }; + const libraryClosure = closure(defaultLibraries); + const ownPrograms = roots.map((root) => { + const own = closure([root]); + for (const library of libraryClosure) own.add(library); + return own; + }); + for (const file of files) { + if (rootSet.has(file) || ownPrograms.some((own) => own.has(file))) continue; + refused.push( + `${file.fileName} entered the program otherwise (${ + reasonsOf(file) + .map((reason) => describeReason(program, reason)) + .join("; ") || "no reason recorded" + })`, + ); + } + if (refused.length > 0) { + throw new HarnessStagingError( + MODE, + roots.map((root) => root.fileName).join(", "), + `${context}: SPEC 7.6's program condition does not hold — ` + + `${refused.join("; ")}. Nothing enters the program but the root, ` + + `TypeScript's own libraries for the option set, and what the root's ` + + `import declaration brings in; neither an @types package TypeScript ` + + `includes automatically nor a module it imports implicitly adds ` + + `anything (SPEC 7.6 Covered setups, Program; TEST-SPEC §7.6 Placement: ` + + `where a condition fails, no arm asserts anything there)`, + ); + } + const libraries = files.filter((file) => isTypeScriptLibrary(file.fileName)); + const librarySet = new Set(libraries); + const others = files.filter( + (file) => !rootSet.has(file) && !librarySet.has(file), + ); + const librariesAlone = files.every( + (file) => librarySet.has(file) || !contributesGlobals(file), + ); + let unbatchable: string | undefined; + if (roots.length > 1) { + const nonRoots = files.filter((file) => !rootSet.has(file)); + const scriptRoot = roots.find(contributesGlobals); + const augmentingRoot = roots.find(augmentsModules); + const partial = roots.find((root, index) => { + const own = ownPrograms[index]; + return ( + own === undefined || + nonRoots.some((file) => !own.has(file)) || + roots.some((other) => other !== root && own.has(other)) + ); + }); + if (scriptRoot !== undefined) { + unbatchable = `${scriptRoot.fileName} contributes to the global scope`; + } else if (augmentingRoot !== undefined) { + unbatchable = `${augmentingRoot.fileName} augments a module`; + } else if (partial !== undefined) { + unbatchable = + `the roots' imports bring in different files (${partial.fileName}'s ` + + `own program is not every non-root file of the batch, or holds ` + + `another root)`; + } + } + return { libraries, others, ownPrograms, unbatchable, librariesAlone }; +} + +/** One error of a file's program (module header). */ +export interface ProgramError { + /** Where TypeScript reports it. */ + readonly origin: "options" | "global" | "configuration file" | "another file"; + /** The file it is located in, for the last two origins. */ + readonly file?: string; + /** Its 1-based line and column there. */ + readonly line?: number; + readonly column?: number; + /** TypeScript's error code, a diagnostic aid: verdicts pin none. */ + readonly code: number; + readonly message: string; +} + +/** Where an export listing finds a name (module header). */ +export type ExportSource = "exports" | "export assignment"; + +/** + * One name the module a covered file's import resolves to declares, with + * its meanings (module header; TEST-SPEC T7.6-1). + */ +export interface ListedExport { + /** The name, as an import spells it. */ + readonly name: string; + /** A value meaning an import may use as a value. */ + readonly value: boolean; + /** + * A value meaning no import may use as a value, reached only through + * `export type`, `import type`, or `export type *` (`value` then false). + */ + readonly typeOnlyValue: boolean; + /** A type meaning. */ + readonly type: boolean; + /** A namespace meaning. */ + readonly namespace: boolean; + /** + * Where the listing finds it: among the module's exports, among the + * members of its export assignment's value, or both, in that order. + */ + readonly listedIn: readonly ExportSource[]; +} + +/** + * The listing of the module a covered file's one import declaration + * resolves to, in that file's program (module header; TEST-SPEC T7.6-1). + */ +export interface ExportListing { + /** + * The file declaring the module, by the name TypeScript read it under; + * undefined where TypeScript resolves the import to no module it reads + * declarations from. + */ + readonly module: string | undefined; + /** Whether that module declares an export assignment (`export =`). */ + readonly exportAssignment: boolean; + /** Every name it declares, in UTF-16 code-unit order. */ + readonly exports: readonly ListedExport[]; +} + +/** + * A symbol's meaning flags through its aliases, as TypeScript reads them + * (module header): an alias TypeScript cannot resolve carries every meaning. + */ +function meaningFlags(checker: ts.TypeChecker, symbol: ts.Symbol): number { + if ((symbol.flags & ts.SymbolFlags.Alias) === 0) return symbol.flags; + const target = checker.getAliasedSymbol(symbol); + return checker.isUnknownSymbol(target) + ? ts.SymbolFlags.All + : symbol.flags | target.flags; +} + +/** Whether an alias along `symbol`'s chain is declared type-only. */ +function declaredTypeOnly(checker: ts.TypeChecker, symbol: ts.Symbol): boolean { + const seen = new Set<ts.Symbol>(); + let current: ts.Symbol | undefined = symbol; + while ( + current !== undefined && + (current.flags & ts.SymbolFlags.Alias) !== 0 && + !seen.has(current) + ) { + seen.add(current); + if ( + current.declarations?.some((declaration) => + ts.isTypeOnlyImportOrExportDeclaration(declaration), + ) === true + ) { + return true; + } + current = checker.getImmediateAliasedSymbol(current); + } + return false; +} + +/** + * Whether an escaped symbol name is TypeScript's own rather than one an + * import spells: TypeScript gives every spelled name beginning `__` one more + * `_`, so an escaped name beginning `__` and then another character names a + * symbol-keyed member, a private name, or an internal entry. + */ +function isInternalName(escapedName: string): boolean { + return escapedName.startsWith("__") && escapedName.charAt(2) !== "_"; +} + +/** A name's meanings as the listing gathers them, before it is frozen. */ +interface GatheredExport { + value: boolean; + typeOnlyValue: boolean; + type: boolean; + namespace: boolean; + readonly listedIn: Set<ExportSource>; +} + +/** + * The export listing of `root`'s one import declaration in `program` + * (module header), read once the program's diagnostics are all read; a + * root holding no import declaration, or more than one, is a misuse. + */ +function listModuleExports( + program: ts.Program, + root: ts.SourceFile, + context: string, +): ExportListing { + const declarations = root.statements.filter(ts.isImportDeclaration); + const [declaration] = declarations; + if (declarations.length !== 1 || declaration === undefined) { + throw new Error( + `module channel's TypeScript driver: an export listing reads the ` + + `module a covered file's one import declaration resolves to, and ` + + `${root.fileName} holds ${String(declarations.length)} import ` + + `declarations (${context})`, + ); + } + const checker = program.getTypeChecker(); + const moduleSymbol = checker.getSymbolAtLocation(declaration.moduleSpecifier); + if (moduleSymbol === undefined) { + return Object.freeze({ + module: undefined, + exportAssignment: false, + exports: Object.freeze([]), + }); + } + const moduleFile = moduleSymbol.declarations?.[0]?.getSourceFile().fileName; + if (moduleFile === undefined) { + throw new Error( + `module channel's TypeScript driver: TypeScript resolves the import of ` + + `${root.fileName} to a module with no declaration (${context})`, + ); + } + const assignment = moduleSymbol.exports?.get( + ts.InternalSymbolName.ExportEquals, + ); + const moduleType = + assignment === undefined + ? checker.getTypeOfSymbol(moduleSymbol) + : undefined; + const gathered = new Map<string, GatheredExport>(); + const gather = (symbol: ts.Symbol, source: ExportSource): void => { + if (isInternalName(symbol.escapedName as string)) return; + const name = ts.unescapeLeadingUnderscores(symbol.escapedName); + const flags = meaningFlags(checker, symbol); + const carriesValue = (flags & ts.SymbolFlags.Value) !== 0; + let typeOnly = false; + if (carriesValue && source === "exports") { + typeOnly = + moduleType === undefined + ? declaredTypeOnly(checker, symbol) + : checker.getPropertyOfType(moduleType, name) !== symbol; + } + const entry = gathered.get(name) ?? { + value: false, + typeOnlyValue: false, + type: false, + namespace: false, + listedIn: new Set<ExportSource>(), + }; + if (carriesValue && !typeOnly) entry.value = true; + if (carriesValue && typeOnly) entry.typeOnlyValue = true; + if ((flags & ts.SymbolFlags.Type) !== 0) entry.type = true; + if ((flags & ts.SymbolFlags.Namespace) !== 0) entry.namespace = true; + entry.listedIn.add(source); + gathered.set(name, entry); + }; + for (const symbol of checker.getExportsOfModule(moduleSymbol)) { + gather(symbol, "exports"); + } + if (assignment !== undefined) { + for (const member of checker.getPropertiesOfType( + checker.getTypeOfSymbol(assignment), + )) { + gather(member, "export assignment"); + } + } + const sources: readonly ExportSource[] = ["exports", "export assignment"]; + const exports = [...gathered.keys()].sort().map((name): ListedExport => { + const entry = gathered.get(name); + if (entry === undefined) throw new Error("unreachable: a gathered name"); + return Object.freeze({ + name, + value: entry.value, + typeOnlyValue: entry.typeOnlyValue && !entry.value, + type: entry.type, + namespace: entry.namespace, + listedIn: Object.freeze( + sources.filter((source) => entry.listedIn.has(source)), + ), + }); + }); + return Object.freeze({ + module: moduleFile, + exportAssignment: assignment !== undefined, + exports: Object.freeze(exports), + }); +} + +/** A root's share of a program's run: its program's errors and files. */ +interface RootOutcome { + readonly errors: readonly ProgramError[]; + readonly programFiles: readonly string[]; + /** Its import's export listing, where the request asked for one. */ + readonly exportListing: ExportListing | undefined; +} + +/** One program's run over its roots. */ +interface ProgramOutcome { + readonly perRoot: readonly RootOutcome[]; + /** The program's options, read back from it. */ + readonly compilerOptions: Readonly<ts.CompilerOptions>; + /** Why its roots could not share it, or undefined where they could. */ + readonly unbatchable: string | undefined; +} + +/** + * The libraries' own diagnostics, by option set and library list, wherever + * no other file of the program contributes to the global scope (module + * header). + */ +const libraryDiagnostics = new Map<string, readonly ts.Diagnostic[]>(); + +/** A file's syntactic, semantic, and (where on) declaration diagnostics. */ +function diagnosticsOf( + program: ts.Program, + file: ts.SourceFile, + declarations: boolean, +): ts.Diagnostic[] { + const list: ts.Diagnostic[] = [ + ...program.getSyntacticDiagnostics(file), + ...program.getSemanticDiagnostics(file), + ]; + if (declarations) list.push(...program.getDeclarationDiagnostics(file)); + return list; +} + +/** A root's errors: every error-category diagnostic, deduplicated. */ +function programErrors( + diagnostics: readonly ts.Diagnostic[], + root: ts.SourceFile, + optionDiagnostics: ReadonlySet<ts.Diagnostic>, +): readonly ProgramError[] { + return Object.freeze( + ts + .sortAndDeduplicateDiagnostics(diagnostics) + .filter( + (diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error, + ) + .map((diagnostic): ProgramError => { + const message = flatten(diagnostic); + if (diagnostic.file === undefined) { + return Object.freeze({ + origin: optionDiagnostics.has(diagnostic) ? "options" : "global", + code: diagnostic.code, + message, + }); + } + const at = diagnostic.file.getLineAndCharacterOfPosition( + diagnostic.start ?? 0, + ); + return Object.freeze({ + origin: + diagnostic.file === root ? "configuration file" : "another file", + file: diagnostic.file.fileName, + line: at.line + 1, + column: at.character + 1, + code: diagnostic.code, + message, + }); + }), + ); +} + +/** A program over `rootPaths` under `setup`'s option set, its roots read. */ +function createProgram( + setup: CoveredSetup, + rootPaths: readonly string[], + currentDirectory: string, + context: string, +): { readonly program: ts.Program; readonly roots: readonly ts.SourceFile[] } { + const options = programOptions(setup.optionSet); + const program = ts.createProgram({ + rootNames: [...rootPaths], + options, + host: compilerHost(options, currentDirectory, context), + }); + const roots = rootPaths.map((rootPath) => { + const root = program.getSourceFile(rootPath); + if (root === undefined) { + throw new HarnessStagingError( + MODE, + rootPath, + `${context}: TypeScript read no root file at ${rootPath} under ` + + `${setup.label}`, + ); + } + return root; + }); + return { program, roots }; +} + +/** The program's options, read back from it, arrays copied. */ +function readBackOptions(program: ts.Program): Readonly<ts.CompilerOptions> { + const options: ts.CompilerOptions = {}; + for (const [key, value] of Object.entries(program.getCompilerOptions())) { + options[key] = Array.isArray(value) ? [...(value as string[])] : value; + } + return Object.freeze(options); +} + +/** Each root's own program's files, in program order. */ +function ownProgramFiles( + program: ts.Program, + own: ReadonlySet<ts.SourceFile>, +): readonly string[] { + return Object.freeze( + program + .getSourceFiles() + .filter((file) => own.has(file)) + .map((file) => file.fileName), + ); +} + +/** + * Run one program over `rootPaths` with the sharing the module header + * argues: the libraries' diagnostics read once per option set and library + * list where that is sound, then the program's other shared files, then + * each root; each root's errors read from the shared diagnostics and its own, + * and then, where `listExports` asks, its import's export listing. + */ +function runSharedProgram( + setup: CoveredSetup, + rootPaths: readonly string[], + currentDirectory: string, + context: string, + listExports: boolean, +): ProgramOutcome { + const { program, roots } = createProgram( + setup, + rootPaths, + currentDirectory, + context, + ); + const files = classifyProgram(program, roots, context); + const declarations = emitsDeclarations(program.getCompilerOptions()); + const optionDiagnostics = program.getOptionsDiagnostics(); + const shared: ts.Diagnostic[] = [ + ...optionDiagnostics, + ...program.getGlobalDiagnostics(), + ]; + const libraryKeyOfProgram = [ + setup.optionSet.name, + ...files.libraries.map((file) => file.fileName).sort(), + ].join(LF); + const remembered = files.librariesAlone + ? libraryDiagnostics.get(libraryKeyOfProgram) + : undefined; + if (remembered !== undefined) { + shared.push(...remembered); + } else { + const read = files.libraries.flatMap((file) => + diagnosticsOf(program, file, declarations), + ); + shared.push(...read); + if (files.librariesAlone) { + libraryDiagnostics.set(libraryKeyOfProgram, Object.freeze(read)); + } + } + for (const file of files.others) { + shared.push(...diagnosticsOf(program, file, declarations)); + } + const globalBefore = program.getGlobalDiagnostics().length; + const own = roots.map((root) => diagnosticsOf(program, root, declarations)); + let unbatchable = files.unbatchable; + if ( + roots.length > 1 && + unbatchable === undefined && + (program.getGlobalDiagnostics().length !== globalBefore || + own.some((list) => + list.some((diagnostic) => diagnostic.file === undefined), + )) + ) { + unbatchable = "a root's check raised a global diagnostic"; + } + const finalGlobal = roots.length === 1 ? program.getGlobalDiagnostics() : []; + const options = new Set(optionDiagnostics); + const perRoot = roots.map((root, index) => ({ + errors: programErrors( + [...shared, ...(own[index] ?? []), ...finalGlobal], + root, + options, + ), + programFiles: ownProgramFiles( + program, + files.ownPrograms[index] ?? new Set(), + ), + })); + return { + perRoot: perRoot.map((outcome, index) => { + const root = roots[index]; + if (root === undefined) + throw new Error("unreachable: a root per outcome"); + return { + ...outcome, + exportListing: listExports + ? listModuleExports(program, root, context) + : undefined, + }; + }), + compilerOptions: readBackOptions(program), + unbatchable, + }; +} + +/** + * The reference reading (module header): one root, nothing shared but + * parsed libraries, every diagnostic read as `ts.getPreEmitDiagnostics` + * reads it, and the global diagnostics again once everything is checked; + * then, where `listExports` asks, the root's export listing. + */ +function runUnsharedProgram( + setup: CoveredSetup, + rootPath: string, + currentDirectory: string, + context: string, + listExports: boolean, +): ProgramOutcome { + const { program, roots } = createProgram( + setup, + [rootPath], + currentDirectory, + context, + ); + const files = classifyProgram(program, roots, context); + const root = roots[0]; + if (root === undefined) throw new Error("unreachable: one root"); + const diagnostics = [ + ...ts.getPreEmitDiagnostics(program), + ...program.getGlobalDiagnostics(), + ]; + const errors = programErrors( + diagnostics, + root, + new Set(program.getOptionsDiagnostics()), + ); + return { + perRoot: [ + { + errors, + programFiles: ownProgramFiles( + program, + files.ownPrograms[0] ?? new Set(), + ), + exportListing: listExports + ? listModuleExports(program, root, context) + : undefined, + }, + ], + compilerOptions: readBackOptions(program), + unbatchable: undefined, + }; +} + +/** One file a test stages for the driver to judge. */ +export interface CoveredFile { + /** Names the file in every diagnosis; unique within one staging request. */ + readonly label: string; + /** Its bytes, written unchanged under each extension its setups name. */ + readonly text: string | Uint8Array; +} + +/** {@link stageCoveredFiles}'s request. */ +export interface CoveredFilesRequest { + readonly staging: ModuleStaging; + /** + * The directory the files are written in, staging-relative: the importing + * files' directory (the project directory for the canonical placement). + */ + readonly directory: string; + /** The project kind staged for `directory`; every setup must be of it. */ + readonly project: ProjectKind; + /** + * For a CommonJS project whose nearest `package.json` holds the `type` + * `"commonjs"` (T7.6-5(c)): that member, which Reach confirms with the + * project kind (helpers/module-channel.ts `ReachStaging.nearestType`); + * the setups stay the CommonJS project's. + */ + readonly nearestType?: CommonJsTypeMember; + /** + * The placement every file's import reaches: Reach is verified for each + * written file against it, confirming the project kind too. Without one, + * no package is reached and nothing of Reach is checked. + */ + readonly placement?: Placement; + /** + * Whether nothing but `placement` is installed in the staging (the + * canonical placement's "nothing else installed"), confirmed where set. + */ + readonly alone?: boolean; + readonly files: readonly CoveredFile[]; + /** The setups to judge: every covered setup of `project` unless given. */ + readonly setups?: readonly CoveredSetup[]; + /** + * The programs' current directory, staging-relative: `directory` unless + * given, inside the staging either way. + */ + readonly currentDirectory?: string; + /** + * Whether each verdict carries the export listing of the module its + * file's one import declaration resolves to (module header), every file + * then holding exactly one import declaration. + */ + readonly listExports?: boolean; + /** Leads every diagnosis: the arm the files serve. */ + readonly context: string; +} + +/** A file's verdict in one setup (module header). */ +export interface CoveredVerdict { + readonly setup: CoveredSetup; + /** The file's label. */ + readonly label: string; + /** The configuration file, by its physical path: the program's root. */ + readonly file: string; + /** The placement's path, where the request named one. */ + readonly placement: string | undefined; + /** Every error TypeScript reports for the file's program. */ + readonly errors: readonly ProgramError[]; + /** No error anywhere in the program (TEST-SPEC §7.6 Verdict). */ + readonly typeChecks: boolean; + /** At least one error located in the configuration file. */ + readonly failsToTypeCheck: boolean; + /** The file's program's files, by the names TypeScript read them under. */ + readonly programFiles: readonly string[]; + /** The program's options, read back from it. */ + readonly compilerOptions: Readonly<ts.CompilerOptions>; + /** + * The export listing of the module the file's import resolves to, where + * the request asked for it (`listExports`); undefined otherwise. + */ + readonly exportListing: ExportListing | undefined; + /** How it was reached: in a batch, in a program of its own, or unshared. */ + readonly judged: "batched" | "own program" | "unshared"; +} + +/** The per-staging counter naming the files the driver writes. */ +const writtenFiles = new WeakMap<ModuleStaging, number>(); + +/** The staging-relative path of `name` in `directory`. */ +function inDirectory(directory: string, name: string): string { + return directory === "" || directory === "." ? name : `${directory}/${name}`; +} + +/** How a misuse's diagnosis names a request. */ +function describeRequest(request: CoveredFilesRequest): string { + return `${request.context}; directory ${JSON.stringify(request.directory)}`; +} + +/** + * Write `request.files` once per extension the setups name and verify Reach + * for each written file (module header), resolving to the judge of those + * files. Nothing is type-checked yet: {@link CoveredFiles.judge} checks one + * setup at a time, so a body can fail at its first failing setup. + */ +export async function stageCoveredFiles( + request: CoveredFilesRequest, +): Promise<CoveredFiles> { + const setups = request.setups ?? coveredSetupsOf(request.project); + if (request.files.length === 0) { + throw new Error( + `module channel's TypeScript driver: no file to judge (${describeRequest(request)})`, + ); + } + if ( + new Set(request.files.map((file) => file.label)).size !== + request.files.length + ) { + throw new Error( + `module channel's TypeScript driver: two files share a label (${describeRequest(request)})`, + ); + } + if (setups.length === 0) { + throw new Error( + `module channel's TypeScript driver: no setup to judge in (${describeRequest(request)})`, + ); + } + for (const setup of setups) { + if (!COVERED_SETUPS.includes(setup) || setup.project !== request.project) { + throw new Error( + `module channel's TypeScript driver: ${setup.label} is no covered ` + + `setup of the ${request.project} project (${describeRequest(request)})`, + ); + } + } + const { staging } = request; + const extensions = COVERED_EXTENSIONS.filter((extension) => + setups.some((setup) => setup.extension === extension), + ); + const serials = request.files.map(() => { + const serial = (writtenFiles.get(staging) ?? 0) + 1; + writtenFiles.set(staging, serial); + return serial; + }); + const written = new Map<CoveredExtension, readonly string[]>(); + for (const extension of extensions) { + const paths: string[] = []; + for (const [index, file] of request.files.entries()) { + const name = `covered-file-${String(serials[index])}${extension}`; + const at = await staging.writeFile( + inDirectory(request.directory, name), + file.text, + ); + const physical = await guardStep( + `reading the physical path of ${at} (${request.context})`, + () => fsp.realpath(at), + ); + if (!physical.startsWith(`${staging.root}${path.sep}`)) { + throw new HarnessStagingError( + MODE, + physical, + `${request.context}: the configuration file ${at} lies at ` + + `${physical}, outside the staging ${staging.root}`, + ); + } + if (request.placement !== undefined) { + await staging.verifyReach({ + importingFile: path + .relative(staging.root, physical) + .split(path.sep) + .join("/"), + placement: request.placement, + project: request.project, + ...(request.nearestType === undefined + ? {} + : { nearestType: request.nearestType }), + ...(request.alone === undefined ? {} : { alone: request.alone }), + }); + } + paths.push(slashed(physical)); + } + written.set(extension, Object.freeze(paths)); + } + const currentDirectory = await guardStep( + `reading the physical path of the programs' current directory (${request.context})`, + async () => { + const given = staging.path(request.currentDirectory ?? request.directory); + try { + return await fsp.realpath(given); + } catch (error) { + throw new Error( + `module channel's TypeScript driver: the programs' current ` + + `directory ${given} cannot be read (${String(error)}); stage it ` + + `before judging (${describeRequest(request)})`, + ); + } + }, + ); + if ( + currentDirectory !== staging.root && + !currentDirectory.startsWith(`${staging.root}${path.sep}`) + ) { + throw new HarnessStagingError( + MODE, + currentDirectory, + `${request.context}: the programs' current directory ${currentDirectory} ` + + `lies outside the staging ${staging.root}; each program's host takes a ` + + `directory inside the staging as its current directory`, + ); + } + return new CoveredFiles(request, setups, written, slashed(currentDirectory)); +} + +/** + * The judge of one request's files (module header): each covered setup + * judged in one program per call, the files' verdicts in request order. + */ +export class CoveredFiles { + /** The setups the files are judged in, in the request's order. */ + readonly setups: readonly CoveredSetup[]; + /** Leads every diagnosis. */ + readonly context: string; + readonly #labels: readonly string[]; + readonly #placement: string | undefined; + readonly #written: ReadonlyMap<CoveredExtension, readonly string[]>; + readonly #currentDirectory: string; + readonly #listExports: boolean; + + constructor( + request: CoveredFilesRequest, + setups: readonly CoveredSetup[], + written: ReadonlyMap<CoveredExtension, readonly string[]>, + currentDirectory: string, + ) { + this.setups = Object.freeze([...setups]); + this.context = request.context; + this.#labels = Object.freeze(request.files.map((file) => file.label)); + this.#placement = request.placement?.path; + this.#written = written; + this.#currentDirectory = currentDirectory; + this.#listExports = request.listExports === true; + } + + /** What a step's description adds where each program lists exports too. */ + get #listing(): string { + return this.#listExports ? ", listing each import's exports" : ""; + } + + /** The written files of `setup`'s extension, by physical path. */ + #files(setup: CoveredSetup): readonly string[] { + const files = this.setups.includes(setup) + ? this.#written.get(setup.extension) + : undefined; + if (files === undefined) { + throw new Error( + `module channel's TypeScript driver: ${setup.label} is not among ` + + `the setups these files were staged for (${this.context})`, + ); + } + return files; + } + + /** A verdict from a program's outcome for one root. */ + #verdict( + setup: CoveredSetup, + index: number, + outcome: ProgramOutcome, + rootIndex: number, + judged: CoveredVerdict["judged"], + ): CoveredVerdict { + const root = outcome.perRoot[rootIndex]; + const file = this.#files(setup)[index]; + const label = this.#labels[index]; + if (root === undefined || file === undefined || label === undefined) { + throw new Error("unreachable: a verdict for every staged file"); + } + return Object.freeze({ + setup, + label, + file, + placement: this.#placement, + errors: root.errors, + typeChecks: root.errors.length === 0, + failsToTypeCheck: root.errors.some( + (error) => error.origin === "configuration file", + ), + programFiles: root.programFiles, + compilerOptions: outcome.compilerOptions, + exportListing: root.exportListing, + judged, + }); + } + + /** + * Judge every file in `setup` (module header): one program whose roots + * they all are, or, where that batch is not sound, one program per file; + * each program's check a harness step under its own guard. + */ + judge(setup: CoveredSetup): readonly CoveredVerdict[] { + const files = this.#files(setup); + const batch = guardSyncStep( + `type-checking ${String(files.length)} configuration file(s) in one ` + + `program${this.#listing}, ${setup.label} (${this.context})`, + () => + runSharedProgram( + setup, + files, + this.#currentDirectory, + this.context, + this.#listExports, + ), + ); + if (files.length === 1 || batch.unbatchable === undefined) { + return Object.freeze( + files.map((_file, index) => + this.#verdict( + setup, + index, + batch, + index, + files.length === 1 ? "own program" : "batched", + ), + ), + ); + } + return Object.freeze( + files.map((file, index) => { + const own = guardSyncStep( + `type-checking ${file} in a program of its own${this.#listing}, ` + + `${setup.label}, since ` + + `${batch.unbatchable ?? "the batch is unsound"} (${this.context})`, + () => + runSharedProgram( + setup, + [file], + this.#currentDirectory, + this.context, + this.#listExports, + ), + ); + return this.#verdict(setup, index, own, 0, "own program"); + }), + ); + } + + /** + * Judge the file labelled `label` in `setup` by the reference reading + * (module header): one root, nothing shared but parsed libraries. + */ + judgeUnshared(setup: CoveredSetup, label: string): CoveredVerdict { + const index = this.#labels.indexOf(label); + const file = this.#files(setup)[index]; + if (index < 0 || file === undefined) { + throw new Error( + `module channel's TypeScript driver: no staged file is labelled ` + + `${JSON.stringify(label)} (${this.context})`, + ); + } + const outcome = guardSyncStep( + `type-checking ${file} unshared${this.#listing}, ${setup.label} ` + + `(${this.context})`, + () => + runUnsharedProgram( + setup, + file, + this.#currentDirectory, + this.context, + this.#listExports, + ), + ); + return this.#verdict(setup, index, outcome, 0, "unshared"); + } +} + +/** How a diagnosis lists a verdict's errors: the first twelve, then a count. */ +export function describeErrors(errors: readonly ProgramError[]): string { + if (errors.length === 0) return "no error"; + const shown = errors.slice(0, 12).map((error) => { + const at = + error.file === undefined + ? error.origin + : `${error.origin} ${error.file}:${String(error.line)}:${String(error.column)}`; + return `TS${String(error.code)} (${at}): ${error.message.split(LF).join(" ")}`; + }); + const rest = errors.length - shown.length; + return shown.join("; ") + (rest > 0 ? `; and ${String(rest)} more` : ""); +} + +/** `n` and `word`, pluralized. */ +function count(n: number, word: string): string { + return `${String(n)} ${word}${n === 1 ? "" : "s"}`; +} + +/** How a diagnosis states one listed export: its name and its meanings. */ +export function describeListedExport(entry: ListedExport): string { + const meanings = [ + ...(entry.value ? ["value"] : []), + ...(entry.typeOnlyValue ? ["value reached only type-only"] : []), + ...(entry.type ? ["type"] : []), + ...(entry.namespace ? ["namespace"] : []), + ]; + return ( + `${JSON.stringify(entry.name)} (${meanings.join(", ") || "no meaning"}; ` + + `listed among ${entry.listedIn + .map((source) => + source === "exports" + ? "the module's exports" + : "the export assignment's members", + ) + .join(" and ")})` + ); +} + +/** + * How a diagnosis states an export listing (module header): the module + * TypeScript resolves the import to and every name it declares. + */ +export function describeExportListing( + listing: ExportListing | undefined, +): string { + if (listing === undefined) return "no export listing (none was asked for)"; + if (listing.module === undefined) { + return ( + "no module: TypeScript resolves the import to no module it reads " + + "declarations from, so it declares no export" + ); + } + const names = listing.exports.map(describeListedExport); + return ( + `the module ${listing.module}` + + (listing.exportAssignment ? ", which declares an export assignment," : "") + + ` declaring ${count(listing.exports.length, "export")}` + + (names.length === 0 ? "" : `: ${names.join(", ")}`) + ); +} + +/** + * Assert that a file type-checks (TEST-SPEC §7.6 Verdict): TypeScript + * reports no error for its program, in any of its files; a diagnosed + * failure naming the setup and every error otherwise. + */ +export function assertTypeChecks( + verdict: CoveredVerdict, + context: string, +): void { + if (verdict.typeChecks) return; + fail( + `${context}: the configuration file ${verdict.label} (${verdict.file}) ` + + `does not type-check in ${verdict.setup.label}: TypeScript 5.9.3 ` + + `reports ${count(verdict.errors.length, "error")} for its program — ` + + `${describeErrors(verdict.errors)} (TEST-SPEC §7.6 Verdict: a file ` + + `type-checks when TypeScript reports no error for its program, in any ` + + `of its files)`, + ); +} + +/** + * Assert a shape-violation arm (TEST-SPEC §7.6 Verdict, Pairing): its valid + * twin type-checks in the same setup and placement, and the arm fails to + * type-check there — at least one error located in its configuration file. + * Either failing is a diagnosed failure; verdicts of different setups, + * placements, or directories are a misuse. + */ +export function assertShapeViolation( + twin: CoveredVerdict, + arm: CoveredVerdict, + context: string, +): void { + if ( + twin.setup !== arm.setup || + twin.placement !== arm.placement || + path.posix.dirname(twin.file) !== path.posix.dirname(arm.file) + ) { + throw new Error( + `module channel's TypeScript driver: ${arm.label} is paired with ` + + `${twin.label} across setups, placements, or directories; a ` + + `shape-violation arm is paired with its twin in the same setup and ` + + `placement (${context})`, + ); + } + if (!twin.typeChecks) { + fail( + `${context}: the shape-violation arm ${arm.label} counts only where its ` + + `valid twin type-checks in the same setup and placement, and the twin ` + + `${twin.label} (${twin.file}) does not type-check in ` + + `${twin.setup.label}: TypeScript 5.9.3 reports ` + + `${count(twin.errors.length, "error")} for its program — ` + + `${describeErrors(twin.errors)} (TEST-SPEC §7.6 Pairing)`, + ); + } + if (!arm.failsToTypeCheck) { + fail( + `${context}: the shape-violation arm ${arm.label} (${arm.file}) does not ` + + `fail to type-check in ${arm.setup.label}: TypeScript 5.9.3 reports no ` + + `error located in the configuration file (${count(arm.errors.length, "error")} ` + + `in its program: ${describeErrors(arm.errors)}), while its valid twin ` + + `${twin.label} type-checks there (TEST-SPEC §7.6 Verdict: a file fails ` + + `to type-check when TypeScript reports at least one error located in ` + + `the configuration file)`, + ); + } +} diff --git a/test/helpers/module-channel-warning-calibration.cjs b/test/helpers/module-channel-warning-calibration.cjs new file mode 100644 index 00000000..0c33b76c --- /dev/null +++ b/test/helpers/module-channel-warning-calibration.cjs @@ -0,0 +1,72 @@ +// The module channel's warning calibration on a Node.js release (TEST-SPEC +// T7.6-7(a), S-10, S-3). Harness code, never product code, and it imports +// none: helpers/module-channel-node.ts (`learnWarningForm`) copies these +// bytes into a fresh directory of its own under the OS temporary directory +// and runs +// +// <release>/bin/node <this file> <report> <warnings> +// +// as a module run is run — no option before this file, a fresh HOME and +// TMPDIR, the harness's PATH, and nothing else in the environment — through +// the subprocess driver under its own hang guard, so the release prints +// warnings exactly as it prints them in a module run. `<warnings>` is a +// JSON array of the warnings to emit, each `{ type, code, message, detail }` +// (`code` and `detail` null where the warning carries none). +// +// It registers a `warning` listener on `process`, recording each warning +// the runtime delivers as the bootstrap's listener records it, and an +// `exit` listener writing the report — its protocol, the process +// identifier, and the warnings delivered — to `<report>`; then it emits +// each warning through `process.emitWarning`, in order. The release prints +// each one to standard error as it prints its own, and the driver learns +// the release's printed form from that output beside the report. Nothing +// here writes to standard output or standard error itself, sets a timer, +// or keeps the process alive. + +"use strict"; + +const fs = require("node:fs"); + +/** The report's protocol, which the driver's decoder requires. */ +const PROTOCOL = "xspec-warning-calibration/1"; + +const reportPath = process.argv[2]; +const emitted = JSON.parse(process.argv[3]); +const warnings = []; + +process.on("warning", (warning) => { + const type = warning === null ? "null" : typeof warning; + const readable = type === "object" || type === "function"; + warnings.push({ + type, + name: readable ? readText(warning, "name") : null, + code: readable ? readText(warning, "code") : null, + message: readable ? readText(warning, "message") : null, + detail: readable ? readText(warning, "detail") : null, + stack: readable ? readText(warning, "stack") : null, + }); +}); +process.on("exit", () => { + fs.writeFileSync( + reportPath, + JSON.stringify({ protocol: PROTOCOL, pid: process.pid, warnings }), + ); +}); + +for (const warning of emitted) { + process.emitWarning(warning.message, { + type: warning.type, + code: warning.code === null ? undefined : warning.code, + detail: warning.detail === null ? undefined : warning.detail, + }); +} + +/** `object[key]` where it is a string; null otherwise, or where it throws. */ +function readText(object, key) { + try { + const value = object[key]; + return typeof value === "string" ? value : null; + } catch { + return null; + } +} diff --git a/test/helpers/module-channel.ts b/test/helpers/module-channel.ts new file mode 100644 index 00000000..70469fcc --- /dev/null +++ b/test/helpers/module-channel.ts @@ -0,0 +1,1917 @@ +// The module channel's stagings (TEST-SPEC §7.6 *Placement*, H-1, H-2, H-8, +// H-11, C-2, S-3, S-7; SPEC 7.6 *Package and installation*, *Reach*). +// Harness machinery only: this module never imports product code, never +// loads a file of a package as a module or names one by its path as a +// channel (H-2), and runs no product. The one process it starts is a +// Node.js release E-1 provisions, asked which names it resolves to its own +// built-in modules. +// +// TEST-SPEC §7.6's Placement rule: the product's package directory, exactly +// as distributed — nothing installed into it afterwards, never a +// development tree (H-2) — is installed by placement alone, with no +// package-manager run, install step, or network access, under a name `N` of +// 7.6's grammar outside its exclusions, in a fresh staging whose ancestors +// H-1 has verified; every staging meets Reach's four conditions, and where a +// condition fails 7.6 promises nothing and no arm asserts anything there. +// This module makes those stagings for every test of 7.6 (P-17 and P-18 +// among them): +// +// - The package directory (`modulePackageDirectory`; C-2, H-8), checked +// before anything is staged. None given: every body of 7.6 fails there as +// a diagnosed assertion failure (`HarnessAssertionError`, declining +// shrinking), the module channel counting as part of the product, its +// diagnosis naming the executable — the binding's command line — beside +// which none is given, as every product-facing body's diagnosis names the +// absent artifact when no product is installed (H-8; S-7's no-product +// sweep, test/self/s7-red-green-sweep.test.ts). Given, +// it must be an absolute path — never resolved against the working +// directory, as helpers/node-releases.ts refuses a relative +// XSPEC_NODE_RELEASES_DIR — naming a directory. On the built product's +// binding (`missingFilesFailDiagnosed`, helpers/subprocess.ts) a path +// that does not exist is its missing product, failing diagnosed likewise; +// on any other binding (S-7's stub, a stand-in) it is a harness error. +// The directory is read once, entry by entry, never written and never +// followed below its root: a plain file by its bytes and mode, a +// directory by its mode, a symbolic link by its target. An entry of +// another kind is a harness error, and so — the conservative choice, H-2 +// forbidding a development tree, whose installed dependencies would +// resolve inside a placed copy — is an entry named `node_modules`, of any +// kind, at its root: a distribution carries none and a development tree +// does (a distribution bundling dependencies there is refused too). +// - The manifest's name (`readManifestName`; T7.6-4(a), T7-9(d)): read by +// parsing the directory's `package.json` and nothing else, under the +// strict reading below. A manifest that is absent, no readable plain +// file, not well-formed, or holding no string `name` gives none, and the +// reading says why. +// - N (`moduleNameGrammarProblem`, `moduleNameExclusion`, +// `verifyModuleName`; SPEC 7.6): `name` or `@scope/name`, each a +// non-empty run of lowercase ASCII letters, digits, `-`, `.`, and `_` +// beginning with a letter or digit, the whole at most 214 characters; +// never a name in the `@types` scope or an `@typescript` name beginning +// `lib-`; and, on a runtime arm, never a name one of the arm's releases +// resolves to a built-in module, the release itself asked +// (`require("node:module").isBuiltin`, run through the subprocess driver +// under its own hang guard), so the answer is that release's: `fs` is +// refused, `test` (built in only as `node:test`) admitted. The canonical +// N (`canonicalModuleName`) is the first of two fixed, unscoped, dot-free +// names that differs from the name the manifest gives, so the canonical +// install is an aliased one whatever the package calls itself. +// - Stagings (`ModuleStaging`): each a fresh directory under the OS +// temporary directory, its physical path used throughout, H-1's ancestor +// half verified as it is made (`verifyStagingIsolation`, +// helpers/staging-isolation.ts, under the staging mode `module-channel`) +// and again, with a Node.js run's exact environment, working directory, +// and release executables, wherever a driver asks before a run +// (`verifyIsolation`). The three project kinds (`stageProject`): an +// ES-module project, its `package.json` holding `"type": "module"`; a +// CommonJS project whose `package.json` holds no `type`; and one with no +// `package.json`. +// - Placements (`place`, `placeCanonical`): a copy at `node_modules/N` in a +// holding directory the caller names — the importing file's own or an +// ancestor, never itself named `node_modules` — or a symbolic link there +// to a copy elsewhere in the staging under no `node_modules`. Each copy is +// made entry by entry (helpers/tree-copy.ts: bytes and modes kept, links +// as links), given the package directory's own mode, and read back equal +// to the package as read before anything was staged. No staging write +// lands in a placed copy afterwards (H-2: nothing installed into it). +// Another package a staging installs beside a placement (T7.6-4(c), (e)) +// is written file by file, or copied entry by entry from a directory of +// the harness (`copyDirectory`: TypeScript's package), never at or below +// a placement. +// - Reach (`verifyReach`), checked on the finished staging before any tool +// runs, for each importing file: physical naming (the file named by its +// physical path, the path each tool is given); the holding directory the +// file's own or an ancestor along that path, the placement in place; +// nothing nearer (with `S`, `D`, and `T` as SPEC 7.6 defines them); no +// self-reference (no manifest in the file's directory or an ancestor +// giving a `name` that, each backslash read as `/`, is empty, `N`, or +// `N`'s scope, with or without one trailing `/`); and well-formed +// manifests. Where the caller declares them, it confirms the project kind +// — read off the manifest nearest the file: `"type": "module"` for an +// ES-module project; for a CommonJS project, no `type` member, or +// `"type": "commonjs"` where the caller declares that member +// (`nearestType`: T7.6-5(c), a CommonJS project as SPEC 7.6 reads it, +// judged in the CommonJS project's covered setups); no manifest at all +// for the third kind — and that nothing but the placement is installed +// in the staging (`alone`: the canonical placement's "nothing else +// installed"). +// - The strict manifest reading (`readManifestStrictly`, +// `judgeManifestBytes`; Reach's well-formed manifests): a readable plain +// file — a symbolic link to one followed, anything else never opened — +// holding, as UTF-8 with no byte-order mark, a JSON object that repeats no +// member name (in any object it holds, the conservative reading), whose +// `name` and `type` members, where present, are strings, and none of whose +// strings, member names included, escapes a lone surrogate. +// - Every failure but the two diagnosed ones is a `HarnessStagingError` of +// mode `module-channel` (helpers/permissions.ts) raised before any tool +// runs: a harness error (H-11), never a pass, a product failure, or a skip +// (H-9). A misuse of this module (a path that is no staging-relative path +// of names) is a plain `Error`. Each examination is a harness step under +// its own guard (TEST-SPEC S-3, helpers/step-guards.ts). + +import { Buffer } from "node:buffer"; +import type { Stats } from "node:fs"; +import * as fsp from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; +import { fail } from "./assertions.js"; +import type { NodeRelease } from "./node-releases.js"; +import type { StagingMode } from "./permissions.js"; +import { HarnessStagingError } from "./permissions.js"; +import type { StagedNodeRun } from "./staging-isolation.js"; +import { + NODE_MODULES_NAME, + PACKAGE_MANIFEST_NAME, + verifyStagingIsolation, +} from "./staging-isolation.js"; +import { guardStep } from "./step-guards.js"; +import type { ProductBinding, RunResult } from "./subprocess.js"; +import { rethrowHarnessError, runProduct } from "./subprocess.js"; +import { copyTreeBytes } from "./tree-copy.js"; + +/** The staging mode every refusal of this module names. */ +const MODE: StagingMode = "module-channel"; + +/** The prefix of every staging's directory under the OS temporary one. */ +export const MODULE_STAGING_PREFIX = "xspec-module-staging-"; + +/** 7.6's limit on N's length, in characters. */ +export const MODULE_NAME_MAX_LENGTH = 214; + +/** + * The canonical N's candidates (module header): fixed, unscoped, dot-free + * names of 7.6's grammar, built in on no release, differing from `xspec`, + * the executable's name, and from the names S-7's stub package and the + * committed stand-ins give. The first differing from the manifest's name is + * the canonical N. + */ +export const CANONICAL_MODULE_NAMES: readonly [string, string] = [ + "staged-config-module", + "staged-config-module-alias", +]; + +const LF = String.fromCodePoint(0x0a); +const BACKSLASH = String.fromCodePoint(0x5c); +const BYTE_ORDER_MARK = String.fromCodePoint(0xfeff); + +/** One of N's segments: 7.6's run of characters (module header). */ +const NAME_SEGMENT = /^[a-z0-9][a-z0-9._-]*$/; + +/** TEST-SPEC §7.6's Placement rule, closing a placement's refusal. */ +const PLACEMENT_RULE = + "the package directory, exactly as given, is installed by placement " + + "alone — a copy at node_modules/N, or a symbolic link there to a copy " + + "elsewhere in the staging under no node_modules — in a holding directory " + + "that is the importing file's own or an ancestor and is not itself named " + + "node_modules, under a name N of 7.6's grammar outside its exclusions " + + "(TEST-SPEC §7.6 Placement; SPEC 7.6 Package and installation)"; + +/** Reach's rule, closing a refusal of a finished staging. */ +const REACH_RULE = + "every staging of the module channel meets Reach's four conditions — " + + "nothing nearer, no self-reference, physical naming, and well-formed " + + "manifests — before any tool runs: where a condition fails, 7.6 promises " + + "nothing and no arm asserts anything there, so a staging failing one is a " + + "harness defect, never a pass, a product failure, or a skip (TEST-SPEC " + + "§7.6 Placement, H-11, H-9; SPEC 7.6 Reach)"; + +/** H-1's verification as it applies to the module channel's stagings. */ +const ISOLATION_RULE = + "an arm staging the defineConfig module runs only once the harness has " + + "verified, under the environment TypeScript and Node.js run in — " + + "TypeScript's current directory inside the staging, Node.js run with no " + + "NODE_PATH and a fresh HOME — that no ancestor of the staging root holds a " + + "package.json or a node_modules entry and that none of Node.js's global " + + "module folders holds a package, an unmet precondition a harness error, " + + "never a pass, a product failure, or a skip (TEST-SPEC H-1, H-11, H-9; " + + "SPEC 7.6)"; + +/** The package directory's rule, closing a refusal of one. */ +const PACKAGE_RULE = + "the module channel is given the product's package directory beside the " + + "executable as an absolute path naming a directory that holds exactly " + + "what the package's distribution carries — plain files, directories, and " + + "symbolic links, nothing installed into it, never a development tree " + + "(an entry named node_modules at its root is refused as one) — which the " + + "harness copies and never writes into (TEST-SPEC H-2, C-2, H-8; SPEC 7.6)"; + +// --------------------------------------------------------------------------- +// Arms and N +// --------------------------------------------------------------------------- + +/** + * What a staging serves: a type-checking arm (TypeScript's one route, on + * which a built-in name is no exclusion), or a runtime arm on the releases + * it runs (Node.js's routes, on which a name one of them resolves to a + * built-in module is excluded). + */ +export type ModuleArm = + | { readonly kind: "type-checking" } + | { readonly kind: "runtime"; readonly releases: readonly NodeRelease[] }; + +/** The type-checking arm. */ +export const TYPE_CHECKING_ARM: ModuleArm = Object.freeze({ + kind: "type-checking", +}); + +/** The runtime arm on `releases` (at least one). */ +export function runtimeArm(releases: readonly NodeRelease[]): ModuleArm { + if (releases.length === 0) { + throw new Error( + "module channel: a runtime arm runs on at least one Node.js release", + ); + } + return Object.freeze({ kind: "runtime", releases: [...releases] }); +} + +/** + * Why `name` is not a name of 7.6's grammar (module header), or null when it + * is one. Its exclusions are {@link moduleNameExclusion}'s and, on a runtime + * arm, {@link builtInNamesOn}'s. + */ +export function moduleNameGrammarProblem(name: string): string | null { + if (name.length > MODULE_NAME_MAX_LENGTH) { + return ( + `is ${String(name.length)} characters long, past 7.6's limit of ` + + `${String(MODULE_NAME_MAX_LENGTH)}` + ); + } + const segments = name.startsWith("@") + ? splitScoped(name) + : { scope: undefined, name }; + if (segments === undefined) { + return "is a scope with no name after it: a scoped name is @scope/name"; + } + if (segments.scope !== undefined && !NAME_SEGMENT.test(segments.scope)) { + return `has the scope ${JSON.stringify(segments.scope)}, ${SEGMENT_RULE}`; + } + if (!NAME_SEGMENT.test(segments.name)) { + return segments.scope === undefined + ? `is ${SEGMENT_RULE}` + : `has the name ${JSON.stringify(segments.name)} after its scope, ` + + SEGMENT_RULE; + } + return null; +} + +const SEGMENT_RULE = + "not a non-empty run of lowercase ASCII letters, digits, -, ., and _ " + + "beginning with a letter or digit (SPEC 7.6)"; + +/** `@scope/name` split at its first `/`, or undefined where it has none. */ +function splitScoped( + name: string, +): { readonly scope: string; readonly name: string } | undefined { + const slash = name.indexOf("/"); + if (slash < 0) return undefined; + return { scope: name.slice(1, slash), name: name.slice(slash + 1) }; +} + +/** + * Which of 7.6's exclusions for every arm `name` falls under, or null: a + * name in the `@types` scope, or an `@typescript` name beginning `lib-`. + */ +export function moduleNameExclusion(name: string): string | null { + if (name.startsWith("@types/")) { + return ( + "is a name in the @types scope, which TypeScript reserves for " + + "declaration packages (SPEC 7.6)" + ); + } + if (name.startsWith("@typescript/lib-")) { + return ( + "is a name in the @typescript scope beginning lib-, the form under " + + "which TypeScript looks up replacements for its libraries (SPEC 7.6)" + ); + } + return null; +} + +/** The canonical N for a package whose manifest gives `manifestName`. */ +export function canonicalModuleName(manifestName: string | undefined): string { + const [first, second] = CANONICAL_MODULE_NAMES; + return manifestName === first ? second : first; +} + +/** + * Which of `names` — each a name of 7.6's grammar — `release` resolves to + * one of its own built-in modules (module header), the release itself + * asked: one run of it, through the subprocess driver under its own hang + * guard, with no `NODE_OPTIONS` or `NODE_PATH`, evaluating + * `require("node:module").isBuiltin` over the names, which reports exactly + * the names `require` and `import` resolve to a built-in without the + * `node:` scheme. A run that fails or answers otherwise than one boolean + * per name leaves the exclusion unverified: `HarnessStagingError`. + */ +export async function builtInNamesOn( + release: NodeRelease, + names: readonly string[], + context: string, +): Promise<ReadonlySet<string>> { + for (const name of names) { + const problem = moduleNameGrammarProblem(name); + if (problem !== null) { + throw new Error( + `module channel: ${JSON.stringify(name)} ${problem}; only names of ` + + `7.6's grammar are put to a release (${context})`, + ); + } + } + const unverified = (detail: string): HarnessStagingError => + new HarnessStagingError( + MODE, + release.executable, + `${context}: whether the Node.js release ${release.version} resolves ` + + `${describeNames(names)} to built-in modules is unverified — ` + + `${detail}; a runtime arm never stages a name its release resolves ` + + `to a built-in module (TEST-SPEC §7.6 Placement; SPEC 7.6)`, + ); + // The names are of 7.6's grammar, so their JSON spelling is a plain + // string literal in the evaluated script. + const script = + `process.stdout.write(JSON.stringify(${JSON.stringify(names)}` + + `.map((name) => require("node:module").isBuiltin(name))));`; + const binding: ProductBinding = { + label: + `the Node.js release ${release.version} (${release.executable}), ` + + `asked which names it resolves to built-in modules`, + command: release.executable, + requiredFiles: [release.executable], + }; + let result: RunResult; + try { + result = await runProduct(binding, { + cwd: os.tmpdir(), + argv: ["--eval", script], + env: { NODE_OPTIONS: undefined, NODE_PATH: undefined }, + }); + } catch (error) { + rethrowHarnessError(error); + throw unverified(`its run failed (${describeError(error)})`); + } + if (result.exitCode !== 0 || result.signal !== null || result.stderr !== "") { + throw unverified( + `its run ended with exit code ${String(result.exitCode)} and signal ` + + `${String(result.signal)}, standard error ` + + JSON.stringify(result.stderr.slice(0, 400)), + ); + } + let answers: unknown; + try { + answers = JSON.parse(result.stdout); + } catch (error) { + throw unverified( + `its answer ${JSON.stringify(result.stdout.slice(0, 400))} is not ` + + `JSON (${describeError(error)})`, + ); + } + if ( + !Array.isArray(answers) || + answers.length !== names.length || + !answers.every((answer) => typeof answer === "boolean") + ) { + throw unverified( + `its answer ${JSON.stringify(result.stdout.slice(0, 400))} is not ` + + `one boolean per name`, + ); + } + return new Set(names.filter((_name, index) => answers[index] === true)); +} + +/** + * Verify that `name` is a name of 7.6's grammar outside its exclusions for + * `arm` (module header): on every arm, no `@types` name and no + * `@typescript/lib-` name; on a runtime arm, no name any of its releases + * resolves to a built-in module, each release asked. Resolves when it is; + * throws `HarnessStagingError` naming the rule it breaks otherwise. + */ +export async function verifyModuleName( + name: string, + arm: ModuleArm, + context: string, +): Promise<void> { + const refused = (detail: string): HarnessStagingError => + new HarnessStagingError( + MODE, + name, + `${context}: the name ${JSON.stringify(name)} ${detail}; ` + + PLACEMENT_RULE, + ); + const problem = moduleNameGrammarProblem(name); + if (problem !== null) throw refused(problem); + const exclusion = moduleNameExclusion(name); + if (exclusion !== null) throw refused(exclusion); + if (arm.kind !== "runtime") return; + const builtIn: string[] = []; + for (const release of arm.releases) { + const names = await builtInNamesOn(release, [name], context); + if (names.has(name)) builtIn.push(release.version); + } + if (builtIn.length > 0) { + throw refused( + `is a name the Node.js release${builtIn.length === 1 ? "" : "s"} ` + + `${builtIn.join(", ")} resolve${builtIn.length === 1 ? "s" : ""} ` + + `to a built-in module, which a runtime arm never stages (SPEC 7.6: ` + + `excluded from Node.js's resolution and the runtime contract)`, + ); + } +} + +/** Names, for a diagnosis. */ +function describeNames(names: readonly string[]): string { + const shown = names.slice(0, 5).map((name) => JSON.stringify(name)); + return names.length > 5 + ? `${shown.join(", ")}, and ${String(names.length - 5)} more` + : shown.join(", "); +} + +// --------------------------------------------------------------------------- +// The strict manifest reading +// --------------------------------------------------------------------------- + +/** + * A manifest read strictly (module header): well-formed, with its top-level + * members as JSON gives them, or not, with what makes it so. + */ +export type ManifestReading = + | { + readonly wellFormed: true; + readonly members: Readonly<Record<string, unknown>>; + } + | { readonly wellFormed: false; readonly problem: string }; + +/** + * Judge a manifest's bytes strictly (module header): UTF-8 with no + * byte-order mark, a JSON object, no member name repeated in any object it + * holds, no string (member names included) escaping a lone surrogate, and + * `name` and `type`, where present, strings. + */ +export function judgeManifestBytes(bytes: Uint8Array): ManifestReading { + const refused = (problem: string): ManifestReading => ({ + wellFormed: false, + problem, + }); + let text: string; + try { + // `fatal`: an ill-formed sequence throws; `ignoreBOM`: a byte-order mark + // is kept, so that it is seen and refused. + text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode( + bytes, + ); + } catch { + return refused("is not UTF-8"); + } + if (text.startsWith(BYTE_ORDER_MARK)) { + return refused("begins with a byte-order mark"); + } + let value: unknown; + try { + value = JSON.parse(text); + } catch (error) { + return refused(`is not JSON (${describeError(error)})`); + } + if (typeof value !== "object" || value === null || Array.isArray(value)) { + return refused(`holds ${describeJsonKind(value)}, not a JSON object`); + } + // JSON.parse has accepted the text, so the scan reads a valid document. + const scanned = scanJsonStrings(text); + if (scanned !== null) return refused(scanned); + const members = value as Readonly<Record<string, unknown>>; + for (const member of ["name", "type"]) { + if (Object.hasOwn(members, member) && typeof members[member] !== "string") { + return refused( + `holds a ${JSON.stringify(member)} member that is ` + + `${describeJsonKind(members[member])}, not a string`, + ); + } + } + return { wellFormed: true, members }; +} + +/** + * Read the manifest at `file` strictly (module header): undefined where no + * entry occupies the path; else its reading, a manifest that is no readable + * plain file (a symbolic link to one followed) refused unopened. + */ +export async function readManifestStrictly( + file: string, +): Promise<ManifestReading | undefined> { + const refused = (problem: string): ManifestReading => ({ + wellFormed: false, + problem, + }); + let stats: Stats; + try { + stats = await fsp.lstat(file); + } catch (error) { + if (isAbsence(error)) return undefined; + return refused(`cannot be examined (${describeError(error)})`); + } + if (stats.isSymbolicLink()) { + try { + stats = await fsp.stat(file); + } catch (error) { + return refused( + `is a symbolic link reaching nothing readable ` + + `(${describeError(error)})`, + ); + } + } + if (!stats.isFile()) { + return refused(`is ${entryKind(stats)}, not a readable plain file`); + } + let bytes: Buffer; + try { + bytes = await fsp.readFile(file); + } catch (error) { + return refused(`cannot be read (${describeError(error)})`); + } + return judgeManifestBytes(bytes); +} + +const QUOTE = 0x22; +const BACKSLASH_CODE = 0x5c; +const COLON = 0x3a; +const OPEN_BRACE = 0x7b; +const CLOSE_BRACE = 0x7d; +const OPEN_BRACKET = 0x5b; +const CLOSE_BRACKET = 0x5d; +const LETTER_U = 0x75; + +/** JSON's whitespace: tab, line feed, carriage return, and space. */ +function isJsonWhitespace(code: number): boolean { + return code === 0x09 || code === 0x0a || code === 0x0d || code === 0x20; +} + +/** JSON's two-character escapes, each by its letter's code. */ +const SIMPLE_ESCAPES: ReadonlyMap<number, string> = new Map([ + [QUOTE, String.fromCodePoint(QUOTE)], + [BACKSLASH_CODE, BACKSLASH], + [0x2f, "/"], + [0x62, String.fromCodePoint(0x08)], + [0x66, String.fromCodePoint(0x0c)], + [0x6e, String.fromCodePoint(0x0a)], + [0x72, String.fromCodePoint(0x0d)], + [0x74, String.fromCodePoint(0x09)], +]); + +/** + * Scan a JSON text JSON.parse has accepted for what it lets through (module + * header): a member name repeated in one object, compared as decoded, and a + * string escaping a lone surrogate. The first found, or null. + */ +function scanJsonStrings(text: string): string | null { + // One entry per open container: an object's member names, null for an + // array. + const containers: (Set<string> | null)[] = []; + let index = 0; + while (index < text.length) { + const code = text.charCodeAt(index); + if (code !== QUOTE) { + if (code === OPEN_BRACE) containers.push(new Set()); + else if (code === OPEN_BRACKET) containers.push(null); + else if (code === CLOSE_BRACE || code === CLOSE_BRACKET) { + containers.pop(); + } + index += 1; + continue; + } + const string = readJsonString(text, index); + if (string.loneSurrogate !== undefined) { + return ( + `holds a string escaping the lone surrogate U+` + + string.loneSurrogate.toString(16).toUpperCase().padStart(4, "0") + ); + } + let next = string.end; + while (next < text.length && isJsonWhitespace(text.charCodeAt(next))) { + next += 1; + } + const names = containers[containers.length - 1]; + if (text.charCodeAt(next) === COLON && names instanceof Set) { + if (names.has(string.value)) { + return `repeats the member name ${JSON.stringify(string.value)} in one object`; + } + names.add(string.value); + } + index = string.end; + } + return null; +} + +/** + * The JSON string opening at `start` (its quote): its decoded value, the + * index past its closing quote, and the first lone surrogate it escapes — + * a high surrogate's escape not followed at once by a low surrogate's, or a + * low surrogate's escape not preceded by a high one's. + */ +function readJsonString( + text: string, + start: number, +): { + readonly value: string; + readonly end: number; + readonly loneSurrogate: number | undefined; +} { + const parts: string[] = []; + let lone: number | undefined; + let index = start + 1; + while (index < text.length) { + const code = text.charCodeAt(index); + if (code === QUOTE) { + return { value: parts.join(""), end: index + 1, loneSurrogate: lone }; + } + if (code !== BACKSLASH_CODE) { + parts.push(text.charAt(index)); + index += 1; + continue; + } + const letter = text.charCodeAt(index + 1); + if (letter !== LETTER_U) { + parts.push(SIMPLE_ESCAPES.get(letter) ?? ""); + index += 2; + continue; + } + const unit = Number.parseInt(text.slice(index + 2, index + 6), 16); + index += 6; + if (unit >= 0xd800 && unit <= 0xdbff) { + if ( + text.charCodeAt(index) === BACKSLASH_CODE && + text.charCodeAt(index + 1) === LETTER_U + ) { + const low = Number.parseInt(text.slice(index + 2, index + 6), 16); + if (low >= 0xdc00 && low <= 0xdfff) { + parts.push(String.fromCharCode(unit, low)); + index += 6; + continue; + } + } + lone ??= unit; + } else if (unit >= 0xdc00 && unit <= 0xdfff) { + lone ??= unit; + } + parts.push(String.fromCharCode(unit)); + } + return { value: parts.join(""), end: text.length, loneSurrogate: lone }; +} + +/** + * The name a package's manifest gives (module header): `name`, exactly as + * spelled, where its `package.json` reads as a well-formed manifest holding + * a string `name`; otherwise undefined, `detail` saying why. + */ +export interface ManifestName { + readonly name: string | undefined; + /** Why the manifest gives no name; empty where it gives one. */ + readonly detail: string; +} + +/** + * Read the name the manifest of the package directory `packageDir` gives + * (T7.6-4(a), T7-9(d); module header): by parsing its `package.json` and + * nothing else, strictly. One harness step under its own guard. + */ +export async function readManifestName( + packageDir: string, +): Promise<ManifestName> { + const file = path.join(packageDir, PACKAGE_MANIFEST_NAME); + const reading = await guardStep( + `reading the name the manifest ${file} gives (readManifestName)`, + () => readManifestStrictly(file), + ); + if (reading === undefined) { + return { name: undefined, detail: `${file} is absent` }; + } + if (!reading.wellFormed) { + return { name: undefined, detail: `${file} ${reading.problem}` }; + } + const name = reading.members["name"]; + return typeof name === "string" + ? { name, detail: "" } + : { name: undefined, detail: `${file} holds no name member` }; +} + +// --------------------------------------------------------------------------- +// The package directory +// --------------------------------------------------------------------------- + +/** One entry of a package directory as read, never followed. */ +export type PackageEntry = + | { readonly kind: "file"; readonly mode: number; readonly bytes: Buffer } + | { readonly kind: "directory"; readonly mode: number } + | { readonly kind: "symlink"; readonly target: Buffer }; + +/** + * A package directory, or a copy of one, as read (module header): the + * directory's own permission bits, and each entry below it by its relative + * path's exact bytes (`/`-separated, latin1-encoded), in byte order. + */ +export interface PackageTree { + readonly mode: number; + readonly entries: ReadonlyMap<string, PackageEntry>; +} + +/** The package directory a binding gives, checked (module header). */ +export interface PackageDirectory { + /** The directory, exactly as the binding gives it. */ + readonly path: string; + /** What it held when checked. */ + readonly tree: PackageTree; + /** The name its manifest gives ({@link readManifestName}). */ + readonly manifestName: ManifestName; +} + +/** + * The package directory `binding` gives beside its executable, checked + * before anything is staged (module header; TEST-SPEC H-2, H-8, C-2). None + * given — and, on the built product's binding, a path that does not exist + * — is H-8's missing product: a diagnosed assertion failure declining + * shrinking, nothing staged. A relative path, a path naming no directory + * on any other binding, anything but a directory, an unreadable one, an + * entry of another kind than a plain file, a directory, or a symbolic link, + * and an entry named `node_modules` at its root (the development tree) are + * `HarnessStagingError`s. Never writes into it. + */ +export async function modulePackageDirectory( + binding: ProductBinding, + context: string, +): Promise<PackageDirectory> { + const given = binding.packageDir; + if (given === undefined) { + const executable = [binding.command, ...(binding.prefixArgs ?? [])]; + fail( + `${context}: ${binding.label}: no package directory is given beside ` + + `the executable (${executable.join(" ")}) — the module channel ` + + `counts as part of the product, ` + + `so every test of 7.6 fails here, diagnosed (TEST-SPEC H-8, C-2; ` + + `H-2's module channel). Give the directory ` + + `.github/scripts/pack-package.sh prints as XSPEC_PACKAGE_DIR ` + + `(AGENTS.md). Nothing was staged.`, + { shrinkable: false }, + ); + } + const refused = (detail: string): HarnessStagingError => + new HarnessStagingError( + MODE, + given, + `${context}: ${binding.label}: the package directory ` + + `${JSON.stringify(given)} ${detail}; ${PACKAGE_RULE}`, + ); + if (!path.isAbsolute(given)) { + throw refused( + "is not an absolute path: a package directory is never resolved " + + "against the working directory", + ); + } + const examined = await guardStep( + `examining the package directory ${given} (${context})`, + async () => { + try { + return { stats: await fsp.stat(given) }; + } catch (error) { + return { error }; + } + }, + ); + if ("error" in examined) { + if ( + isAbsence(examined.error) && + binding.missingFilesFailDiagnosed === true + ) { + fail( + `${context}: ${binding.label}: the package directory ${given} does ` + + `not exist (${describeError(examined.error)}) — the product's ` + + `package is not installed beside it, so every test of 7.6 fails ` + + `here, diagnosed (TEST-SPEC H-8). Pack it with ` + + ".github/scripts/pack-package.sh after `npm run build` " + + `(AGENTS.md). Nothing was staged.`, + { shrinkable: false }, + ); + } + throw refused( + isAbsence(examined.error) + ? `does not exist (${describeError(examined.error)}): only the ` + + `built product's missing package is H-8's diagnosed missing ` + + `product, and any other binding's is a defect in the harness` + : `cannot be examined (${describeError(examined.error)})`, + ); + } + if (!examined.stats.isDirectory()) { + throw refused(`is ${entryKind(examined.stats)}, not a directory`); + } + const tree = await readPackageTree(given, context, refused, { + refuseInstalled: true, + }); + return Object.freeze({ + path: given, + tree, + manifestName: Object.freeze(await readManifestName(given)), + }); +} + +/** + * Read the package directory, or copy, at `root` (module header): its own + * mode, and every entry below it, never followed. An entry of another kind + * than a plain file, a directory, or a symbolic link, a failed read, and — + * with `refuseInstalled` — an entry named `node_modules` at its root, of + * any kind, are `refused`. One harness step under its own guard. + */ +export async function readPackageTree( + root: string, + context: string, + refused: (detail: string) => HarnessStagingError, + options: { readonly refuseInstalled?: boolean } = {}, +): Promise<PackageTree> { + return guardStep( + `reading the package tree at ${root} (${context})`, + async () => { + const entries = new Map<string, PackageEntry>(); + let mode: number; + try { + mode = (await fsp.stat(root)).mode & 0o7777; + } catch (error) { + throw refused(`cannot be examined (${describeError(error)})`); + } + const walk = async ( + directory: Buffer, + relative: Buffer, + ): Promise<void> => { + let names: Buffer[]; + try { + names = await fsp.readdir(directory, { encoding: "buffer" }); + } catch (error) { + throw refused( + `holds the directory ${directory.toString()} that cannot be ` + + `listed (${describeError(error)})`, + ); + } + names.sort(Buffer.compare); + for (const name of names) { + const childRelative = + relative.length === 0 + ? name + : Buffer.concat([relative, Buffer.from("/"), name]); + const child = Buffer.concat([directory, Buffer.from("/"), name]); + const shown = childRelative.toString(); + if ( + options.refuseInstalled === true && + relative.length === 0 && + name.equals(Buffer.from(NODE_MODULES_NAME)) + ) { + throw refused( + `holds an entry named ${NODE_MODULES_NAME} at its root — a ` + + `development tree's installed dependencies, which would ` + + `resolve inside a placed copy; a distribution carries none ` + + `(TEST-SPEC H-2: never a development tree)`, + ); + } + let stats: Stats; + try { + stats = await fsp.lstat(child); + } catch (error) { + throw refused( + `holds ${shown}, which cannot be examined ` + + `(${describeError(error)})`, + ); + } + const key = childRelative.toString("latin1"); + if (stats.isSymbolicLink()) { + entries.set(key, { + kind: "symlink", + target: await fsp.readlink(child, { encoding: "buffer" }), + }); + } else if (stats.isDirectory()) { + entries.set(key, { kind: "directory", mode: stats.mode & 0o7777 }); + await walk(child, childRelative); + } else if (stats.isFile()) { + let bytes: Buffer; + try { + bytes = await fsp.readFile(child); + } catch (error) { + throw refused( + `holds the file ${shown}, which cannot be read ` + + `(${describeError(error)})`, + ); + } + entries.set(key, { + kind: "file", + mode: stats.mode & 0o7777, + bytes, + }); + } else { + throw refused( + `holds ${shown}, ${entryKind(stats)} — neither a plain file, a ` + + `directory, nor a symbolic link, which no distribution carries`, + ); + } + } + }; + await walk(Buffer.from(root), Buffer.alloc(0)); + return Object.freeze({ mode, entries }); + }, + ); +} + +/** + * How `actual` differs from `expected` (two package trees): the first few + * differences — an entry added, removed, or changed in kind, mode, bytes, + * or target, or the directory's own mode — or null where they are equal. + */ +export function describeTreeDifference( + expected: PackageTree, + actual: PackageTree, +): string | null { + const differences: string[] = []; + if (expected.mode !== actual.mode) { + differences.push( + `the directory's own mode is ${octal(actual.mode)}, not ` + + octal(expected.mode), + ); + } + const keys = [ + ...new Set([...expected.entries.keys(), ...actual.entries.keys()]), + ]; + keys.sort((left, right) => + Buffer.compare(Buffer.from(left, "latin1"), Buffer.from(right, "latin1")), + ); + for (const key of keys) { + const shown = Buffer.from(key, "latin1").toString(); + const was = expected.entries.get(key); + const is = actual.entries.get(key); + if (was === undefined) differences.push(`${shown} is added`); + else if (is === undefined) differences.push(`${shown} is missing`); + else { + const change = describeEntryChange(was, is); + if (change !== null) differences.push(`${shown} ${change}`); + } + } + if (differences.length === 0) return null; + const shown = differences.slice(0, 5).join("; "); + return differences.length > 5 + ? `${shown}; and ${String(differences.length - 5)} more` + : shown; +} + +/** How one entry changed, or null where it did not. */ +function describeEntryChange( + was: PackageEntry, + is: PackageEntry, +): string | null { + if (was.kind !== is.kind) return `is a ${is.kind}, not a ${was.kind}`; + if (was.kind === "symlink" && is.kind === "symlink") { + return was.target.equals(is.target) + ? null + : `links to ${JSON.stringify(is.target.toString())}, not ` + + JSON.stringify(was.target.toString()); + } + if (was.kind === "directory" && is.kind === "directory") { + return was.mode === is.mode + ? null + : `has mode ${octal(is.mode)}, not ${octal(was.mode)}`; + } + if (was.kind === "file" && is.kind === "file") { + if (was.mode !== is.mode) { + return `has mode ${octal(is.mode)}, not ${octal(was.mode)}`; + } + return was.bytes.equals(is.bytes) + ? null + : `holds ${String(is.bytes.length)} bytes differing from the ` + + `${String(was.bytes.length)} read before`; + } + return null; +} + +function octal(mode: number): string { + return `0${mode.toString(8).padStart(3, "0")}`; +} + +// --------------------------------------------------------------------------- +// Stagings +// --------------------------------------------------------------------------- + +/** + * The three project kinds (module header; SPEC 7.6 Covered setups): an + * ES-module project, its `package.json` holding `"type": "module"`; a + * CommonJS project whose `package.json` holds no `type` member; and a + * CommonJS project with no `package.json` at all. + */ +export type ProjectKind = "es-module" | "commonjs" | "no-manifest"; + +/** Every project kind, in TEST-SPEC §7.6's order. */ +export const PROJECT_KINDS: readonly ProjectKind[] = [ + "es-module", + "commonjs", + "no-manifest", +]; + +/** The manifest a project kind's directory holds, or undefined for none. */ +function projectManifest(kind: ProjectKind): string | undefined { + switch (kind) { + case "es-module": + return `${JSON.stringify({ type: "module" }, null, 2)}${LF}`; + case "commonjs": + return `${JSON.stringify({})}${LF}`; + case "no-manifest": + return undefined; + } +} + +/** + * The `type` member a CommonJS project's nearest `package.json` may hold + * (T7.6-5(c)): `"commonjs"`, which TypeScript and Node.js read as they read + * a manifest holding no `type` — CommonJS, since SPEC 7.6 makes a project + * an ES-module one where its nearest manifest's `type` is `"module"` and a + * CommonJS one otherwise — so such a project is judged in the CommonJS + * project's covered setups. + */ +export type CommonJsTypeMember = "commonjs"; + +/** A copy at `node_modules/N`, or a symbolic link there to a copy. */ +export type PlacementForm = "copy" | "symlink"; + +/** One placement a staging is asked for ({@link ModuleStaging.place}). */ +export interface PlacementRequest { + /** N: a name of 7.6's grammar outside its exclusions for `arm`. */ + readonly name: string; + /** The holding directory, staging-relative (`""` for the root). */ + readonly holdingDir: string; + /** The arm the staging serves ({@link ModuleArm}). */ + readonly arm: ModuleArm; + /** A copy (the default), or a symbolic link to a copy at `copyDir`. */ + readonly form?: PlacementForm; + /** + * For a symbolic-link placement: where its copy lies, staging-relative, + * under no `node_modules` — `placed-copies/copy-<k>` unless given. + */ + readonly copyDir?: string; +} + +/** A placement made ({@link ModuleStaging.place}). */ +export interface Placement { + /** N. */ + readonly name: string; + /** The holding directory, absolute and physical. */ + readonly holdingDir: string; + /** `<holdingDir>/node_modules/N`. */ + readonly path: string; + readonly form: PlacementForm; + /** The copy: `path` itself, or the directory a symbolic link reaches. */ + readonly copy: string; +} + +/** One importing file's staging, as Reach is checked on it. */ +export interface ReachStaging { + /** The importing file, staging-relative, by its physical path. */ + readonly importingFile: string; + /** The placement its import reaches. */ + readonly placement: Placement; + /** The project kind the staging declares, confirmed where given. */ + readonly project?: ProjectKind; + /** + * For a CommonJS project (`project` `"commonjs"`) whose nearest + * `package.json` holds a `type` member: that member, `"commonjs"` + * (T7.6-5(c)), confirmed with the project kind in place of "no `type` + * member". Declared beside any other kind, or none, it is a misuse. + */ + readonly nearestType?: CommonJsTypeMember; + /** + * Whether nothing but `placement` is installed in the staging (the + * canonical placement's "nothing else installed"), confirmed where set. + */ + readonly alone?: boolean; +} + +/** {@link ModuleStaging.create}'s options. */ +export interface ModuleStagingOptions { + /** + * The directory the staging is made in: the OS temporary directory unless + * given — a self-test's probe directory alone gives one. + */ + readonly parent?: string; +} + +/** + * A fresh staging of the module channel (module header): made only once + * the binding's package directory is checked, at its physical path, its + * ancestors verified by H-1; placements, the three project kinds, and Reach + * checked on the finished staging. Dispose of it once its arm is done. + */ +export class ModuleStaging { + /** The staging's root: absolute and physical. */ + readonly root: string; + /** The package directory placed here, as checked. */ + readonly package: PackageDirectory; + /** Leads every diagnosis: the arm the staging serves. */ + readonly context: string; + readonly #placements: Placement[] = []; + #copies = 0; + #disposed = false; + + private constructor(root: string, pkg: PackageDirectory, context: string) { + this.root = root; + this.package = pkg; + this.context = context; + } + + /** + * Check `binding`'s package directory ({@link modulePackageDirectory}: + * none given fails diagnosed, before anything is staged), then make a + * fresh staging under the OS temporary directory (or `options.parent`), + * at its physical path, and verify H-1's ancestor half on it. A failed + * verification removes the staging and throws `HarnessStagingError`. + */ + static async create( + binding: ProductBinding, + context: string, + options: ModuleStagingOptions = {}, + ): Promise<ModuleStaging> { + const pkg = await modulePackageDirectory(binding, context); + const parent = options.parent ?? os.tmpdir(); + const made = await guardStep( + `creating a fresh module-channel staging under ${parent} (${context})`, + () => fsp.mkdtemp(path.join(parent, MODULE_STAGING_PREFIX)), + ); + try { + const root = await guardStep( + `reading the physical path of the staging ${made} (${context})`, + () => fsp.realpath(made), + ); + const staging = new ModuleStaging(root, pkg, context); + await staging.verifyIsolation(); + return staging; + } catch (error) { + await removeTree(made, context); + throw error; + } + } + + /** The canonical N for this staging's package ({@link canonicalModuleName}). */ + get canonicalName(): string { + return canonicalModuleName(this.package.manifestName.name); + } + + /** + * The absolute path of `rel`, a staging-relative path of names separated + * by `/` (`""` or `"."` for the root); anything else is a usage error. + */ + path(rel: string): string { + if (rel === "" || rel === ".") return this.root; + const names = rel.split("/"); + if ( + path.isAbsolute(rel) || + names.some((name) => name === "" || name === "." || name === "..") + ) { + throw new Error( + `module channel: ${JSON.stringify(rel)} is no staging-relative path ` + + `of names separated by / (${this.context})`, + ); + } + return path.join(this.root, ...names); + } + + /** Write `contents` at `rel`, never over an entry, creating its parents. */ + async writeFile(rel: string, contents: string | Uint8Array): Promise<string> { + const target = this.path(rel); + this.#refuseInsidePlacement(target, "the file"); + await guardStep(`writing ${target} (${this.context})`, async () => { + await fsp.mkdir(path.dirname(target), { recursive: true }); + await fsp.writeFile(target, contents, { flag: "wx" }); + }); + return target; + } + + /** Make the directory `rel`, and its parents. */ + async makeDirectory(rel: string): Promise<string> { + const target = this.path(rel); + this.#refuseInsidePlacement(target, "the directory"); + await guardStep(`making the directory ${target} (${this.context})`, () => + fsp.mkdir(target, { recursive: true }), + ); + return target; + } + + /** + * Make a symbolic link at `rel` to `targetRel`, both staging-relative, the + * link naming its target's absolute path, so it never reaches outside the + * staging. + */ + async link(rel: string, targetRel: string): Promise<string> { + const at = this.path(rel); + const target = this.path(targetRel); + this.#refuseInsidePlacement(at, "the symbolic link"); + await guardStep( + `linking ${at} to ${target} (${this.context})`, + async () => { + await fsp.mkdir(path.dirname(at), { recursive: true }); + await fsp.symlink(target, at); + }, + ); + return at; + } + + /** + * Copy the directory `source` entry by entry (helpers/tree-copy.ts: bytes, + * modes, and symbolic links kept) to the new directory `rel`, given + * `source`'s own mode, creating its parents: another package installed in + * the staging beside a placement (T7.6-4(e): TypeScript's package at + * `node_modules/typescript`), never at or below a placement — the package + * directory itself is installed by {@link place} alone. An occupied `rel` + * fails. Returns the copy's absolute path. + */ + async copyDirectory(rel: string, source: string): Promise<string> { + const target = this.path(rel); + this.#refuseInsidePlacement(target, "the copied directory"); + await guardStep( + `making ${target} for a copy of ${source} (${this.context})`, + async () => { + await fsp.mkdir(path.dirname(target), { recursive: true }); + await fsp.mkdir(target); + }, + ); + await copyTreeBytes(Buffer.from(source), Buffer.from(target)); + await guardStep( + `giving ${target} the mode of ${source} (${this.context})`, + async () => { + await fsp.chmod(target, (await fsp.stat(source)).mode & 0o7777); + }, + ); + return target; + } + + /** + * Stage a project of `kind` in the directory `rel` (module header): its + * `package.json` for an ES-module or a CommonJS project, none for the + * third kind. Returns the directory's absolute path. + */ + async stageProject(rel: string, kind: ProjectKind): Promise<string> { + const directory = this.path(rel); + this.#refuseInsidePlacement(directory, "the project directory"); + const manifest = projectManifest(kind); + await guardStep( + `staging ${kind} project at ${directory} (${this.context})`, + async () => { + await fsp.mkdir(directory, { recursive: true }); + if (manifest !== undefined) { + await fsp.writeFile( + path.join(directory, PACKAGE_MANIFEST_NAME), + manifest, + { flag: "wx" }, + ); + } + }, + ); + return directory; + } + + /** + * Place the package directory under `request.name` in the holding + * directory `request.holdingDir` (module header): N verified for the arm + * ({@link verifyModuleName}), a copy made entry by entry at + * `node_modules/N`, or at `copyDir` with a symbolic link to it at + * `node_modules/N`, each copy read back equal to the package as checked. + * A holding directory named `node_modules`, a copy under one, an occupied + * path, and a copy that differs are `HarnessStagingError`s. + */ + async place(request: PlacementRequest): Promise<Placement> { + const form = request.form ?? "copy"; + const holdingDir = this.path(request.holdingDir); + const placementPath = path.join( + holdingDir, + NODE_MODULES_NAME, + ...request.name.split("/"), + ); + const context = `${this.context}, placing the package at ${placementPath}`; + await verifyModuleName(request.name, request.arm, context); + const refused = (detail: string): HarnessStagingError => + new HarnessStagingError( + MODE, + placementPath, + `${context}: ${detail}; ${PLACEMENT_RULE}`, + ); + if (path.basename(holdingDir) === NODE_MODULES_NAME) { + throw refused( + `the holding directory ${holdingDir} is itself named ` + + `${NODE_MODULES_NAME}, a directory TypeScript's lookup and ` + + `require's skip`, + ); + } + this.#refuseInsidePlacement(holdingDir, "the holding directory"); + if (form === "copy" && request.copyDir !== undefined) { + throw new Error( + `module channel: copyDir names where a symbolic-link placement's ` + + `copy lies; a copy placement lies at node_modules/N (${context})`, + ); + } + let copy = placementPath; + if (form === "symlink") { + this.#copies += 1; + const copyRel = + request.copyDir ?? `placed-copies/copy-${String(this.#copies)}`; + if (copyRel.split("/").includes(NODE_MODULES_NAME)) { + throw refused( + `the copy a symbolic-link placement reaches, ${copyRel}, lies ` + + `under a directory named ${NODE_MODULES_NAME}: it lies elsewhere ` + + `in the staging, under no ${NODE_MODULES_NAME}`, + ); + } + copy = this.path(copyRel); + this.#refuseInsidePlacement(copy, "the linked copy"); + } + const occupied = await guardStep( + `making room for ${placementPath} (${context})`, + async () => { + await fsp.mkdir(path.dirname(placementPath), { recursive: true }); + await fsp.mkdir(path.dirname(copy), { recursive: true }); + const taken: string[] = []; + for (const target of new Set([placementPath, copy])) { + if ((await lstatOrAbsent(target)) !== undefined) taken.push(target); + } + return taken; + }, + ); + if (occupied.length > 0) { + throw refused(`${occupied.join(" and ")} is occupied already`); + } + await this.#copyPackageTo(copy, context, refused); + if (form === "symlink") { + await guardStep(`linking ${placementPath} to ${copy} (${context})`, () => + fsp.symlink(copy, placementPath), + ); + } + const placement: Placement = Object.freeze({ + name: request.name, + holdingDir, + path: placementPath, + form, + copy, + }); + this.#placements.push(placement); + return placement; + } + + /** + * The canonical placement (TEST-SPEC §7.6 Placement): a copy at + * `node_modules/N` in the holding directory `holdingDir` — the importing + * file's own — N {@link canonicalName}. + */ + async placeCanonical(holdingDir: string, arm: ModuleArm): Promise<Placement> { + return this.place({ name: this.canonicalName, holdingDir, arm }); + } + + /** + * Verify H-1's isolation of the staging (helpers/staging-isolation.ts): + * its ancestor half, and, given a Node.js run's exact environment, + * working directory, and release executables, its global half. + */ + async verifyIsolation(run?: StagedNodeRun): Promise<void> { + await verifyStagingIsolation({ + root: this.root, + role: "the module channel's staging", + context: this.context, + mode: MODE, + rule: ISOLATION_RULE, + ...(run === undefined ? {} : { run }), + }); + } + + /** Remove the staging, its placements included; idempotent. */ + async dispose(): Promise<void> { + if (this.#disposed) return; + this.#disposed = true; + await removeTree(this.root, this.context); + } + + /** Copy the package directory to the new directory `destination`. */ + async #copyPackageTo( + destination: string, + context: string, + refused: (detail: string) => HarnessStagingError, + ): Promise<void> { + await guardStep(`creating ${destination} (${context})`, () => + fsp.mkdir(destination), + ); + await copyTreeBytes( + Buffer.from(this.package.path), + Buffer.from(destination), + ); + await guardStep( + `giving ${destination} the package directory's mode (${context})`, + () => fsp.chmod(destination, this.package.tree.mode), + ); + const copied = await readPackageTree(destination, context, (detail) => + refused(`the copy at ${destination} ${detail}`), + ); + const difference = describeTreeDifference(this.package.tree, copied); + if (difference !== null) { + throw refused( + `the copy at ${destination} differs from the package directory ` + + `${this.package.path} as read before anything was staged: ` + + difference, + ); + } + } + + /** Refuse a staging write at or below a placement or its copy (H-2). */ + #refuseInsidePlacement(target: string, what: string): void { + for (const placement of this.#placements) { + for (const placed of new Set([placement.path, placement.copy])) { + if (target === placed || target.startsWith(`${placed}${path.sep}`)) { + throw new HarnessStagingError( + MODE, + target, + `${this.context}: ${what} ${target} lies in the placed copy ` + + `${placed}: nothing is installed into the package directory, ` + + `exactly as distributed, after its placement (TEST-SPEC H-2, ` + + `§7.6 Placement)`, + ); + } + } + } + } + + /** + * Verify Reach's four conditions for one importing file on the finished + * staging, before any tool runs (module header): physical naming, the + * placement in place in a holding directory that is the file's own or an + * ancestor along its physical path, nothing nearer, no self-reference, + * and well-formed manifests; and, where `reach` declares them, the project + * kind (with a CommonJS project's nearest `type` member, where declared) + * and that nothing but the placement is installed in the staging. + * Resolves when every one holds; throws `HarnessStagingError` naming the + * first that fails. One harness step under its own guard. + */ + async verifyReach(reach: ReachStaging): Promise<void> { + if (reach.nearestType !== undefined && reach.project !== "commonjs") { + throw new Error( + `module channel: a nearest package.json's type member is declared ` + + `for a CommonJS project ("commonjs") alone, not beside ` + + (reach.project === undefined + ? "no project kind" + : `the project kind ${JSON.stringify(reach.project)}`) + + ` (${this.context})`, + ); + } + const importingFile = this.path(reach.importingFile); + const refused = (detail: string): HarnessStagingError => + new HarnessStagingError( + MODE, + importingFile, + `${this.context}: the staging of the importing file ${importingFile} ` + + `${detail}; ${REACH_RULE}`, + ); + await guardStep( + `verifying Reach for ${importingFile} (${this.context})`, + async () => { + await verifyPlacementReached(importingFile, reach.placement, refused); + await verifyNothingNearer(importingFile, reach.placement, refused); + await verifyManifests( + importingFile, + reach.placement.name, + reach.project, + reach.nearestType, + refused, + ); + if (reach.alone === true) { + await this.#verifyAlone(reach.placement, refused); + } + }, + ); + } + + /** + * The canonical placement's "nothing else installed" (module header): + * within the staging, read without following a link or entering a placed + * copy, the only entry named `node_modules` is the placement's holding + * directory's, holding the placement alone (a scoped one, its scope's + * directory holding it alone). + */ + async #verifyAlone( + placement: Placement, + refused: (detail: string) => HarnessStagingError, + ): Promise<void> { + const expected = path.join(placement.holdingDir, NODE_MODULES_NAME); + const skipped = new Set( + this.#placements.flatMap((placed) => [placed.path, placed.copy]), + ); + const found: string[] = []; + const walk = async (directory: string): Promise<void> => { + for (const entry of await fsp.readdir(directory, { + withFileTypes: true, + })) { + const child = path.join(directory, entry.name); + if (skipped.has(child)) continue; + if (entry.name === NODE_MODULES_NAME) found.push(child); + if (entry.isDirectory()) await walk(child); + } + }; + await walk(this.root); + const others = found.filter((entry) => entry !== expected); + if (others.length > 0) { + throw refused( + `is declared to have nothing but its placement ${placement.path} ` + + `installed, yet ${describePaths(others)} ${others.length === 1 ? "is an entry" : "are entries"} named ` + + `${NODE_MODULES_NAME} too (TEST-SPEC §7.6 Placement: nothing ` + + `else installed anywhere TypeScript or Node.js looks)`, + ); + } + const scoped = placement.name.startsWith("@") + ? splitScoped(placement.name) + : undefined; + const levels: [string, string][] = + scoped === undefined + ? [[expected, placement.name]] + : [ + [expected, `@${scoped.scope}`], + [path.join(expected, `@${scoped.scope}`), scoped.name], + ]; + for (const [directory, only] of levels) { + const names = (await fsp.readdir(directory)).sort(); + if (names.length !== 1 || names[0] !== only) { + throw refused( + `is declared to have nothing but its placement ${placement.path} ` + + `installed, yet ${directory} holds ${JSON.stringify(names)} ` + + `(TEST-SPEC §7.6 Placement: nothing else installed anywhere ` + + `TypeScript or Node.js looks)`, + ); + } + } + } +} + +/** + * Physical naming, and the placement in place (module header): the + * importing file a plain file named by its physical path; the holding + * directory the file's own or an ancestor along that path, not itself + * named `node_modules`; the placement a directory there, or a symbolic link + * reaching its copy, a directory under no `node_modules`. + */ +async function verifyPlacementReached( + importingFile: string, + placement: Placement, + refused: (detail: string) => HarnessStagingError, +): Promise<void> { + let physical: string; + try { + physical = await fsp.realpath(importingFile); + } catch (error) { + throw refused( + `fails physical naming: the file's physical path cannot be read ` + + `(${describeError(error)})`, + ); + } + if (physical !== importingFile) { + throw refused( + `fails physical naming: the path given reaches the file through a ` + + `symbolic link, its physical path being ${physical} — TypeScript is ` + + `given the importing file by its physical path, and Node.js loads it ` + + `by that path (SPEC 7.6 Reach)`, + ); + } + const stats = await fsp.lstat(importingFile); + if (!stats.isFile()) { + throw refused( + `fails physical naming: it is ${entryKind(stats)}, not a plain file`, + ); + } + const directory = path.dirname(importingFile); + const holding = placement.holdingDir; + if (directory !== holding && !directory.startsWith(`${holding}${path.sep}`)) { + throw refused( + `has the placement ${placement.path} in the holding directory ` + + `${holding}, which is neither the importing file's directory nor one ` + + `of its ancestors along its physical path (SPEC 7.6 Package and ` + + `installation)`, + ); + } + if (path.basename(holding) === NODE_MODULES_NAME) { + throw refused( + `has its holding directory ${holding} named ${NODE_MODULES_NAME} ` + + `(SPEC 7.6 Package and installation)`, + ); + } + const placed = await lstatOrAbsent(placement.path); + if (placement.form === "copy") { + if (placed?.isDirectory() !== true) { + throw refused( + `has no copy of the package at its placement ${placement.path} ` + + `(${placed === undefined ? "absent" : entryKind(placed)})`, + ); + } + return; + } + if (placed?.isSymbolicLink() !== true) { + throw refused( + `has no symbolic link at its placement ${placement.path} ` + + `(${placed === undefined ? "absent" : entryKind(placed)})`, + ); + } + const reached = await fsp.realpath(placement.path).catch(() => undefined); + const copy = await fsp.realpath(placement.copy).catch(() => undefined); + if ( + reached === undefined || + reached !== copy || + !(await fsp.stat(reached)).isDirectory() || + reached.split(path.sep).includes(NODE_MODULES_NAME) + ) { + throw refused( + `has its placement ${placement.path} reach ${String(reached)}, not ` + + `its copy ${placement.copy}, a directory under no ` + + `${NODE_MODULES_NAME} (SPEC 7.6 Package and installation)`, + ); + } +} + +/** + * Nothing nearer (SPEC 7.6 Reach): in the holding directory, no entry but + * the placement occupies a path beginning `node_modules/S.`; in every + * directory from the importing file's own up to, excluding, the holding + * directory, none occupies `node_modules/N` or `node_modules/D`, or a path + * beginning `node_modules/S.` or `node_modules/T.`. + */ +async function verifyNothingNearer( + importingFile: string, + placement: Placement, + refused: (detail: string) => HarnessStagingError, +): Promise<void> { + const names = lookupNamesOf(placement.name); + const nearer: string[] = []; + const holdingModules = path.join(placement.holdingDir, NODE_MODULES_NAME); + for (const entry of await entriesBeginning( + holdingModules, + names.s, + refused, + )) { + if (entry !== placement.path) nearer.push(entry); + } + let directory = path.dirname(importingFile); + while (directory !== placement.holdingDir) { + const modules = path.join(directory, NODE_MODULES_NAME); + for (const exact of [placement.name, names.d]) { + const entry = path.join(modules, ...exact.split("/")); + if ((await lstatOrAbsent(entry)) !== undefined) nearer.push(entry); + } + nearer.push(...(await entriesBeginning(modules, names.s, refused))); + nearer.push(...(await entriesBeginning(modules, names.t, refused))); + const parent = path.dirname(directory); + if (parent === directory) break; + directory = parent; + } + if (nearer.length > 0) { + throw refused( + `fails Reach's nothing-nearer condition for N ` + + `${JSON.stringify(placement.name)} (S ${JSON.stringify(names.s)}, D ` + + `${JSON.stringify(names.d)}, T ${JSON.stringify(names.t)}): ` + + `${describePaths(nearer)} ${nearer.length === 1 ? "lies" : "lie"} ` + + `nearer than the placement ${placement.path}`, + ); + } +} + +/** + * `S`, `D`, and `T` for N (SPEC 7.6 Reach): `S` N cut before the first `.` + * of its last segment; `D` the name under which TypeScript looks up + * declarations for N (`@types/N`, `@types/scope__name` for `@scope/name`); + * `T` `D` cut the same way. + */ +function lookupNamesOf(name: string): { + readonly s: string; + readonly d: string; + readonly t: string; +} { + const scoped = name.startsWith("@") ? splitScoped(name) : undefined; + const s = + scoped === undefined + ? cutAtDot(name) + : `@${scoped.scope}/${cutAtDot(scoped.name)}`; + const typed = scoped === undefined ? name : `${scoped.scope}__${scoped.name}`; + return { s, d: `@types/${typed}`, t: `@types/${cutAtDot(typed)}` }; +} + +/** A segment cut before its first `.`, or the segment where it has none. */ +function cutAtDot(segment: string): string { + const dot = segment.indexOf("."); + return dot < 0 ? segment : segment.slice(0, dot); +} + +/** + * The entries of the `node_modules` directory `modules` whose paths begin + * `node_modules/<prefix>.` (a scoped prefix read inside its scope's + * directory), each as an absolute path. An absent directory holds none; a + * listing failing otherwise leaves the condition unverified. + */ +async function entriesBeginning( + modules: string, + prefix: string, + refused: (detail: string) => HarnessStagingError, +): Promise<string[]> { + const scoped = prefix.startsWith("@") ? splitScoped(prefix) : undefined; + const directory = + scoped === undefined ? modules : path.join(modules, `@${scoped.scope}`); + const start = `${scoped === undefined ? prefix : scoped.name}.`; + let names: string[]; + try { + names = await fsp.readdir(directory); + } catch (error) { + if (isAbsence(error)) return []; + throw refused( + `leaves Reach's nothing-nearer condition unverified: ${directory} ` + + `cannot be listed (${describeError(error)})`, + ); + } + return names + .filter((name) => name.startsWith(start)) + .sort() + .map((name) => path.join(directory, name)); +} + +/** + * Well-formed manifests and no self-reference (SPEC 7.6 Reach), and the + * declared project kind: every `package.json` in the importing file's + * directory or one of its ancestors, up to the filesystem root, read + * strictly, none giving a `name` read as N or a leading part of it; the + * nearest one deciding the project kind — for a CommonJS project, its + * `type` member none, or `nearestType` where declared. + */ +async function verifyManifests( + importingFile: string, + name: string, + project: ProjectKind | undefined, + nearestType: CommonJsTypeMember | undefined, + refused: (detail: string) => HarnessStagingError, +): Promise<void> { + let nearest: { readonly file: string; readonly type: unknown } | undefined; + let directory = path.dirname(importingFile); + for (;;) { + const file = path.join(directory, PACKAGE_MANIFEST_NAME); + const reading = await readManifestStrictly(file); + if (reading !== undefined) { + if (!reading.wellFormed) { + throw refused( + `fails Reach's well-formed-manifests condition: the manifest ` + + `${file} ${reading.problem} — every package.json in the ` + + `importing file's directory or one of its ancestors is a ` + + `readable file holding, as UTF-8 with no byte-order mark, a JSON ` + + `object that repeats no member name, whose name and type ` + + `members, where present, are strings, and none of whose strings ` + + `escapes a lone surrogate`, + ); + } + const given = reading.members["name"]; + if (typeof given === "string" && readsAsLeadingPart(given, name)) { + throw refused( + `fails Reach's no-self-reference condition: the manifest ${file} ` + + `gives the name ${JSON.stringify(given)}, which TypeScript or ` + + `Node.js reads as ${JSON.stringify(name)} or a leading part of it`, + ); + } + nearest ??= { file, type: reading.members["type"] }; + } + const parent = path.dirname(directory); + if (parent === directory) break; + directory = parent; + } + if (project === undefined) return; + const found = + nearest === undefined + ? "no package.json in the importing file's directory or an ancestor" + : `the nearest package.json, ${nearest.file}, holding ` + + (nearest.type === undefined + ? "no type member" + : `the type ${JSON.stringify(nearest.type)}`); + const holds = + project === "es-module" + ? nearest !== undefined && nearest.type === "module" + : project === "commonjs" + ? nearest !== undefined && nearest.type === nearestType + : nearest === undefined; + if (!holds) { + const declared = + project === "commonjs" && nearestType !== undefined + ? "a CommonJS project whose nearest package.json holds the type " + + JSON.stringify(nearestType) + : PROJECT_KIND_DESCRIPTIONS[project]; + throw refused(`is declared ${declared}, yet it has ${found}`); + } +} + +/** Each project kind as its staging declares it. */ +const PROJECT_KIND_DESCRIPTIONS: Readonly<Record<ProjectKind, string>> = { + "es-module": + 'an ES-module project, its nearest package.json holding "type": "module"', + commonjs: "a CommonJS project whose nearest package.json has no type member", + "no-manifest": "a project with no package.json at all", +}; + +/** + * Whether TypeScript or Node.js reads a manifest's `name` as N or a leading + * part of it (SPEC 7.6 Reach): each backslash read as `/`, it is empty, or + * is N or N's scope (`@scope` for `@scope/name`) with or without one + * trailing `/`. + */ +function readsAsLeadingPart(given: string, name: string): boolean { + const read = given.split(BACKSLASH).join("/"); + const leading = [name]; + const scoped = name.startsWith("@") ? splitScoped(name) : undefined; + if (scoped !== undefined) leading.push(`@${scoped.scope}`); + return ( + read === "" || leading.some((part) => read === part || read === `${part}/`) + ); +} + +/** + * Remove a staging, a read-only directory a copy kept made writable first + * where the removal needs it. One harness step under its own guard. + */ +async function removeTree(directory: string, context: string): Promise<void> { + await guardStep( + `removing the module-channel staging ${directory} (${context})`, + async () => { + try { + await fsp.rm(directory, { + recursive: true, + force: true, + maxRetries: 2, + }); + } catch { + await makeDirectoriesWritable(Buffer.from(directory)); + await fsp.rm(directory, { + recursive: true, + force: true, + maxRetries: 2, + }); + } + }, + ); +} + +/** Best-effort: give every directory under `directory` owner access. */ +async function makeDirectoriesWritable(directory: Buffer): Promise<void> { + await fsp.chmod(directory, 0o700).catch(() => undefined); + const names = await fsp + .readdir(directory, { encoding: "buffer" }) + .catch(() => [] as Buffer[]); + for (const name of names) { + const child = Buffer.concat([directory, Buffer.from("/"), name]); + const stats = await fsp.lstat(child).catch(() => undefined); + if (stats?.isDirectory() === true) await makeDirectoriesWritable(child); + } +} + +/** `lstat` of `entry`, or undefined where it is absent. */ +async function lstatOrAbsent(entry: string): Promise<Stats | undefined> { + try { + return await fsp.lstat(entry); + } catch (error) { + if (isAbsence(error)) return undefined; + throw error; + } +} + +// --------------------------------------------------------------------------- +// Diagnoses +// --------------------------------------------------------------------------- + +/** Paths, for a diagnosis: the first few. */ +function describePaths(paths: readonly string[]): string { + const shown = paths.slice(0, 5).join(", "); + return paths.length > 5 + ? `${shown}, and ${String(paths.length - 5)} more` + : shown; +} + +/** A JSON value's kind, for a diagnosis. */ +function describeJsonKind(value: unknown): string { + if (value === null) return "null"; + if (Array.isArray(value)) return "an array"; + if (typeof value === "object") return "an object"; + return `a ${typeof value}`; +} + +/** Whether a failed examination failed for want of the entry. */ +function isAbsence(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException | null)?.code; + return code === "ENOENT" || code === "ENOTDIR"; +} + +/** A filesystem entry's kind, for a diagnosis. */ +function entryKind(stats: Stats): string { + if (stats.isSymbolicLink()) return "a symbolic link"; + if (stats.isDirectory()) return "a directory"; + if (stats.isFile()) return "a plain file"; + if (stats.isFIFO()) return "a FIFO"; + if (stats.isSocket()) return "a socket"; + if (stats.isBlockDevice()) return "a block device"; + if (stats.isCharacterDevice()) return "a character device"; + return "an entry of another kind"; +} + +/** An error, for a diagnosis: its code where it has one, else its message. */ +function describeError(error: unknown): string { + if (error instanceof Error) { + const code = (error as NodeJS.ErrnoException).code; + return typeof code === "string" + ? `${code}: ${error.message}` + : `${error.name}: ${error.message}`; + } + return String(error); +} diff --git a/test/helpers/node-releases.ts b/test/helpers/node-releases.ts new file mode 100644 index 00000000..5495e951 --- /dev/null +++ b/test/helpers/node-releases.ts @@ -0,0 +1,448 @@ +// E-1's Node.js releases, read on the harness side (TEST-SPEC E-1, H-11, +// H-9, S-10; H-2's module channel; SPEC 7.6; T7.6-6, T7.6-7, P-17). Harness +// machinery only: this module never imports product code, and it runs +// nothing — neither the product nor a release. +// +// TEST-SPEC E-1: the Node.js releases on which the module channel loads the +// `defineConfig` module are each provisioned by the environment before the +// run — in CI, at setup — beside the one the suite runs on, and no test +// downloads a runtime; a listed release the environment has not provisioned +// is a harness error (H-11) for every run needing it, never a skip (H-9) +// and never a product failure. The list follows E-1's rule and is pinned by +// exact version, so consecutive runs exercise the same releases (E-5). +// +// - The list: `test/node-releases.json` is the one copy of it that CI's +// provisioning (.github/scripts/provision-node-releases.sh) and the +// harness both read, so the releases provisioned and the releases +// exercised cannot drift. The harness finds it relative to this module, +// never to the working directory ({@link NODE_RELEASE_LIST_PATH}), and +// reads it strictly ({@link parseNodeReleaseList}): one JSON object +// holding a `releases` array of exact `major.minor.patch` versions — each +// part a decimal numeral without a leading zero, nothing before or after +// — at least one, none listed twice, beside which only a string +// `comment` may stand. Anything else is {@link NodeReleaseError} of fault +// `list`, naming the list's path: never a shorter list, a skipped +// release, or a default. +// - The releases: the directory the environment variable +// `XSPEC_NODE_RELEASES_DIR` names holds each release as the provisioning +// script installs it, its executable at `<directory>/v<version>/bin/node`. +// {@link resolveNodeRelease} resolves one listed release there, and +// {@link resolveNodeReleases} every one, in list order. The variable is +// read by the call resolving a release — when a run needs one, never when +// this module is imported — so a test needing no release never fails for +// its absence. The variable unset, empty, not an absolute path, or naming +// no directory is {@link NodeReleaseError} of fault `directory`, naming +// the variable (and the path looked at); a listed release whose executable +// is absent there, not a file, or not executable by this process is one of +// fault `release`, naming each such release and the path looked at; and a +// version the list does not hold is refused (fault `list`), so no run +// exercises a release E-1 does not list. +// - Each such error is a harness error (H-11): never a +// `HarnessAssertionError`, so never a diagnosed product failure; thrown, +// never an empty answer or a skip; and let through unchanged by every +// helper converting a run's rejection into a diagnosed failure +// (`rethrowHarnessError`, helpers/subprocess.ts). +// - Whether an executable is the release its directory names — the version +// the running process reports — is S-10's check, made by running it; this +// module runs nothing. +// - Reading the list and examining the directory are harness steps, each +// under its own guard (TEST-SPEC S-3, helpers/step-guards.ts). + +import type { Stats } from "node:fs"; +import { constants as fsConstants } from "node:fs"; +import * as fsp from "node:fs/promises"; +import * as path from "node:path"; +import { fileURLToPath } from "node:url"; +import { guardStep } from "./step-guards.js"; + +/** The environment variable naming the directory of E-1's releases. */ +export const NODE_RELEASES_DIR_VARIABLE = "XSPEC_NODE_RELEASES_DIR"; + +/** + * `test/node-releases.json`, E-1's list: found relative to this module, + * never to the working directory (module header). + */ +export const NODE_RELEASE_LIST_PATH = fileURLToPath( + new URL("../node-releases.json", import.meta.url), +); + +/** + * What a {@link NodeReleaseError} found wanting: E-1's list itself, or a + * version it does not hold (`list`); the variable naming the releases' + * directory, or that directory (`directory`); or a listed release's + * executable there (`release`). + */ +export type NodeReleaseFault = "list" | "directory" | "release"; + +/** E-1's rule, closing every {@link NodeReleaseError}. */ +const PROVISIONING_RULE = + "E-1's Node.js releases, those test/node-releases.json lists, are " + + "provisioned by the environment before the run, each release's " + + "executable at <directory>/v<version>/bin/node where " + + `${NODE_RELEASES_DIR_VARIABLE} names <directory> (in CI at setup; ` + + "locally with .github/scripts/provision-node-releases.sh <directory>, " + + "AGENTS.md); a listed release the environment has not provisioned is a " + + "harness error for every run needing it, never a skip and never a " + + "product failure (TEST-SPEC E-1, H-11, H-9)"; + +/** + * E-1's list unreadable or malformed, a version it does not hold, the + * releases' directory unnamed or unusable, or a listed release not + * provisioned there (module header): a harness error (H-11), never a + * `HarnessAssertionError` — so never a diagnosed product failure — and + * never a skip (H-9). + */ +export class NodeReleaseError extends Error { + /** What was found wanting ({@link NodeReleaseFault}). */ + readonly fault: NodeReleaseFault; + /** + * The releases it names: each listed release found unprovisioned (fault + * `release`), or each version refused as unlisted; empty otherwise. + */ + readonly releases: readonly string[]; + + constructor( + fault: NodeReleaseFault, + detail: string, + releases: readonly string[] = [], + ) { + super(`harness error (H-11): ${detail}; ${PROVISIONING_RULE}`); + this.name = "NodeReleaseError"; + this.fault = fault; + this.releases = Object.freeze([...releases]); + } +} + +/** One release E-1 lists, where the environment provisioned it. */ +export interface NodeRelease { + /** Its exact version, as listed (`22.0.0`). */ + readonly version: string; + /** + * Its executable, absolute, as spelled from the variable's directory: + * `<XSPEC_NODE_RELEASES_DIR>/v<version>/bin/node`. + */ + readonly executable: string; +} + +/** Where releases are looked for ({@link resolveNodeReleases}). */ +export interface NodeReleaseLookup { + /** + * The environment `XSPEC_NODE_RELEASES_DIR` is read from, when the call + * runs: `process.env` unless given. + */ + readonly environment?: Readonly<Record<string, string | undefined>>; + /** E-1's list: {@link NODE_RELEASE_LIST_PATH} unless given. */ + readonly listPath?: string; +} + +/** The list's own keys (module header): `releases`, and `comment` beside. */ +const LIST_KEYS: readonly string[] = ["comment", "releases"]; + +/** An exact version: three decimal numerals, none with a leading zero. */ +const EXACT_VERSION = + /^(?:0|[1-9][0-9]*)[.](?:0|[1-9][0-9]*)[.](?:0|[1-9][0-9]*)$/; + +/** + * Read E-1's list from its text `text`, as found at `source` (module + * header): the listed versions, in list order. Anything but the list's + * exact shape throws {@link NodeReleaseError} of fault `list` naming + * `source`. + */ +export function parseNodeReleaseList( + text: string, + source: string, +): readonly string[] { + const refused = (detail: string): NodeReleaseError => + new NodeReleaseError("list", `E-1's release list ${source} ${detail}`); + let list: unknown; + try { + list = JSON.parse(text); + } catch (error) { + throw refused(`is not JSON (${describeError(error)})`); + } + if (typeof list !== "object" || list === null || Array.isArray(list)) { + throw refused(`holds ${describeJson(list)}, not a JSON object`); + } + const record = list as Readonly<Record<string, unknown>>; + for (const key of Object.keys(record)) { + if (!LIST_KEYS.includes(key)) { + throw refused( + `holds the key ${JSON.stringify(key)}, beside which only ` + + `"releases" and "comment" may stand`, + ); + } + } + if ("comment" in record && typeof record["comment"] !== "string") { + throw refused( + `holds ${describeJson(record["comment"])} as its "comment", not a ` + + `string`, + ); + } + if (!("releases" in record)) throw refused(`holds no "releases"`); + const releases = record["releases"]; + if (!Array.isArray(releases)) { + throw refused( + `holds ${describeJson(releases)} as its "releases", not an array`, + ); + } + if (releases.length === 0) throw refused(`lists no release`); + const versions: string[] = []; + for (const [index, release] of (releases as readonly unknown[]).entries()) { + if (typeof release !== "string" || !EXACT_VERSION.test(release)) { + throw refused( + `lists ${describeJson(release)} as release ${String(index + 1)}, ` + + `not an exact major.minor.patch version`, + ); + } + if (versions.includes(release)) { + throw refused(`lists the release ${release} twice`); + } + versions.push(release); + } + return Object.freeze(versions); +} + +/** + * Read E-1's list at `listPath` ({@link NODE_RELEASE_LIST_PATH} unless + * given; module header), one harness step under its own guard: the listed + * versions, in list order, or {@link NodeReleaseError} of fault `list`. + */ +export async function readNodeReleaseList( + listPath: string = NODE_RELEASE_LIST_PATH, +): Promise<readonly string[]> { + return guardStep(`reading E-1's release list ${listPath}`, async () => { + let text: string; + try { + text = await fsp.readFile(listPath, "utf8"); + } catch (error) { + throw new NodeReleaseError( + "list", + `E-1's release list ${listPath} cannot be read ` + + `(${describeError(error)})`, + ); + } + return parseNodeReleaseList(text, listPath); + }); +} + +/** + * Resolve the listed release `version` where the environment provisioned + * it (module header), for a run needing it: reads E-1's list and the + * variable now. Throws {@link NodeReleaseError} — fault `list` for a version + * the list does not hold, `directory` for the variable or its directory, + * `release` for the release's executable — never an empty answer. + */ +export async function resolveNodeRelease( + version: string, + lookup: NodeReleaseLookup = {}, +): Promise<NodeRelease> { + const [release] = await resolveVersions([version], lookup); + return release; +} + +/** + * Resolve every release E-1 lists where the environment provisioned it, in + * list order (module header), for runs needing them all: reads E-1's list + * and the variable now. Throws {@link NodeReleaseError} — fault `directory` + * for the variable or its directory, `release` naming each listed release + * whose executable is not provisioned there — never a shorter list. + */ +export async function resolveNodeReleases( + lookup: NodeReleaseLookup = {}, +): Promise<readonly NodeRelease[]> { + return resolveVersions(null, lookup); +} + +/** Resolve `wanted` (every listed release where null), in its own order. */ +async function resolveVersions( + wanted: readonly string[] | null, + lookup: NodeReleaseLookup, +): Promise<readonly NodeRelease[]> { + const listPath = lookup.listPath ?? NODE_RELEASE_LIST_PATH; + const listed = await readNodeReleaseList(listPath); + const versions = wanted ?? listed; + const unlisted = versions.filter((version) => !listed.includes(version)); + if (unlisted.length > 0) { + throw new NodeReleaseError( + "list", + `${describeReleases(unlisted)} ${isOrAre(unlisted)} not listed in ` + + `E-1's release list ` + + `${listPath} (${listed.join(", ")}): no run exercises a release ` + + `E-1 does not list`, + unlisted, + ); + } + const needed = describeReleases(versions); + const directory = releasesDirectory( + lookup.environment ?? process.env, + needed, + ); + return guardStep( + `resolving ${needed} under ${NODE_RELEASES_DIR_VARIABLE}=${directory}`, + async () => { + await examineDirectory(directory, needed); + const releases: NodeRelease[] = []; + const unprovisioned: string[] = []; + const wanting: string[] = []; + for (const version of versions) { + const executable = path.join(directory, `v${version}`, "bin", "node"); + const problem = await examineExecutable(executable); + if (problem === null) { + releases.push(Object.freeze({ version, executable })); + } else { + unprovisioned.push(version); + wanting.push(`${version}: ${executable} ${problem}`); + } + } + if (unprovisioned.length > 0) { + throw new NodeReleaseError( + "release", + `${describeReleases(unprovisioned)} ${isOrAre(unprovisioned)} ` + + `not provisioned under ` + + `${NODE_RELEASES_DIR_VARIABLE}=${directory} — ` + + wanting.join("; "), + unprovisioned, + ); + } + return Object.freeze(releases); + }, + ); +} + +/** + * The releases' directory, as the variable names it in `environment`: an + * absolute path, or {@link NodeReleaseError} of fault `directory` naming + * the variable. + */ +function releasesDirectory( + environment: Readonly<Record<string, string | undefined>>, + needed: string, +): string { + const value = environment[NODE_RELEASES_DIR_VARIABLE]; + const refused = (detail: string): NodeReleaseError => + new NodeReleaseError( + "directory", + `${needed} cannot be found: ${NODE_RELEASES_DIR_VARIABLE} ${detail}`, + ); + if (value === undefined) { + throw refused( + "is unset, so the environment provisioned no release for this run", + ); + } + if (value === "") { + throw refused( + "is empty, so the environment provisioned no release for this run", + ); + } + if (!path.isAbsolute(value)) { + throw refused( + `is ${JSON.stringify(value)}, not an absolute path: the ` + + `directory of E-1's releases is never found from the working ` + + `directory`, + ); + } + return value; +} + +/** + * Throw {@link NodeReleaseError} of fault `directory` unless `directory` + * is a directory (a symbolic link to one followed). + */ +async function examineDirectory( + directory: string, + needed: string, +): Promise<void> { + const refused = (detail: string): NodeReleaseError => + new NodeReleaseError( + "directory", + `${needed} cannot be found: ${NODE_RELEASES_DIR_VARIABLE}=` + + `${directory} ${detail}`, + ); + let stats: Stats; + try { + stats = await fsp.stat(directory); + } catch (error) { + throw refused( + isAbsence(error) + ? `names no directory (${describeError(error)})` + : `names a directory that cannot be examined ` + + `(${describeError(error)})`, + ); + } + if (!stats.isDirectory()) { + throw refused(`names ${entryKind(stats)}, not a directory`); + } +} + +/** + * What is wanting of a release's executable at `executable`, or null when + * it is provisioned: a file (a symbolic link to one followed) this process + * may execute. + */ +async function examineExecutable(executable: string): Promise<string | null> { + let stats: Stats; + try { + stats = await fsp.stat(executable); + } catch (error) { + return isAbsence(error) + ? `is absent (${describeError(error)})` + : `cannot be examined (${describeError(error)})`; + } + if (!stats.isFile()) return `is ${entryKind(stats)}, not a file`; + try { + await fsp.access(executable, fsConstants.X_OK); + } catch (error) { + return `is not executable by this process (${describeError(error)})`; + } + return null; +} + +/** + * Releases, for a diagnosis: `the Node.js release 22.0.0`, or `the Node.js + * releases 22.0.0, 24.22.2`. + */ +function describeReleases(versions: readonly string[]): string { + return versions.length === 1 + ? `the Node.js release ${versions.join(", ")}` + : `the Node.js releases ${versions.join(", ")}`; +} + +/** The verb agreeing with {@link describeReleases}' subject. */ +function isOrAre(versions: readonly string[]): string { + return versions.length === 1 ? "is" : "are"; +} + +/** Whether `stat` failed for want of the entry: `ENOENT` or `ENOTDIR`. */ +function isAbsence(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException | null)?.code; + return code === "ENOENT" || code === "ENOTDIR"; +} + +/** A filesystem entry's kind, for a diagnosis (`stat` followed links). */ +function entryKind(stats: Stats): string { + if (stats.isDirectory()) return "a directory"; + if (stats.isFIFO()) return "a FIFO"; + if (stats.isSocket()) return "a socket"; + if (stats.isBlockDevice()) return "a block device"; + if (stats.isCharacterDevice()) return "a character device"; + if (stats.isFile()) return "a file"; + return "an entry of another kind"; +} + +/** A JSON value, for a diagnosis. */ +function describeJson(value: unknown): string { + if (value === undefined) return "nothing"; + const text = JSON.stringify(value); + return text.length > 80 ? `${text.slice(0, 77)}...` : text; +} + +/** An error, for a diagnosis: its code where it has one, else its message. */ +function describeError(error: unknown): string { + if (error instanceof Error) { + const code = (error as NodeJS.ErrnoException).code; + return typeof code === "string" + ? `${code}: ${error.message}` + : `${error.name}: ${error.message}`; + } + return String(error); +} diff --git a/test/helpers/permissions.ts b/test/helpers/permissions.ts index 533c006c..265dbd0d 100644 --- a/test/helpers/permissions.ts +++ b/test/helpers/permissions.ts @@ -133,12 +133,21 @@ import { snapshotKeyBytes } from "./snapshot.js"; * ancestor precondition (`self-contained-root`, * helpers/self-contained-root.ts: an ancestor of an arm's staging root * holding an entry named `xspec.config.ts`, the root lying inside a git - * working tree, or either left unverified), and H-2's consumer isolation - * (`consumer-isolation`, helpers/tooling.ts: an ancestor of a consumer - * program's root, or of the directory its runtime output is written to, - * holding an entry named `node_modules`, a package named `xspec` where - * Node.js's resolver would find it from that output, or either left - * unverified). + * working tree, or either left unverified), and H-1's isolation of a + * consumer program from what TypeScript and Node.js read above it + * (`consumer-isolation`, helpers/staging-isolation.ts through + * helpers/tooling.ts: an ancestor of a consumer program's root, or of the + * directory its runtime output is written to, holding an entry named + * `package.json` or `node_modules`, the root or that directory holding an + * entry named `node_modules`, one of Node.js's global module folders under + * a run's environment holding any entry, or any of these left unverified), + * and the module channel's stagings (`module-channel`, + * helpers/module-channel.ts: a package directory given but unusable — a + * relative path, no directory, one holding an entry named `node_modules` at + * its root or an entry of another kind than a plain file, a directory, or a + * symbolic link — a name outside 7.6's grammar or inside its exclusions, a + * placement or its copy not made as declared, H-1's isolation of a staging + * unmet, or one of Reach's conditions failing on a finished staging). */ export type StagingMode = | "write-refusal" @@ -157,7 +166,8 @@ export type StagingMode = | "second-mount" | "pid-namespace" | "self-contained-root" - | "consumer-isolation"; + | "consumer-isolation" + | "module-channel"; /** * An ineffective or impossible staging: a permission staging (E-1, H-11) @@ -179,11 +189,17 @@ export type StagingMode = * H-1's ancestor precondition unmet: an arm presuming nothing above its * staging root whose root has an `xspec.config.ts` above it or lies inside * a git working tree, or where either is left unverified - * (`self-contained-root`, helpers/self-contained-root.ts), or H-2's consumer - * isolation unmet: a consumer program's root or its runtime output with a - * `node_modules` entry above it, or a package named `xspec` within reach of - * Node.js's resolver from that output, or either left unverified - * (`consumer-isolation`, helpers/tooling.ts). Never a + * (`self-contained-root`, helpers/self-contained-root.ts), or H-1's + * isolation of a consumer program unmet: its root or its runtime output with + * a `package.json` or `node_modules` entry above it or a `node_modules` + * entry in it, or a global module folder of Node.js holding an entry under + * a run's environment, or any of these left unverified + * (`consumer-isolation`, helpers/staging-isolation.ts), or a staging of the + * module channel not made as TEST-SPEC §7.6's Placement rule and SPEC 7.6's + * Reach require — an unusable package directory, a name outside 7.6's + * grammar or inside its exclusions, a placement not made as declared, H-1's + * isolation unmet, a Reach condition failing (`module-channel`, + * helpers/module-channel.ts). Never a * `HarnessAssertionError`: nothing here is a product verdict — it is a * harness error, never a diagnosed product failure and never a skip. */ diff --git a/test/helpers/registry.ts b/test/helpers/registry.ts index c860f33a..efc41d8b 100644 --- a/test/helpers/registry.ts +++ b/test/helpers/registry.ts @@ -4,11 +4,13 @@ // // Every product-facing test (TEST-SPEC sections 1–16) is registered as a // `ProductTestEntry`: its stable TEST-SPEC ID, a human title, and a body that -// receives a `ProductBinding` — the executable binding is the only -// product-specific datum a body ever sees (C-2). The identical body therefore -// runs against the built product (the thin Vitest wrappers in test/suite/, -// see test/suite/declare.ts) and against an arbitrary CERTIFICATIONS.md -// fixture product (the certification runner in +// receives a `ProductBinding` — the product binding (the executable and, +// where one is given, the package directory 7.6's module is distributed as) +// is the only product-specific datum a body ever sees (C-2), and it reaches +// the body unchanged, never rebuilt field by field. The identical body +// therefore runs against the built product (the thin Vitest wrappers in +// test/suite/, see test/suite/declare.ts) and against an arbitrary +// CERTIFICATIONS.md fixture product (the certification runner in // test/self/certification-runner.ts): certifying and testing use one code // path, and no test hard-codes the product path. // diff --git a/test/helpers/staged-mdx.ts b/test/helpers/staged-mdx.ts index 4df94202..40e2f61b 100644 --- a/test/helpers/staged-mdx.ts +++ b/test/helpers/staged-mdx.ts @@ -72,7 +72,10 @@ // code group discovers is an MDX source and a code source at once, so its // record here carries its TypeScript declaration too (`ts`): the self-test // judges those bytes as plain TypeScript as well, and the builder stages -// them under both declarations. After a product invocation, a record +// them under both declarations. So does a configuration file read as a spec +// source — `xspec.config.ts` a spec group discovers, and `xspec.config.mdx` +// named by `--config` (T7-10(e)) — its bytes judged as plain TypeScript, the +// grammar either name selects (14.20). After a product invocation, a record // carrying no `ts` at a path the TypeScript check judges is refused by the // undeclared-staging guard's TypeScript arm: its TypeScript reading was // never judged before any product existed. @@ -115,9 +118,12 @@ export class StagedMdx { * discovers it (SPEC 7.2; T2.1-2's `docs/EXTRA.mdx`) — judged as plain * TypeScript too (an `.mdx` name selects plain TypeScript, 14.20); the * record then carries the path's TypeScript declaration as well, in place - * of the workspace declaration's `ts` entry. Undefined for every other - * record: the path is no code source, and S-9's TypeScript check does not - * judge it. + * of the workspace declaration's `ts` entry — as does the record of a + * configuration file read as a spec source (T7-10(e): `xspec.config.ts` a + * spec group discovers, `xspec.config.mdx` named by `--config`), judged as + * plain TypeScript too. Undefined for every other record: the path is + * neither a code source nor a configuration file, and S-9's TypeScript + * check does not judge it. */ readonly ts: TsDeclaration | undefined; @@ -158,8 +164,8 @@ export class StagedMdx { `staged-source ledger: the record ${JSON.stringify(name)} carries ` + `the TypeScript declaration ${JSON.stringify(ts)} — a record's ` + 'TypeScript declaration is "well-formed" or "unparseable" (14.20), ' + - "or absent for a path no code group discovers; a record exists to " + - "be judged (S-9)", + "or absent for a path that is neither a code source nor a " + + "configuration file; a record exists to be judged (S-9)", ); } this.name = name; @@ -177,7 +183,8 @@ export class StagedMdx { * very expression the staging used (moved, never re-spelled), `mdx` the * declaration in effect for that staging — the former `mdx` option, else the * workspace declaration's entry for the path, else well-formed — and `ts`, - * for a path a code group also discovers as a code source, the TypeScript + * for a path a code group also discovers as a code source, or a + * configuration file read as a spec source too (T7-10(e)), the TypeScript * declaration in effect for it (the former `ts` option, else the workspace * declaration's `ts` entry). */ diff --git a/test/helpers/staging-isolation.ts b/test/helpers/staging-isolation.ts new file mode 100644 index 00000000..d0aa9601 --- /dev/null +++ b/test/helpers/staging-isolation.ts @@ -0,0 +1,417 @@ +// H-1's isolation of a staging from what TypeScript and Node.js read above +// it (TEST-SPEC H-1, H-2, H-11, H-9, T13.1-2; SPEC 7.6, 13.1). Harness +// machinery only: this module never imports product code and runs no +// product. +// +// TEST-SPEC H-1: the verification reaches what TypeScript and Node.js read +// above a staging too — an arm staging the `defineConfig` module (SPEC 7.6; +// P-17, P-18) or compiling or running a consumer program (H-2) runs only +// once the harness has verified, under the environment those tools run in — +// TypeScript taking a directory inside the staging as its current one, +// Node.js run with no `NODE_PATH` and a fresh `HOME` — that no ancestor of +// the staging root holds a `package.json` or a `node_modules` entry and that +// none of Node.js's global module folders holds a package, so that no +// manifest outside the staging decides a project's module kind, names a +// self-reference, or breaks Reach's manifest condition (SPEC 7.6), and no +// `@types` package, library replacement (`@typescript/lib-…`), or copy of +// the product's package enters a program or a module search from above; an +// unmet precondition is a harness error (H-11), never a pass, a product +// failure, or a skip (H-9). `verifyStagingIsolation` is that verification, +// one check for every such staging — H-2's consumer programs +// (helpers/tooling.ts: a project's root before TypeScript serves it, the +// runtime output directory before the compiler writes into it and again +// before each run) and the module channel's stagings alike +// (helpers/module-channel.ts: a staging as it is made, and again wherever a +// driver asks before a Node.js run, with that run's exact environment, +// working directory, and release executables) — called before +// the tools read the staging, by a caller that keeps TypeScript's current +// directory inside the staging and gives each Node.js run exactly the +// environment verified: +// +// - The ancestor half: every ancestor directory of the staging root — its +// parent up to the filesystem root, along the root as spelled and along +// its physical path alike, each directory once — holds no entry named +// `package.json` or `node_modules` of any kind, judged by `lstat`: a plain +// file, a directory, or a symbolic link, a dangling one included. Both +// tools read up the tree: TypeScript's module resolution, its automatic +// inclusion of `@types` packages, and its lookup of library replacements +// search the `node_modules` directories above its current directory or an +// importing file, as Node.js's resolver searches those above an importing +// file; and both read the nearest `package.json` above a file for its +// module kind and a package's self-reference, SPEC 7.6's Reach every +// manifest above it. The root's own entries are the staging's; a staging +// holding nothing installed in it either (T13.1-2's consumer project: +// "nothing installed in or above it") has its root refuse an entry named +// `node_modules` too (`nothingInstalledInRoot`). +// - The global half, for a staging Node.js runs on (`run`): none of +// Node.js's global module folders under the environment the run will +// have — its `NODE_PATH` entries, if it has any, each resolved from the +// run's working directory; `.node_modules` and `.node_libraries` under its +// own `HOME` (`USERPROFILE` on Windows); and `lib/node` under the prefix +// of each Node.js executable that will run there (the directory above its +// `bin/`, the executable's own directory on Windows), for the executable +// as spelled and along its physical path, the path Node.js's +// `process.execPath` reports — holds any entry. A folder that exists and +// holds an entry of any name or kind counts as holding a package, the +// conservative reading: Node.js's resolver finds a module there by the +// entry's name, a package may be installed under any name (SPEC 7.6), and +// H-2 keeps "no copy of the product's package under any name" from a +// consumer's reach. A folder that is absent, or is no directory (read as +// the resolver reads it, a symbolic link followed), holds none. +// - An examination failing otherwise than by absence (`ENOENT`, `ENOTDIR`) +// — the root's or an executable's physical path unreadable, an entry's +// `lstat`, a folder's `stat` or listing refused — leaves the precondition +// unverified, an unmet precondition too. +// - Unmet or unverified throws `HarnessStagingError` (helpers/permissions.ts) +// of the caller's mode — `consumer-isolation` for H-2's consumer programs, +// `module-channel` for the module channel's stagings — naming the +// offending entry or what left it unverified, `context` +// leading its detail and the caller's statement of the rule closing it: +// never a `HarnessAssertionError`, since nothing here is a product verdict. +// Each half is one harness step under its own guard (TEST-SPEC S-3, +// helpers/step-guards.ts). + +import type { Stats } from "node:fs"; +import * as fsp from "node:fs/promises"; +import * as path from "node:path"; +import type { StagingMode } from "./permissions.js"; +import { HarnessStagingError } from "./permissions.js"; +import { guardStep } from "./step-guards.js"; + +/** The manifest both tools read up the tree (module header). */ +export const PACKAGE_MANIFEST_NAME = "package.json"; + +/** The directory both tools search up the tree for installed packages. */ +export const NODE_MODULES_NAME = "node_modules"; + +/** H-1's statement of the precondition, closing a refusal by default. */ +export const STAGING_ISOLATION_RULE = + "an arm whose staging TypeScript or Node.js reads runs only once the " + + "harness has verified, under the environment those tools run in, that no " + + "ancestor of the staging root holds a package.json or a node_modules " + + "entry and that none of Node.js's global module folders holds a package " + + "— an unmet precondition a harness error, never a pass, a product " + + "failure, or a skip (TEST-SPEC H-1, H-11, H-9)"; + +/** What each ancestor entry H-1 refuses is read for (module header). */ +const READ_ABOVE: Readonly<Record<string, string>> = { + [PACKAGE_MANIFEST_NAME]: + "which TypeScript and Node.js read as the manifest deciding a file's " + + "module kind and naming a package's self-reference, and SPEC 7.6's " + + "Reach as a manifest above the importing file", + [NODE_MODULES_NAME]: + "from which TypeScript's module resolution, its automatic @types " + + "inclusion, and its library-replacement lookup, and Node.js's " + + "resolver, read installed packages", +}; + +/** The Node.js runs a staging will see (`StagingIsolation.run`). */ +export interface StagedNodeRun { + /** + * The environment each run will have, exactly as it is spawned with + * (`productEnvironment`, helpers/subprocess.ts, the run's own overrides + * merged). + */ + readonly environment: Readonly<Record<string, string>>; + /** The runs' working directory, absolute: relative paths resolve from it. */ + readonly cwd: string; + /** Each Node.js executable that will run there, absolute. */ + readonly executables: readonly string[]; +} + +/** One verification of H-1's isolation (`verifyStagingIsolation`). */ +export interface StagingIsolation { + /** The staging root, absolute. */ + readonly root: string; + /** What the root is, for diagnoses (e.g. `the consumer project root`). */ + readonly role: string; + /** Leads every diagnosis: the arm or step the verification serves. */ + readonly context: string; + /** The mode every refusal names (helpers/permissions.ts). */ + readonly mode: StagingMode; + /** The rule a refusal closes with: H-1's statement unless given. */ + readonly rule?: string; + /** Whether the root refuses an entry named `node_modules` of its own too. */ + readonly nothingInstalledInRoot?: boolean; + /** The Node.js runs on the staging, if any: the global half's inputs. */ + readonly run?: StagedNodeRun; +} + +type Unmet = (detail: string) => HarnessStagingError; + +/** + * Verify H-1's isolation of a staging (module header): no ancestor directory + * of `root` holds an entry named `package.json` or `node_modules`, the root + * itself none named `node_modules` where `nothingInstalledInRoot` is set, + * and, where `run` is given, none of Node.js's global module folders under + * its environment, for its executables, holds an entry. Resolves when every + * half asked for is verified; otherwise throws `HarnessStagingError` of + * `mode` naming the offending entry or what left a half unverified. Runs no + * product. + */ +export async function verifyStagingIsolation( + isolation: StagingIsolation, +): Promise<void> { + const rule = isolation.rule ?? STAGING_ISOLATION_RULE; + const unmet: Unmet = (detail) => + new HarnessStagingError( + isolation.mode, + isolation.root, + `${isolation.context}: H-1's isolation of ${isolation.role} is unmet ` + + `— ${detail}; ${rule}`, + ); + if (!path.isAbsolute(isolation.root)) { + throw unmet( + `the staging root must be an absolute path, got ` + + JSON.stringify(isolation.root), + ); + } + await guardStep( + `verifying that nothing in or above ${isolation.role} ` + + `${isolation.root} is read as a manifest or an installed package ` + + `(${isolation.context})`, + () => verifyAncestorHalf(isolation, unmet), + ); + const run = isolation.run; + if (run !== undefined) { + await guardStep( + `verifying that none of Node.js's global module folders holds a ` + + `package for a run on ${isolation.root} (${isolation.context})`, + () => verifyGlobalHalf(run, unmet), + ); + } +} + +/** The ancestor half, and the root's own `node_modules` (module header). */ +async function verifyAncestorHalf( + isolation: StagingIsolation, + unmet: Unmet, +): Promise<void> { + const { root } = isolation; + if (isolation.nothingInstalledInRoot === true) { + const entry = path.join(root, NODE_MODULES_NAME); + const stats = await examineEntry(entry, unmet); + if (stats !== undefined) { + throw unmet( + `${isolation.role} ${root} itself holds an entry named ` + + `${NODE_MODULES_NAME} (${entryKind(stats)}, ${entry}), though ` + + `nothing is installed in it or above it (TEST-SPEC T13.1-2)`, + ); + } + } + for (const ancestor of await ancestorDirectories(root, unmet)) { + for (const name of [PACKAGE_MANIFEST_NAME, NODE_MODULES_NAME]) { + const entry = path.join(ancestor, name); + const stats = await examineEntry(entry, unmet); + if (stats !== undefined) { + throw unmet( + `the ancestor directory ${ancestor} holds an entry named ${name} ` + + `(${entryKind(stats)}, ${entry}), ${READ_ABOVE[name] ?? ""}`, + ); + } + } + } +} + +/** The global half (module header). */ +async function verifyGlobalHalf( + run: StagedNodeRun, + unmet: Unmet, +): Promise<void> { + for (const folder of await globalFolders(run, unmet)) { + await judgeGlobalFolder(folder, unmet); + } +} + +/** + * Node.js's global module folders for `run`, each once, in the order its + * CommonJS resolver searches them after the `node_modules` directories + * (Node.js's documented GLOBAL_FOLDERS, after `NODE_PATH`'s entries): the + * `NODE_PATH` entries; `.node_modules` and `.node_libraries` under `HOME` + * (`USERPROFILE` on Windows); `lib/node` under each executable's prefix, as + * spelled and along its physical path. + */ +async function globalFolders( + run: StagedNodeRun, + unmet: Unmet, +): Promise<readonly string[]> { + const windows = process.platform === "win32"; + const folders: string[] = []; + const seen = new Set<string>(); + const add = (folder: string): void => { + if (seen.has(folder)) return; + seen.add(folder); + folders.push(folder); + }; + const nodePath = environmentValue(run.environment, "NODE_PATH", windows); + for (const entry of (nodePath ?? "").split(path.delimiter)) { + if (entry !== "") add(path.resolve(run.cwd, entry)); + } + const home = environmentValue( + run.environment, + windows ? "USERPROFILE" : "HOME", + windows, + ); + if (home !== undefined && home !== "") { + add(path.resolve(run.cwd, home, ".node_modules")); + add(path.resolve(run.cwd, home, ".node_libraries")); + } + for (const executable of run.executables) { + if (!path.isAbsolute(executable)) { + throw unmet( + `a Node.js executable that will run there must be named by an ` + + `absolute path, got ${JSON.stringify(executable)}`, + ); + } + let physical: string; + try { + physical = await fsp.realpath(executable); + } catch (error) { + throw unmet( + `the physical path of the Node.js executable ${executable} cannot ` + + `be read (${describeError(error)}), so the global folder under ` + + `its prefix goes unexamined`, + ); + } + for (const spelling of [path.resolve(executable), physical]) { + const prefix = windows + ? path.dirname(spelling) + : path.dirname(path.dirname(spelling)); + add(path.join(prefix, "lib", "node")); + } + } + return folders; +} + +/** + * A variable of `environment` as the run reads it: by its exact name, or on + * Windows, whose environment names ignore case, by any spelling of it. + */ +function environmentValue( + environment: Readonly<Record<string, string>>, + name: string, + windows: boolean, +): string | undefined { + if (!windows) return environment[name]; + const key = Object.keys(environment).find( + (candidate) => candidate.toUpperCase() === name, + ); + return key === undefined ? undefined : environment[key]; +} + +/** One global folder: absent, no directory, or empty, or the half is unmet. */ +async function judgeGlobalFolder(folder: string, unmet: Unmet): Promise<void> { + let stats: Stats; + try { + stats = await fsp.stat(folder); + } catch (error) { + if (isAbsence(error)) return; + throw unmet( + `the examination of the global folder ${folder} failed ` + + `(${describeError(error)}), so whether it holds a package is ` + + `unverified`, + ); + } + if (!stats.isDirectory()) return; + let names: string[]; + try { + names = await fsp.readdir(folder); + } catch (error) { + throw unmet( + `the listing of the global folder ${folder} failed ` + + `(${describeError(error)}), so whether it holds a package is ` + + `unverified`, + ); + } + if (names.length > 0) { + throw unmet( + `the global folder ${folder}, which Node.js's resolver searches for a ` + + `bare specifier under the run's environment, holds ` + + `${describeEntries(names)} — any entry there a module the resolver ` + + `finds by its name — so the folder counts as holding a package`, + ); + } +} + +/** + * The directories above `root`, nearest first: its parent up to the + * filesystem root along the root as spelled, then along its physical path, + * each directory once. A physical path that cannot be read leaves the + * isolation unverified. + */ +async function ancestorDirectories( + root: string, + unmet: Unmet, +): Promise<readonly string[]> { + let physical: string; + try { + physical = await fsp.realpath(root); + } catch (error) { + throw unmet( + `the staging root's physical path cannot be read ` + + `(${describeError(error)}), so the directories above it go ` + + `unexamined`, + ); + } + const ancestors: string[] = []; + const seen = new Set<string>(); + for (const start of [path.resolve(root), physical]) { + let current = start; + for (;;) { + const parent = path.dirname(current); + if (parent === current) break; + current = parent; + if (seen.has(current)) continue; + seen.add(current); + ancestors.push(current); + } + } + return ancestors; +} + +/** + * `lstat` of `entry`: its stats, or `undefined` when it is absent (`ENOENT`, + * `ENOTDIR`). Any other failure leaves the isolation unverified. + */ +async function examineEntry( + entry: string, + unmet: Unmet, +): Promise<Stats | undefined> { + try { + return await fsp.lstat(entry); + } catch (error) { + if (isAbsence(error)) return undefined; + throw unmet( + `the examination of ${entry} failed (${describeError(error)}), ` + + `leaving it unverified`, + ); + } +} + +function isAbsence(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException | undefined)?.code; + return code === "ENOENT" || code === "ENOTDIR"; +} + +/** The entries of a folder, for a diagnosis: the first few, by name. */ +function describeEntries(names: readonly string[]): string { + const sorted = [...names].sort(); + const shown = sorted.slice(0, 5).map((name) => JSON.stringify(name)); + const more = sorted.length - shown.length; + return ( + `${sorted.length === 1 ? "the entry" : `${String(sorted.length)} entries,`} ` + + shown.join(", ") + + (more > 0 ? `, and ${String(more)} more` : "") + ); +} + +function entryKind(stats: Stats): string { + if (stats.isSymbolicLink()) return "a symbolic link"; + if (stats.isDirectory()) return "a directory"; + if (stats.isFile()) return "a plain file"; + return "an entry of another kind"; +} + +function describeError(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} diff --git a/test/helpers/subprocess.ts b/test/helpers/subprocess.ts index 0483e27b..192b2162 100644 --- a/test/helpers/subprocess.ts +++ b/test/helpers/subprocess.ts @@ -3,11 +3,15 @@ // in a subprocess). Harness machinery only: this module never imports product // code — a product is driven strictly as an executable. // -// - A `ProductBinding` names the executable to drive. Product-facing tests -// default to the built product (`builtProductBinding()`); the certification -// runner substitutes a CERTIFICATIONS.md fixture executable through the -// same binding shape, so certifying and testing use one code path (C-2) and -// no test hard-codes the product path. +// - A `ProductBinding` names the executable to drive and, where one is +// given, the package directory 7.6's `defineConfig` module is distributed +// as (C-2; H-2's module channel), which this driver itself never reads. +// Product-facing tests default to the built product +// (`builtProductBinding()`, its package directory the one +// `XSPEC_PACKAGE_DIR` names); the certification runner substitutes a +// CERTIFICATIONS.md fixture executable, with no package directory, through +// the same binding shape, so certifying and testing use one code path +// (C-2) and no test hard-codes the product path. // - Every invocation controls the working directory (required and absolute: // each test runs the product inside its own workspace, H-1/H-2), argv // (passed verbatim to the process, no shell interpretation; raw-byte @@ -199,6 +203,7 @@ import { ProcessGroupLingerError, VoidedTrialsExhaustedError, } from "./kill-discipline.js"; +import { NodeReleaseError } from "./node-releases.js"; import { noteProductInvocation } from "./product-invocations.js"; import { guardStep, @@ -233,8 +238,10 @@ export const DEFAULT_MAX_OUTPUT_BYTES = 512 * 1024 * 1024; /** * How to invoke a product — the built `xspec` or a CERTIFICATIONS.md fixture - * product. The binding is the only product-specific datum a test body sees - * (C-2: an executable binding and nothing else). + * product — and, where one is given, the package directory its + * `defineConfig` module is distributed as. The binding is the only + * product-specific datum a test body sees (C-2: the executable and the + * package directory, with the workspace, and nothing else). */ export interface ProductBinding { /** Human label used in failure diagnoses. */ @@ -269,6 +276,33 @@ export interface ProductBinding { * whole in-scope set would otherwise certify without ever running). */ readonly missingFilesFailDiagnosed?: boolean; + /** + * The package directory 7.6's `defineConfig` module is distributed as, + * given beside the executable (TEST-SPEC C-2; H-2's module channel): an + * absolute path to a directory holding exactly what the package's + * distribution carries, never a development tree. Absent, no package + * directory is given, and H-8 holds every test of 7.6 to a diagnosed + * failure, the module channel counting as part of the product. The built + * product's binding takes it from the environment + * ({@link builtProductBinding}); {@link builtProductBindingAt}'s carries + * none, and neither does a CERTIFICATIONS.md fixture's (its preamble: no + * scope includes the module, so each fixture is bound with its executable + * and no package directory). + * + * The harness copies the directory into stagings and reads its manifest's + * `name` where a test says so (TEST-SPEC T7.6-4(a), T7-9(d)); it never + * writes into it, never loads or reads one of its files as a module, and + * never treats a file of it as a channel by its path (H-2: a subpath, or a + * file of the package named by its path, is never a channel). This + * driver never reads it. Whether the path is usable — absolute, naming a + * directory, holding a distribution rather than a development tree — is + * for the module channel to check where a test of 7.6 reaches for the + * module (helpers/module-channel.ts, `modulePackageDirectory`, which + * `ModuleStaging.create` runs before anything is staged), never when the + * binding is made, so that a test which never reaches the module never + * fails for it. + */ + readonly packageDir?: string; } /** @@ -364,9 +398,11 @@ export class HarnessEvaluationError extends Error { * evaluation of the answer failed ({@link HarnessEvaluationError}), a group * kill could not confirm its group gone (`ProcessGroupLingerError`), every * attempt of a voidable trial was voided (`VoidedTrialsExhaustedError`; - * both helpers/kill-discipline.ts), or a harness step outlasted its own - * guard (`HarnessStepTimeoutError`, helpers/step-guards.ts; TEST-SPEC S-3) - * — and return otherwise. A helper that turns a rejected run — the + * both helpers/kill-discipline.ts), a harness step outlasted its own guard + * (`HarnessStepTimeoutError`, helpers/step-guards.ts; TEST-SPEC S-3), or a + * Node.js release E-1 lists is not provisioned for the run needing it, or + * its list is unreadable (`NodeReleaseError`, helpers/node-releases.ts; + * TEST-SPEC E-1) — and return otherwise. A helper that turns a rejected run — the * hang-guard kill, a premature exit, a spawn failure, a T6.5-22(a) breach, * a T12.7-1 near-marker — into a diagnosed failure (H-8) calls it first, so * a harness-side failure always surfaces as the harness error it is, never @@ -378,7 +414,8 @@ export function rethrowHarnessError(error: unknown): void { error instanceof HarnessEvaluationError || error instanceof ProcessGroupLingerError || error instanceof VoidedTrialsExhaustedError || - error instanceof HarnessStepTimeoutError + error instanceof HarnessStepTimeoutError || + error instanceof NodeReleaseError ) { throw error; } @@ -407,25 +444,47 @@ function describeCause(cause: unknown): string { const repoRoot = path.resolve(fileURLToPath(new URL("../..", import.meta.url))); +/** + * The environment variable naming the product's package directory, exactly + * as distributed (TEST-SPEC H-2's module channel, C-2): the directory + * `.github/scripts/pack-package.sh` prints, which CI's full-suite job sets + * after its build and its harness-self job leaves unset (AGENTS.md). + */ +export const PACKAGE_DIR_VARIABLE = "XSPEC_PACKAGE_DIR"; + /** * The default binding: the built product executable (`dist/cli/bin.js`, see * AGENTS.md), resolved relative to this module — never to the process cwd — * in the built product's binding shape ({@link builtProductBindingAt}), so * running a product-facing test before the product is built fails it - * diagnosed (H-8). + * diagnosed (H-8); and beside it, as its {@link ProductBinding.packageDir}, + * the package directory {@link PACKAGE_DIR_VARIABLE} names in `environment` + * (`process.env` unless given), read when the binding is made and carried + * exactly as spelled there, never resolved against the working directory. + * With the variable unset or empty, the binding carries none. */ -export function builtProductBinding(): ProductBinding { - return builtProductBindingAt(path.join(repoRoot, "dist", "cli", "bin.js")); +export function builtProductBinding( + environment: Readonly<Record<string, string | undefined>> = process.env, +): ProductBinding { + const binding = builtProductBindingAt( + path.join(repoRoot, "dist", "cli", "bin.js"), + ); + const packageDir = environment[PACKAGE_DIR_VARIABLE]; + return packageDir === undefined || packageDir === "" + ? binding + : { ...binding, packageDir }; } /** - * The built product's binding shape at the artifact path `binJs`: Node runs - * it, it is the one required file, and its absence is H-8's missing product - * — every run failing diagnosed, declining shrinking - * ({@link ProductBinding.missingFilesFailDiagnosed}). Product-facing tests - * take {@link builtProductBinding}; the path parameter exists for checks of - * the no-product run, which need the artifact absent whatever the - * checkout's `dist/` holds (S-3's missing-artifact vector). + * The built product's binding shape at the artifact path `binJs`, with no + * package directory: Node runs it, it is the one required file, and its + * absence is H-8's missing product — every run failing diagnosed, declining + * shrinking ({@link ProductBinding.missingFilesFailDiagnosed}). + * Product-facing tests take {@link builtProductBinding}; the path parameter + * exists for checks of the no-product run, which need the artifact absent + * whatever the checkout's `dist/` holds (S-3's missing-artifact vector), and + * which give the module channel nothing either, whatever the environment + * names (H-8: the module channel counts as part of the product). */ export function builtProductBindingAt(binJs: string): ProductBinding { return { diff --git a/test/helpers/tooling.ts b/test/helpers/tooling.ts index 9693e89e..a0e2f237 100644 --- a/test/helpers/tooling.ts +++ b/test/helpers/tooling.ts @@ -31,11 +31,12 @@ // `diffModuleSkeletons` compares two such skeletons (T1.1-2: the two tag // names' generated modules expose the same skeleton). // - Compiled consumers run under plain Node (`runConsumer`) through the -// blackbox subprocess driver: `node <entry>` with the sanitized environment -// and `NODE_PATH` dropped, from a directory with no package named `xspec` -// within its reach (the isolation below), so nothing outside the -// program's compiled output can satisfy an import — SPEC.md 13.1's "no -// xspec runtime dependency", observed structurally. +// blackbox subprocess driver: `node <entry>` with the sanitized +// environment, `NODE_PATH` dropped and a fresh, empty `HOME` of the run's +// own, from a directory with nothing installed in or above it and nothing +// in Node.js's global module folders (the isolation below), so nothing +// outside the program's compiled output can satisfy an import — SPEC.md +// 13.1's "no xspec runtime dependency", observed structurally. // - Failure paths are loud (H-8): a missing project root or root file, an // unknown or ambiguous marker, and an unreadable definition target all // throw diagnosed errors instead of yielding empty results a test could @@ -90,17 +91,31 @@ // output keeps the extensionless specifier, which Node.js's // ECMAScript-module loader never resolves: it is type-checked and served, // never executed. -// - Isolation (H-2: no package named `xspec` installed or resolvable; `types` -// at its default): before a project is served, and before its runtime -// output is written, the harness verifies that no ancestor directory of the -// project root, or of the output directory — along its path as spelled and -// along its physical path — holds an entry named `node_modules`, and before -// each run that none of the global folders Node.js's resolver searches -// holds an entry named `xspec`; an isolation unmet or unverified is -// `HarnessStagingError` (mode `consumer-isolation`, -// helpers/permissions.ts), a harness error, never a verdict. A hand-written -// fixture project living in this repository is therefore compiled from a -// copy under the OS temporary directory, as a consumer workspace is. +// - Isolation (TEST-SPEC H-1, H-2, T13.1-2: a consumer project with nothing +// installed in or above it, nothing resolvable from the consumer's +// location by package name — no copy of the product's package under any +// name least of all — and `types` at its default): H-1's verification of +// what TypeScript and Node.js read above a staging +// (`verifyStagingIsolation`, helpers/staging-isolation.ts, which the +// module channel's stagings share) is made before a project is served — +// TypeScript's current directory its root — that no ancestor directory of +// the root, along its path as spelled and along its physical path, holds +// an entry named `package.json` or `node_modules`, and the root itself +// none named `node_modules`; before its runtime output is written, the +// same of the output directory; and before each run, again of the output +// directory and, under exactly the environment the run gets — the +// sanitized environment with `NODE_PATH` dropped and a fresh, empty `HOME` +// (`USERPROFILE` too on Windows), a directory created for the run under +// the OS temporary directory, outside the workspace and the output +// directory, and removed once it ends — that none of Node.js's global +// module folders (the run's `NODE_PATH` entries, `.node_modules` and +// `.node_libraries` under its `HOME`, `lib/node` under the prefix of the +// Node.js running it) holds an entry of any name. An isolation unmet or +// unverified is `HarnessStagingError` (mode `consumer-isolation`, +// helpers/permissions.ts), a harness error, never a verdict. A +// hand-written fixture project living in this repository is therefore +// compiled from a copy under the OS temporary directory, as a consumer +// workspace is. // - No other configuration is reachable: `ConsumerProject.load` takes one of // the two exactly and no compiler option of its own, refusing anything // else (a plain `Error`: a harness misuse, never a verdict). So no @@ -115,13 +130,13 @@ // test/vitest.config.ts) — never the product's `typescript` dependency. import * as fs from "node:fs"; -import type { Stats } from "node:fs"; import * as fsp from "node:fs/promises"; import * as os from "node:os"; import * as path from "node:path"; import ts from "typescript-5.9.3"; import { fail, HarnessAssertionError } from "./assertions.js"; -import { HarnessStagingError } from "./permissions.js"; +import { verifyStagingIsolation } from "./staging-isolation.js"; +import type { StagedNodeRun } from "./staging-isolation.js"; import { guardStep, guardSyncStep } from "./step-guards.js"; import type { ProductBinding, RunResult } from "./subprocess.js"; import { productEnvironment, runProduct } from "./subprocess.js"; @@ -393,7 +408,14 @@ export interface RuntimeEmit { export interface CompiledRunOptions { /** process.argv arguments after the entry path. */ readonly argv?: readonly string[]; - /** Merged last over the sanitized environment (see subprocess driver). */ + /** + * Merged last over the run's environment — the sanitized environment + * (see subprocess driver), `NODE_PATH` dropped, the run's fresh `HOME` — + * `undefined` removing a variable; the isolation is verified under the + * environment so merged. No suite test sets one; S-4's isolation probes + * set `HOME` or `NODE_PATH` here to stage a global folder the + * verification must refuse. + */ readonly env?: Readonly<Record<string, string | undefined>>; readonly timeoutMs?: number; } @@ -416,9 +438,11 @@ export interface CompiledConsumer { outputOf(source: string): string; /** * Run the compiled output of `source` under plain Node, `dir` its working - * directory (`runConsumer`), once the global folders Node.js's resolver - * searches under the run's environment are verified to hold no package - * named `xspec` (module header: Isolation). + * directory (`runConsumer`), `NODE_PATH` dropped and a fresh, empty `HOME` + * created for the run and removed once it ends, once H-1's isolation is + * verified under exactly the run's environment: nothing installed in or + * above `dir`, and nothing in any of Node.js's global module folders + * (module header: Isolation). */ run(source: string, options?: CompiledRunOptions): Promise<RunResult>; } @@ -473,7 +497,8 @@ export class ConsumerProject { * A configuration other than H-2's two — none included — and any option * beside `rootDir`, `rootFiles`, and `configuration` are refused (a * harness misuse: H-2 fixes every option); the project's root must meet - * H-2's isolation (module header) — `HarnessStagingError` otherwise. + * H-1's isolation (module header: nothing installed in it or above it) — + * `HarnessStagingError` otherwise. */ static async load(options: ConsumerProjectOptions): Promise<ConsumerProject> { const configuration: unknown = options.configuration; @@ -529,11 +554,16 @@ export class ConsumerProject { ); } } - await verifyConsumerIsolation( - options.rootDir, - "the consumer project root", - `a consumer project under ${configurationLabel(options.configuration)}`, - ); + // TypeScript's current directory is the root (`getCurrentDirectory`), + // inside the staging, as H-1 verifies it. + await verifyStagingIsolation({ + root: options.rootDir, + role: "the consumer project root", + context: `a consumer project under ${configurationLabel(options.configuration)}`, + mode: "consumer-isolation", + rule: ISOLATION_RULE, + nothingInstalledInRoot: true, + }); return new ConsumerProject(options); } @@ -1046,31 +1076,33 @@ export class ConsumerProject { interface RunConsumerOptions { /** Absolute output directory; the run's working directory. */ readonly dir: string; - /** Compiled entry module, `dir`-relative (or absolute). */ - readonly entry: string; + /** Compiled entry module, absolute. */ + readonly entryAbs: string; /** process.argv arguments after the entry path. */ readonly argv?: readonly string[]; - /** Merged last over the sanitized environment (see subprocess driver). */ - readonly env?: Readonly<Record<string, string | undefined>>; + /** + * The run's environment overrides, merged last over the sanitized + * environment (`consumerEnvironmentOverrides`): exactly those its + * isolation was verified under. + */ + readonly env: Readonly<Record<string, string | undefined>>; readonly timeoutMs?: number; } /** * Run a compiled consumer program under plain Node (SPEC.md 13.1) via the * blackbox subprocess driver: exact exit code, separated stdout/stderr bytes, - * hang guard. `NODE_PATH` is dropped so module resolution sees only the - * files of `dir` and the directories above it — the compiled output's own - * directory, outside the workspace and verified isolated. Reached only - * through `CompiledConsumer.run` (`withCompiledConsumer`), H-2's runtime. + * hang guard. With `NODE_PATH` dropped and a fresh, empty `HOME`, module + * resolution sees only the files of `dir` and the directories above it — + * the compiled output's own directory, outside the workspace — and Node.js's + * global module folders, all verified isolated. Reached only through + * `CompiledConsumer.run` (`withCompiledConsumer`), H-2's runtime. */ async function runConsumer(options: RunConsumerOptions): Promise<RunResult> { - const entryAbs = path.isAbsolute(options.entry) - ? options.entry - : path.resolve(options.dir, options.entry); - return await runProduct(consumerBinding(entryAbs), { + return await runProduct(consumerBinding(options.entryAbs), { cwd: options.dir, argv: options.argv ?? [], - env: consumerEnvironmentOverrides(options.env), + env: options.env, timeoutMs: options.timeoutMs, }); } @@ -1085,11 +1117,22 @@ function consumerBinding(entryAbs: string): ProductBinding { }; } -/** A consumer run's environment overrides: `NODE_PATH` dropped, then `env`. */ +/** + * A consumer run's environment overrides (TEST-SPEC H-1: Node.js run with no + * `NODE_PATH` and a fresh `HOME`): `NODE_PATH` dropped, `HOME` — and, on + * Windows, where Node.js reads the home directory from it, `USERPROFILE` — + * the run's fresh one, then the run's own `env`. + */ function consumerEnvironmentOverrides( + home: string, env: Readonly<Record<string, string | undefined>> | undefined, ): Readonly<Record<string, string | undefined>> { - return { NODE_PATH: undefined, ...(env ?? {}) }; + return { + NODE_PATH: undefined, + HOME: home, + ...(process.platform === "win32" ? { USERPROFILE: home } : {}), + ...(env ?? {}), + }; } /** One-line rendering of a diagnostic for failure diagnoses. */ @@ -1278,13 +1321,14 @@ export function assertTypeErrorsAt( /** * H-2's runtime (module header): compile `project` — served under H-2's * CommonJS configuration — to CommonJS JavaScript in a fresh directory under - * the OS temporary directory, outside the workspace, its isolation verified - * first, and run `body` over the output; the directory is removed once - * `body` settles. The compile fails diagnosed when the compiler skips its - * emit, reports an emit diagnostic, or produces output for a program file - * outside the project root, which the output directory mirrors. Refused, - * as a harness misuse, under the ES-module configuration, whose output is - * type-checked and served, never executed. + * the OS temporary directory, outside the workspace, its isolation (H-1: + * nothing installed above it) verified first, and run `body` over the + * output; the directory is removed once `body` settles. The compile fails + * diagnosed when the compiler skips its emit, reports an emit diagnostic, + * or produces output for a program file outside the project root, which + * the output directory mirrors. Refused, as a harness misuse, under the + * ES-module configuration, whose output is type-checked and served, never + * executed. */ export async function withCompiledConsumer<T>( project: ConsumerProject, @@ -1306,7 +1350,13 @@ export async function withCompiledConsumer<T>( () => fsp.mkdtemp(path.join(os.tmpdir(), "xspec-consumer-out-")), ); try { - await verifyConsumerIsolation(dir, "the runtime output directory", label); + await verifyStagingIsolation({ + root: dir, + role: "the runtime output directory", + context: label, + mode: "consumer-isolation", + rule: ISOLATION_RULE, + }); const emitted = project.emitTo(dir); if ( emitted.emitSkipped || @@ -1367,18 +1417,44 @@ class CompiledOutput implements CompiledConsumer { options: CompiledRunOptions = {}, ): Promise<RunResult> { const entry = this.outputOf(source); - await verifyNoGlobalPackage( - path.join(this.dir, entry), - options.env, - this.#label, + const entryAbs = path.join(this.dir, entry); + const context = `${this.#label}, running ${entry}`; + // The run's fresh, empty HOME (module header: Isolation): beside the + // output directory under the OS temporary directory, never inside it or + // the workspace, and removed once the run ends. + const home = await guardStep( + `creating the fresh HOME of ${context} (CompiledConsumer.run)`, + () => fsp.mkdtemp(path.join(os.tmpdir(), "xspec-consumer-home-")), ); - return await runConsumer({ - dir: this.dir, - entry, - argv: options.argv, - env: options.env, - timeoutMs: options.timeoutMs, - }); + try { + const env = consumerEnvironmentOverrides(home, options.env); + const run: StagedNodeRun = { + environment: productEnvironment(consumerBinding(entryAbs), env), + cwd: this.dir, + executables: [process.execPath], + }; + await verifyStagingIsolation({ + root: this.dir, + role: "the runtime output directory", + context, + mode: "consumer-isolation", + rule: ISOLATION_RULE, + nothingInstalledInRoot: true, + run, + }); + return await runConsumer({ + dir: this.dir, + entryAbs, + argv: options.argv, + env, + timeoutMs: options.timeoutMs, + }); + } finally { + await guardStep( + `removing the fresh HOME of ${context} (CompiledConsumer.run)`, + () => fsp.rm(home, { recursive: true, force: true, maxRetries: 2 }), + ); + } } } @@ -1405,203 +1481,24 @@ function describeExpected(expectation: ExpectedTypeError): string { ); } -/** The entry H-2's isolation keeps from every directory above a program. */ -const NODE_MODULES = "node_modules"; - -/** The package name H-2 keeps from every consumer run's reach. */ -const XSPEC_PACKAGE_NAME = "xspec"; - -const ISOLATION_RULE = - "a consumer program is compiled and run with no package named xspec " + - "installed or resolvable, its every option at the release's default — " + - "types included, which a node_modules directory above it would extend — " + - "an unmet isolation a harness error, never a verdict (TEST-SPEC H-2)"; - -type IsolationUnmet = (detail: string) => HarnessStagingError; - -/** - * H-2's isolation of `dir` — a consumer project's root, or a runtime - * output directory (module header): no ancestor directory of it, along its - * path as spelled and along its physical path, each once, holds an entry - * named `node_modules` of any kind. `HarnessStagingError` (mode - * `consumer-isolation`) otherwise, or when an examination leaves it - * unverified (`examineEntry`). - */ -async function verifyConsumerIsolation( - dir: string, - role: string, - context: string, -): Promise<void> { - const unmet: IsolationUnmet = (detail) => - new HarnessStagingError( - "consumer-isolation", - dir, - `${context}: H-2's isolation of ${role} is unmet — ${detail}; ` + - ISOLATION_RULE, - ); - await guardStep( - `verifying H-2's isolation of ${role} ${dir} (${context})`, - async () => { - for (const ancestor of await isolationAncestors(dir, unmet)) { - const entry = path.join(ancestor, NODE_MODULES); - const stats = await examineEntry(entry, unmet); - if (stats !== undefined) { - throw unmet( - `the ancestor directory ${ancestor} holds an entry named ` + - `${NODE_MODULES} (${isolationEntryKind(stats)}, ${entry}), from ` + - `which TypeScript's module resolution and default types, and ` + - `Node.js's resolver, read packages`, - ); - } - } - }, - ); -} - /** - * Before a compiled consumer's run (`CompiledConsumer.run`): none of the - * global folders Node.js's CommonJS resolver searches for a bare specifier - * under the run's environment — its `NODE_PATH` entries (dropped unless - * `env` sets them), `$HOME/.node_modules`, `$HOME/.node_libraries`, and - * `$PREFIX/lib/node` of the Node.js running it — holds an entry named - * `xspec`. `HarnessStagingError` (mode `consumer-isolation`) otherwise. + * The rule every refusal of a consumer program's isolation closes with + * (module header: Isolation; helpers/staging-isolation.ts): TEST-SPEC H-1's + * verification as it applies to H-2's consumer programs. */ -async function verifyNoGlobalPackage( - entryAbs: string, - env: Readonly<Record<string, string | undefined>> | undefined, - context: string, -): Promise<void> { - const unmet: IsolationUnmet = (detail) => - new HarnessStagingError( - "consumer-isolation", - entryAbs, - `${context}: H-2's isolation of the compiled consumer's run is unmet ` + - `— ${detail}; ${ISOLATION_RULE}`, - ); - const environment = productEnvironment( - consumerBinding(entryAbs), - consumerEnvironmentOverrides(env), - ); - await guardStep( - `verifying that no global folder holds ${XSPEC_PACKAGE_NAME} before ` + - `running ${entryAbs} (${context})`, - async () => { - for (const folder of nodeGlobalFolders(environment)) { - const entry = path.join(folder, XSPEC_PACKAGE_NAME); - const stats = await examineEntry(entry, unmet); - if (stats !== undefined) { - throw unmet( - `the global folder ${folder}, which Node.js's resolver searches ` + - `under the run's environment, holds an entry named ` + - `${XSPEC_PACKAGE_NAME} (${isolationEntryKind(stats)}, ${entry})`, - ); - } - } - }, - ); -} - -/** - * The global folders Node.js's CommonJS resolver searches for a bare - * specifier under `environment` (Node.js's documented GLOBAL_FOLDERS, after - * `NODE_PATH`'s entries), for the Node.js executable running the harness — - * the one a compiled consumer runs under. - */ -function nodeGlobalFolders( - environment: Readonly<Record<string, string>>, -): readonly string[] { - const windows = process.platform === "win32"; - const home = windows ? environment["USERPROFILE"] : environment["HOME"]; - const prefix = windows - ? path.resolve(process.execPath, "..") - : path.resolve(process.execPath, "..", ".."); - const folders: string[] = []; - for (const entry of (environment["NODE_PATH"] ?? "").split(path.delimiter)) { - if (entry !== "") folders.push(path.resolve(entry)); - } - if (home !== undefined && home !== "") { - folders.push(path.resolve(home, ".node_modules")); - folders.push(path.resolve(home, ".node_libraries")); - } - folders.push(path.resolve(prefix, "lib", "node")); - return folders; -} - -/** - * The directories above `dir`, nearest first: its parent up to the - * filesystem root along `dir` as spelled, then along its physical path, - * each directory once. A physical path that cannot be read leaves the - * isolation unverified. - */ -async function isolationAncestors( - dir: string, - unmet: IsolationUnmet, -): Promise<readonly string[]> { - let physical: string; - try { - physical = await fsp.realpath(dir); - } catch (error) { - throw unmet( - `its physical path cannot be read (${isolationErrorText(error)}), so ` + - `the directories above it go unexamined`, - ); - } - const ancestors: string[] = []; - const seen = new Set<string>(); - for (const start of [path.resolve(dir), physical]) { - let current = start; - for (;;) { - const parent = path.dirname(current); - if (parent === current) break; - current = parent; - if (seen.has(current)) continue; - seen.add(current); - ancestors.push(current); - } - } - return ancestors; -} - -/** - * `lstat` of `entry`: its stats, or `undefined` when no process of the - * harness's identity reaches it — absent (`ENOENT`, `ENOTDIR`) or behind a - * refused search (`EACCES`, `EPERM`), which TypeScript's resolution in this - * process and Node.js's in a run it starts meet alike. Any other failure - * leaves the isolation unverified. - */ -async function examineEntry( - entry: string, - unmet: IsolationUnmet, -): Promise<Stats | undefined> { - try { - return await fsp.lstat(entry); - } catch (error) { - const code = (error as NodeJS.ErrnoException).code; - if ( - code === "ENOENT" || - code === "ENOTDIR" || - code === "EACCES" || - code === "EPERM" - ) { - return undefined; - } - throw unmet( - `the examination of ${entry} failed (${isolationErrorText(error)}), ` + - `leaving it unverified`, - ); - } -} - -function isolationEntryKind(stats: Stats): string { - if (stats.isSymbolicLink()) return "a symbolic link"; - if (stats.isDirectory()) return "a directory"; - if (stats.isFile()) return "a plain file"; - return "an entry of another kind"; -} - -function isolationErrorText(error: unknown): string { - return error instanceof Error ? error.message : String(error); -} +const ISOLATION_RULE = + "a consumer program is compiled and run only once the harness has " + + "verified, under the environment TypeScript and Node.js run in — " + + "TypeScript's current directory inside the staging, Node.js run with no " + + "NODE_PATH and a fresh HOME — that nothing is installed in the project " + + "or above it: no ancestor of its root or of its runtime output holds a " + + "package.json or a node_modules entry, its root holds no node_modules " + + "entry, and none of Node.js's global module folders holds a package, so " + + "that nothing is resolvable by package name — no copy of the product's " + + "package under any name least of all — and the program's every option, " + + "types included, stays at the release's default; an unmet isolation a " + + "harness error, never a pass, a product failure, or a skip (TEST-SPEC " + + "H-1, H-2, H-11, T13.1-2)"; const SKELETON_STOP_NOTES: Readonly< Record<NonNullable<SkeletonMember["stopped"]>, string> diff --git a/test/helpers/workspace.ts b/test/helpers/workspace.ts index 0f650c6a..17702855 100644 --- a/test/helpers/workspace.ts +++ b/test/helpers/workspace.ts @@ -57,8 +57,12 @@ // whose name ends in a TypeScript or JavaScript source suffix // (`TS_DEFAULT_SUFFIXES`: `.ts`, `.tsx`, `.mts`, `.cts`, `.js`, `.jsx`, // `.mjs`, `.cjs` — so `.d.ts` names and every configuration file the suite -// stages, `xspec.config.ts` and each `--config` target, all named `.ts`) -// is declared well-formed and must be accepted both ways. A staging +// stages, `xspec.config.ts` and each `--config` target, all named `.ts` +// but T7-1's `xspec.config.mts`, `xspec.config.cts`, and +// `xspec.config.tsx`, which the default reaches as well, and T7-10(e)'s +// `xspec.config.mdx`, an MDX staged-source record carrying its +// TypeScript declaration, below) is declared well-formed and must be +// accepted both ways. A staging // declares the exceptions per path in `ts: { unparseable, unchecked, // wellFormed }` (or per `file()` call, `{ ts: ... }`): `unparseable` for a // file TEST-SPEC declares unparseable (14.20: a TypeScript syntax error, @@ -120,7 +124,9 @@ // effective TypeScript declaration is `unchecked` (P-8's and P-11's // mutations, a noise file, a tampered product-written module) or // `per-draw` (a property draw's composed configuration or code source, -// judged well-formed at staging — the section-16 modules' alone). An MDX +// judged well-formed at staging — the section-16 modules' alone, and +// T7-9(d)'s one configuration composed once the package directory's +// manifest is read, test/suite/registry/section-7-import.ts). An MDX // record carrying no `ts` at a path the TypeScript check judges (a // code-group `.mdx` path) is refused likewise: the self-test judged it as // MDX alone. `edit()` is a declared staging by construction, and so is @@ -345,9 +351,12 @@ export interface WorkspaceTsDecl { * undeclared-staging guard exempts the path, at creation and for a later * plain `file()` staging — the initial-file form of `per-draw`. Only the * section-16 modules list a path here (`tsPathsOf` over a rendered map, - * plus any code source at another name); a deterministic test never does - * (a later-arm workspace's initial code sources and configuration are - * records). + * plus any code source at another name), and T7-9(d) its configuration + * importing the name the module channel's package manifest gives, known + * only once the package directory is read and judged before staging + * (test/suite/registry/section-7-import.ts `composedInstallConfig`); a + * deterministic test never does (a later-arm workspace's initial code + * sources and configuration are records). */ readonly perDraw?: readonly string[]; } @@ -360,8 +369,9 @@ export interface WorkspaceTsDecl { * staging exactly as `well-formed` is — and generated per trial, so no * module-level record can hold it and the undeclared-staging guard exempts * it. Only the section-16 modules pass it — to `file()`, or as the - * workspace declaration's `ts.perDraw` list for a draw's initial files; a - * deterministic test never does, and a staged-source record never carries + * workspace declaration's `ts.perDraw` list for a draw's initial files — + * beside T7-9(d)'s one composed configuration (`WorkspaceTsDecl.perDraw`); + * a deterministic test never does, and a staged-source record never carries * it. */ export type TsFileDeclaration = TsDeclaration | "unchecked" | "per-draw"; @@ -1405,7 +1415,10 @@ export function judgeMdxDeclaration( * included) and JavaScript's, which a code group globbing them discovers as * code sources parsed as plain TypeScript (SPEC 14.20: any name but `.tsx` * selects plain TypeScript). Every configuration file the suite stages is - * named `.ts` (`xspec.config.ts`, each `--config` target). Matched + * named `.ts` (`xspec.config.ts`, each `--config` target) but T7-1's + * `xspec.config.mts`, `xspec.config.cts`, and `xspec.config.tsx`, which + * the default reaches as well, and T7-10(e)'s `xspec.config.mdx`, whose MDX + * staged-source record carries its TypeScript declaration. Matched * case-sensitively, as SPEC spells the `.tsx` suffix. */ export const TS_DEFAULT_SUFFIXES = [ diff --git a/test/node-releases.json b/test/node-releases.json new file mode 100644 index 00000000..ece9e258 --- /dev/null +++ b/test/node-releases.json @@ -0,0 +1,4 @@ +{ + "comment": "TEST-SPEC E-1's Node.js releases, on which the module channel loads the defineConfig module (SPEC 7.6; T7.6-6, T7.6-7, P-17, S-10). The list follows E-1's rule and is pinned by exact version; set on 2026-10-29. CI provisions each at setup with .github/scripts/provision-node-releases.sh, and the harness finds them under XSPEC_NODE_RELEASES_DIR (AGENTS.md). Change it only through the normal change process, with E-1.", + "releases": ["22.0.0", "22.11.0", "22.12.0", "22.23.4", "24.22.2", "26.13.0"] +} diff --git a/test/self/certification-document.test.ts b/test/self/certification-document.test.ts index bd7e0436..a4569b40 100644 --- a/test/self/certification-document.test.ts +++ b/test/self/certification-document.test.ts @@ -10,7 +10,10 @@ // executed certification. A fixture or ID-set change in the document that the // harness does not mirror fails loudly here instead of letting certification // pass while silently covering less — the document-level analogue of the -// registry's unknown-ID hard errors (C-1 vacuity guard). +// registry's unknown-ID hard errors (C-1 vacuity guard). The manifest's +// bindings follow the document's preamble too: each fixture bound with its +// executable and no package directory (C-2), no scope including the +// `defineConfig` module. // // The parser is deliberately strict: fixture-shaped lines in unexpected // positions, malformed headings or ID tokens, and duplicate or dangling @@ -31,8 +34,8 @@ const CERTIFICATIONS_PATH = fileURLToPath( // equality below carries the detail; these pins force a deliberate visit to // this gate when the document's fixture set changes, and guard against a // parser regression losing entries wholesale. -const EXPECTED_CONFORMERS = 9; -const EXPECTED_VIOLATORS = 30; +const EXPECTED_CONFORMERS = 10; +const EXPECTED_VIOLATORS = 32; /** A violator entry as parsed from CERTIFICATIONS.md. */ interface DocumentViolator { @@ -265,7 +268,7 @@ function parseDocument(): readonly DocumentConformer[] { ); } -test("CERTIFICATIONS.md defines exactly 9 conformers and 30 violators (C-1 whole-document gate)", () => { +test("CERTIFICATIONS.md defines exactly 10 conformers and 32 violators (C-1 whole-document gate)", () => { const document = parseDocument(); expect( { @@ -352,3 +355,36 @@ test("every manifest fixture executable exists (C-2 binding, invocable in CI wit "to run it", ).toEqual([]); }); + +test("every manifest fixture is bound with its executable and no package directory, as CERTIFICATIONS.md's preamble binds each fixture (C-2; no scope includes the defineConfig module)", () => { + expect( + fs.readFileSync(CERTIFICATIONS_PATH, "utf8"), + "CERTIFICATIONS.md's preamble binds each fixture with its executable and " + + "no package directory; a document binding one otherwise needs the " + + "manifest's bindings (certification-fixtures.ts) revisited", + ).toContain( + "so each fixture is bound with its executable and no package directory", + ); + const carrying: string[] = []; + let checked = 0; + for (const entry of CERTIFICATION_FIXTURES) { + const bindings = [ + entry.binding(), + ...entry.violators.map((viol) => viol.binding()), + ]; + for (const binding of bindings) { + checked += 1; + if ("packageDir" in binding) { + carrying.push(`${binding.label}: ${String(binding.packageDir)}`); + } + } + } + // Every conformer's and violator's binding was looked at: the pinned + // counts above, so the check is never vacuous. + expect(checked).toBe(EXPECTED_CONFORMERS + EXPECTED_VIOLATORS); + expect( + carrying, + "a CERTIFICATIONS.md fixture's binding carries no package directory " + + "(C-2; CERTIFICATIONS.md's preamble)", + ).toEqual([]); +}); diff --git a/test/self/certification-fixture-grammar.test.ts b/test/self/certification-fixture-grammar.test.ts index 89ad4f4e..882f9700 100644 --- a/test/self/certification-fixture-grammar.test.ts +++ b/test/self/certification-fixture-grammar.test.ts @@ -107,6 +107,17 @@ import { TestWorkspace } from "../helpers/workspace.js"; import type { WorkspaceDecl } from "../helpers/workspace.js"; import { T13_5_8_BOM } from "../suite/registry/section-13.5.js"; import { CERTIFICATION_FIXTURES } from "./certification-fixtures.js"; +import { + AVAIL_STAGING, + CORE_STAGING, + DISC_STAGING, + IMPORT_STAGING, + MD_SOURCE, + MD_STAGING, + ORPHAN_STAGING, + SPEC_GROUP_CONFIG, + VALID_STAGING, +} from "./certification-fixture-stagings.js"; /** A decoder of a surface's document (H-3): fails diagnosed, never defaults. */ type DocumentCheck = (doc: unknown, context: string) => void; @@ -661,36 +672,11 @@ const FILE_OUTSIDE_ROOT = 'of the syntax class; 12.3: `ids --file <glob>` follows "the rules of ' + '7, as in 11"'; -// --- stagings shared by the tables -------------------------------------------- - -/** One spec group of `.mdx` sources (SPEC 7.1), no other configuration. */ -const SPEC_GROUP_CONFIG = `import { defineConfig } from "xspec" - -export default defineConfig({ - specs: { - main: ["specs/*.mdx"] - } -}) -`; - // --- CONF-DISC (CERTIFICATIONS.md §CONF-DISC: `build`, `check`, `ids`, // `inventory`, and `query edges`) ---------------------------------------------- - -/** - * One trivial single-section `.mdx` source in one spec group, as - * §CONF-DISC's scope admits: no code group (so the conformer never loads - * TypeScript), Markdown emission absent — a valid workspace `build` - * regenerates and `ids` lists. - */ -const DISC_STAGING: WorkspaceDecl = { - files: { - "xspec.config.ts": SPEC_GROUP_CONFIG, - "specs/A.mdx": `<S id="a"> -Alpha text. -</S> -`, - }, -}; +// +// The table's declaration is DISC_STAGING (certification-fixture-stagings.ts, +// shared with the configuration-import guard), as each table's below is. const DISC_FILE = "specs/A.mdx"; /** The workspace's one `contains` edge: the root to its section (5.2). */ @@ -1071,27 +1057,378 @@ const DISC_TABLE: GrammarTable = { ], }; -// --- CONF-AVAIL (CERTIFICATIONS.md §CONF-AVAIL: `view` and `occurrences`) ----- +// --- CONF-IMPORT (CERTIFICATIONS.md §CONF-IMPORT: `build`, `check`, `ids`, +// and `inventory`) -------------------------------------------------------------- +// +// The table's declaration is IMPORT_STAGING, T7-9's workspace outside its +// install stagings: two trivial single-section spec sources, Markdown +// emitted next to them. None of the four commands is mutating (13.5), so +// `--test-hold` is an unknown flag of each. A `check` row that answers runs +// on the built workspace alone (`IMPORT_BUILT`): on one never built, a +// conforming `check` reports the missing derived files and graph data +// (12.2, 14.10), and nothing in §CONF-IMPORT's scope presents a finding. /** - * One finding-free spec source as §CONF-AVAIL's scope admits: a section `a`, - * and a section `b` whose `d` prop and embedding each reference `a` locally - * — two resolving occurrences (5.7), so the answers compared hold records. + * A backtick, for the code spans of this section's clauses, which spell + * no escape sequence. */ -const AVAIL_STAGING: WorkspaceDecl = { - files: { - "xspec.config.ts": SPEC_GROUP_CONFIG, - "specs/A.mdx": `<S id="a"> -Alpha text. -</S> +const TICK = "`"; -<S id="b" d={"a"}> -Beta: {text("a")} -</S> -`, - }, +const IMPORT_IDS = idsOf([ + { file: "specs/A.mdx", ids: ["a"] }, + { file: "specs/B.mdx", ids: ["b"] }, +]); +const IMPORT_INVENTORY = inventoryOf(["specs/A.mdx", "specs/B.mdx"]); +const IMPORT_INVENTORY_FORM = `${INVENTORY_JSON_ONLY}; §CONF-IMPORT's Scope: "${TICK}inventory${TICK} (11.6) in its full 12.7 document form"`; +const IMPORT_CHECK_BUILT = + "§CONF-IMPORT's Scope: `check` (12.2) over a workspace `build` has just " + + "regenerated, behaving per 12.0 — finding-free, exit 0"; + +/** The workspace built before a `check` row, and its twin's alike. */ +const IMPORT_BUILT: RowPreparation = async (binding, workspace, context) => { + await prepareStep(binding, workspace, ["build"], context); +}; + +const IMPORT_TABLE: GrammarTable = { + conformer: "CONF-IMPORT", + staging: IMPORT_STAGING, + rows: [ + // Flag tokens anywhere (12.0). + { + argv: ["--json", "build"], + clause: FLAGS_ANYWHERE, + exit: 0, + stdout: like(["build", "--json"], findingFreeReport), + }, + { + argv: ["--json", "check"], + clause: `${FLAGS_ANYWHERE}; ${IMPORT_CHECK_BUILT}`, + exit: 0, + stdout: like(["check", "--json"], findingFreeReport), + prepare: IMPORT_BUILT, + }, + { + argv: ["--json", "ids"], + clause: FLAGS_ANYWHERE, + exit: 0, + stdout: like(["ids", "--json"], IMPORT_IDS), + }, + { + argv: ["--json", "inventory"], + clause: FLAGS_ANYWHERE, + exit: 0, + stdout: like(["inventory", "--json"], IMPORT_INVENTORY), + }, + { + argv: ["--config", "xspec.config.ts", "ids", "--json"], + clause: `${FLAGS_ANYWHERE}; ${ARITY_BY_NAME}`, + exit: 0, + stdout: like( + ["ids", "--json", "--config", "xspec.config.ts"], + IMPORT_IDS, + ), + }, + { + argv: ["check", "--config", "xspec.config.ts", "--json"], + clause: `${FLAGS_ANYWHERE}; ${ARITY_BY_NAME}; ${IMPORT_CHECK_BUILT}`, + exit: 0, + stdout: like( + ["check", "--json", "--config", "xspec.config.ts"], + findingFreeReport, + ), + prepare: IMPORT_BUILT, + }, + // The JSON-only surface answers in JSON without `--json` (12.0, 11). + { + argv: ["inventory"], + clause: IMPORT_INVENTORY_FORM, + exit: 0, + stdout: like(["inventory", "--json"], IMPORT_INVENTORY), + }, + // `--` ends flag reading (12.0). + { + argv: ["ids", "--json", "--"], + clause: DASH_DASH, + exit: 0, + stdout: like(["ids", "--json"], IMPORT_IDS), + }, + { + argv: ["build", "--json", "--"], + clause: DASH_DASH, + exit: 0, + stdout: like(["build", "--json"], findingFreeReport), + }, + { + argv: ["check", "--json", "--"], + clause: `${DASH_DASH}; ${IMPORT_CHECK_BUILT}`, + exit: 0, + stdout: like(["check", "--json"], findingFreeReport), + prepare: IMPORT_BUILT, + }, + { + argv: ["--", "build"], + clause: `${DASH_DASH}: the command word included`, + exit: 0, + stdout: like(["build"]), + }, + { + argv: ["ids", "--", "--json"], + clause: `${DASH_DASH}, so ${TICK}--json${TICK} is no flag but ${TICK}ids${TICK}'s surplus operand (${SURPLUS}); ${NO_JSON_EMPTY}`, + exit: 2, + stdout: EMPTY, + }, + { + argv: ["inventory", "--", "--json"], + clause: `${DASH_DASH}, so ${TICK}--json${TICK} is no flag but ${TICK}inventory${TICK}'s surplus operand (${SURPLUS}; 11.6: ${TICK}inventory${TICK} takes no operand); ${INVENTORY_JSON_ONLY}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + // Arity fixed by name: a value-taking flag takes the whole next token. + { + argv: ["build", "--test-hold", "--json"], + clause: `${ARITY_BY_NAME}: ${TICK}--test-hold${TICK} takes ${TICK}--json${TICK} as its value (CERTIFICATIONS.md preamble: "so ${TICK}build --test-hold --json${TICK} consumes ${TICK}--json${TICK} as its value and leaves JSON out of effect"), and is ${TICK}build${TICK}'s unknown flag (${NOT_MUTATING}); ${NO_JSON_EMPTY}`, + exit: 2, + stdout: EMPTY, + hold: { path: "--json", created: false }, + }, + { + argv: ["build", "--base", "--json"], + clause: `${ARITY_BY_NAME}: ${TICK}--base${TICK} (9, 10.7) takes ${TICK}--json${TICK} as its value and is ${TICK}build${TICK}'s unknown flag (${UNKNOWN_FLAG}); ${NO_JSON_EMPTY}`, + exit: 2, + stdout: EMPTY, + }, + { + argv: ["ids", "--name", "--json"], + clause: `${ARITY_BY_NAME}: ${TICK}--name${TICK} (10.7) takes ${TICK}--json${TICK} as its value and is ${TICK}ids${TICK}'s unknown flag (${UNKNOWN_FLAG}); ${NO_JSON_EMPTY}`, + exit: 2, + stdout: EMPTY, + }, + { + argv: ["nosuch", "--config", "--json"], + clause: `${ARITY_BY_NAME}: ${TICK}--config${TICK} takes ${TICK}--json${TICK} as its value, so JSON output is out of effect for the unknown command (${NO_COMMAND}); ${NO_JSON_EMPTY}`, + exit: 2, + stdout: EMPTY, + }, + { + argv: ["nosuch", "--bogus", "--json"], + clause: `${NO_VALUE_UNLESS_KNOWN}, so ${TICK}--json${TICK} is read as a flag; ${JSON_IN_EFFECT}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + { + argv: ["ids", "--json", "--config", "--json"], + clause: `${WHOLE_NEXT_TOKEN}, so ${TICK}--config${TICK} names the path ${TICK}--json${TICK}; ${CONFIG_AS_GIVEN}`, + exit: 2, + stdout: { + form: "error-document", + code: "configuration-error", + path: "--json", + }, + }, + // `--test-hold` beside commands that are not mutating (13.5). + { + argv: ["check", "--test-hold", "h", "--json"], + clause: `${UNKNOWN_FLAG}, ${TICK}check${TICK} not mutating (${NOT_MUTATING}); ${JSON_IN_EFFECT}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + hold: { path: "h", created: false }, + }, + { + argv: ["ids", "--test-hold", "h", "--json"], + clause: `${UNKNOWN_FLAG}, ${TICK}ids${TICK} not mutating (${NOT_MUTATING}); ${JSON_IN_EFFECT}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + hold: { path: "h", created: false }, + }, + { + argv: ["inventory", "--test-hold", "h"], + clause: `${UNKNOWN_FLAG}, ${TICK}inventory${TICK} not mutating (${NOT_MUTATING}); ${INVENTORY_JSON_ONLY}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + hold: { path: "h", created: false }, + }, + { + argv: ["--test-hold", "h", "build"], + clause: `${ARITY_BY_NAME}: before the command word ${TICK}--test-hold${TICK} takes ${TICK}h${TICK}, and ${TICK}build${TICK} is the command, whose unknown flag it is (${UNKNOWN_FLAG}); ${NO_JSON_EMPTY}`, + exit: 2, + stdout: EMPTY, + hold: { path: "h", created: false }, + }, + // Usage errors of the syntax class (12.0), each in the error document + // whenever JSON output is in effect — decided before any of the + // fixture's scope refusals, which the remaining rows reach no further. + { + argv: ["--json", "nosuch"], + clause: `${NO_COMMAND}; ${JSON_IN_EFFECT}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + { + argv: [], + clause: `${NO_COMMAND}: no command word; ${NO_JSON_EMPTY}`, + exit: 2, + stdout: EMPTY, + }, + { + argv: ["query"], + clause: `${SUBCOMMAND_ORDER}, and they "MUST match the command's synopsis exactly" — ${TICK}query${TICK} names a subcommand (11.1); ${QUERY_JSON_ONLY}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + { + argv: ["query", "nosuch"], + clause: `${NO_COMMAND}: an unknown subcommand; ${QUERY_JSON_ONLY}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + { + argv: ["query", "edges", "extra"], + clause: `${SURPLUS} (11.1: ${TICK}query edges${TICK} takes no operand); ${QUERY_JSON_ONLY}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + { + argv: ["query", "node"], + clause: `${NO_COMMAND}: a missing operand (11.1: ${TICK}query node <node>${TICK}); ${QUERY_JSON_ONLY}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + { + argv: ["query", "reachable", "--from", "specs/A.mdx"], + clause: `${MISSING_REQUIRED}; ${QUERY_JSON_ONLY}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + { + argv: ["query", "edges", "--from", "specs/A.mdx#a#b"], + clause: `${MALFORMED_IDENTITY}; ${QUERY_JSON_ONLY}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + { + argv: ["query", "edges", "--kinds", "contains,,embeds"], + clause: `${INVALID_KINDS}; ${QUERY_JSON_ONLY}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + { + argv: ["inventory", "extra"], + clause: `${SURPLUS} (11.6: ${TICK}inventory${TICK} takes no operand); ${INVENTORY_JSON_ONLY}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + { + argv: ["ids", "extra", "--json"], + clause: `${SURPLUS} — 12.0's own example, ${TICK}xspec ids extra${TICK}; ${JSON_IN_EFFECT}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + { + argv: ["ids", "--tree", "extra", "--json"], + clause: `${SURPLUS} — ${TICK}--tree${TICK} is ${TICK}ids${TICK}'s own flag (12.3); ${JSON_IN_EFFECT}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + { + argv: ["build", "extra", "--json"], + clause: `${SURPLUS} (12.1: ${TICK}build${TICK} takes no operand); ${JSON_IN_EFFECT}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + { + argv: ["check", "extra"], + clause: `${SURPLUS} (12.2: ${TICK}check${TICK} takes no operand); ${NO_JSON_EMPTY}`, + exit: 2, + stdout: EMPTY, + }, + { + argv: ["ids", "--json", "--json"], + clause: `${REPEATED}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + { + argv: ["inventory", "--json", "--json"], + clause: `${REPEATED}; ${INVENTORY_JSON_ONLY}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + { + argv: ["build", "--json", "--config"], + clause: `${MISSING_VALUE}; ${JSON_IN_EFFECT}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + { + argv: ["check", "--config=x", "--json"], + clause: + 'SPEC 12.0: "`--name=value` is not a spelling of any flag" — an ' + + 'unknown flag — and "a `--` token naming no flag of any command ' + + 'takes no value", so the `--json` after it is read as a flag; ' + + PLAIN_DOCUMENT, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + { + argv: ["view", "--bogus"], + clause: `${UNKNOWN_FLAG}; ${jsonOnly("`view`")}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + { + argv: ["ids", "--json", "--config", MALFORMED_CONFIG], + clause: `${MALFORMED} — a malformed ${TICK}--config${TICK} path is no configuration error but a plain usage error; ${JSON_IN_EFFECT}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + { + argv: ["ids", "--json", "--file", "../A.mdx"], + clause: `${FILE_OUTSIDE_ROOT}; ${JSON_IN_EFFECT}; ${PLAIN_DOCUMENT}`, + exit: 2, + stdout: PLAIN_USAGE_ERROR, + }, + // Configuration located at the path `--config` names (12.0, 14). + { + argv: ["build", "--json", "--config", "./nosuch.ts"], + clause: `${CONFIG_AS_GIVEN}; ${JSON_IN_EFFECT}`, + exit: 2, + stdout: { + form: "error-document", + code: "configuration-error", + path: "./nosuch.ts", + }, + }, + { + argv: ["check", "--json", "--config", "./nosuch.ts"], + clause: `${CONFIG_AS_GIVEN}; ${JSON_IN_EFFECT}`, + exit: 2, + stdout: { + form: "error-document", + code: "configuration-error", + path: "./nosuch.ts", + }, + }, + { + argv: ["ids", "--config", "./nosuch.ts"], + clause: `${CONFIG_AS_GIVEN}; ${NO_JSON_EMPTY}`, + exit: 2, + stdout: EMPTY, + }, + { + argv: ["inventory", "--config", "./nosuch.ts"], + clause: `${CONFIG_AS_GIVEN}; ${INVENTORY_JSON_ONLY}`, + exit: 2, + stdout: { + form: "error-document", + code: "configuration-error", + path: "./nosuch.ts", + }, + }, + ], }; +// --- CONF-AVAIL (CERTIFICATIONS.md §CONF-AVAIL: `view` and `occurrences`) ----- + const AVAIL_FILE = "specs/A.mdx"; const AVAIL_TARGET = "specs/A.mdx#a"; /** `b`'s `d` entry, then its embedding: occurrence order (5.7). */ @@ -1309,21 +1646,6 @@ const AVAIL_TABLE: GrammarTable = { // --- CONF-ORPHAN (CERTIFICATIONS.md §CONF-ORPHAN: `build` and `check`) -------- -/** - * One spec group of one trivial single-section source, as §CONF-ORPHAN's - * scope admits (its staging constraint: the spec glob matches `.mdx` names - * alone), Markdown emission absent: a valid workspace `build` regenerates. - */ -const ORPHAN_STAGING: WorkspaceDecl = { - files: { - "xspec.config.ts": SPEC_GROUP_CONFIG, - "specs/A.mdx": `<S id="a"> -Alpha text. -</S> -`, - }, -}; - /** * The preamble's universality, for the JSON-only surfaces (12.0) — none of * them §CONF-ORPHAN's: a usage error there is still a usage error with JSON @@ -1633,29 +1955,10 @@ const ORPHAN_TABLE: GrammarTable = { // `query nodes`) -------------------------------------------------------------- /** - * One finding-free spec source as §CONF-VALID's scope admits — sections - * carrying `id` and `tags` props, `a` tagged `x` and `y` and `b` untagged — - * so a `--tag` filter selects a proper subset (11.1). - */ -const VALID_STAGING: WorkspaceDecl = { - files: { - "xspec.config.ts": SPEC_GROUP_CONFIG, - "specs/A.mdx": `<S id="a" tags="x y"> -Alpha text. -</S> - -<S id="b"> -Beta text. -</S> -`, - }, -}; - -/** - * The same shape failing `build`'s validations with one condition 4 (14.4), - * as T1.4-1's whitespace arms stage one: the second section's `id` spells a - * segment containing U+0020 (1.4). `a` keeps its defined identity, and `b c` - * is a spelled identity (11.2), malformed. + * VALID_STAGING's shape failing `build`'s validations with one condition 4 + * (14.4), as T1.4-1's whitespace arms stage one: the second section's `id` + * spells a segment containing U+0020 (1.4). `a` keeps its defined identity, + * and `b c` is a spelled identity (11.2), malformed. */ const VALID_FAILING_STAGING: WorkspaceDecl = { files: { @@ -2184,44 +2487,8 @@ const VALID_TABLE: GrammarTable = { // --- CONF-MD (CERTIFICATIONS.md §CONF-MD: `build`, `check`, and `query // node`, `query nodes`, and `query edges` as its scope serves them) --------- -/** SPEC 1.3's own nested shape: `a` containing `a.b`, finding-free. */ -const MD_SOURCE = `<S id="a"> -Alpha text. - -<S id="a.b"> -Beta text. -</S> -</S> -`; - -/** - * One spec group with Markdown emission next to each source (7.3, 13.2) — - * so a `build` that runs writes `specs/A.md`, and an exit-2 row's unchanged - * workspace shows that none ran — and MD_SOURCE, a valid workspace as - * §CONF-MD's scope admits ("every file well-formed MDX (14.20) and - * valid"). No row runs `check` to exit 0: on a workspace never built, a - * conforming `check` reports the missing derived files and graph data - * (12.2, 14.10), which §CONF-MD's scope leaves out ("for T3-1's - * grammar-boundary arm, `check` exiting 0", after its `build`), so `check` - * appears in exit-2 rows alone. - */ -const MD_STAGING: WorkspaceDecl = { - files: { - "xspec.config.ts": `import { defineConfig } from "xspec" - -export default defineConfig({ - specs: { - main: ["specs/*.mdx"] - }, - markdown: { emit: true } -}) -`, - "specs/A.mdx": MD_SOURCE, - }, -}; - /** - * The same source under a configuration lacking the required `specs` key + * MD_STAGING's source under a configuration lacking the required `specs` key * (SPEC 7: "`specs` is required"), a configuration error (14.14). */ const MD_NO_SPECS_STAGING: WorkspaceDecl = { @@ -2798,22 +3065,6 @@ const MD_TABLE: GrammarTable = { // --base`; `rename`, file-form `move`, and the mutating `review` // subcommands, `--test-hold` included) ------------------------------------------ -/** - * One spec group of one single-section source, as §CONF-CORE's scope admits - * (no imports, embeddings, `d` props, or tags; no `code`, `markdown`, - * `coverage`, or `policy` keys; no git): a valid workspace every served read - * answers and every served mutating command performs on. - */ -const CORE_STAGING: WorkspaceDecl = { - files: { - "xspec.config.ts": SPEC_GROUP_CONFIG, - "specs/A.mdx": `<S id="a"> -Alpha text. -</S> -`, - }, -}; - const CORE_FILE = "specs/A.mdx"; const CORE_TARGET = `${CORE_FILE}#a`; const CORE_IDS = idsOf([{ file: CORE_FILE, ids: ["a"] }]); @@ -3560,6 +3811,7 @@ const CORE_TABLE: GrammarTable = { const GRAMMAR_TABLES: readonly GrammarTable[] = [ DISC_TABLE, + IMPORT_TABLE, AVAIL_TABLE, ORPHAN_TABLE, VALID_TABLE, diff --git a/test/self/certification-fixture-import.test.ts b/test/self/certification-fixture-import.test.ts new file mode 100644 index 00000000..735fdcb0 --- /dev/null +++ b/test/self/certification-fixture-import.test.ts @@ -0,0 +1,524 @@ +// The certification fixtures' reading of the configuration's import +// (CERTIFICATIONS.md preamble, third paragraph; SPEC 7, 2.4). +// +// CERTIFICATIONS.md requires: "Every conformer reads the configuration's +// import as 7 states too: its module specifier is any static string literal +// (2.4), never interpreted, resolved, or loaded, and the configuration file +// is a source only where a configured group discovers it." Certification +// exercises only the specifiers its in-scope tests stage, so a reader that +// refuses every specifier but one passes it while breaking the rule; this +// guard pins the rule itself, as the invocation-grammar guard +// (certification-fixture-grammar.test.ts) pins 12.0's grammar: one test per +// conformer with a reader of its own, each run through the subprocess +// driver against the conformer's binding from CERTIFICATION_FIXTURES. A +// violator runs its conformer's `product.mjs` with one deviation switch, so +// the conformer's reader is its violators' too; and the CONF-RACE, +// CONF-READERS, and CONF-LEFTOVER conformers run CONF-CORE's `product.mjs` +// deviation-free, so CONF-CORE's row pins their readers as well. +// +// Each row stages its conformer's valid workspace — its grammar table's own +// declaration (certification-fixture-stagings.ts) — once as the twin, +// importing from "xspec", and once per entry of SPELLINGS, each +// configuration differing from the twin's in the specifier alone: the +// spelling spliced in by concatenation exactly as the file is to hold it +// (no printer, no decoding, no re-quoting), every backslash, line +// terminator, and U+FFFD built from its code point, so this source holds +// none. S-9's TypeScript check judges each configuration well-formed as it +// is staged (helpers/workspace.ts), so no spelling a scanner rejects is +// staged. On each workspace the row runs, in order, commands its grammar +// table drives within the conformer's served surface, each under `--json` +// (`build` first wherever a later command would otherwise meet a workspace +// never built), and each run must exit and answer exactly as the twin's +// same run: exit code and standard output byte-equal, and the workspace +// after it byte-equal to the twin's after the same run (H-6's lock-path +// exclusion aside) but for the configuration file, which differs by design +// and must still hold its staged bytes, and graph data (`isGraphDataKey`), +// whose opaque content a differing configuration file may change (TEST-SPEC +// T7-9 leaves it out of its compares alike). The twin's own runs must exit +// as SPEC fixes them over its valid workspace, each answering one JSON +// document, so a fixture refusing the twin as well cannot pass by agreeing +// with itself. The rule's other half — the configuration file a source only +// where a configured group discovers it — each reader keeps by deciding +// discovery by its configured globs alone, none of which matches the +// configuration file here; the spelling that designates the configuration +// file itself (`"./xspec.config.ts"`) fails a reader that resolves its +// specifier and so takes that file up as a source. +// +// Every spelling of a row runs, each failing at its first deviating command +// (later commands would run on a state the deviation left), and the test +// then fails once listing every failing spelling, so a red check shows each +// deviation in one run. Anything but a diagnosed assertion failure +// (`HarnessAssertionError`) — a hang guard's kill, an output overflow, a +// staging error — propagates at once: it is a harness defect, never a +// spelling's verdict. +// +// Run: `npx vitest run --config test/vitest.config.ts --project self +// test/self/certification-fixture-import.test.ts`, under the unprivileged +// namespace as the whole self project runs (AGENTS.md). + +import { Buffer } from "node:buffer"; +import { test } from "vitest"; +import { isGraphDataKey } from "../helpers/adapters/index.js"; +import { + assertBytesEqual, + assertExitCode, + bytesEqual, + fail, + HarnessAssertionError, + parseJsonStdout, +} from "../helpers/assertions.js"; +import { + assertSnapshotsEqual, + describeEntry, + snapshotDirectory, +} from "../helpers/snapshot.js"; +import type { DirectorySnapshot } from "../helpers/snapshot.js"; +import { runProduct } from "../helpers/subprocess.js"; +import type { ProductBinding, RunResult } from "../helpers/subprocess.js"; +import { TestWorkspace } from "../helpers/workspace.js"; +import type { WorkspaceDecl } from "../helpers/workspace.js"; +import { CERTIFICATION_FIXTURES } from "./certification-fixtures.js"; +import { + AVAIL_STAGING, + CORE_STAGING, + DISC_STAGING, + IMPORT_STAGING, + MD_STAGING, + ORPHAN_STAGING, + VALID_STAGING, +} from "./certification-fixture-stagings.js"; + +/** The configuration file every staging here holds at its root (SPEC 7). */ +const CONFIG_PATH = "xspec.config.ts"; +/** The twin's import, spelled exactly once in each staging's configuration. */ +const TWIN_IMPORT = 'from "xspec"'; + +const BACKSLASH = String.fromCodePoint(0x5c); +const LINE_FEED = String.fromCodePoint(0x0a); +const CARRIAGE_RETURN = String.fromCodePoint(0x0d); +const LINE_SEPARATOR = String.fromCodePoint(0x2028); +const REPLACEMENT_CHARACTER = String.fromCodePoint(0xfffd); + +/** One specifier spelling: the literal exactly as the file holds it. */ +interface Spelling { + /** What it is, for diagnoses (the literal itself may hold line breaks). */ + readonly label: string; + /** The static string literal (2.4), its quotes included. */ + readonly literal: string; +} + +/** + * The spellings each conformer's reader must accept as its `"xspec"` twin + * (SPEC 7: "a bare or scoped package name, a relative or absolute path, a + * URL, and the empty string are accepted alike, in either quote style and + * with escape sequences, line continuations, or U+FFFD") — the scoped name, + * the single-quoted relative path, the empty string, an escape, a line + * continuation, and a raw U+FFFD among them, beside the spellings a reader + * matching a literal's delimiters wrongly would trip on: an escaped quote of + * the literal's own kind, an escaped backslash before its closing quote, the + * other quote kind unescaped, a CRLF or U+2028 continuation, and `//` + * inside the literal. + */ +const SPELLINGS: readonly Spelling[] = [ + { label: "a scoped name", literal: '"@acme/config"' }, + { label: "a single-quoted relative path", literal: "'./lib/define.js'" }, + { label: "the empty string", literal: '""' }, + { + label: "a URL, its `//` inside the literal", + literal: '"https://example.com/define.js"', + }, + { + label: "a relative path designating the configuration file itself", + literal: '"./xspec.config.ts"', + }, + { + label: "a hexadecimal escape (a backslash, then `x78`)", + literal: `"${BACKSLASH}x78spec"`, + }, + { + label: "a braced Unicode escape (a backslash, then `u{78}`)", + literal: `"${BACKSLASH}u{78}spec"`, + }, + { + label: "a line continuation (a backslash, then U+000A)", + literal: `"xs${BACKSLASH}${LINE_FEED}pec"`, + }, + { + label: "a single-quoted line continuation (a backslash, then CRLF)", + literal: `'xs${BACKSLASH}${CARRIAGE_RETURN}${LINE_FEED}pec'`, + }, + { + label: "a line continuation (a backslash, then U+2028)", + literal: `"xs${BACKSLASH}${LINE_SEPARATOR}pec"`, + }, + { + label: + "an escaped double quote inside double quotes, then an escaped " + + "backslash before the closing quote", + literal: `"a${BACKSLASH}"b${BACKSLASH}${BACKSLASH}"`, + }, + { + label: "a double quote inside single quotes, unescaped", + literal: `'a"b'`, + }, + { + label: "a raw U+FFFD", + literal: `"x${REPLACEMENT_CHARACTER}spec"`, + }, +]; + +/** One command of a row, run under `--json`. */ +interface ImportStep { + /** The arguments after the executable, `--json` among them. */ + readonly argv: readonly string[]; + /** The exit SPEC 12.0 fixes for it over the twin's valid workspace. */ + readonly exit: 0 | 2; +} + +/** One conformer's reader, driven over its grammar table's staging. */ +interface ImportRow { + /** The conformer's `## CONF-…` name in CERTIFICATION_FIXTURES. */ + readonly conformer: string; + /** Its grammar table's declaration: the twin's workspace. */ + readonly staging: WorkspaceDecl; + /** Why these commands and their exits (CERTIFICATIONS.md, SPEC). */ + readonly clause: string; + /** Run in order on one workspace, the twin's and each spelling's alike. */ + readonly steps: readonly ImportStep[]; +} + +const ROWS: readonly ImportRow[] = [ + { + conformer: "CONF-CORE", + staging: CORE_STAGING, + clause: + "§CONF-CORE's surface: `build`; the reads `check`, `ids`, `show`, " + + "`query`, and `review list`; `review create --strategy audit`, " + + "`rename`, and file-form `move` performing on a valid workspace " + + "(exit 0, 12.0); and `impact --base` without git, the exit-2 " + + "unreadable-baseline case of 6.3/12.0", + steps: [ + { argv: ["build", "--json"], exit: 0 }, + { argv: ["check", "--json"], exit: 0 }, + { argv: ["ids", "--json"], exit: 0 }, + { argv: ["show", "specs/A.mdx#a", "--json"], exit: 0 }, + { argv: ["query", "nodes", "--json"], exit: 0 }, + { + argv: [ + "review", + "create", + "--strategy", + "audit", + "--name", + "s", + "--json", + ], + exit: 0, + }, + { argv: ["review", "list", "--json"], exit: 0 }, + { argv: ["rename", "specs/A.mdx", "a", "b", "--json"], exit: 0 }, + { argv: ["move", "specs/A.mdx", "specs/B.mdx", "--json"], exit: 0 }, + { argv: ["impact", "--base", "main", "--json"], exit: 2 }, + ], + }, + { + conformer: "CONF-VALID", + staging: VALID_STAGING, + clause: + "§CONF-VALID's surface: `build` and `query node`/`query nodes`, " + + "`--tag` filtered, over a valid workspace (exit 0, 12.0)", + steps: [ + { argv: ["build", "--json"], exit: 0 }, + { argv: ["query", "nodes", "--json"], exit: 0 }, + { argv: ["query", "nodes", "--tag", "x", "--json"], exit: 0 }, + { argv: ["query", "node", "specs/A.mdx#a", "--json"], exit: 0 }, + ], + }, + { + conformer: "CONF-MD", + staging: MD_STAGING, + clause: + "§CONF-MD's surface: `build`, then `check` exiting 0 on the built " + + "workspace, and `query node`, `query nodes`, and `query edges` " + + "unfiltered (exit 0, 12.0)", + steps: [ + { argv: ["build", "--json"], exit: 0 }, + { argv: ["check", "--json"], exit: 0 }, + { argv: ["query", "nodes", "--json"], exit: 0 }, + { argv: ["query", "node", "specs/A.mdx#a", "--json"], exit: 0 }, + { argv: ["query", "edges", "--json"], exit: 0 }, + ], + }, + { + conformer: "CONF-DISC", + staging: DISC_STAGING, + clause: + "§CONF-DISC's surface over a valid workspace: `build`, `ids`, " + + "`inventory`, and `query edges --from <path>` (exit 0, 12.0)", + steps: [ + { argv: ["build", "--json"], exit: 0 }, + { argv: ["ids", "--json"], exit: 0 }, + { argv: ["inventory", "--json"], exit: 0 }, + { argv: ["query", "edges", "--from", "specs/A.mdx", "--json"], exit: 0 }, + ], + }, + { + conformer: "CONF-IMPORT", + staging: IMPORT_STAGING, + clause: + "§CONF-IMPORT's surface: `build`, `check` on the built workspace, " + + "`ids`, and `inventory`, each under `--json`, over T7-9's valid " + + "workspace (exit 0, 12.0)", + steps: [ + { argv: ["build", "--json"], exit: 0 }, + { argv: ["check", "--json"], exit: 0 }, + { argv: ["ids", "--json"], exit: 0 }, + { argv: ["inventory", "--json"], exit: 0 }, + ], + }, + { + conformer: "CONF-AVAIL", + staging: AVAIL_STAGING, + clause: + "§CONF-AVAIL's surface: `view`, with and without `--text`, and " + + "`occurrences`, unrestricted and with `--to`, answering from the " + + "current sources (11.2; exit 0, 12.0)", + steps: [ + { argv: ["view", "--json"], exit: 0 }, + { argv: ["view", "--text", "--json"], exit: 0 }, + { argv: ["occurrences", "--json"], exit: 0 }, + { argv: ["occurrences", "--to", "specs/A.mdx#a", "--json"], exit: 0 }, + ], + }, + { + conformer: "CONF-ORPHAN", + staging: ORPHAN_STAGING, + clause: + "§CONF-ORPHAN's surface: `build`, then `check` on the built " + + "workspace (exit 0, 12.0)", + steps: [ + { argv: ["build", "--json"], exit: 0 }, + { argv: ["check", "--json"], exit: 0 }, + ], + }, +]; + +/** The clause every spelling's run is held to. */ +const IMPORT_RULE = + "CERTIFICATIONS.md preamble: every conformer reads the configuration's " + + 'import as 7 states — "its module specifier is any static string ' + + 'literal (2.4), never interpreted, resolved, or loaded"; SPEC 7: a ' + + "configuration's validity, and everything xspec derives from it as " + + "configuration, are independent of the specifier's designation and " + + "spelling"; + +function conformerBinding(name: string): ProductBinding { + const entry = CERTIFICATION_FIXTURES.find((fixture) => fixture.name === name); + if (entry === undefined) { + throw new Error( + `import row names ${name}, which CERTIFICATION_FIXTURES does not list`, + ); + } + return entry.binding(); +} + +function spell(argv: readonly string[]): string { + return "`" + argv.join(" ") + "`"; +} + +/** The staging's configuration text, which must be a plain string. */ +function configurationOf(staging: WorkspaceDecl): string { + const text = staging.files?.[CONFIG_PATH]; + if (typeof text !== "string") { + throw new Error( + `import guard: a staging's ${CONFIG_PATH} must be plain text to vary`, + ); + } + return text; +} + +/** + * The staging with its configuration's specifier spelled `literal`: the + * twin's text with its one `from "xspec"` respelled by concatenation, so + * the two configurations differ in the specifier alone. + */ +function respecified(staging: WorkspaceDecl, literal: string): WorkspaceDecl { + const text = configurationOf(staging); + const at = text.indexOf(TWIN_IMPORT); + if (at === -1 || text.indexOf(TWIN_IMPORT, at + 1) !== -1) { + throw new Error( + `import guard: a staging's ${CONFIG_PATH} must spell ${TWIN_IMPORT} ` + + `exactly once`, + ); + } + const respelled = + text.slice(0, at) + "from " + literal + text.slice(at + TWIN_IMPORT.length); + return { ...staging, files: { ...staging.files, [CONFIG_PATH]: respelled } }; +} + +/** + * The compared view of a workspace snapshot: every entry but the + * configuration file and graph data (module header); H-6's lock-path + * exclusion is the compare's own. + */ +function comparedView(snapshot: DirectorySnapshot): DirectorySnapshot { + return { + ...snapshot, + entries: new Map( + [...snapshot.entries].filter( + ([key]) => key !== CONFIG_PATH && !isGraphDataKey(key), + ), + ), + }; +} + +/** What one of the twin's runs left: its result and the compared view. */ +interface TwinOutcome { + readonly result: RunResult; + readonly view: DirectorySnapshot; +} + +/** + * Run the row's commands on the twin's workspace, each exiting as SPEC fixes + * it and answering one JSON document, recording what each left. + */ +async function runTwin( + binding: ProductBinding, + row: ImportRow, + workspace: TestWorkspace, +): Promise<TwinOutcome[]> { + const outcomes: TwinOutcome[] = []; + for (const step of row.steps) { + const context = + `${row.conformer}: the twin importing from "xspec", ` + + `${spell(step.argv)} (${row.clause})`; + const result = await runProduct(binding, { + cwd: workspace.root, + argv: step.argv, + }); + assertExitCode(result, step.exit, context); + parseJsonStdout( + result, + `${context} — with JSON output in effect, its entire stdout is one ` + + `JSON document (SPEC 12.0)`, + ); + outcomes.push({ + result, + view: comparedView(await snapshotDirectory(workspace.root)), + }); + } + return outcomes; +} + +/** + * Run the row's commands on a fresh workspace whose specifier is spelled + * `spelling`, each answering exactly as the twin's same run (module header). + */ +async function checkSpelling( + binding: ProductBinding, + row: ImportRow, + spelling: Spelling, + twin: readonly TwinOutcome[], +): Promise<void> { + const staging = respecified(row.staging, spelling.literal); + const stagedConfiguration = Buffer.from(configurationOf(staging), "utf8"); + const workspace = await TestWorkspace.create(staging); + try { + for (const [index, step] of row.steps.entries()) { + const outcome = twin[index]; + if (outcome === undefined) { + throw new Error( + `import guard: no twin outcome for step ${String(index)}`, + ); + } + const context = + `${row.conformer}, ${spelling.label}: ` + spell(step.argv); + const result = await runProduct(binding, { + cwd: workspace.root, + argv: step.argv, + }); + assertExitCode( + result, + step.exit, + `${context} must exit as the twin importing from "xspec" does ` + + `(${IMPORT_RULE})`, + ); + assertBytesEqual( + result.stdoutBytes, + outcome.result.stdoutBytes, + `${context}: standard output, against the twin's same run ` + + `(${IMPORT_RULE})`, + ); + const snapshot = await snapshotDirectory(workspace.root); + const configuration = snapshot.entries.get(CONFIG_PATH); + if ( + configuration?.kind !== "file" || + !bytesEqual(configuration.bytes, stagedConfiguration) + ) { + fail( + `${context}: the configuration file must still hold its staged ` + + `bytes — no command writes it (SPEC 13.4: every file xspec ` + + `writes is a derived, durable, or transient file) — but it ` + + `holds ` + + (configuration === undefined + ? "nothing" + : describeEntry(configuration)), + ); + } + assertSnapshotsEqual( + outcome.view, + comparedView(snapshot), + `${context}: the workspace after it, against the twin's after the ` + + `same run — the configuration file and graph data aside, whose ` + + `opaque content a differing configuration file may change ` + + `(TEST-SPEC T7-9) — (${IMPORT_RULE})`, + ); + } + } finally { + await workspace.dispose(); + } +} + +/** Run every spelling of a row, then fail once listing each failing one. */ +async function runImportRow(row: ImportRow): Promise<void> { + const binding = conformerBinding(row.conformer); + const twinWorkspace = await TestWorkspace.create(row.staging); + try { + const twin = await runTwin(binding, row, twinWorkspace); + const failures: string[] = []; + for (const spelling of SPELLINGS) { + try { + await checkSpelling(binding, row, spelling, twin); + } catch (error) { + if (!(error instanceof HarnessAssertionError)) throw error; + failures.push( + `- ${spelling.label}: ` + + error.message.split(LINE_FEED).join(`${LINE_FEED} `), + ); + } + } + if (failures.length > 0) { + fail( + `${row.conformer}: ${String(failures.length)} of ` + + `${String(SPELLINGS.length)} specifier spellings fail ` + + `(${IMPORT_RULE}):${LINE_FEED}` + + failures.join(LINE_FEED), + ); + } + } finally { + await twinWorkspace.dispose(); + } +} + +for (const row of ROWS) { + test( + `${row.conformer} reads the configuration's import as SPEC 7 states: ` + + "any static string literal its specifier, never interpreted, " + + "resolved, or loaded (CERTIFICATIONS.md preamble)", + async () => { + // No guard of its own (TEST-SPEC S-3, helpers/hang-guards.ts): the + // row's fixture invocations each carry the driver's. + await runImportRow(row); + }, + ); +} diff --git a/test/self/certification-fixture-stagings.ts b/test/self/certification-fixture-stagings.ts new file mode 100644 index 00000000..66f86dc7 --- /dev/null +++ b/test/self/certification-fixture-stagings.ts @@ -0,0 +1,179 @@ +// The certification fixtures' valid workspace shapes, shared by the guards +// that drive a conformer's reader directly (CERTIFICATIONS.md preamble, +// third paragraph): the invocation-grammar guard +// (certification-fixture-grammar.test.ts), whose tables stage these as their +// declarations, and the configuration-import guard +// (certification-fixture-import.test.ts), which stages each once importing +// from "xspec" and once per spelling of its specifier. One declaration per +// conformer with a reader of its own, each a workspace its scope admits and +// every command its table drives answers over; each configuration file +// spells its import's specifier `"xspec"` exactly once, as the import guard +// requires of the twin it varies. + +import type { WorkspaceDecl } from "../helpers/workspace.js"; + +/** One spec group of `.mdx` sources (SPEC 7.1), no other configuration. */ +export const SPEC_GROUP_CONFIG = `import { defineConfig } from "xspec" + +export default defineConfig({ + specs: { + main: ["specs/*.mdx"] + } +}) +`; + +/** + * CONF-DISC: one trivial single-section `.mdx` source in one spec group, as + * §CONF-DISC's scope admits: no code group (so the conformer never loads + * TypeScript), Markdown emission absent — a valid workspace `build` + * regenerates and `ids` lists. + */ +export const DISC_STAGING: WorkspaceDecl = { + files: { + "xspec.config.ts": SPEC_GROUP_CONFIG, + "specs/A.mdx": `<S id="a"> +Alpha text. +</S> +`, + }, +}; + +/** CONF-IMPORT's configuration: one spec group, Markdown next to sources. */ +const IMPORT_CONFIG = `import { defineConfig } from "xspec" + +export default defineConfig({ + specs: { + main: ["specs/*.mdx"] + }, + markdown: { emit: true } +}) +`; + +/** + * CONF-IMPORT: T7-9's workspace outside its install stagings, as + * §CONF-IMPORT's scope admits — one spec group globbing `specs/*.mdx` over + * `specs/A.mdx` and `specs/B.mdx`, each a trivial single-section source + * whose one section carries an `id` alone around plain text (T7-9(d)'s + * `<S id="a">A</S>`), and `markdown` with `emit: true`, emitting next to + * sources (7.3, 13.2); no code group, `coverage`, `policy`, git, or + * `node_modules`, so that no configured group discovers the configuration + * file. A valid workspace `build` regenerates, `check` then finds current, + * `ids` lists, and `inventory` reports. + */ +export const IMPORT_STAGING: WorkspaceDecl = { + files: { + "xspec.config.ts": IMPORT_CONFIG, + "specs/A.mdx": `<S id="a">A</S> +`, + "specs/B.mdx": `<S id="b">B</S> +`, + }, +}; + +/** + * CONF-AVAIL: one finding-free spec source as §CONF-AVAIL's scope admits: a + * section `a`, and a section `b` whose `d` prop and embedding each reference + * `a` locally — two resolving occurrences (5.7), so the answers compared + * hold records. + */ +export const AVAIL_STAGING: WorkspaceDecl = { + files: { + "xspec.config.ts": SPEC_GROUP_CONFIG, + "specs/A.mdx": `<S id="a"> +Alpha text. +</S> + +<S id="b" d={"a"}> +Beta: {text("a")} +</S> +`, + }, +}; + +/** + * CONF-ORPHAN: one spec group of one trivial single-section source, as + * §CONF-ORPHAN's scope admits (its staging constraint: the spec glob matches + * `.mdx` names alone), Markdown emission absent: a valid workspace `build` + * regenerates. + */ +export const ORPHAN_STAGING: WorkspaceDecl = { + files: { + "xspec.config.ts": SPEC_GROUP_CONFIG, + "specs/A.mdx": `<S id="a"> +Alpha text. +</S> +`, + }, +}; + +/** + * CONF-VALID: one finding-free spec source as §CONF-VALID's scope admits — + * sections carrying `id` and `tags` props, `a` tagged `x` and `y` and `b` + * untagged — so a `--tag` filter selects a proper subset (11.1). + */ +export const VALID_STAGING: WorkspaceDecl = { + files: { + "xspec.config.ts": SPEC_GROUP_CONFIG, + "specs/A.mdx": `<S id="a" tags="x y"> +Alpha text. +</S> + +<S id="b"> +Beta text. +</S> +`, + }, +}; + +/** CONF-MD: SPEC 1.3's own nested shape, `a` containing `a.b`, finding-free. */ +export const MD_SOURCE = `<S id="a"> +Alpha text. + +<S id="a.b"> +Beta text. +</S> +</S> +`; + +/** + * CONF-MD: one spec group with Markdown emission next to each source (7.3, + * 13.2) — so a `build` that runs writes `specs/A.md`, and an exit-2 row's + * unchanged workspace shows that none ran — and MD_SOURCE, a valid workspace + * as §CONF-MD's scope admits ("every file well-formed MDX (14.20) and + * valid"). No `check` runs on it to exit 0 before its `build`: on a + * workspace never built, a conforming `check` reports the missing derived + * files and graph data (12.2, 14.10), which §CONF-MD's scope leaves out + * ("for T3-1's grammar-boundary arm, `check` exiting 0", after its + * `build`), so the grammar table runs `check` in exit-2 rows alone, and the + * import guard only once `build` has run. + */ +export const MD_STAGING: WorkspaceDecl = { + files: { + "xspec.config.ts": `import { defineConfig } from "xspec" + +export default defineConfig({ + specs: { + main: ["specs/*.mdx"] + }, + markdown: { emit: true } +}) +`, + "specs/A.mdx": MD_SOURCE, + }, +}; + +/** + * CONF-CORE: one spec group of one single-section source, as §CONF-CORE's + * scope admits (no imports, embeddings, `d` props, or tags; no `code`, + * `markdown`, `coverage`, or `policy` keys; no git): a valid workspace every + * served read answers and every served mutating command performs on. + */ +export const CORE_STAGING: WorkspaceDecl = { + files: { + "xspec.config.ts": SPEC_GROUP_CONFIG, + "specs/A.mdx": `<S id="a"> +Alpha text. +</S> +`, + }, +}; diff --git a/test/self/certification-fixtures.ts b/test/self/certification-fixtures.ts index 8d1accac..d07d4f5d 100644 --- a/test/self/certification-fixtures.ts +++ b/test/self/certification-fixtures.ts @@ -4,6 +4,10 @@ // shape as the built product — an executable/workspace binding and nothing // else (C-2), so certifying and testing use one code path and fixtures are // invocable in CI without network or a build step (plain Node ESM programs). +// No binding here carries a package directory: CERTIFICATIONS.md's preamble +// binds each fixture with its executable and no package directory, since no +// scope includes the `defineConfig` module (certification-document.test.ts +// pins both). // // CERTIFICATION_FIXTURES lists every CERTIFICATIONS.md fixture in document // order: each conformer with its in-scope test IDs and each violator with the @@ -545,6 +549,38 @@ export const CERTIFICATION_FIXTURES: readonly CertificationConformer[] = [ violator("VIOL-DISC-DERIVED", "conf-disc/bin-derived.mjs", ["T7-6"]), ], ), + // CONF-IMPORT (§CONF-IMPORT): the configuration's import specifier — + // `build`, `check`, `ids`, and `inventory`, each under `--json`, over + // T7-9's workspace outside its install stagings as P-19 draws over it (one + // spec group of trivial single-section `.mdx` sources, Markdown emitted + // next to sources, no code group), the specifier any static string literal + // TypeScript 5.9.3's scanner accepts, in either quote style, read as + // spelled — escape sequences and line continuations included — and never + // interpreted, resolved, or loaded (SPEC 7, 2.4). + conformer( + "CONF-IMPORT", + "conf-import/bin.mjs", + ["P-19"], + [ + // VIOL-IMPORT-BRACED: the braced form of the Unicode escape sequence + // is not recognized in the import's specifier where its code point is + // at or below U+FFFF (leading zeros and surrogates included): such a + // specifier is judged not well-formed TypeScript (14.20), a + // configuration error (14.14), every command exiting 2 with the 12.7 + // configuration-error document. A braced escape begins only at a + // backslash that itself begins an escape sequence, so an escaped + // backslash before `u{…}` is read as the conformer reads it; braced + // escapes above U+FFFF, the four-digit form, every other escape, line + // continuations, and both quote styles are unchanged. + violator("VIOL-IMPORT-BRACED", "conf-import/bin-braced.mjs", ["P-19"]), + // VIOL-IMPORT-SINGLE: a single-quoted module specifier is refused — a + // configuration error (14.14), every command exiting 2 with the 12.7 + // configuration-error document. Double-quoted specifiers, whatever + // their content, and every other literal of the configuration, + // single-quoted globs included, are unchanged. + violator("VIOL-IMPORT-SINGLE", "conf-import/bin-single.mjs", ["P-19"]), + ], + ), // CONF-AVAIL (§CONF-AVAIL): availability answers and JSON datum forms — // `view` (with and without `--text`) and `occurrences` over spec-only // `.mdx` workspaces, answering in the form-exact 12.7 document forms with diff --git a/test/self/certification-runner.test.ts b/test/self/certification-runner.test.ts index 770a9426..993355ea 100644 --- a/test/self/certification-runner.test.ts +++ b/test/self/certification-runner.test.ts @@ -7,7 +7,8 @@ // ordering; and the runner's per-test-ID attribution, its H-8 outcome // taxonomy (diagnosed assertion failure vs harness error vs hang — a hang // being a product invocation's own hang guard tripped, TEST-SPEC S-3), its -// completion guarantees with no guard of its own, and its per-fixture report +// completion guarantees with no guard of its own, its handing each body the +// binding it was given, unchanged (C-2), and its per-fixture report // rendering. // // Ground truth comes from known-behavior stand-in products written into a @@ -483,6 +484,35 @@ test("renderFixtureReport is per-fixture, per-test-ID legible, one line per test expect(report.results[1]!.diagnosis).toContain("\n"); }); +test("the runner hands each body the very binding it was given — the same object, its package directory included, never rebuilt field by field (C-2: the executable and the package directory reach a body by one code path)", async () => { + // Nothing reads the binding's fields here: the bodies invoke nothing, so + // neither the command nor the package directory needs to exist. + const binding: ProductBinding = { + label: "binding-identity probe", + command: process.execPath, + packageDir: "/xspec-runner-binding-probe/package", + }; + const received: ProductBinding[] = []; + const recorder = (id: string): ProductTestEntry => + defineProductTest({ + id, + title: "records the binding its body receives", + run: async (product) => { + received.push(product); + }, + }); + const report = await runProductTests( + binding, + [recorder("T99-10"), recorder("T99-11")], + { concurrency: 2 }, + ); + expect(report.counts).toEqual({ pass: 2, fail: 0, error: 0, hang: 0 }); + expect(received).toHaveLength(2); + for (const product of received) { + expect(product).toBe(binding); + } +}); + test("the product-test manifest loads as a well-formed registry (import-time canary for the assembled suite)", () => { expect(productTestSuite).toBeInstanceOf(ProductTestSuite); expect(productTestSuite.all()).toHaveLength(productTestSuite.size); diff --git a/test/self/certification-runner.ts b/test/self/certification-runner.ts index 4a6232b0..77920917 100644 --- a/test/self/certification-runner.ts +++ b/test/self/certification-runner.ts @@ -1,9 +1,12 @@ // Certification runner (TEST-SPEC 17 preamble, C-1, C-2). Executes the full // product-facing suite or a named subset — `ProductTestEntry` values resolved // from the registry (test/suite/registry/index.ts) — against an arbitrary -// fixture product supplied as an executable binding and nothing else (C-2), -// and attributes an outcome to every test ID so certification results are -// legible per fixture, per test, in CI output (C-1; the harness-self job). +// fixture product supplied as a product binding (the executable and, where +// one is given, the package directory 7.6's module is distributed as) and +// nothing else (C-2), handing each body that binding unchanged, never +// rebuilt field by field, and attributes an outcome to every test ID so +// certification results are legible per fixture, per test, in CI output +// (C-1; the harness-self job). // One code path: the runner invokes exactly the registered bodies the Vitest // suite runs against the built product (test/suite/declare.ts). // diff --git a/test/self/certification.test.ts b/test/self/certification.test.ts index 466f6cab..a22cecc0 100644 --- a/test/self/certification.test.ts +++ b/test/self/certification.test.ts @@ -1,8 +1,8 @@ // Certification of CERTIFICATIONS.md fixtures (TEST-SPEC 17 C-1, C-2). // // One per-fixture verification is generated below for every entry of the -// CERTIFICATION_FIXTURES manifest (certification-fixtures.ts) — all nine -// conformers and all thirty violators — and the whole-document gate +// CERTIFICATION_FIXTURES manifest (certification-fixtures.ts) — all ten +// conformers and all thirty-two violators — and the whole-document gate // (certification-document.test.ts) proves that manifest equal to // specs/CERTIFICATIONS.md, so certification demonstrably runs against each // fixture in the document (C-1). diff --git a/test/self/module-channel-node-effects.test.ts b/test/self/module-channel-node-effects.test.ts new file mode 100644 index 00000000..0456aa9c --- /dev/null +++ b/test/self/module-channel-node-effects.test.ts @@ -0,0 +1,674 @@ +// Self-checks for the module channel's observations of a run's effects +// (TEST-SPEC 17 preamble: internal self-tests cover harness machinery +// certification does not exercise; T7.6-7(b), (c), and (e), §7.6 Pairing, +// H-2, H-3, S-3, E-1; helpers/module-channel-node.ts and its bootstrap, +// helpers/module-channel-bootstrap.cjs). T7.6-7, whose observations these +// are (test/suite/registry/section-7.6-ii.ts, beside T7.6-6), and S-10's +// checks — each observation catching the effect it exists for on each +// release and route — build on these; here the observations' plumbing is +// pinned before any product exists, on each of E-1's releases, so +// XSPEC_NODE_RELEASES_DIR must name them, as CI's harness-self job and +// AGENTS.md's recipe do +// (unset, every test here that runs a release fails as the harness error +// NodeReleaseError, never a skip): +// - a conforming dual stand-in, along each route on each release, with +// T7.6-7(e)'s FIFOs staged — `xspec.config.ts` in the working directory, +// in the importing module's directory, and in HOME — leaves every +// observation unchanged: no entry created, modified, or removed in the +// staging, the working directory, HOME, or TMPDIR; the process state +// unchanged across the load and the calls, its comparison observing the +// global object, process, and ECMAScript's built-ins; each FIFO still a +// FIFO; and no problem reported, the pairing met; +// - end to end on one release, a stand-in writing a file into TMPDIR and one +// adding a global and starting a timer are reported, as problems in words +// naming the place and the observations (S-10's catches of each effect on +// every release and route are its own); +// - a place's snapshot on a directory of its own: each kind named, a FIFO +// recorded by its kind and never opened, and a write and a rewrite found; +// - the pure functions on vectors: the comparison of two snapshots, and the +// problem functions, each led by the pairing. +// +// The stand-in packages are small hand-written, non-xspec packages, written +// at run time into fresh directories under the OS temporary directory from +// the texts below (STAND_INS), so the committed tree holds no package of +// this file's own. + +import { Buffer } from "node:buffer"; +import * as fsp from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; +import { expect, onTestFinished, test } from "vitest"; +import { stageFifo } from "../helpers/lock-staging.js"; +import { ModuleStaging, runtimeArm } from "../helpers/module-channel.js"; +import type { Placement } from "../helpers/module-channel.js"; +import { + assertModuleLoaded, + CALL_CASES, + comparePlaceSnapshots, + fifoProblems, + MODULE_ROUTES, + prepareModuleRun, + REQUIRED_STATE_SUBJECTS, + RUN_FIFO_NAME, + runtimeOutputProblems, + snapshotPlace, + stateProblems, + writeProblems, +} from "../helpers/module-channel-node.js"; +import type { + CallResult, + LoadedModuleRun, + ModuleRoute, + ModuleRunRequest, + PlaceEntry, + RunEffects, + StateChange, +} from "../helpers/module-channel-node.js"; +import { resolveNodeReleases } from "../helpers/node-releases.js"; +import type { NodeRelease } from "../helpers/node-releases.js"; +import type { ProductBinding } from "../helpers/subprocess.js"; + +const LF = String.fromCodePoint(0x0a); + +/** A manifest's text. */ +function manifest(members: Record<string, unknown>): string { + return `${JSON.stringify(members, null, 2)}${LF}`; +} + +/** A module's text, from its lines. */ +function lines(...text: string[]): string { + return `${text.join(LF)}${LF}`; +} + +/** A CommonJS module's `defineConfig`, an identity function. */ +const COMMONJS_DEFINE_CONFIG = [ + "exports.defineConfig = function defineConfig(settings) {", + " return settings;", + "};", +]; + +/** + * The stand-in packages (module header), each a map from a file's + * package-relative path to its text. + */ +const STAND_INS = { + /** Conforming: an ES-module entry for import, a CommonJS one for require. */ + dual: { + "package.json": manifest({ + name: "effects-dual-standin", + version: "1.0.0", + type: "module", + main: "./index.cjs", + exports: { ".": { import: "./index.js", require: "./index.cjs" } }, + }), + "index.js": lines( + "export function defineConfig(settings) {", + " return settings;", + "}", + ), + "index.cjs": lines(...COMMONJS_DEFINE_CONFIG), + }, + /** Writes a file into the run's TMPDIR while it loads. */ + writing: { + "package.json": manifest({ + name: "effects-writing-standin", + version: "1.0.0", + main: "./index.js", + }), + "index.js": lines( + 'const path = require("node:path");', + 'const os = require("node:os");', + 'require("node:fs").writeFileSync(path.join(os.tmpdir(), "xspec-written"), "written");', + ...COMMONJS_DEFINE_CONFIG, + ), + }, + /** Adds a global and starts a timer while it loads. */ + stateful: { + "package.json": manifest({ + name: "effects-stateful-standin", + version: "1.0.0", + main: "./index.js", + }), + "index.js": lines( + "globalThis.xspecEffect = 1;", + "setTimeout(() => {}, 200);", + ...COMMONJS_DEFINE_CONFIG, + ), + }, +} as const satisfies Record<string, Record<string, string>>; + +/** A fresh, empty directory of this test's own, removed once it ends. */ +async function freshDirectory(prefix: string): Promise<string> { + const directory = await fsp.realpath( + await fsp.mkdtemp(path.join(os.tmpdir(), prefix)), + ); + onTestFinished(() => fsp.rm(directory, { recursive: true, force: true })); + return directory; +} + +/** Write `files` into a fresh package directory, returned. */ +async function writeStandIn(files: Record<string, string>): Promise<string> { + const directory = await freshDirectory("xspec-effects-standin-"); + for (const [name, text] of Object.entries(files)) { + await fsp.writeFile(path.join(directory, name), text, { flag: "wx" }); + } + return directory; +} + +/** + * A binding of the certification fixtures' shape beside `packageDir`: its + * executable is never run here. + */ +function standInBinding(packageDir: string): ProductBinding { + return { + label: "module-channel effects stand-in binding", + command: process.execPath, + requiredFiles: [process.execPath], + packageDir, + }; +} + +/** A staging and its canonical placement in a CommonJS project. */ +interface StagedPackage { + readonly staging: ModuleStaging; + readonly placement: Placement; +} + +/** + * Stage the stand-in `files` at the canonical placement in a CommonJS + * project, for runs on `releases`; disposed of once the test ends. + */ +async function stageStandIn( + files: Record<string, string>, + releases: readonly NodeRelease[], + context: string, +): Promise<StagedPackage> { + const staging = await ModuleStaging.create( + standInBinding(await writeStandIn(files)), + context, + ); + onTestFinished(() => staging.dispose()); + await staging.stageProject("project", "commonjs"); + const placement = await staging.placeCanonical( + "project", + runtimeArm(releases), + ); + return { staging, placement }; +} + +/** One run's request over `staged`, observing its effects. */ +function request( + staged: StagedPackage, + release: NodeRelease, + route: ModuleRoute, + context: string, +): ModuleRunRequest { + return { + staging: staged.staging, + placement: staged.placement, + route, + release, + project: "commonjs", + alone: true, + effects: true, + context, + }; +} + +/** The first of E-1's releases, for the checks one release serves. */ +async function firstRelease(): Promise<NodeRelease> { + const [release] = await resolveNodeReleases(); + if (release === undefined) throw new Error("E-1 lists no release"); + return release; +} + +test("a conforming dual stand-in, along each of Node.js's four routes on each of E-1's releases, with T7.6-7(e)'s FIFOs staged — xspec.config.ts in the run's working directory, in the importing module's directory (staged once, found by every later run), and in its HOME — leaves every observation unchanged: no entry created, modified, or removed in the staging, the working directory, HOME, or TMPDIR; the process state unchanged across the load and the calls, its comparison observing the global object, process, and ECMAScript's global constructors, namespace objects, and prototypes; each FIFO still a FIFO; the run ended on its own; and no problem is reported, the pairing met (TEST-SPEC T7.6-7(b), (c), (e), §7.6 Pairing)", async () => { + const releases = await resolveNodeReleases(); + const staged = await stageStandIn( + STAND_INS.dual, + releases, + "effects self-test: dual", + ); + const importingFifo = path.join(staged.placement.holdingDir, RUN_FIFO_NAME); + for (const release of releases) { + for (const route of MODULE_ROUTES) { + const context = `effects self-test: dual, ${release.version}, ${route}`; + const prepared = await prepareModuleRun( + request(staged, release, route, context), + ); + let loaded: LoadedModuleRun; + try { + expect(prepared.fifos, context).toEqual([ + path.join(prepared.cwd, RUN_FIFO_NAME), + importingFifo, + path.join(prepared.home, RUN_FIFO_NAME), + ]); + for (const fifo of prepared.fifos) { + expect((await fsp.lstat(fifo)).isFIFO(), context).toBe(true); + } + loaded = assertModuleLoaded(await prepared.launch(), "stand-in"); + } finally { + await prepared.dispose(); + } + const effects = loaded.effects; + expect(effects, context).toBeDefined(); + if (effects === undefined) continue; + expect( + effects.writes.map((writes) => [writes.place, writes.root]), + context, + ).toEqual([ + ["staging", staged.staging.root], + ["working directory", loaded.cwd], + ["HOME", loaded.home], + ["TMPDIR", loaded.tmp], + ]); + expect( + effects.writes.flatMap((writes) => writes.changes), + context, + ).toEqual([]); + expect(effects.fifos, context).toEqual( + prepared.fifos.map((fifo) => ({ path: fifo, found: "FIFO" })), + ); + const { state } = loaded.report; + expect(state.changes, context).toEqual([]); + expect(state.omitted, context).toBe(0); + for (const label of REQUIRED_STATE_SUBJECTS) { + expect(state.subjects, context).toContain(label); + } + expect(stateProblems(loaded), context).toEqual([]); + expect(writeProblems(loaded), context).toEqual([]); + expect(fifoProblems(loaded), context).toEqual([]); + expect(await runtimeOutputProblems(loaded), context).toEqual([]); + } + } + expect((await fsp.lstat(importingFifo)).isFIFO()).toBe(true); +}); + +test("end to end on one release, each of T7.6-7(b)'s and (c)'s observations reports what a stand-in does while it loads, as problems in words: a file written into TMPDIR (b), naming the place and the entry created; a global added and a timer started (c), each under its observation; the FIFOs still FIFOs, and the pairing met (TEST-SPEC T7.6-7(b), (c), §7.6 Pairing)", async () => { + const release = await firstRelease(); + const run = async ( + standIn: keyof typeof STAND_INS, + ): Promise<LoadedModuleRun> => { + const context = `effects self-test: ${standIn}, ${release.version}`; + const staged = await stageStandIn(STAND_INS[standIn], [release], context); + const prepared = await prepareModuleRun( + request(staged, release, "require", context), + ); + try { + return assertModuleLoaded(await prepared.launch(), "stand-in"); + } finally { + await prepared.dispose(); + } + }; + + const writing = await run("writing"); + expect( + writing.effects?.writes.map((writes) => [writes.place, writes.changes]), + ).toEqual([ + ["staging", []], + ["working directory", []], + ["HOME", []], + [ + "TMPDIR", + [ + { + path: "xspec-written", + change: "created", + detail: "it is a plain file of 7 byte(s)", + }, + ], + ], + ]); + const written = writeProblems(writing); + expect(written).toHaveLength(1); + expect(written[0]).toContain(`in the run's TMPDIR (${writing.tmp})`); + expect(written[0]).toContain('"xspec-written" was created'); + expect(written[0]).toContain("TEST-SPEC T7.6-7(b)"); + expect(fifoProblems(writing)).toEqual([]); + expect(stateProblems(writing)).toEqual([]); + + const stateful = await run("stateful"); + expect( + stateful.report.state.changes.map((change) => [ + change.observation, + change.subject, + ]), + ).toEqual([ + ["global-object", "the global object"], + ["timers-and-handles", "the pending timers and handles"], + ]); + const changed = stateProblems(stateful); + expect(changed).toHaveLength(2); + expect(changed[0]).toContain('an own property "xspecEffect" was added'); + expect(changed[1]).toContain("0 timer(s) were pending (Timeout), and 1 are"); + for (const problem of changed) { + expect(problem).toContain("TEST-SPEC T7.6-7(c)"); + } + expect(writeProblems(stateful)).toEqual([]); + expect(fifoProblems(stateful)).toEqual([]); +}); + +test("a place's snapshot names each entry's kind — a plain file with its bytes, a directory, a symbolic link with its target, never followed, and a FIFO by its kind alone, never opened — the place itself under '.'; two snapshots of an unchanged place compare equal, and a file written and a file rewritten are found, by path (TEST-SPEC T7.6-7(b), S-3)", async () => { + const place = await freshDirectory("xspec-effects-place-"); + const beside = await freshDirectory("xspec-effects-place-scratch-"); + await fsp.writeFile(path.join(place, "file"), "bytes", { flag: "wx" }); + await fsp.mkdir(path.join(place, "directory")); + await fsp.writeFile(path.join(place, "directory", "inner"), "inner", { + flag: "wx", + }); + await fsp.symlink("directory/inner", path.join(place, "link")); + await stageFifo({ root: place, tempRoot: beside }, "fifo"); + const before = await snapshotPlace(place, "effects self-test: place"); + expect([...before.entries()]).toEqual([ + ["", { kind: "directory", listed: true }], + ["directory", { kind: "directory", listed: true }], + [ + "directory/inner", + { kind: "plain file", bytes: Buffer.from("inner", "utf8") }, + ], + ["fifo", { kind: "FIFO" }], + ["file", { kind: "plain file", bytes: Buffer.from("bytes", "utf8") }], + [ + "link", + { kind: "symbolic link", target: Buffer.from("directory/inner", "utf8") }, + ], + ]); + expect( + comparePlaceSnapshots( + before, + await snapshotPlace(place, "effects self-test: place"), + ), + ).toEqual([]); + await fsp.writeFile(path.join(place, "added"), "new", { flag: "wx" }); + await fsp.writeFile(path.join(place, "file"), "BYTES"); + const changes = comparePlaceSnapshots( + before, + await snapshotPlace(place, "effects self-test: place"), + ); + expect( + changes.map((change) => [change.path, change.change, change.detail]), + ).toEqual([ + ["added", "created", "it is a plain file of 3 byte(s)"], + ["file", "modified", expect.stringContaining("its bytes changed")], + ]); + expect(await snapshotPlace(path.join(place, "absent"), "absent")).toEqual( + new Map(), + ); +}); + +test("the comparison of two snapshots, on vectors: an entry created, removed, or modified — its kind (a FIFO turned into a socket among them), a plain file's bytes, whether it reads, a directory's listing, a link's target — each reported in bytewise path order, the place itself as '.', a name that is no UTF-8 rendered by its bytes; nothing reported where nothing differs (TEST-SPEC T7.6-7(b))", () => { + const file = (text: string | null): PlaceEntry => ({ + kind: "plain file", + bytes: text === null ? null : Buffer.from(text, "utf8"), + }); + const directory = (listed = true): PlaceEntry => ({ + kind: "directory", + listed, + }); + const link = (target: string): PlaceEntry => ({ + kind: "symbolic link", + target: Buffer.from(target, "utf8"), + }); + const notUtf8 = Buffer.from([0x6e, 0xff]).toString("latin1"); + const before = new Map<string, PlaceEntry>([ + ["", directory()], + ["d", directory()], + ["d/kept", file("same")], + ["fifo", { kind: "FIFO" }], + ["gone", file("was here")], + ["link", link("a")], + ["listing", directory()], + ["readable", file("readable")], + ["rewritten", file("old")], + [notUtf8, file("n")], + ]); + const after = new Map<string, PlaceEntry>([ + ["", directory()], + ["d", directory()], + ["d/kept", file("same")], + ["d/new", file("new")], + ["fifo", { kind: "socket" }], + ["link", link("b")], + ["listing", directory(false)], + ["readable", file(null)], + ["rewritten", file("new")], + [notUtf8, file("n")], + ]); + expect(comparePlaceSnapshots(before, before)).toEqual([]); + const changes = comparePlaceSnapshots(before, after); + expect(changes.map((change) => [change.path, change.change])).toEqual([ + ["d/new", "created"], + ["fifo", "modified"], + ["gone", "removed"], + ["link", "modified"], + ["listing", "modified"], + ["readable", "modified"], + ["rewritten", "modified"], + ]); + const detail = (at: string): string | undefined => + changes.find((change) => change.path === at)?.detail; + expect(detail("fifo")).toBe("a FIFO became a socket"); + expect(detail("gone")).toBe("it was a plain file of 8 byte(s)"); + expect(detail("link")).toBe('its target changed from "a" to "b"'); + expect(detail("listing")).toBe("its listing is now refused"); + expect(detail("readable")).toBe("its bytes can no longer be read"); + expect(detail("rewritten")).toContain("its bytes changed"); + const rootless = new Map(after); + rootless.delete(""); + rootless.set(notUtf8, file("N")); + expect( + comparePlaceSnapshots(after, rootless).map((change) => [ + change.path, + change.change, + ]), + ).toEqual([ + [".", "removed"], + ["<path bytes 6eff>", "modified"], + ]); +}); + +/** Every one of T7.6-6's calls returning its argument. */ +const ALL_RETURNED: readonly CallResult[] = CALL_CASES.map((name) => ({ + case: name, + outcome: "returned-argument", + returned: null, + thrown: null, +})); + +/** A vector's loaded run: a conforming one, observing its effects, unless overridden. */ +function vectorRun( + fields: { + readonly results?: readonly CallResult[]; + readonly changes?: readonly StateChange[]; + readonly omitted?: number; + readonly effects?: RunEffects | undefined; + } = {}, +): LoadedModuleRun { + return { + description: "vector run", + route: "require", + release: { version: "0.0.0", executable: "/releases/v0.0.0/bin/node" }, + placement: { + name: "xspec-config", + holdingDir: "/s/p", + path: "/s/p/node_modules/xspec-config", + form: "copy", + copy: "/s/p/node_modules/xspec-config", + }, + importingModule: "/s/p/importing-module-require.cjs", + cwd: "/run/work", + home: "/run/home", + tmp: "/run/tmp", + environment: { HOME: "/run/home", TMPDIR: "/run/tmp" }, + result: { + exitCode: 0, + signal: null, + stdout: "", + stderr: "", + stdoutBytes: Buffer.alloc(0), + stderrBytes: Buffer.alloc(0), + commandLine: "vector", + }, + outcome: "loaded", + report: { + argv: [], + release: { version: "v0.0.0", execPath: "/node", execArgv: [] }, + pid: 7, + environment: {}, + cwd: "/run/work", + phase: "completed", + importingModule: { topLevelThis: "object", location: "/s/p/i.cjs" }, + load: { + outcome: "loaded", + value: { + type: "object", + ownKeys: [{ kind: "string", name: "defineConfig", enumerable: true }], + }, + }, + calls: { + reading: { type: "function", thrown: null }, + results: fields.results ?? ALL_RETURNED, + traps: [], + }, + state: { + subjects: [...REQUIRED_STATE_SUBJECTS], + changes: fields.changes ?? [], + omitted: fields.omitted ?? 0, + }, + bootstrapError: null, + warnings: [], + exit: { code: 0 }, + }, + reportProblem: undefined, + effects: + "effects" in fields + ? fields.effects + : { + writes: [ + { place: "staging", root: "/s", changes: [] }, + { place: "working directory", root: "/run/work", changes: [] }, + { place: "HOME", root: "/run/home", changes: [] }, + { place: "TMPDIR", root: "/run/tmp", changes: [] }, + ], + fifos: [ + { path: "/run/work/xspec.config.ts", found: "FIFO" }, + { path: "/s/p/xspec.config.ts", found: "FIFO" }, + { path: "/run/home/xspec.config.ts", found: "FIFO" }, + ], + }, + }; +} + +test("T7.6-7(b), (c), and (e)'s problem functions, on vectors: a conforming run reports nothing; each difference listed, each more counted, each place's change, and each FIFO no longer a FIFO in place — gone, or another kind — is a problem in words led by the run's description and citing its clause; each function reports the pairing first where defineConfig did not return its argument; and reading a run's effects that were never observed is a usage error (TEST-SPEC T7.6-7(b), (c), (e), §7.6 Pairing)", () => { + const conforming = vectorRun(); + expect(stateProblems(conforming)).toEqual([]); + expect(writeProblems(conforming)).toEqual([]); + expect(fifoProblems(conforming)).toEqual([]); + + const state = stateProblems( + vectorRun({ + changes: [ + { + observation: "built-ins", + subject: "Math", + detail: 'an own property "x" was added', + }, + ], + omitted: 4, + }), + ); + expect(state).toHaveLength(2); + expect(state[0]).toBe( + "vector run: a global built-in object's own properties changed across " + + 'the load and the calls — Math: an own property "x" was added ' + + "(TEST-SPEC T7.6-7(c); SPEC 7.6 Runtime: beyond the runtime's own " + + "resolution of the specifier and loading of the package's files, " + + "neither loading the module nor calling defineConfig has any effect — " + + "no change to the global object or to any other state of the process)", + ); + expect(state[1]).toContain("differs in 4 more way(s)"); + + const written = writeProblems( + vectorRun({ + effects: { + writes: [ + { + place: "staging", + root: "/s", + changes: [ + { path: "p/new", change: "created", detail: "it is a directory" }, + ], + }, + { + place: "HOME", + root: "/run/home", + changes: [ + { + path: ".npmrc", + change: "removed", + detail: "it was a plain file of 1 byte(s)", + }, + ], + }, + ], + fifos: [], + }, + }), + ); + expect(written).toEqual([ + 'vector run: in the staging (/s), "p/new" was created: it is a ' + + "directory (TEST-SPEC T7.6-7(b); SPEC 7.6 Runtime: beyond the " + + "runtime's own resolution of the specifier and loading of the " + + "package's files, neither loading the module nor calling defineConfig " + + "has any effect — no filesystem write)", + expect.stringContaining( + `in the run's HOME (/run/home), ".npmrc" was removed`, + ), + ]); + + const fifos = fifoProblems( + vectorRun({ + effects: { + writes: [], + fifos: [ + { path: "/run/work/xspec.config.ts", found: null }, + { path: "/s/p/xspec.config.ts", found: "plain file" }, + { path: "/run/home/xspec.config.ts", found: "FIFO" }, + ], + }, + }), + ); + expect(fifos).toHaveLength(2); + expect(fifos[0]).toContain( + "the FIFO /run/work/xspec.config.ts is gone, no longer a FIFO in place", + ); + expect(fifos[1]).toContain( + "the FIFO /s/p/xspec.config.ts is now a plain file", + ); + expect(fifos[1]).toContain("TEST-SPEC T7.6-7(e), S-3"); + + const copying = vectorRun({ + results: ALL_RETURNED.map((result) => + result.case === "object" + ? { + ...result, + outcome: "returned-other", + returned: { type: "object", text: null }, + } + : result, + ), + }); + for (const problems of [ + stateProblems(copying), + writeProblems(copying), + fifoProblems(copying), + ]) { + expect(problems).toHaveLength(1); + expect(problems[0]).toContain("no absence counts in this run"); + } + + const unobserved = vectorRun({ effects: undefined }); + expect(() => writeProblems(unobserved)).toThrow("ModuleRunRequest.effects"); + expect(() => fifoProblems(unobserved)).toThrow("ModuleRunRequest.effects"); + expect(stateProblems(unobserved)).toEqual([]); +}); diff --git a/test/self/module-channel-node-observations.test.ts b/test/self/module-channel-node-observations.test.ts new file mode 100644 index 00000000..1d6c6106 --- /dev/null +++ b/test/self/module-channel-node-observations.test.ts @@ -0,0 +1,1021 @@ +// Self-checks for the module channel's runtime observations (TEST-SPEC 17 +// preamble: internal self-tests cover harness machinery certification does +// not exercise; T7.6-6, T7.6-7(a), §7.6 Pairing, H-2, H-3, S-3, E-1; +// helpers/module-channel-node.ts, its bootstrap +// helpers/module-channel-bootstrap.cjs, and its warning calibration +// helpers/module-channel-warning-calibration.cjs). T7.6-6 and T7.6-7, 7.6's +// runtime tests registered so far (test/suite/registry/section-7.6-ii.ts), +// read these observations — T7.6-6 its own, T7.6-7 the output oracle — and +// they and S-10's checks — each observation catching the effect it exists +// for on each release and route — build on these; here the observations' +// plumbing is pinned before any product exists, on each of E-1's releases, +// so XSPEC_NODE_RELEASES_DIR must name them, as CI's harness-self job and +// AGENTS.md's recipe do (unset, every test here that runs a release fails +// as the harness error NodeReleaseError, never a skip): +// - a conforming dual stand-in, along each route on each release: the +// route's own-key listing exactly defineConfig, every one of T7.6-6's +// calls returning its argument by SameValue, no trap of either Proxy +// invoked, the frozen object returned without a throw, both streams +// empty, and the output oracle passing, the pairing met; +// - the printed form learned from each release, once per release: the +// form renders, byte for byte, the standard error of stand-ins emitting a +// warning of their own while loading — a CommonJS one along require, an +// ES-module one along static import — and the oracle finds each warning's +// stack beginning in the package's files, by path and by file URL; +// - conforming stand-ins whose manifests draw the runtime's own warnings +// pass the oracle: DEP0128 along require (an invalid main beside +// index.js), DEP0151 along each import route (an ES-module package's main +// lookup), and an ES-module-only package along require on each release +// that loads it, the experimental warning on one that prints it; +// - end to end on one release, each observation reports the deviation it +// exists for — a CommonJS-only entry's namespace carrying default, an +// enumerable __esModule, -0 returned as 0, arguments copied, a Proxy's +// trap touched, a frozen object refused, a defineConfig that is no +// function, a process ending inside a call — as problems in words, never +// a throw (S-10's catches of each effect on every release and route are +// its own); +// - the pure functions on vectors: the rendering, the first frame, the +// package frame, and each problem function, each conforming vector clean +// and each deviating one caught. +// +// The stand-in packages are small hand-written, non-xspec packages, written +// at run time into fresh directories under the OS temporary directory from +// the texts below (STAND_INS), so the committed tree holds no package of +// this file's own. + +import { Buffer } from "node:buffer"; +import * as fsp from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; +import { pathToFileURL } from "node:url"; +import { expect, onTestFinished, test } from "vitest"; +import { ModuleStaging, runtimeArm } from "../helpers/module-channel.js"; +import type { Placement } from "../helpers/module-channel.js"; +import { + assertModuleLoaded, + CALL_CASES, + examinationProblems, + exportsProblems, + identityProblems, + learnWarningForm, + MODULE_ROUTES, + moduleRunProblem, + outputProblems, + packageFrame, + pairingProblem, + renderWarnings, + runModuleRoute, + runtimeOutputProblems, + warningFirstFrame, +} from "../helpers/module-channel-node.js"; +import type { + CallResult, + CapturedWarning, + DefineConfigReading, + LoadedModuleRun, + ModuleRoute, + ModuleRunRequest, + OwnKey, + TrapInvocation, + WarningForm, +} from "../helpers/module-channel-node.js"; +import { resolveNodeReleases } from "../helpers/node-releases.js"; +import type { NodeRelease } from "../helpers/node-releases.js"; +import type { ProductBinding } from "../helpers/subprocess.js"; + +const LF = String.fromCodePoint(0x0a); + +/** A loaded value's own `defineConfig` key, as the report lists it. */ +const DEFINE_CONFIG_KEY: OwnKey = { + kind: "string", + name: "defineConfig", + enumerable: true, +}; + +/** A module namespace's own `Symbol.toStringTag` key, likewise. */ +const TO_STRING_TAG_KEY: OwnKey = { + kind: "symbol", + name: "Symbol.toStringTag", + enumerable: false, +}; + +/** Every one of T7.6-6's calls returning its argument. */ +const ALL_RETURNED: readonly CallResult[] = CALL_CASES.map((name) => ({ + case: name, + outcome: "returned-argument", + returned: null, + thrown: null, +})); + +/** The import routes: each but `require`. */ +const IMPORT_ROUTES: readonly ModuleRoute[] = MODULE_ROUTES.filter( + (route) => route !== "require", +); + +/** A manifest's text. */ +function manifest(members: Record<string, unknown>): string { + return `${JSON.stringify(members, null, 2)}${LF}`; +} + +/** A module's text, from its lines. */ +function lines(...text: string[]): string { + return `${text.join(LF)}${LF}`; +} + +/** An ES module's `defineConfig`, an identity function. */ +const MODULE_DEFINE_CONFIG = [ + "export function defineConfig(settings) {", + " return settings;", + "}", +]; + +/** A CommonJS module's `defineConfig`, an identity function. */ +const COMMONJS_DEFINE_CONFIG = [ + "exports.defineConfig = function defineConfig(settings) {", + " return settings;", + "};", +]; + +/** A CommonJS package named `name` with one entry, `index.js`, of `body`. */ +function commonJsStandIn( + name: string, + body: readonly string[], +): Record<string, string> { + return { + "package.json": manifest({ name, version: "1.0.0", main: "./index.js" }), + "index.js": lines(...body), + }; +} + +/** A CommonJS package whose `defineConfig` runs `body` on `settings`. */ +function commonJsDefineConfig( + name: string, + body: readonly string[], +): Record<string, string> { + return commonJsStandIn(name, [ + "exports.defineConfig = function defineConfig(settings) {", + ...body, + "};", + ]); +} + +/** + * The stand-in packages (module header), each a map from a file's + * package-relative path to its text. + */ +const STAND_INS = { + /** Conforming: an ES-module entry for import, a CommonJS one for require. */ + dual: { + "package.json": manifest({ + name: "observation-dual-standin", + version: "1.0.0", + type: "module", + main: "./index.cjs", + exports: { ".": { import: "./index.js", require: "./index.cjs" } }, + }), + "index.js": lines(...MODULE_DEFINE_CONFIG), + "index.cjs": lines(...COMMONJS_DEFINE_CONFIG), + }, + /** Emits a warning of its own while loading, from a CommonJS module. */ + commonJsWarning: commonJsStandIn("observation-commonjs-warning-standin", [ + 'process.emitWarning("xspec observation self-test warning", {', + ' type: "XspecSelfTestWarning",', + ' code: "XSPEC_SELF_TEST",', + ' detail: "its detail",', + "});", + ...COMMONJS_DEFINE_CONFIG, + ]), + /** Emits a warning of its own while loading, from an ES module. */ + moduleWarning: { + "package.json": manifest({ + name: "observation-module-warning-standin", + version: "1.0.0", + type: "module", + exports: "./index.js", + }), + "index.js": lines( + 'process.emitWarning("xspec observation self-test warning", {', + ' type: "XspecSelfTestWarning",', + ' code: "XSPEC_SELF_TEST",', + "});", + ...MODULE_DEFINE_CONFIG, + ), + }, + /** Conforming, its `main` invalid beside an `index.js` (DEP0128). */ + invalidMain: { + "package.json": manifest({ + name: "observation-invalid-main-standin", + version: "1.0.0", + main: "./missing.js", + }), + "index.js": lines(...COMMONJS_DEFINE_CONFIG), + }, + /** Conforming, an ES-module package whose `main` needs a lookup (DEP0151). */ + mainLookup: { + "package.json": manifest({ + name: "observation-main-lookup-standin", + version: "1.0.0", + type: "module", + main: "./lib", + }), + "lib/index.js": lines(...MODULE_DEFINE_CONFIG), + }, + /** Conforming, serving only an ES-module entry. */ + moduleOnly: { + "package.json": manifest({ + name: "observation-module-only-standin", + version: "1.0.0", + type: "module", + exports: "./index.js", + }), + "index.js": lines(...MODULE_DEFINE_CONFIG), + }, + /** A CommonJS-only entry, whose import namespace carries `default`. */ + commonJsOnly: commonJsStandIn( + "observation-commonjs-only-standin", + COMMONJS_DEFINE_CONFIG, + ), + /** An enumerable `__esModule` beside `defineConfig`. */ + enumerableEsModule: commonJsStandIn("observation-esmodule-standin", [ + "exports.__esModule = true;", + ...COMMONJS_DEFINE_CONFIG, + ]), + /** Returns 0 for -0. */ + negativeZero: commonJsDefineConfig("observation-negative-zero-standin", [ + " return Object.is(settings, -0) ? 0 : settings;", + ]), + /** Returns a copy of an object or array argument. */ + copying: commonJsDefineConfig("observation-copying-standin", [ + ' return settings !== null && typeof settings === "object"', + " ? { ...settings }", + " : settings;", + ]), + /** Lists a function argument's own keys before returning it. */ + examining: commonJsDefineConfig("observation-examining-standin", [ + ' if (typeof settings === "function") Object.keys(settings);', + " return settings;", + ]), + /** Throws on a frozen object argument. */ + frozenRefusing: commonJsDefineConfig("observation-frozen-refusing-standin", [ + ' if (settings !== null && typeof settings === "object" && Object.isFrozen(settings)) {', + ' throw new TypeError("xspec self-test: a frozen configuration");', + " }", + " return settings;", + ]), + /** Exports a `defineConfig` that is no function. */ + notAFunction: commonJsStandIn("observation-not-a-function-standin", [ + "exports.defineConfig = 42;", + ]), + /** Exits the process when called with a boolean. */ + exitingInCall: commonJsDefineConfig("observation-exiting-standin", [ + ' if (typeof settings === "boolean") process.exit(0);', + " return settings;", + ]), +} as const satisfies Record<string, Record<string, string>>; + +/** A fresh, empty directory of this test's own, removed once it ends. */ +async function freshDirectory(prefix: string): Promise<string> { + const directory = await fsp.realpath( + await fsp.mkdtemp(path.join(os.tmpdir(), prefix)), + ); + onTestFinished(() => fsp.rm(directory, { recursive: true, force: true })); + return directory; +} + +/** Write `files` into a fresh package directory, returned. */ +async function writeStandIn(files: Record<string, string>): Promise<string> { + const directory = await freshDirectory("xspec-observation-standin-"); + for (const [name, text] of Object.entries(files)) { + const target = path.join(directory, ...name.split("/")); + await fsp.mkdir(path.dirname(target), { recursive: true }); + await fsp.writeFile(target, text, { flag: "wx" }); + } + return directory; +} + +/** + * A binding of the certification fixtures' shape beside `packageDir`: its + * executable is never run here. + */ +function standInBinding(packageDir: string): ProductBinding { + return { + label: "module-channel observation stand-in binding", + command: process.execPath, + requiredFiles: [process.execPath], + packageDir, + }; +} + +/** A staging and its canonical placement in a CommonJS project. */ +interface StagedPackage { + readonly staging: ModuleStaging; + readonly placement: Placement; +} + +/** + * Stage the stand-in `files` at the canonical placement in a CommonJS + * project, for runs on `releases`; disposed of once the test ends. + */ +async function stageStandIn( + files: Record<string, string>, + releases: readonly NodeRelease[], + context: string, +): Promise<StagedPackage> { + const staging = await ModuleStaging.create( + standInBinding(await writeStandIn(files)), + context, + ); + onTestFinished(() => staging.dispose()); + await staging.stageProject("project", "commonjs"); + const placement = await staging.placeCanonical( + "project", + runtimeArm(releases), + ); + return { staging, placement }; +} + +/** One run's request over `staged`, the project declared and alone. */ +function request( + staged: StagedPackage, + release: NodeRelease, + route: ModuleRoute, + context: string, +): ModuleRunRequest { + return { + staging: staged.staging, + placement: staged.placement, + route, + release, + project: "commonjs", + alone: true, + context, + }; +} + +/** One loaded run of a stand-in the harness expects to load. */ +async function loadedRun( + staged: StagedPackage, + release: NodeRelease, + route: ModuleRoute, + context: string, +): Promise<LoadedModuleRun> { + return assertModuleLoaded( + await runModuleRoute(request(staged, release, route, context)), + "stand-in", + ); +} + +/** The first of E-1's releases, for the checks one release serves. */ +async function firstRelease(): Promise<NodeRelease> { + const [release] = await resolveNodeReleases(); + if (release === undefined) throw new Error("E-1 lists no release"); + return release; +} + +test("a conforming dual stand-in, along each of Node.js's four routes on each of E-1's releases: the route's own-key listing is exactly defineConfig (an import namespace's string keys, a require result's enumerable keys), defineConfig is read once as a function and every one of T7.6-6's calls returns its argument by SameValue — each identity value, no argument, a further argument, the two recording Proxies, the frozen object — with no trap of either Proxy invoked; both streams are empty and the output oracle passes, the pairing met (TEST-SPEC T7.6-6, T7.6-7(a), §7.6 Pairing)", async () => { + const releases = await resolveNodeReleases(); + const staged = await stageStandIn( + STAND_INS.dual, + releases, + "observation self-test: dual", + ); + for (const release of releases) { + const form = await learnWarningForm(release); + for (const route of MODULE_ROUTES) { + const context = `observation self-test: dual, ${release.version}, ${route}`; + const run = await loadedRun(staged, release, route, context); + const { calls, load, warnings } = run.report; + expect(load.value, context).toEqual({ + type: "object", + ownKeys: + route === "require" + ? [DEFINE_CONFIG_KEY] + : [DEFINE_CONFIG_KEY, TO_STRING_TAG_KEY], + }); + expect(calls.reading, context).toEqual({ + type: "function", + thrown: null, + }); + expect(calls.results, context).toEqual(ALL_RETURNED); + expect(calls.traps, context).toEqual([]); + expect(exportsProblems(run), context).toEqual([]); + expect(identityProblems(run), context).toEqual([]); + expect(examinationProblems(run), context).toEqual([]); + expect(pairingProblem(run), context).toBeNull(); + expect(run.result.stdout, context).toBe(""); + expect(run.result.stderr, context).toBe(""); + expect(warnings, context).toEqual([]); + expect(outputProblems(run, form), context).toEqual([]); + } + } +}); + +test("the output oracle's printed form is learned from each of E-1's releases, once per release in a process: it renders, byte for byte, the standard error of a stand-in emitting a warning of its own while loading — a CommonJS one along require, carrying a code and a detail, and an ES-module one along static import, carrying a code alone — and the oracle finds each such warning's stack beginning in the package's files, its first frame naming the package's entry by path and by file URL, the pairing met and nothing else amiss (TEST-SPEC T7.6-7(a))", async () => { + const releases = await resolveNodeReleases(); + const vectors = [ + { + staged: await stageStandIn( + STAND_INS.commonJsWarning, + releases, + "observation self-test: CommonJS warning", + ), + route: "require", + entry: (placement: Placement): string => + path.join(placement.path, "index.js"), + }, + { + staged: await stageStandIn( + STAND_INS.moduleWarning, + releases, + "observation self-test: ES-module warning", + ), + route: "static-import", + entry: (placement: Placement): string => + pathToFileURL(path.join(placement.path, "index.js")).href, + }, + ] as const; + for (const release of releases) { + const form = await learnWarningForm(release); + expect(learnWarningForm(release), release.version).toBe( + learnWarningForm(release), + ); + expect(form.version, release.version).toBe(release.version); + for (const hint of [form.hints.deprecation, form.hints.other]) { + expect(hint.length, release.version).toBeGreaterThan(0); + expect(hint.includes(LF), release.version).toBe(false); + } + for (const vector of vectors) { + const context = `observation self-test: warning, ${release.version}, ${vector.route}`; + const run = await loadedRun( + vector.staged, + release, + vector.route, + context, + ); + const [warning] = run.report.warnings; + expect(run.report.warnings, context).toHaveLength(1); + if (warning === undefined) continue; + expect(warning.name, context).toBe("XspecSelfTestWarning"); + const rendering = renderWarnings( + run.report.warnings, + run.report.pid, + form, + ); + expect(rendering.ok, context).toBe(true); + if (!rendering.ok) continue; + expect(Buffer.from(rendering.text, "utf8"), context).toEqual( + Buffer.from(run.result.stderrBytes), + ); + const frame = packageFrame(warning, run.placement); + expect(frame, context).toContain(vector.entry(run.placement)); + expect(warningFirstFrame(warning), context).toBe(frame); + expect(pairingProblem(run), context).toBeNull(); + const problems = outputProblems(run, form); + expect(problems, context).toHaveLength(1); + expect(problems[0], context).toContain( + "begins its stack in the package's files", + ); + } + } +}); + +test("conforming stand-ins whose manifests draw the runtime's own warnings pass the output oracle on each of E-1's releases: DEP0128 along require (an invalid main beside index.js) and DEP0151 along each import route (an ES-module package's main lookup), each run's one warning that deprecation; and an ES-module-only package along require on each release that loads it, its warnings, where the release prints one, the experimental warning — 22.12.0 among E-1's releases printing it (TEST-SPEC T7.6-7(a): the release's own warnings in resolving the specifier and loading the package's files admitted)", async () => { + const releases = await resolveNodeReleases(); + const invalidMain = await stageStandIn( + STAND_INS.invalidMain, + releases, + "observation self-test: invalid main", + ); + const mainLookup = await stageStandIn( + STAND_INS.mainLookup, + releases, + "observation self-test: main lookup", + ); + const moduleOnly = await stageStandIn( + STAND_INS.moduleOnly, + releases, + "observation self-test: ES-module only", + ); + const vectors: readonly (readonly [StagedPackage, ModuleRoute, string])[] = [ + [invalidMain, "require", "DEP0128"], + ...IMPORT_ROUTES.map((route) => [mainLookup, route, "DEP0151"] as const), + ]; + const printedExperimental: string[] = []; + for (const release of releases) { + for (const [staged, route, code] of vectors) { + const context = `observation self-test: ${code}, ${release.version}, ${route}`; + const run = await loadedRun(staged, release, route, context); + expect( + run.report.warnings.map((warning) => [warning.name, warning.code]), + context, + ).toEqual([["DeprecationWarning", code]]); + expect(exportsProblems(run), context).toEqual([]); + expect(pairingProblem(run), context).toBeNull(); + expect(await runtimeOutputProblems(run), context).toEqual([]); + } + const context = `observation self-test: ES-module only, ${release.version}, require`; + const run = await runModuleRoute( + request(moduleOnly, release, "require", context), + ); + if (run.outcome === "load-failed") continue; + const loaded = assertModuleLoaded(run, "stand-in"); + for (const warning of loaded.report.warnings) { + expect(warning.name, context).toBe("ExperimentalWarning"); + printedExperimental.push(release.version); + } + expect(exportsProblems(loaded), context).toEqual([]); + expect(pairingProblem(loaded), context).toBeNull(); + expect(await runtimeOutputProblems(loaded), context).toEqual([]); + } + expect(printedExperimental).toContain("22.12.0"); +}); + +test("end to end on one release, each of T7.6-6's observations reports the deviation it exists for, as problems in words: a CommonJS-only entry's import namespace carrying default and an enumerable __esModule (the listings), -0 returned as 0 and object arguments copied (identity), a Proxy's traps touched and a frozen object refused (no examination), a defineConfig that is no function (no call made), and a process ending inside a call (an incomplete run naming the call) (TEST-SPEC T7.6-6, §7.6 Pairing)", async () => { + const release = await firstRelease(); + const run = async ( + standIn: keyof typeof STAND_INS, + route: ModuleRoute, + ): Promise<LoadedModuleRun> => { + const context = `observation self-test: ${standIn}, ${release.version}, ${route}`; + const staged = await stageStandIn(STAND_INS[standIn], [release], context); + return loadedRun(staged, release, route, context); + }; + + const commonJsOnly = await run("commonJsOnly", "static-import"); + const namespace = exportsProblems(commonJsOnly); + expect(namespace).toHaveLength(1); + expect(namespace[0]).toContain("own string-keyed properties"); + expect(namespace[0]).toContain('"default"'); + + const esModule = await run("enumerableEsModule", "require"); + const listing = exportsProblems(esModule); + expect(listing).toHaveLength(1); + expect(listing[0]).toContain('"__esModule"'); + expect(pairingProblem(esModule)).toBeNull(); + + const negativeZero = await run("negativeZero", "require"); + const zero = identityProblems(negativeZero); + expect(zero).toHaveLength(1); + expect(zero[0]).toContain("defineConfig(-0): it returned 0 (number)"); + expect(examinationProblems(negativeZero)).toEqual([]); + expect(pairingProblem(negativeZero)).toContain("defineConfig(-0)"); + + const copying = await run("copying", "require"); + expect( + copying.report.calls.results + .filter((result) => result.outcome !== "returned-argument") + .map((result) => result.case), + ).toEqual(["object", "array", "further-arguments", "frozen"]); + expect(identityProblems(copying)).toHaveLength(3); + const copied = examinationProblems(copying); + expect(copied).toHaveLength(1); + expect(copied[0]).toContain("it returned another object instead"); + + const examining = await run("examining", "require"); + const { traps } = examining.report.calls; + expect(traps.length).toBeGreaterThan(0); + expect(traps[0]).toEqual({ proxy: "first", trap: "ownKeys" }); + expect(traps.every((invocation) => invocation.proxy === "first")).toBe(true); + expect(identityProblems(examining)).toEqual([]); + const examined = examinationProblems(examining); + expect(examined).toHaveLength(1); + expect(examined[0]).toContain("ownKeys on the first Proxy"); + expect(pairingProblem(examining)).toBeNull(); + + const frozenRefusing = await run("frozenRefusing", "require"); + expect(identityProblems(frozenRefusing)).toEqual([]); + const refused = examinationProblems(frozenRefusing); + expect(refused).toHaveLength(1); + expect(refused[0]).toContain( + "defineConfig(f) with f a frozen object: it threw TypeError", + ); + + const notAFunction = await run("notAFunction", "require"); + expect(notAFunction.report.calls.reading).toEqual({ + type: "number", + thrown: null, + }); + expect(notAFunction.report.calls.results).toEqual([]); + expect(exportsProblems(notAFunction)).toEqual([]); + for (const problems of [ + identityProblems(notAFunction), + examinationProblems(notAFunction), + ]) { + expect(problems).toHaveLength(1); + expect(problems[0]).toContain("a value of type number, no function"); + } + expect(pairingProblem(notAFunction)).not.toBeNull(); + + const context = `observation self-test: exitingInCall, ${release.version}, require`; + const exiting = await runModuleRoute( + request( + await stageStandIn(STAND_INS.exitingInCall, [release], context), + release, + "require", + context, + ), + ); + expect(exiting.outcome).toBe("incomplete"); + expect(exiting.report?.phase).toBe("calling"); + expect(exiting.report?.calls?.results.map((result) => result.case)).toEqual( + CALL_CASES.slice(0, CALL_CASES.indexOf("boolean")), + ); + expect(moduleRunProblem(exiting)).toContain( + "loaded the module, but ended during T7.6-6's call defineConfig(false)", + ); +}); + +/** A form of the vectors' own, for the vectors' own release. */ +const VECTOR_FORM: WarningForm = { + version: "0.0.0", + hints: { deprecation: "HINT FOR A DEPRECATION", other: "HINT FOR ANY OTHER" }, +}; + +/** A placement of the vectors' own, a symbolic link to its copy. */ +const VECTOR_PLACEMENT: Placement = { + name: "xspec-config", + holdingDir: "/s/p", + path: "/s/p/node_modules/xspec-config", + form: "symlink", + copy: "/s/placed-copies/copy-1", +}; + +/** A captured warning, an Error's reading unless overridden. */ +function captured(fields: Partial<CapturedWarning>): CapturedWarning { + return { + type: "object", + name: "Warning", + code: null, + message: "a message", + detail: null, + stack: null, + ...fields, + }; +} + +/** A vector's loaded run: a conforming one unless overridden. */ +function vectorRun( + fields: { + readonly route?: ModuleRoute; + readonly ownKeys?: readonly OwnKey[] | null; + readonly reading?: DefineConfigReading; + readonly results?: readonly CallResult[]; + readonly traps?: readonly TrapInvocation[]; + readonly warnings?: readonly CapturedWarning[]; + readonly stdout?: string; + readonly stderr?: string; + } = {}, +): LoadedModuleRun { + const route = fields.route ?? "require"; + const stdout = fields.stdout ?? ""; + const stderr = fields.stderr ?? ""; + return { + description: `vector run (${route})`, + route, + release: { version: "0.0.0", executable: "/releases/v0.0.0/bin/node" }, + placement: VECTOR_PLACEMENT, + importingModule: "/s/p/importing-module.cjs", + cwd: "/run/work", + home: "/run/home", + tmp: "/run/tmp", + environment: { HOME: "/run/home", TMPDIR: "/run/tmp" }, + result: { + exitCode: 0, + signal: null, + stdout, + stderr, + stdoutBytes: Buffer.from(stdout, "utf8"), + stderrBytes: Buffer.from(stderr, "utf8"), + commandLine: "vector", + }, + outcome: "loaded", + report: { + argv: [], + release: { version: "v0.0.0", execPath: "/node", execArgv: [] }, + pid: 7, + environment: {}, + cwd: "/run/work", + phase: "completed", + importingModule: { topLevelThis: "object", location: "/s/p/i.cjs" }, + load: { + outcome: "loaded", + value: { + type: "object", + ownKeys: + fields.ownKeys === undefined ? [DEFINE_CONFIG_KEY] : fields.ownKeys, + }, + }, + calls: { + reading: fields.reading ?? { type: "function", thrown: null }, + results: fields.results ?? ALL_RETURNED, + traps: fields.traps ?? [], + }, + state: { subjects: [], changes: [], omitted: 0 }, + bootstrapError: null, + warnings: fields.warnings ?? [], + exit: { code: 0 }, + }, + reportProblem: undefined, + effects: undefined, + }; +} + +/** ALL_RETURNED with `name`'s call replaced by `result`'s fields. */ +function withCall( + name: CallResult["case"], + result: Partial<CallResult>, +): readonly CallResult[] { + return ALL_RETURNED.map((entry) => + entry.case === name ? { ...entry, ...result } : entry, + ); +} + +test("the output oracle's pure functions on vectors: the release's printed forms rendered in order — the process identifier, a non-empty code bracketed, the type and message joined as the release joins them, a detail on its own line, the hint for a first deprecation or for any other first warning, a line feed after each — and a warning no Error reads as refused; the first frame read after the stack's head, a message line shaped like a frame left to the head; and a package frame named by the placement's path, its copy's, or a file URL, never by a sibling's (TEST-SPEC T7.6-7(a))", () => { + expect(renderWarnings([], 7, VECTOR_FORM)).toEqual({ ok: true, text: "" }); + const first = captured({ + name: "XspecWarning", + code: "XSPEC", + message: `a message${LF}over two lines`, + detail: `a detail${LF}over two lines`, + }); + const deprecation = captured({ + name: "DeprecationWarning", + code: "DEP0000", + message: "a deprecation", + }); + expect(renderWarnings([first, deprecation], 7, VECTOR_FORM)).toEqual({ + ok: true, + text: + `(node:7) [XSPEC] XspecWarning: a message${LF}over two lines${LF}` + + `a detail${LF}over two lines${LF}HINT FOR ANY OTHER${LF}` + + `(node:7) [DEP0000] DeprecationWarning: a deprecation${LF}`, + }); + expect(renderWarnings([deprecation, first], 42, VECTOR_FORM)).toEqual({ + ok: true, + text: + `(node:42) [DEP0000] DeprecationWarning: a deprecation${LF}` + + `HINT FOR A DEPRECATION${LF}` + + `(node:42) [XSPEC] XspecWarning: a message${LF}over two lines${LF}` + + `a detail${LF}over two lines${LF}`, + }); + expect( + renderWarnings( + [ + captured({ code: "", message: "an empty code" }), + captured({ name: "NoMessageWarning", message: "" }), + captured({ name: "", message: "no name" }), + ], + 7, + VECTOR_FORM, + ), + ).toEqual({ + ok: true, + text: + `(node:7) Warning: an empty code${LF}HINT FOR ANY OTHER${LF}` + + `(node:7) NoMessageWarning${LF}(node:7) no name${LF}`, + }); + for (const refused of [ + captured({ type: "string", name: null }), + captured({ name: null }), + captured({ message: null }), + ]) { + expect(renderWarnings([first, refused], 7, VECTOR_FORM).ok).toBe(false); + } + + const internal = " at tryPackage (node:internal/modules/cjs/loader:1:1)"; + const shaped = " at shaped (/s/p/node_modules/xspec-config/index.js:1:1)"; + expect( + warningFirstFrame( + captured({ + name: "XspecWarning", + message: `first line${LF}${shaped}`, + stack: `XspecWarning: first line${LF}${shaped}${LF}${internal}`, + }), + ), + ).toBe(internal); + expect( + warningFirstFrame(captured({ stack: `Warning: a message${LF}${shaped}` })), + ).toBe(shaped); + expect(warningFirstFrame(captured({ stack: "Warning: a message" }))).toBe( + null, + ); + expect(warningFirstFrame(captured({ stack: null }))).toBe(null); + expect( + warningFirstFrame( + captured({ stack: `another head${LF}${internal}${LF}${shaped}` }), + ), + ).toBe(internal); + + const framed = (frame: string): CapturedWarning => + captured({ stack: `Warning: a message${LF}${frame}` }); + for (const frame of [ + " at f (/s/p/node_modules/xspec-config/index.js:1:9)", + " at f (/s/placed-copies/copy-1/lib/index.js:2:3)", + " at file:///s/p/node_modules/xspec-config/index.js:1:9", + " at file:///s/placed-copies/copy-1/index.js:1:9", + ]) { + expect(packageFrame(framed(frame), VECTOR_PLACEMENT), frame).toBe(frame); + } + for (const frame of [ + " at f (/s/p/node_modules/xspec-config-other/index.js:1:9)", + " at f (/s/placed-copies/copy-10/index.js:1:9)", + internal, + ]) { + expect(packageFrame(framed(frame), VECTOR_PLACEMENT), frame).toBe(null); + } + // A path a file URL spells otherwise: the space percent-encoded there. + const spaced: Placement = { + ...VECTOR_PLACEMENT, + holdingDir: "/s/a project", + path: "/s/a project/node_modules/xspec-config", + form: "copy", + copy: "/s/a project/node_modules/xspec-config", + }; + for (const frame of [ + " at file:///s/a%20project/node_modules/xspec-config/index.js:1:9", + " at f (/s/a project/node_modules/xspec-config/index.js:1:9)", + ]) { + expect(packageFrame(framed(frame), spaced), frame).toBe(frame); + } +}); + +test("T7.6-6's and T7.6-7(a)'s problem functions on vectors: each conforming vector clean, and each deviation caught by the observation it exists for — a namespace carrying default, an enumerable __esModule (a non-enumerable one admitted), an enumerable symbol, defineConfig itself not enumerable or its enumerability unread, keys unlisted; -0 returned as 0, a read that threw, no function read; a trap invoked, a frozen object refused, the second Proxy returned; the pairing unmet; output on standard output, a stray byte on standard error, a warning beginning its stack in the package, one the oracle cannot render; and a form of another release refused (TEST-SPEC T7.6-6, T7.6-7(a), §7.6 Pairing)", () => { + const one = (problems: readonly string[], ...mentions: string[]): void => { + expect(problems).toHaveLength(1); + for (const mention of mentions) expect(problems[0]).toContain(mention); + }; + const named = ( + name: string, + enumerable: boolean | null, + kind: OwnKey["kind"] = "string", + ): OwnKey => ({ kind, name, enumerable }); + + expect( + exportsProblems( + vectorRun({ + route: "static-import", + ownKeys: [DEFINE_CONFIG_KEY, TO_STRING_TAG_KEY], + }), + ), + ).toEqual([]); + one( + exportsProblems( + vectorRun({ + route: "dynamic-import-from-commonjs", + ownKeys: [named("default", true), DEFINE_CONFIG_KEY, TO_STRING_TAG_KEY], + }), + ), + "own string-keyed properties", + '"default"', + ); + one( + exportsProblems(vectorRun({ route: "static-import", ownKeys: null })), + "could not be listed", + ); + expect(exportsProblems(vectorRun())).toEqual([]); + expect( + exportsProblems( + vectorRun({ ownKeys: [DEFINE_CONFIG_KEY, named("__esModule", false)] }), + ), + ).toEqual([]); + one( + exportsProblems( + vectorRun({ ownKeys: [named("__esModule", true), DEFINE_CONFIG_KEY] }), + ), + "own enumerable properties", + '"__esModule"', + ); + one( + exportsProblems( + vectorRun({ + ownKeys: [DEFINE_CONFIG_KEY, named("xspec", true, "symbol")], + }), + ), + "Symbol(xspec)", + ); + one( + exportsProblems(vectorRun({ ownKeys: [named("defineConfig", false)] })), + "are [], not exactly", + ); + one( + exportsProblems( + vectorRun({ ownKeys: [DEFINE_CONFIG_KEY, named("other", null)] }), + ), + "could not be read", + ); + one(exportsProblems(vectorRun({ ownKeys: null })), "could not be listed"); + + expect(identityProblems(vectorRun())).toEqual([]); + const zero = vectorRun({ + results: withCall("negative-zero", { + outcome: "returned-other", + returned: { type: "number", text: "0" }, + }), + }); + one(identityProblems(zero), "defineConfig(-0): it returned 0 (number)"); + expect(examinationProblems(zero)).toEqual([]); + const thrown = { + type: "object", + name: "TypeError", + code: null, + message: "a getter threw", + stack: null, + }; + const threw = vectorRun({ reading: { type: null, thrown }, results: [] }); + one(identityProblems(threw), "threw TypeError"); + one(examinationProblems(threw), "threw TypeError"); + const noFunction = vectorRun({ + reading: { type: "undefined", thrown: null }, + results: [], + }); + one(identityProblems(noFunction), "is undefined, no function"); + + expect(examinationProblems(vectorRun())).toEqual([]); + const trapped = vectorRun({ + traps: [ + { proxy: "first", trap: "get" }, + { proxy: "second", trap: "has" }, + ], + }); + one( + examinationProblems(trapped), + "get on the first Proxy, has on the second Proxy", + ); + expect(identityProblems(trapped)).toEqual([]); + expect(pairingProblem(trapped)).toBeNull(); + one( + examinationProblems( + vectorRun({ results: withCall("frozen", { outcome: "threw", thrown }) }), + ), + "defineConfig(f) with f a frozen object: it threw TypeError", + ); + const second = vectorRun({ + results: withCall("proxies", { + outcome: "returned-other", + returned: { type: "function", text: "the second Proxy" }, + }), + }); + one(examinationProblems(second), "the second Proxy (function)"); + expect(identityProblems(second)).toEqual([]); + + expect(pairingProblem(vectorRun())).toBeNull(); + expect(pairingProblem(zero)).toContain("§7.6 Pairing"); + expect(pairingProblem(second)).toContain("the second Proxy (function)"); + expect(pairingProblem(noFunction)).toContain("no function"); + + const warning = captured({ + name: "DeprecationWarning", + code: "DEP0128", + message: "an invalid main", + stack: `DeprecationWarning: an invalid main${LF} at tryPackage (node:internal/modules/cjs/loader:1:1)`, + }); + const printed = `(node:7) [DEP0128] DeprecationWarning: an invalid main${LF}HINT FOR A DEPRECATION${LF}`; + expect(outputProblems(vectorRun(), VECTOR_FORM)).toEqual([]); + expect( + outputProblems( + vectorRun({ warnings: [warning], stderr: printed }), + VECTOR_FORM, + ), + ).toEqual([]); + one( + outputProblems(vectorRun({ stdout: "x" }), VECTOR_FORM), + "standard output is not empty", + ); + one( + outputProblems(vectorRun({ stderr: "x" }), VECTOR_FORM), + "is not exactly the release's printed forms of the 0 warning(s)", + ); + one( + outputProblems( + vectorRun({ warnings: [warning], stderr: `${printed}x` }), + VECTOR_FORM, + ), + "is not exactly the release's printed forms of the 1 warning(s)", + ); + one( + outputProblems( + vectorRun({ + warnings: [ + { + ...warning, + stack: `DeprecationWarning: an invalid main${LF} at Object.<anonymous> (/s/p/node_modules/xspec-config/index.js:1:9)`, + }, + ], + stderr: printed, + }), + VECTOR_FORM, + ), + "begins its stack in the package's files", + ); + one( + outputProblems( + vectorRun({ warnings: [captured({ type: "string", name: null })] }), + VECTOR_FORM, + ), + "the oracle knows no printed form of it", + ); + one(outputProblems(zero, VECTOR_FORM), "§7.6 Pairing"); + expect(() => + outputProblems(vectorRun(), { ...VECTOR_FORM, version: "22.0.0" }), + ).toThrow("judges no run on 0.0.0"); +}); diff --git a/test/self/module-channel-node.test.ts b/test/self/module-channel-node.test.ts new file mode 100644 index 00000000..86e5f029 --- /dev/null +++ b/test/self/module-channel-node.test.ts @@ -0,0 +1,1084 @@ +// Self-checks for the module channel's Node.js release driver (TEST-SPEC 17 +// preamble: internal self-tests cover harness machinery certification does +// not exercise; H-2, T7.6-6's run conditions, T7.6-7, §7.6 Pairing, H-1, +// S-3, E-1; helpers/module-channel-node.ts and its bootstrap, +// helpers/module-channel-bootstrap.cjs). T7.6-6 and T7.6-7, 7.6's runtime +// tests registered so far (test/suite/registry/section-7.6-ii.ts), and S-10's +// checks of the driver — each release's identity, each route's entry, each +// observation's catch — build on these; here the driver's own plumbing is +// pinned before any product exists, on each of E-1's releases, so +// XSPEC_NODE_RELEASES_DIR must name them, as CI's harness-self job and +// AGENTS.md's recipe do (unset, every test here fails as the harness error +// NodeReleaseError, never a skip): +// - a dual stand-in package loads along each of Node.js's four routes on +// each provisioned release, each importing module running as its route's +// kind from the importing file's place, with an environment of exactly +// HOME, TMPDIR, and PATH — HOME and TMPDIR fresh for each run — no option, +// the run's own working directory, and nothing on either stream; +// - the observation channel round-trips: the report on disk decodes to +// what the driver returns, holding the arguments the driver passed, from +// a place outside the staging, the working directory, HOME, and TMPDIR, +// and a warning the stand-in emits comes back with its type, code, +// message, detail, and stack; +// - a stray NODE_OPTIONS (a user condition the dual stand-in's exports map +// would answer), NODE_PATH, NODE_PRESERVE_SYMLINKS, and NODE_NO_WARNINGS +// in the ambient environment reach no run; +// - each way a run can fail to load is reported as such — a package with no +// entry (S-7's stub package), a module exiting while it loads, one killed +// by a signal, one overwriting the report, one setting a nonzero exit +// code — as a diagnosed failure for a product and a harness error for a +// stand-in, and a run kept alive ends at its own guard; +// - the importing modules' place: each route's file written once, found +// byte-equal by a later run, and any other occupant refused; +// - the report's decoder, on vectors: exactly the bootstrap's members, each +// of its kind, consistent with its phase, or a malformed report. +// +// The stand-in packages are small hand-written, non-xspec packages, written +// at run time into fresh directories under the OS temporary directory from +// the texts below (STAND_INS), so the committed tree holds no package of +// this file's own; S-7's stub package (test/fixtures/empty-stub-package/) +// is the one committed directory placed here. + +import * as fsp from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { expect, onTestFinished, test } from "vitest"; +import { HarnessAssertionError } from "../helpers/assertions.js"; +import { ModuleStaging, runtimeArm } from "../helpers/module-channel.js"; +import type { Placement } from "../helpers/module-channel.js"; +import { + assertModuleLoaded, + CALL_CASES, + decodeModuleRunReport, + importingModuleKind, + importingModuleName, + importingModuleText, + MODULE_ROUTES, + MODULE_RUN_PREFIX, + MODULE_RUN_PROTOCOL, + moduleRunEnvironment, + prepareModuleRun, + runModuleRoute, + STATE_OBSERVATIONS, +} from "../helpers/module-channel-node.js"; +import type { + ModuleRoute, + ModuleRun, + ModuleRunRequest, +} from "../helpers/module-channel-node.js"; +import { resolveNodeReleases } from "../helpers/node-releases.js"; +import type { NodeRelease } from "../helpers/node-releases.js"; +import { HarnessStagingError } from "../helpers/permissions.js"; +import { ProductRunTimeoutError, runProduct } from "../helpers/subprocess.js"; +import type { ProductBinding } from "../helpers/subprocess.js"; + +const LF = String.fromCodePoint(0x0a); + +/** S-7's stub package: a manifest naming no entry. */ +const STUB_PACKAGE_DIR = fileURLToPath( + new URL("../fixtures/empty-stub-package", import.meta.url), +); + +/** The harness's bootstrap, which each run's directory holds a copy of. */ +const BOOTSTRAP_SOURCE = fileURLToPath( + new URL("../helpers/module-channel-bootstrap.cjs", import.meta.url), +); + +/** The user condition a stray NODE_OPTIONS would carry into a run. */ +const STRAY_CONDITION = "xspec-stray-condition"; + +/** A loaded value's own `defineConfig` key, as the report lists it. */ +const DEFINE_CONFIG_KEY = { + kind: "string", + name: "defineConfig", + enumerable: true, +} as const; + +/** A module namespace's own `Symbol.toStringTag` key, likewise. */ +const TO_STRING_TAG_KEY = { + kind: "symbol", + name: "Symbol.toStringTag", + enumerable: false, +} as const; + +/** A manifest's text. */ +function manifest(members: Record<string, unknown>): string { + return `${JSON.stringify(members, null, 2)}${LF}`; +} + +/** A module's text, from its lines. */ +function lines(...text: string[]): string { + return `${text.join(LF)}${LF}`; +} + +/** + * The stand-in packages (module header), each a map from file name to text. + * Every one but `dual` is a CommonJS package with one entry, `index.js`. + */ +const STAND_INS = { + /** + * A dual package: an ES-module entry for `import`, a CommonJS one for + * `require`, each exporting exactly `defineConfig`, an identity function; + * and, first in its exports map, an entry for the stray user condition, + * exporting `strayCondition` alone, which no run without the condition + * reaches. + */ + dual: { + "package.json": manifest({ + name: "node-driver-dual-standin", + version: "1.0.0", + type: "module", + main: "./index.cjs", + exports: { + ".": { + [STRAY_CONDITION]: "./stray.cjs", + import: "./index.js", + require: "./index.cjs", + }, + }, + }), + "index.js": lines( + "export function defineConfig(settings) {", + " return settings;", + "}", + ), + "index.cjs": lines( + "exports.defineConfig = function defineConfig(settings) {", + " return settings;", + "};", + ), + "stray.cjs": lines("exports.strayCondition = true;"), + }, + /** Emits one process warning while it loads, through the runtime's facility. */ + warning: commonJsStandIn("node-driver-warning-standin", [ + 'process.emitWarning("xspec driver self-test warning", {', + ' type: "XspecSelfTestWarning",', + ' code: "XSPEC_SELF_TEST",', + ' detail: "its detail",', + "});", + ]), + /** Exits while it loads, its exit code 0. */ + exiting: commonJsStandIn("node-driver-exiting-standin", ["process.exit(0);"]), + /** Kills its own process with SIGKILL while it loads. */ + killed: commonJsStandIn("node-driver-killed-standin", [ + 'process.kill(process.pid, "SIGKILL");', + ]), + /** + * Overwrites the report as the process exits: its own `exit` listener, + * registered after the bootstrap's, writes text that is no JSON to the + * report's path, the third argument after the executable. + */ + tampering: commonJsStandIn("node-driver-tampering-standin", [ + 'process.on("exit", () => {', + ' require("node:fs").writeFileSync(process.argv[3], "not a report");', + "});", + ]), + /** Sets the process's exit code to 3 while it loads. */ + exitCode: commonJsStandIn("node-driver-exit-code-standin", [ + "process.exitCode = 3;", + ]), + /** Keeps the process alive with an interval timer it starts while loading. */ + lingering: commonJsStandIn("node-driver-lingering-standin", [ + "setInterval(() => {}, 1000);", + ]), +} as const satisfies Record<string, Record<string, string>>; + +/** + * A CommonJS stand-in named `name`: `index.js` exporting `defineConfig`, an + * identity function, after `effect`'s statements. + */ +function commonJsStandIn( + name: string, + effect: readonly string[], +): Record<string, string> { + return { + "package.json": manifest({ name, version: "1.0.0", main: "./index.js" }), + "index.js": lines( + ...effect, + "exports.defineConfig = function defineConfig(settings) {", + " return settings;", + "};", + ), + }; +} + +/** A fresh, empty directory of this test's own, removed once it ends. */ +async function freshDirectory(prefix: string): Promise<string> { + const directory = await fsp.realpath( + await fsp.mkdtemp(path.join(os.tmpdir(), prefix)), + ); + onTestFinished(() => fsp.rm(directory, { recursive: true, force: true })); + return directory; +} + +/** Write `files` into a fresh package directory, returned. */ +async function writeStandIn(files: Record<string, string>): Promise<string> { + const directory = await freshDirectory("xspec-node-driver-standin-"); + for (const [name, text] of Object.entries(files)) { + await fsp.writeFile(path.join(directory, name), text, { flag: "wx" }); + } + return directory; +} + +/** + * A binding of the certification fixtures' shape beside `packageDir`: its + * executable is never run here. + */ +function standInBinding(packageDir: string): ProductBinding { + return { + label: "module-channel Node.js driver stand-in binding", + command: process.execPath, + requiredFiles: [process.execPath], + packageDir, + }; +} + +/** A staging and its canonical placement in a CommonJS project. */ +interface StagedPackage { + readonly staging: ModuleStaging; + readonly placement: Placement; +} + +/** + * Stage `packageDir` at the canonical placement in the CommonJS project + * `project`, for runs on `releases`; disposed of once the test ends. + */ +async function stagePackage( + packageDir: string, + releases: readonly NodeRelease[], + context: string, +): Promise<StagedPackage> { + const staging = await ModuleStaging.create( + standInBinding(packageDir), + context, + ); + onTestFinished(() => staging.dispose()); + await staging.stageProject("project", "commonjs"); + const placement = await staging.placeCanonical( + "project", + runtimeArm(releases), + ); + return { staging, placement }; +} + +/** One run's request over `staged`, the project declared and alone. */ +function request( + staged: StagedPackage, + release: NodeRelease, + route: ModuleRoute, + context: string, +): ModuleRunRequest { + return { + staging: staged.staging, + placement: staged.placement, + route, + release, + project: "commonjs", + alone: true, + context, + }; +} + +/** The first of E-1's releases, for the vectors one release serves. */ +async function firstRelease(): Promise<NodeRelease> { + const [release] = await resolveNodeReleases(); + if (release === undefined) throw new Error("E-1 lists no release"); + return release; +} + +/** Whether `inner` is `outer` or lies under it. */ +function within(inner: string, outer: string): boolean { + return inner === outer || inner.startsWith(`${outer}${path.sep}`); +} + +async function exists(entry: string): Promise<boolean> { + return fsp.lstat(entry).then( + () => true, + () => false, + ); +} + +/** The error `work` throws, which it must. */ +function thrownBy(work: () => unknown): unknown { + try { + work(); + } catch (error) { + return error; + } + throw new Error("expected a throw, and nothing was thrown"); +} + +/** Expect `run`'s failure to load charged to the product, then the harness. */ +function expectChargedBothWays(run: ModuleRun, mentions: string): void { + const diagnosed = thrownBy(() => assertModuleLoaded(run, "product")); + expect(diagnosed).toBeInstanceOf(HarnessAssertionError); + expect((diagnosed as Error).message).toContain(run.description); + expect((diagnosed as Error).message).toContain(mentions); + const harness = thrownBy(() => assertModuleLoaded(run, "stand-in")); + expect(harness).toBeInstanceOf(Error); + expect(harness).not.toBeInstanceOf(HarnessAssertionError); + expect((harness as Error).message.startsWith("harness error (H-11): ")).toBe( + true, + ); + expect((harness as Error).message).toContain(mentions); +} + +test("a dual stand-in package loads along each of Node.js's four routes on each of E-1's releases: each importing module runs as its route's kind from the importing file's place, under exactly HOME, TMPDIR, and PATH — HOME and TMPDIR fresh for each run — with no option, in the run's own working directory outside the staging, nothing on either stream, and each run's directory removed afterwards (TEST-SPEC T7.6-6's run conditions, T7.6-7, H-2, E-1)", async () => { + const releases = await resolveNodeReleases(); + const dual = await writeStandIn(STAND_INS.dual); + const staged = await stagePackage(dual, releases, "driver self-test: dual"); + const fresh = new Set<string>(); + for (const release of releases) { + for (const route of MODULE_ROUTES) { + const context = `driver self-test: dual, ${release.version}, ${route}`; + const run = await runModuleRoute( + request(staged, release, route, context), + ); + const loaded = assertModuleLoaded(run, "stand-in"); + const report = loaded.report; + expect(report.load.value, context).toEqual({ + type: "object", + ownKeys: + route === "require" + ? [DEFINE_CONFIG_KEY] + : [DEFINE_CONFIG_KEY, TO_STRING_TAG_KEY], + }); + expect(run.result.stdout, context).toBe(""); + expect(run.result.stderr, context).toBe(""); + expect(report.warnings, context).toEqual([]); + expect(report.exit, context).toEqual({ code: 0 }); + expect(report.release.version, context).toBe(`v${release.version}`); + expect(report.release.execPath, context).toBe( + await fsp.realpath(release.executable), + ); + expect(report.release.execArgv, context).toEqual([]); + expect(run.environment, context).toEqual( + moduleRunEnvironment(run.home, run.tmp), + ); + expect(Object.keys(report.environment).sort(), context).toEqual( + process.env["PATH"] === undefined || process.env["PATH"] === "" + ? ["HOME", "TMPDIR"] + : ["HOME", "PATH", "TMPDIR"], + ); + expect(report.environment, context).toEqual(run.environment); + expect(report.environment["HOME"], context).toBe(run.home); + expect(report.environment["TMPDIR"], context).toBe(run.tmp); + expect(report.cwd, context).toBe(run.cwd); + expect(path.dirname(run.importingModule), context).toBe( + staged.placement.holdingDir, + ); + expect(path.basename(run.importingModule), context).toBe( + importingModuleName(route), + ); + expect(report.importingModule, context).toEqual( + importingModuleKind(route) === "module" + ? { + topLevelThis: "undefined", + location: pathToFileURL(run.importingModule).href, + } + : { topLevelThis: "object", location: run.importingModule }, + ); + for (const place of [run.cwd, run.home, run.tmp]) { + expect(within(place, staged.staging.root), context).toBe(false); + expect(fresh.has(place), context).toBe(false); + fresh.add(place); + expect(await exists(place), context).toBe(false); + } + expect(run.cwd, context).not.toBe(path.dirname(run.importingModule)); + expect( + path.basename(path.dirname(run.cwd)).startsWith(MODULE_RUN_PREFIX), + context, + ).toBe(true); + } + } + expect(fresh.size).toBe(releases.length * MODULE_ROUTES.length * 3); +}); + +test("the observation channel round-trips: each run's report, written outside the staging, its working directory, HOME, and TMPDIR, decodes on disk to what the driver returns, holding the arguments the driver passed, from a bootstrap byte-equal to the harness's; and a warning the stand-in emits while loading comes back with its type, code, message, detail, and a stack beginning in the package, the release printing it with the run's process identifier (TEST-SPEC T7.6-7(a), H-3)", async () => { + const release = await firstRelease(); + const warning = await writeStandIn(STAND_INS.warning); + const staged = await stagePackage( + warning, + [release], + "driver self-test: warning", + ); + const bootstrap = await fsp.readFile(BOOTSTRAP_SOURCE); + for (const route of MODULE_ROUTES) { + const context = `driver self-test: warning, ${route}`; + const prepared = await prepareModuleRun( + request(staged, release, route, context), + ); + try { + expect(await fsp.readFile(prepared.bootstrap), context).toEqual( + bootstrap, + ); + for (const place of [ + staged.staging.root, + prepared.cwd, + prepared.home, + prepared.tmp, + ]) { + expect(within(prepared.reportPath, place), context).toBe(false); + } + expect(await exists(prepared.reportPath), context).toBe(false); + const run = await prepared.launch(); + const loaded = assertModuleLoaded(run, "stand-in"); + expect( + decodeModuleRunReport(await fsp.readFile(prepared.reportPath)), + context, + ).toEqual({ ok: true, report: run.report }); + expect(loaded.report.argv, context).toEqual([ + prepared.bootstrap, + prepared.importingModule, + prepared.reportPath, + route, + ]); + expect(loaded.report.warnings, context).toHaveLength(1); + const [captured] = loaded.report.warnings; + expect({ ...captured, stack: null }, context).toEqual({ + type: "object", + name: "XspecSelfTestWarning", + code: "XSPEC_SELF_TEST", + message: "xspec driver self-test warning", + detail: "its detail", + stack: null, + }); + const frames = (captured?.stack ?? "").split(LF); + expect(frames[1], context).toContain( + path.join(staged.placement.path, "index.js"), + ); + expect(run.result.stdout, context).toBe(""); + expect(run.result.stderr, context).toContain( + `(node:${String(loaded.report.pid)}) [XSPEC_SELF_TEST] ` + + "XspecSelfTestWarning: xspec driver self-test warning", + ); + } finally { + await prepared.dispose(); + } + expect(await exists(prepared.root), context).toBe(false); + } +}); + +test("a stray NODE_OPTIONS carrying a user condition the stand-in's exports map answers, a stray NODE_PATH, NODE_PRESERVE_SYMLINKS, and NODE_NO_WARNINGS in the ambient environment reach no run, on each of E-1's releases, along static import and require: each run's environment stays exactly its own, and each loads the conditionless entry (TEST-SPEC T7.6-6: no option, no environment variable, no user condition; S-10)", async () => { + const releases = await resolveNodeReleases(); + const dual = await writeStandIn(STAND_INS.dual); + const staged = await stagePackage( + dual, + releases, + "driver self-test: stray environment", + ); + // The vector is live: the release given the condition itself loads the + // condition's entry from the project. + const [first] = releases; + if (first === undefined) throw new Error("E-1 lists no release"); + const answered = await runProduct( + { + label: `the Node.js release ${first.version}, given the stray condition`, + command: first.executable, + requiredFiles: [first.executable], + }, + { + cwd: staged.placement.holdingDir, + argv: [ + `--conditions=${STRAY_CONDITION}`, + "--eval", + "process.stdout.write(Object.keys(require(" + + `${JSON.stringify(staged.placement.name)})).join(","));`, + ], + env: { NODE_OPTIONS: undefined, NODE_PATH: undefined }, + }, + ); + expect(answered.stdout).toBe("strayCondition"); + const strayPath = await freshDirectory("xspec-node-driver-stray-path-"); + const strays: Record<string, string> = { + NODE_OPTIONS: `--conditions=${STRAY_CONDITION}`, + NODE_PATH: strayPath, + NODE_PRESERVE_SYMLINKS: "1", + NODE_NO_WARNINGS: "1", + }; + const saved = Object.keys(strays).map( + (name): [string, string | undefined] => [name, process.env[name]], + ); + Object.assign(process.env, strays); + try { + for (const release of releases) { + for (const route of ["static-import", "require"] as const) { + const context = `driver self-test: stray environment, ${release.version}, ${route}`; + const run = await runModuleRoute( + request(staged, release, route, context), + ); + const loaded = assertModuleLoaded(run, "stand-in"); + expect( + loaded.report.load.value.ownKeys + ?.filter((key) => key.kind === "string") + .map((key) => key.name), + context, + ).toEqual(["defineConfig"]); + for (const name of Object.keys(strays)) { + expect(loaded.report.environment[name], context).toBeUndefined(); + } + expect(loaded.report.environment, context).toEqual(run.environment); + expect(loaded.report.release.execArgv, context).toEqual([]); + } + } + } finally { + for (const [name, value] of saved) { + if (value === undefined) { + delete process.env[name]; + } else { + process.env[name] = value; + } + } + } +}); + +test("each way a run can fail to load is reported as such — a package naming no entry (S-7's stub package) along each route, a module exiting while it loads, one killing its own process, one overwriting the report, one setting exit code 3 — each a diagnosed failure for a product and a harness error for a stand-in; and a run its module keeps alive ends at its own guard, its directory removed (TEST-SPEC H-8, H-3, S-3, §7.6 Pairing)", async () => { + const release = await firstRelease(); + const stub = await stagePackage( + STUB_PACKAGE_DIR, + [release], + "driver self-test: stub package", + ); + for (const route of MODULE_ROUTES) { + const context = `driver self-test: stub package, ${route}`; + const run = await runModuleRoute(request(stub, release, route, context)); + expect(run.outcome, context).toBe("load-failed"); + const load = run.report?.load; + expect(load?.outcome, context).toBe("failed"); + if (load?.outcome === "failed") { + expect(load.error.code, context).toBe( + route === "require" ? "MODULE_NOT_FOUND" : "ERR_MODULE_NOT_FOUND", + ); + } + expect(run.report?.importingModule, context).toBeNull(); + expectChargedBothWays(run, "did not load the module"); + } + + const vectors: readonly { + readonly standIn: keyof typeof STAND_INS; + readonly check: (run: ModuleRun) => void; + readonly mentions: string; + }[] = [ + { + standIn: "exiting", + check: (run) => { + expect(run.outcome).toBe("incomplete"); + expect(run.report?.phase).toBe("loading"); + expect(run.report?.exit).toEqual({ code: 0 }); + expect(run.result.exitCode).toBe(0); + }, + mentions: "ended before the load completed or failed", + }, + { + standIn: "killed", + check: (run) => { + expect(run.outcome).toBe("no-report"); + expect(run.report).toBeUndefined(); + expect(run.result.signal).toBe("SIGKILL"); + }, + mentions: "left no report: the process was killed by SIGKILL", + }, + { + standIn: "tampering", + check: (run) => { + expect(run.outcome).toBe("malformed-report"); + expect(run.reportProblem).toContain("no UTF-8 JSON"); + expect(run.result.exitCode).toBe(0); + }, + mentions: "left a malformed report", + }, + { + standIn: "exitCode", + check: (run) => { + expect(run.outcome).toBe("loaded"); + expect(run.report?.exit).toEqual({ code: 3 }); + expect(run.result.exitCode).toBe(3); + }, + mentions: "exited with code 3, not with exit code 0 on its own", + }, + ]; + for (const vector of vectors) { + const context = `driver self-test: ${vector.standIn}`; + const packageDir = await writeStandIn(STAND_INS[vector.standIn]); + const staged = await stagePackage(packageDir, [release], context); + const run = await runModuleRoute( + request(staged, release, "require", context), + ); + vector.check(run); + expectChargedBothWays(run, vector.mentions); + } + + const lingering = await stagePackage( + await writeStandIn(STAND_INS.lingering), + [release], + "driver self-test: lingering", + ); + const prepared = await prepareModuleRun({ + ...request(lingering, release, "require", "driver self-test: lingering"), + guards: { timeoutMs: 3_000 }, + }); + try { + await expect(prepared.launch()).rejects.toBeInstanceOf( + ProductRunTimeoutError, + ); + } finally { + await prepared.dispose(); + } + expect(await exists(prepared.root)).toBe(false); +}); + +test("the importing modules' place: each route's file, named for its route and naming the placement by a specifier spelling exactly N, stands beside the others in the importing file's directory, written once and found byte-equal by a later run; any other occupant of its path is a HarnessStagingError, and a specifier outside 7.6's grammar a usage error (TEST-SPEC T7.6-6: a harness-written importing module in the importing file's place; SPEC 7.6 Reach)", async () => { + const release = await firstRelease(); + const dual = await writeStandIn(STAND_INS.dual); + const staged = await stagePackage( + dual, + [release], + "driver self-test: importing modules", + ); + const name = staged.placement.name; + for (const route of MODULE_ROUTES) { + const text = importingModuleText(route, name); + expect(text, route).toContain(JSON.stringify(name)); + for (const round of [1, 2]) { + const context = `driver self-test: importing modules, ${route}, run ${String(round)}`; + assertModuleLoaded( + await runModuleRoute(request(staged, release, route, context)), + "stand-in", + ); + } + expect( + await fsp.readFile( + path.join(staged.placement.holdingDir, importingModuleName(route)), + "utf8", + ), + route, + ).toBe(text); + } + expect((await fsp.readdir(staged.placement.holdingDir)).sort()).toEqual( + [ + ...MODULE_ROUTES.map((route) => importingModuleName(route)), + "node_modules", + "package.json", + ].sort(), + ); + await staged.staging.writeFile( + `project/sub/${importingModuleName("require")}`, + `// not the importing module${LF}`, + ); + await expect( + prepareModuleRun({ + ...request(staged, release, "require", "driver self-test: occupied"), + importingDir: "project/sub", + }), + ).rejects.toBeInstanceOf(HarnessStagingError); + expect(() => importingModuleText("require", "Not A Name")).toThrow( + "7.6's grammar", + ); +}); + +test(`a CommonJS project whose nearest package.json holds "type": "commonjs" is declared so to the driver: Reach confirms the project kind with that type before the run, which loads the module; declared as a CommonJS project holding no type, the run is refused before it starts (TEST-SPEC T7.6-5(c); helpers/module-channel.ts ReachStaging.nearestType)`, async () => { + const release = await firstRelease(); + const dual = await writeStandIn(STAND_INS.dual); + const context = "driver self-test: a nearest manifest typed commonjs"; + const staging = await ModuleStaging.create(standInBinding(dual), context); + onTestFinished(() => staging.dispose()); + await staging.stageProject("project", "no-manifest"); + await staging.writeFile( + "project/package.json", + manifest({ type: "commonjs" }), + ); + const placement = await staging.placeCanonical( + "project", + runtimeArm([release]), + ); + const staged = { staging, placement }; + assertModuleLoaded( + await runModuleRoute({ + ...request(staged, release, "require", context), + nearestType: "commonjs", + }), + "stand-in", + ); + await expect( + runModuleRoute(request(staged, release, "require", context)), + ).rejects.toBeInstanceOf(HarnessStagingError); +}); + +test("the report's decoder reads exactly the bootstrap's members, each of its kind and consistent with the phase — T7.6-6's own-key listing and calls, and T7.6-7(c)'s comparison of the process state, among them — and says what makes any other report malformed — a missing or extra member, another protocol, a value of another kind, a phase of its own, a load outcome, calls, or a state compared inconsistent with the phase or the note, calls out of the bootstrap's order or unfinished at completion, a call verdict inconsistent with its values, a trap or proxy of its own, an observation of its own, a count of omitted differences that is no non-negative integer, bytes that are no UTF-8 or no JSON (TEST-SPEC H-3: failing loudly when required information is absent)", () => { + const encode = (value: unknown): Uint8Array => + new TextEncoder().encode(JSON.stringify(value)); + const thrown = { + type: "object", + name: "Error", + code: "MODULE_NOT_FOUND", + message: "Cannot find module", + stack: "Error: Cannot find module", + }; + const warning = { + type: "object", + name: "DeprecationWarning", + code: "DEP0128", + message: "Invalid 'main' field", + detail: null, + stack: "DeprecationWarning: Invalid 'main' field", + }; + const returned = (name: string): Record<string, unknown> => ({ + case: name, + outcome: "returned-argument", + returned: null, + thrown: null, + }); + const results = CALL_CASES.map(returned); + const calls = { + reading: { type: "function", thrown: null }, + results, + traps: [], + }; + const withResults = ( + altered: readonly Record<string, unknown>[], + ): Record<string, unknown> => ({ ...calls, results: altered }); + const state = { + subjects: ["the global object", "Array", "Array.prototype", "process"], + changes: [], + omitted: 0, + }; + const change = { + observation: "global-object", + subject: "the global object", + detail: 'an own property "x" was added', + }; + const valid = { + protocol: MODULE_RUN_PROTOCOL, + argv: ["/run/bootstrap.cjs", "/staging/importing.cjs", "/run/r", "require"], + release: { version: "v22.0.0", execPath: "/node", execArgv: [] }, + pid: 4242, + environment: { HOME: "/run/home", TMPDIR: "/run/tmp" }, + cwd: "/run/work", + phase: "completed", + importingModule: { topLevelThis: "object", location: "/staging/i.cjs" }, + load: { + outcome: "loaded", + value: { type: "object", ownKeys: [DEFINE_CONFIG_KEY] }, + }, + calls, + state, + bootstrapError: null, + warnings: [warning], + exit: { code: 0 }, + }; + const omit = ( + record: Record<string, unknown>, + member: string, + ): Record<string, unknown> => + Object.fromEntries( + Object.entries(record).filter(([name]) => name !== member), + ); + const failedLoad = { + ...valid, + load: { outcome: "failed", error: thrown }, + importingModule: null, + calls: null, + state: null, + }; + const loading = { + ...valid, + phase: "loading", + load: null, + importingModule: null, + calls: null, + state: null, + }; + const calling = { ...valid, phase: "calling", state: null }; + const listing = (ownKeys: unknown): Record<string, unknown> => ({ + ...valid, + load: { outcome: "loaded", value: { type: "object", ownKeys } }, + }); + const decodes: readonly [string, unknown][] = [ + ["a loaded report", valid], + ["a failed load", failedLoad], + ["a run ending while loading", loading], + ["a bootstrap failure", { ...loading, bootstrapError: thrown, exit: null }], + [ + "a run ending while reading defineConfig", + { + ...calling, + calls: { ...calls, reading: null, results: [] }, + }, + ], + [ + "a run ending during the calls", + { ...calling, calls: withResults(results.slice(0, 3)) }, + ], + ["a run ending as the state was compared", calling], + [ + "a bootstrap failure during the calls", + { + ...calling, + calls: withResults(results.slice(0, 1)), + bootstrapError: thrown, + exit: null, + }, + ], + [ + "a state compared with differences listed, each observation's, and more omitted", + { + ...valid, + state: { + ...state, + changes: STATE_OBSERVATIONS.map((observation) => ({ + ...change, + observation, + })), + omitted: 3, + }, + }, + ], + [ + "a defineConfig that is no function", + { + ...valid, + calls: { + ...calls, + reading: { type: "undefined", thrown: null }, + results: [], + }, + }, + ], + [ + "a read of defineConfig that threw", + { + ...valid, + calls: { ...calls, reading: { type: null, thrown }, results: [] }, + }, + ], + [ + "calls returning another value or throwing, and traps invoked", + { + ...valid, + calls: { + ...withResults([ + { + ...returned("object"), + outcome: "returned-other", + returned: { type: "object", text: null }, + }, + { ...returned("array"), outcome: "threw", thrown }, + ...results.slice(2), + ]), + traps: [ + { proxy: "first", trap: "get" }, + { proxy: "second", trap: "ownKeys" }, + ], + }, + }, + ], + [ + "a symbol key with no description, and a key whose enumerability is unknown", + listing([ + DEFINE_CONFIG_KEY, + { kind: "symbol", name: null, enumerable: false }, + { kind: "string", name: "other", enumerable: null }, + ]), + ], + [ + "a loaded value whose keys are not listed", + { + ...valid, + load: { outcome: "loaded", value: { type: "number", ownKeys: null } }, + }, + ], + ]; + for (const [label, value] of decodes) { + expect(decodeModuleRunReport(encode(value)).ok, label).toBe(true); + } + expect(decodeModuleRunReport(encode(valid))).toEqual({ + ok: true, + report: omit(valid, "protocol"), + }); + const malformed: readonly [string, unknown][] = [ + ["a missing member", omit(valid, "pid")], + ["an extra member", { ...valid, extra: 1 }], + ["another protocol", { ...valid, protocol: "xspec-module-run/0" }], + ["a number for a string", { ...valid, cwd: 1 }], + [ + "an environment value of another kind", + { ...valid, environment: { HOME: 1 } }, + ], + ["a phase of its own", { ...valid, phase: "started" }], + [ + "completed without a load", + { ...valid, load: null, importingModule: null }, + ], + ["a load while still loading", { ...valid, phase: "loading" }], + [ + "completed with a bootstrap failure", + { ...valid, bootstrapError: thrown }, + ], + [ + "the note without a loaded module", + { ...valid, load: { outcome: "failed", error: thrown } }, + ], + ["a loaded module without the note", { ...valid, importingModule: null }], + ["a load outcome of its own", { ...valid, load: { outcome: "skipped" } }], + [ + "a warning missing its detail", + { ...valid, warnings: [omit(warning, "detail")] }, + ], + ["an argument of another kind", { ...valid, argv: [1] }], + ["an exit code that is no integer", { ...valid, exit: { code: 1.5 } }], + ["a process identifier of zero", { ...valid, pid: 0 }], + ["an array for the report", [valid]], + ["the previous protocol", { ...valid, protocol: "xspec-module-run/2" }], + ["an older protocol", { ...valid, protocol: "xspec-module-run/1" }], + ["a loaded module whose state was not compared", { ...valid, state: null }], + ["a state compared while still loading", { ...loading, state }], + ["a state compared in the phase calling", { ...valid, phase: "calling" }], + ["a state compared beside a failed load", { ...failedLoad, state }], + [ + "an observation of its own", + { + ...valid, + state: { ...state, changes: [{ ...change, observation: "memory" }] }, + }, + ], + [ + "a difference missing its detail", + { + ...valid, + state: { ...state, changes: [omit(change, "detail")] }, + }, + ], + [ + "a negative count of omitted differences", + { ...valid, state: { ...state, omitted: -1 } }, + ], + [ + "a fractional count of omitted differences", + { ...valid, state: { ...state, omitted: 1.5 } }, + ], + [ + "a subject that is no string", + { ...valid, state: { ...state, subjects: [1] } }, + ], + [ + "a state missing its subjects", + { ...valid, state: omit(state, "subjects") }, + ], + ["calls while still loading", { ...loading, calls }], + ["calls without a loaded module", { ...failedLoad, calls }], + ["a loaded module without calls", { ...valid, calls: null }], + [ + "the phase calling without calls", + { ...valid, phase: "calling", calls: null }, + ], + [ + "completed with defineConfig unread", + { ...valid, calls: { ...calls, reading: null, results: [] } }, + ], + [ + "completed with a call missing", + { ...valid, calls: withResults(results.slice(0, -1)) }, + ], + [ + "calls out of the bootstrap's order", + { + ...valid, + calls: withResults([ + ...results.slice(1, 2), + ...results.slice(0, 1), + ...results.slice(2), + ]), + }, + ], + [ + "a call of its own", + { ...valid, calls: withResults([...results, returned("another")]) }, + ], + [ + "calls made with no function read", + { + ...valid, + calls: { ...calls, reading: { type: "object", thrown: null } }, + }, + ], + [ + "a reading with both a type and a thrown value", + { ...valid, calls: { ...calls, reading: { type: "function", thrown } } }, + ], + [ + "a returned value beside the outcome returned-argument", + { + ...valid, + calls: withResults([ + { ...returned("object"), returned: { type: "object", text: null } }, + ...results.slice(1), + ]), + }, + ], + [ + "the outcome threw without the thrown value", + { + ...valid, + calls: withResults([ + { ...returned("object"), outcome: "threw" }, + ...results.slice(1), + ]), + }, + ], + [ + "a call outcome of its own", + { + ...valid, + calls: withResults([ + { ...returned("object"), outcome: "returned" }, + ...results.slice(1), + ]), + }, + ], + [ + "a trap of its own", + { + ...valid, + calls: { ...calls, traps: [{ proxy: "first", trap: "call" }] }, + }, + ], + [ + "a proxy of its own", + { + ...valid, + calls: { ...calls, traps: [{ proxy: "third", trap: "get" }] }, + }, + ], + [ + "a string key with no name", + listing([{ kind: "string", name: null, enumerable: true }]), + ], + [ + "a key of another kind", + listing([{ kind: "number", name: "0", enumerable: true }]), + ], + [ + "an enumerability that is no boolean", + listing([{ ...DEFINE_CONFIG_KEY, enumerable: "yes" }]), + ], + [ + "the previous listing of names", + { + ...valid, + load: { + outcome: "loaded", + value: { type: "object", ownPropertyNames: ["defineConfig"] }, + }, + }, + ], + ]; + for (const [label, value] of malformed) { + const decoding = decodeModuleRunReport(encode(value)); + expect(decoding.ok, label).toBe(false); + } + expect(decodeModuleRunReport(Uint8Array.of(0xff, 0xfe)).ok).toBe(false); + expect( + decodeModuleRunReport(new TextEncoder().encode("not a report")).ok, + ).toBe(false); +}); diff --git a/test/self/module-channel-staging.test.ts b/test/self/module-channel-staging.test.ts new file mode 100644 index 00000000..99982490 --- /dev/null +++ b/test/self/module-channel-staging.test.ts @@ -0,0 +1,1335 @@ +// Self-checks for the module channel's stagings (TEST-SPEC 17 preamble: +// internal self-tests cover harness machinery certification does not +// exercise; §7.6 Placement, H-1, H-2, H-8, C-2; SPEC 7.6 Package and +// installation, Reach; helpers/module-channel.ts). The machinery every test +// of 7.6 stages through is pinned here on its own, before any product +// exists: +// - the package directory: none given fails diagnosed before anything is +// staged (H-8); on the built product's binding a directory that does not +// exist is its missing product, diagnosed likewise, and on any other a +// harness error; a relative path, a plain file, a development tree (an +// entry named `node_modules` at its root, of any kind), and an entry that +// is neither a plain file, a directory, nor a symbolic link (a FIFO, made +// by helpers/lock-staging.ts's `stageFifo` and never opened) are harness +// errors on every binding; +// - placement by copy alone: the copy at `node_modules/N` is byte-equal to +// the source, modes and symbolic links kept, and the source is untouched, +// read entry by entry before and after; a symbolic-link placement reaches +// a copy elsewhere in the staging, under no `node_modules`; +// - N's grammar and exclusions on vectors, `fs` and `path` refused on a +// runtime arm — each of E-1's releases asked, so XSPEC_NODE_RELEASES_DIR +// must name them, as CI's harness-self job and AGENTS.md's recipe do — +// and admitted on a type-checking one; the canonical N; the manifest's +// name; +// - H-1 through Task 8's module: a staging under an ancestor holding a +// `package.json` or a `node_modules` entry is refused, and so is a run +// whose fresh HOME holds a global module folder's entry; +// - the three project kinds, each confirmed on its finished staging; +// - each Reach condition refused when broken, and admitted where Reach bars +// nothing (an unrelated package at `node_modules/a` beside `a.js`, an +// ancestor manifest named `unrelated`), and the canonical placement's +// "nothing else installed"; +// - no staging write lands in a placed copy (H-2), and a directory copied +// beside a placement (T7.6-4(e)'s TypeScript package) is byte-equal to +// its source. +// +// The stand-in package, test/fixtures/module-channel-standin/, documented +// here since JSON holds no comment: a small hand-written, non-xspec package +// — `package.json` naming `module-channel-standin`, version `1.0.0`, `main` +// `index.js`, and `types` `index.d.ts`; `index.js`, a CommonJS module +// exporting `answer`; `index.d.ts`, its declaration; and `lib/helper.js`, so +// that a copy has a directory to keep. Nothing here loads or type-checks +// it: what it serves is a directory to place. Stagings with modes and +// links of their own are made from it at run time, under the OS temporary +// directory, so the committed tree holds no symbolic link. + +import * as fsp from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; +import { fileURLToPath } from "node:url"; +import { expect, onTestFinished, test } from "vitest"; +import { HarnessAssertionError } from "../helpers/assertions.js"; +import { stageFifo } from "../helpers/lock-staging.js"; +import { + builtInNamesOn, + CANONICAL_MODULE_NAMES, + canonicalModuleName, + describeTreeDifference, + judgeManifestBytes, + MODULE_NAME_MAX_LENGTH, + MODULE_STAGING_PREFIX, + ModuleStaging, + moduleNameExclusion, + moduleNameGrammarProblem, + modulePackageDirectory, + PROJECT_KINDS, + readManifestName, + readPackageTree, + runtimeArm, + TYPE_CHECKING_ARM, + verifyModuleName, +} from "../helpers/module-channel.js"; +import type { + ModuleArm, + PackageTree, + Placement, + PlacementForm, + ProjectKind, +} from "../helpers/module-channel.js"; +import { resolveNodeReleases } from "../helpers/node-releases.js"; +import { HarnessStagingError } from "../helpers/permissions.js"; +import { builtProductBindingAt } from "../helpers/subprocess.js"; +import type { ProductBinding } from "../helpers/subprocess.js"; + +/** The committed stand-in package (module header), resolved like a fixture. */ +const STANDIN_PACKAGE_DIR = fileURLToPath( + new URL("../fixtures/module-channel-standin", import.meta.url), +); + +/** The name the stand-in's manifest gives. */ +const STANDIN_NAME = "module-channel-standin"; + +/** S-7's stub package (test/self/s7-red-green-sweep.test.ts). */ +const STUB_PACKAGE_DIR = fileURLToPath( + new URL("../fixtures/empty-stub-package", import.meta.url), +); + +const BACKSLASH = String.fromCodePoint(0x5c); +const BYTE_ORDER_MARK = String.fromCodePoint(0xfeff); + +/** + * A binding of the certification fixtures' shape beside `packageDir`: its + * executable is never run here, and a missing package directory is no + * diagnosed missing product on it. + */ +function standInBinding(packageDir?: string): ProductBinding { + return { + label: "module-channel stand-in binding", + command: process.execPath, + requiredFiles: [process.execPath], + ...(packageDir === undefined ? {} : { packageDir }), + }; +} + +/** The built product's binding shape beside `packageDir`. */ +function builtBinding(packageDir?: string): ProductBinding { + const binding = builtProductBindingAt( + path.join(os.tmpdir(), "xspec-module-channel-absent", "bin.js"), + ); + return packageDir === undefined ? binding : { ...binding, packageDir }; +} + +/** A fresh, empty directory of this test's own, removed once it ends. */ +async function freshDirectory(): Promise<string> { + const directory = await fsp.realpath( + await fsp.mkdtemp(path.join(os.tmpdir(), "xspec-module-channel-probe-")), + ); + onTestFinished(() => fsp.rm(directory, { recursive: true, force: true })); + return directory; +} + +/** A staging beside `packageDir`, disposed once the test ends. */ +async function stagingBeside( + packageDir: string = STANDIN_PACKAGE_DIR, + context = "module-channel self-test", +): Promise<ModuleStaging> { + const staging = await ModuleStaging.create( + standInBinding(packageDir), + context, + ); + onTestFinished(() => staging.dispose()); + return staging; +} + +/** A copy of the committed stand-in in `into`, made file by file. */ +async function copyOfStandIn(into: string): Promise<string> { + const directory = path.join(into, "package"); + await fsp.mkdir(path.join(directory, "lib"), { recursive: true }); + for (const file of [ + "package.json", + "index.js", + "index.d.ts", + "lib/helper.js", + ]) { + await fsp.copyFile( + path.join(STANDIN_PACKAGE_DIR, file), + path.join(directory, file), + ); + } + return directory; +} + +/** What `pending` rejected with (a test failure where it resolved). */ +async function rejectionOf( + pending: Promise<unknown>, + what: string, +): Promise<unknown> { + try { + await pending; + } catch (error) { + return error; + } + throw new Error(`expected ${what} to reject, but it resolved`); +} + +/** + * `pending` rejects with the module channel's harness error, its message + * holding each of `holding`; never a diagnosed failure. + */ +async function expectRefused( + pending: Promise<unknown>, + what: string, + ...holding: readonly string[] +): Promise<HarnessStagingError> { + const error = await rejectionOf(pending, what); + expect(error, what).toBeInstanceOf(HarnessStagingError); + expect(error, what).not.toBeInstanceOf(HarnessAssertionError); + const refusal = error as HarnessStagingError; + expect(refusal.mode, what).toBe("module-channel"); + for (const part of holding) expect(refusal.message, what).toContain(part); + return refusal; +} + +/** `pending` rejects with H-8's diagnosed failure, declining shrinking. */ +async function expectDiagnosed( + pending: Promise<unknown>, + what: string, + ...holding: readonly string[] +): Promise<void> { + const error = await rejectionOf(pending, what); + expect(error, what).toBeInstanceOf(HarnessAssertionError); + expect((error as HarnessAssertionError).shrinkable, what).toBe(false); + for (const part of holding) { + expect((error as Error).message, what).toContain(part); + } +} + +test("no package directory given: making a staging fails as a diagnosed assertion failure declining shrinking, its diagnosis naming the executable beside which none is given (the absent artifact S-7's no-product sweep requires named), on the built product's binding and any other alike, before anything is staged (TEST-SPEC H-8, C-2)", async () => { + const parent = await freshDirectory(); + for (const binding of [standInBinding(), builtBinding()]) { + await expectDiagnosed( + ModuleStaging.create(binding, "no package directory", { parent }), + `${binding.label} with no package directory`, + "no package directory is given", + [binding.command, ...(binding.prefixArgs ?? [])].join(" "), + "Nothing was staged", + ); + } + expect(await fsp.readdir(parent), "nothing was staged").toEqual([]); +}); + +test("a package directory that does not exist is the built product's missing product — a diagnosed failure, nothing staged — and a harness error on any other binding; a relative path and a plain file are harness errors on every binding, the relative one never resolved against the working directory (TEST-SPEC H-8, H-2, C-2)", async () => { + const parent = await freshDirectory(); + const absent = path.join(parent, "absent-package"); + await expectDiagnosed( + ModuleStaging.create(builtBinding(absent), "absent package", { parent }), + "the built product's absent package directory", + `the package directory ${absent} does not exist`, + ); + await expectRefused( + ModuleStaging.create(standInBinding(absent), "absent package", { parent }), + "another binding's absent package directory", + "does not exist", + "only the built product's missing package", + ); + const file = path.join(parent, "a-file"); + await fsp.writeFile(file, "not a package"); + for (const binding of [standInBinding(file), builtBinding(file)]) { + await expectRefused( + ModuleStaging.create(binding, "a plain file", { parent }), + `${binding.label}'s plain-file package directory`, + "is a plain file, not a directory", + ); + } + for (const relative of [ + "package", + "./test/fixtures/module-channel-standin", + ]) { + for (const binding of [standInBinding(relative), builtBinding(relative)]) { + await expectRefused( + ModuleStaging.create(binding, "a relative path", { parent }), + `${binding.label}'s relative package directory ${relative}`, + "is not an absolute path", + ); + } + } + expect((await fsp.readdir(parent)).sort(), "nothing was staged").toEqual([ + "a-file", + ]); +}); + +test("a development tree is refused: a package directory holding an entry named node_modules at its root — a directory, a plain file, or a symbolic link — is a harness error, and so is one holding an entry neither a plain file, a directory, nor a symbolic link (a FIFO, never opened); the committed stand-in and S-7's stub package are accepted (TEST-SPEC H-2: never a development tree; C-2)", async () => { + for (const accepted of [STANDIN_PACKAGE_DIR, STUB_PACKAGE_DIR]) { + const checked = await modulePackageDirectory( + standInBinding(accepted), + "an accepted package directory", + ); + expect(checked.path).toBe(accepted); + } + const probe = await freshDirectory(); + const decoy = path.join(probe, "decoy"); + await fsp.mkdir(decoy); + const installs: readonly [string, (at: string) => Promise<unknown>][] = [ + [ + "a directory", + (at) => fsp.mkdir(path.join(at, "dependency"), { recursive: true }), + ], + ["a plain file", (at) => fsp.writeFile(at, "")], + ["a symbolic link", (at) => fsp.symlink(decoy, at)], + ]; + for (const [kind, install] of installs) { + const holder = path.join(probe, `tree-${kind.replace(/ /g, "-")}`); + await fsp.mkdir(holder); + const tree = await copyOfStandIn(holder); + await install(path.join(tree, "node_modules")); + await expectRefused( + modulePackageDirectory(standInBinding(tree), `node_modules as ${kind}`), + `a package directory holding node_modules as ${kind}`, + "holds an entry named node_modules at its root", + "never a development tree", + ); + } + const fifoHolder = path.join(probe, "tree-fifo"); + await fsp.mkdir(fifoHolder); + const withFifo = await copyOfStandIn(fifoHolder); + await stageFifo({ root: withFifo, tempRoot: fifoHolder }, "lib/pipe"); + await expectRefused( + modulePackageDirectory(standInBinding(withFifo), "a FIFO in the package"), + "a package directory holding a FIFO", + "lib/pipe, a FIFO", + ); + expect((await fsp.lstat(path.join(withFifo, "lib", "pipe"))).isFIFO()).toBe( + true, + ); +}); + +/** A package tree's entries, for a readable comparison. */ +function entriesOf(tree: PackageTree): string[] { + return [...tree.entries].map(([key, entry]) => { + const shown = Buffer.from(key, "latin1").toString(); + if (entry.kind === "symlink") + return `${shown} -> ${entry.target.toString()}`; + const mode = entry.mode.toString(8); + return entry.kind === "file" + ? `${shown} (file ${mode}, ${String(entry.bytes.length)} bytes)` + : `${shown} (directory ${mode})`; + }); +} + +/** + * A package directory with modes and a symbolic link of its own, made from + * the stand-in: `bin/run.sh` mode 0755, `lib` mode 0750, `lib/alias.js` a + * link to `helper.js`, `docs/empty` an empty directory, and the directory's + * own mode 0750. + */ +async function variedPackage(): Promise<string> { + const probe = await freshDirectory(); + const directory = await copyOfStandIn(probe); + await fsp.mkdir(path.join(directory, "bin")); + await fsp.writeFile( + path.join(directory, "bin", "run.sh"), + ["#!/bin/sh", "exit 0", ""].join(String.fromCodePoint(0x0a)), + ); + await fsp.chmod(path.join(directory, "bin", "run.sh"), 0o755); + await fsp.chmod(path.join(directory, "lib"), 0o750); + await fsp.symlink("helper.js", path.join(directory, "lib", "alias.js")); + await fsp.mkdir(path.join(directory, "docs", "empty"), { recursive: true }); + await fsp.chmod(directory, 0o750); + return directory; +} + +test("placement by copy alone: the canonical placement is a copy at node_modules/N in the holding directory, N the canonical name, byte-equal to the package directory — directories, modes, and symbolic links kept, the directory's own mode too — and the package directory, read entry by entry before and after, is untouched (TEST-SPEC §7.6 Placement, H-2)", async () => { + for (const source of [STANDIN_PACKAGE_DIR, await variedPackage()]) { + const refused = (detail: string): HarnessStagingError => + new HarnessStagingError("module-channel", source, detail); + const before = await readPackageTree(source, "before", refused); + const staging = await stagingBeside(source); + const placement = await staging.placeCanonical("", TYPE_CHECKING_ARM); + expect(placement).toStrictEqual({ + name: CANONICAL_MODULE_NAMES[0], + holdingDir: staging.root, + path: path.join(staging.root, "node_modules", CANONICAL_MODULE_NAMES[0]), + form: "copy", + copy: path.join(staging.root, "node_modules", CANONICAL_MODULE_NAMES[0]), + }); + expect((await fsp.lstat(placement.path)).isDirectory()).toBe(true); + const copied = await readPackageTree(placement.path, "the copy", refused); + expect(describeTreeDifference(before, copied), source).toBeNull(); + expect(entriesOf(copied)).toStrictEqual(entriesOf(before)); + expect(copied.mode, "the copy keeps the directory's own mode").toBe( + before.mode, + ); + const after = await readPackageTree(source, "after", refused); + expect(describeTreeDifference(before, after), source).toBeNull(); + } + const varied = await variedPackage(); + const tree = entriesOf( + await readPackageTree( + varied, + "the varied package", + (detail) => new HarnessStagingError("module-channel", varied, detail), + ), + ); + expect(tree).toContain("bin/run.sh (file 755, 17 bytes)"); + expect(tree).toContain("lib (directory 750)"); + expect(tree).toContain("lib/alias.js -> helper.js"); + expect( + ( + await readPackageTree( + varied, + "the varied package", + (detail) => new HarnessStagingError("module-channel", varied, detail), + ) + ).mode, + ).toBe(0o750); + // Its mode is the umask's: present, as a directory. + expect( + tree.filter((entry) => entry.startsWith("docs/empty (directory ")), + ).toHaveLength(1); +}); + +test("a symbolic-link placement: node_modules/N is a symbolic link to a copy of the package directory elsewhere in the staging, under no node_modules, the copy byte-equal to the source; a copy under a directory named node_modules is refused, as is a holding directory named node_modules and an occupied placement (TEST-SPEC §7.6 Placement, T7.6-4(b); SPEC 7.6)", async () => { + const source = await variedPackage(); + const refused = (detail: string): HarnessStagingError => + new HarnessStagingError("module-channel", source, detail); + const before = await readPackageTree(source, "before", refused); + const staging = await stagingBeside(source); + const placement = await staging.place({ + name: "linked", + holdingDir: "project", + arm: TYPE_CHECKING_ARM, + form: "symlink", + }); + expect(placement.form).toBe("symlink"); + expect(placement.path).toBe( + path.join(staging.root, "project", "node_modules", "linked"), + ); + expect((await fsp.lstat(placement.path)).isSymbolicLink()).toBe(true); + const reached = await fsp.realpath(placement.path); + expect(reached).toBe(placement.copy); + expect(reached.startsWith(`${staging.root}${path.sep}`)).toBe(true); + expect(path.relative(staging.root, reached).split(path.sep)).not.toContain( + "node_modules", + ); + const copied = await readPackageTree(reached, "the linked copy", refused); + expect(describeTreeDifference(before, copied)).toBeNull(); + await expectRefused( + staging.place({ + name: "under-modules", + holdingDir: "project", + arm: TYPE_CHECKING_ARM, + form: "symlink", + copyDir: "vendor/node_modules/copy", + }), + "a linked copy under node_modules", + "under a directory named node_modules", + ); + await expectRefused( + staging.place({ + name: "held", + holdingDir: "project/node_modules", + arm: TYPE_CHECKING_ARM, + }), + "a holding directory named node_modules", + "is itself named node_modules", + ); + await expectRefused( + staging.place({ + name: "linked", + holdingDir: "project", + arm: TYPE_CHECKING_ARM, + }), + "an occupied placement", + "is occupied already", + ); + expect( + describeTreeDifference( + before, + await readPackageTree(source, "after", refused), + ), + ).toBeNull(); +}); + +/** A name of `length` characters: `prefix` padded with `a`. */ +function nameOfLength(prefix: string, length: number): string { + return `${prefix}${"a".repeat(length - prefix.length)}`; +} + +test("N's grammar and exclusions: name or @scope/name, each a non-empty run of lowercase ASCII letters, digits, -, ., and _ beginning with a letter or digit, at most 214 characters in all; never an @types name or an @typescript name beginning lib-; a placement under a name outside them is refused on every arm (SPEC 7.6 Package and installation)", async () => { + const admitted = [ + "a", + "0a", + "a-b_c", + "a.js", + "a.b", + "x.", + "@scope/name", + "@0/a.b", + "@typescript/lib", + "@typescript/libx", + "@typescript/es5", + "types", + nameOfLength("", MODULE_NAME_MAX_LENGTH), + nameOfLength("@scope/", MODULE_NAME_MAX_LENGTH), + ]; + for (const name of admitted) { + expect(moduleNameGrammarProblem(name), name).toBeNull(); + expect(moduleNameExclusion(name), name).toBeNull(); + } + const outsideGrammar = [ + "", + "A", + "aB", + ".a", + "-a", + "_a", + "a b", + "a~b", + "a/b", + "@scope", + "@scope/", + "@/name", + "@a/b/c", + "@Scope/name", + "caf" + String.fromCodePoint(0xe9), + nameOfLength("", MODULE_NAME_MAX_LENGTH + 1), + nameOfLength("@scope/", MODULE_NAME_MAX_LENGTH + 1), + ]; + for (const name of outsideGrammar) { + expect(moduleNameGrammarProblem(name), JSON.stringify(name)).not.toBeNull(); + } + expect(moduleNameGrammarProblem(nameOfLength("", 215))).toContain( + "215 characters long", + ); + for (const name of [ + "@types/x", + "@types/scope__name", + "@typescript/lib-es5", + "@typescript/lib-dom", + ]) { + expect(moduleNameGrammarProblem(name), name).toBeNull(); + expect(moduleNameExclusion(name), name).not.toBeNull(); + } + for (const [name, holding] of [ + ["@types/x", "the @types scope"], + ["@typescript/lib-es5", "beginning lib-"], + ["Upper", "not a non-empty run"], + [nameOfLength("", 215), "past 7.6's limit of 214"], + ] as const) { + await expectRefused( + verifyModuleName(name, TYPE_CHECKING_ARM, "a vector"), + `the name ${name}`, + holding, + ); + } + const staging = await stagingBeside(); + await expectRefused( + staging.place({ name: "@types/x", holdingDir: "", arm: TYPE_CHECKING_ARM }), + "a placement under @types/x", + "the @types scope", + ); + expect(await fsp.readdir(staging.root), "nothing was placed").toEqual([]); +}); + +test("N on a runtime arm: each of E-1's releases is asked, so fs and path — names every release resolves to built-in modules — are refused, while test, built in only as node:test, and the canonical names are admitted; on a type-checking arm fs and path are admitted (SPEC 7.6: the built-in exclusion is Node.js's resolution's and the runtime contract's alone; T7.6-4(f))", async () => { + const releases = await resolveNodeReleases(); + const runtime: ModuleArm = runtimeArm(releases); + for (const release of releases) { + const builtIn = await builtInNamesOn( + release, + ["fs", "path", "test", ...CANONICAL_MODULE_NAMES], + "the built-in vectors", + ); + expect([...builtIn].sort(), release.version).toEqual(["fs", "path"]); + } + for (const name of ["fs", "path"]) { + const refusal = await expectRefused( + verifyModuleName(name, runtime, "a runtime vector"), + `${name} on a runtime arm`, + "resolve to a built-in module", + ); + for (const release of releases) { + expect(refusal.message).toContain(release.version); + } + await verifyModuleName(name, TYPE_CHECKING_ARM, "a type-checking vector"); + } + for (const name of ["test", ...CANONICAL_MODULE_NAMES]) { + await verifyModuleName(name, runtime, "a runtime vector"); + } + const staging = await stagingBeside(); + await expectRefused( + staging.place({ name: "fs", holdingDir: "runtime", arm: runtime }), + "a runtime placement under fs", + "resolve to a built-in module", + ); + const typeChecked = await staging.place({ + name: "fs", + holdingDir: "type-checked", + arm: TYPE_CHECKING_ARM, + }); + expect(typeChecked.path).toBe( + path.join(staging.root, "type-checked", "node_modules", "fs"), + ); +}); + +test("the canonical N is the first of two fixed, unscoped, dot-free names of 7.6's grammar, built in on no release, that differs from the name the package's manifest gives — the stand-in's, S-7's stub package's, the product's, and either canonical name itself — so the canonical install is an aliased one (TEST-SPEC §7.6 Placement)", async () => { + for (const name of CANONICAL_MODULE_NAMES) { + expect(moduleNameGrammarProblem(name), name).toBeNull(); + expect(name.startsWith("@") || name.includes("."), name).toBe(false); + expect(name).not.toBe("xspec"); + } + expect(CANONICAL_MODULE_NAMES[0]).not.toBe(CANONICAL_MODULE_NAMES[1]); + for (const manifestName of [ + STANDIN_NAME, + "xspec-empty-stub", + "@modularcloud/xspec", + undefined, + ]) { + expect(canonicalModuleName(manifestName)).toBe(CANONICAL_MODULE_NAMES[0]); + } + expect(canonicalModuleName(CANONICAL_MODULE_NAMES[0])).toBe( + CANONICAL_MODULE_NAMES[1], + ); + expect(canonicalModuleName(CANONICAL_MODULE_NAMES[1])).toBe( + CANONICAL_MODULE_NAMES[0], + ); + const stub = await stagingBeside(STUB_PACKAGE_DIR); + expect(stub.canonicalName).not.toBe(stub.package.manifestName.name); +}); + +test("the manifest's name is read by parsing the package directory's package.json alone: the stand-in's and S-7's stub package's names; none, saying why, for a manifest that is absent, not JSON, repeating a member, or holding no string name (T7.6-4(a), T7-9(d))", async () => { + expect(await readManifestName(STANDIN_PACKAGE_DIR)).toStrictEqual({ + name: STANDIN_NAME, + detail: "", + }); + expect(await readManifestName(STUB_PACKAGE_DIR)).toStrictEqual({ + name: "xspec-empty-stub", + detail: "", + }); + const probe = await freshDirectory(); + const vectors: readonly [string, string | undefined, string][] = [ + ["absent", undefined, "is absent"], + ["not-json", "{", "is not JSON"], + [ + "repeated", + '{"name": "a", "name": "b"}', + 'repeats the member name "name"', + ], + ["unnamed", '{"version": "1.0.0"}', "holds no name member"], + ["numbered", '{"name": 1}', 'holds a "name" member that is a number'], + ]; + for (const [label, text, holding] of vectors) { + const directory = path.join(probe, label); + await fsp.mkdir(directory); + if (text !== undefined) { + await fsp.writeFile(path.join(directory, "package.json"), text); + } + const read = await readManifestName(directory); + expect(read.name, label).toBeUndefined(); + expect(read.detail, label).toContain(holding); + } +}); + +test("H-1 through helpers/staging-isolation.ts: a staging is made fresh under the OS temporary directory at its physical path, and only where no ancestor of its root holds an entry named package.json or node_modules — refused otherwise as the module channel's harness error, the refused staging removed — and before a Node.js run its global half admits an empty fresh HOME on E-1's releases and refuses one holding a global module folder's entry (TEST-SPEC H-1, H-11)", async () => { + const ancestors: readonly [string, (at: string) => Promise<void>][] = [ + ["package.json", (at) => fsp.writeFile(at, "{}")], + ["node_modules", (at) => fsp.mkdir(at)], + ]; + for (const [entry, make] of ancestors) { + const parent = await freshDirectory(); + await make(path.join(parent, entry)); + await expectRefused( + ModuleStaging.create( + standInBinding(STANDIN_PACKAGE_DIR), + `an ancestor ${entry}`, + { + parent, + }, + ), + `a staging under an ancestor ${entry}`, + `holds an entry named ${entry}`, + "H-1's isolation of the module channel's staging is unmet", + ); + expect( + await fsp.readdir(parent), + "the refused staging was removed", + ).toEqual([entry]); + } + const staging = await stagingBeside(); + expect(path.dirname(staging.root)).toBe(await fsp.realpath(os.tmpdir())); + expect(path.basename(staging.root).startsWith(MODULE_STAGING_PREFIX)).toBe( + true, + ); + expect(await fsp.realpath(staging.root)).toBe(staging.root); + const releases = await resolveNodeReleases(); + const home = await freshDirectory(); + const run = { + environment: { HOME: home, PATH: process.env["PATH"] ?? "" }, + cwd: staging.root, + executables: releases.map((release) => release.executable), + }; + await staging.verifyIsolation(run); + await fsp.mkdir(path.join(home, ".node_modules", "pkg"), { recursive: true }); + await expectRefused( + staging.verifyIsolation(run), + "a fresh HOME holding .node_modules/pkg", + path.join(home, ".node_modules"), + "counts as holding a package", + ); + await staging.dispose(); + await expect(fsp.lstat(staging.root)).rejects.toThrow(); +}); + +/** An importing file's text: nothing here type-checks or loads it. */ +const IMPORTING_TEXT = ["export {};", ""].join(String.fromCodePoint(0x0a)); + +/** A finished staging for a Reach vector. */ +interface ReachFixture { + readonly staging: ModuleStaging; + readonly placement: Placement; + /** The importing file, staging-relative. */ + readonly importingFile: string; +} + +/** + * A finished staging beside the stand-in: a project of `kind` (ES-module + * unless given) at `project`, the importing file `config.ts` in + * `importingDir` (`project` unless given), and the package placed under + * `name` (the canonical N unless given) in `holdingDir` (the importing + * file's own unless given), by `form`. + */ +async function reachStaging( + options: { + readonly name?: string; + readonly kind?: ProjectKind; + readonly importingDir?: string; + readonly holdingDir?: string; + readonly form?: PlacementForm; + } = {}, +): Promise<ReachFixture> { + const staging = await stagingBeside(); + const importingDir = options.importingDir ?? "project"; + await staging.stageProject("project", options.kind ?? "es-module"); + const placement = await staging.place({ + name: options.name ?? staging.canonicalName, + holdingDir: options.holdingDir ?? importingDir, + arm: TYPE_CHECKING_ARM, + ...(options.form === undefined ? {} : { form: options.form }), + }); + const importingFile = `${importingDir}/config.ts`; + await staging.writeFile(importingFile, IMPORTING_TEXT); + return { staging, placement, importingFile }; +} + +test('the three project kinds are stageable — an ES-module project, its package.json holding "type": "module"; a CommonJS project, its package.json holding no type; one with no package.json — each confirmed on its finished staging with nothing but the canonical placement installed, an ES-module project beneath an ancestor manifest holding "type": "commonjs" included, and a staging declaring a kind it does not have is refused (SPEC 7.6 Covered setups; TEST-SPEC §7.6 Placement, T7.6-5(b))', async () => { + const LF = String.fromCodePoint(0x0a); + const manifests: Readonly<Record<ProjectKind, string | undefined>> = { + "es-module": ["{", ' "type": "module"', "}", ""].join(LF), + commonjs: ["{}", ""].join(LF), + "no-manifest": undefined, + }; + for (const kind of PROJECT_KINDS) { + const { staging, placement, importingFile } = await reachStaging({ kind }); + const manifest = await fsp + .readFile(staging.path("project/package.json"), "utf8") + .catch(() => undefined); + expect(manifest, kind).toBe(manifests[kind]); + await staging.verifyReach({ + importingFile, + placement, + project: kind, + alone: true, + }); + for (const other of PROJECT_KINDS.filter( + (candidate) => candidate !== kind, + )) { + await expectRefused( + staging.verifyReach({ importingFile, placement, project: other }), + `a ${kind} project declared ${other}`, + "is declared", + ); + } + } + const staging = await stagingBeside(); + await staging.writeFile("package.json", JSON.stringify({ type: "commonjs" })); + await staging.stageProject("project", "es-module"); + const placement = await staging.placeCanonical("project", TYPE_CHECKING_ARM); + await staging.writeFile("project/config.ts", IMPORTING_TEXT); + await staging.verifyReach({ + importingFile: "project/config.ts", + placement, + project: "es-module", + alone: true, + }); +}); + +test('a CommonJS project whose nearest package.json holds "type": "commonjs" is confirmed only with that type declared beside its kind, and refused declared as any project kind alone; a manifest holding no type declared so is refused, a nearest type declared beside another kind or none is a misuse, and a CommonJS project beneath an ancestor manifest — one holding "type": "module" above its own, or one naming "unrelated" with none of its own — is confirmed as such (SPEC 7.6 Covered setups; TEST-SPEC T7.6-5(a), (b), (c))', async () => { + const typed = await reachStaging({ kind: "no-manifest" }); + await typed.staging.writeFile( + "project/package.json", + JSON.stringify({ type: "commonjs" }), + ); + const at = { importingFile: typed.importingFile, placement: typed.placement }; + await typed.staging.verifyReach({ + ...at, + project: "commonjs", + nearestType: "commonjs", + alone: true, + }); + for (const project of PROJECT_KINDS) { + await expectRefused( + typed.staging.verifyReach({ ...at, project }), + `a CommonJS project typed "commonjs" declared ${project} alone`, + "is declared", + ); + } + const plain = await reachStaging({ kind: "commonjs" }); + await expectRefused( + plain.staging.verifyReach({ + importingFile: plain.importingFile, + placement: plain.placement, + project: "commonjs", + nearestType: "commonjs", + }), + "a CommonJS project holding no type declared typed", + 'holds the type "commonjs"', + "holding no type member", + ); + for (const project of [undefined, "es-module", "no-manifest"] as const) { + const misuse = await rejectionOf( + typed.staging.verifyReach({ + ...at, + ...(project === undefined ? {} : { project }), + nearestType: "commonjs", + }), + `a nearest type declared beside ${String(project)}`, + ); + expect(misuse, String(project)).not.toBeInstanceOf(HarnessStagingError); + expect(misuse, String(project)).toBeInstanceOf(Error); + expect((misuse as Error).message, String(project)).toContain( + "a CommonJS project", + ); + } + const beneath = await reachStaging({ kind: "commonjs" }); + await beneath.staging.writeFile( + "package.json", + JSON.stringify({ type: "module" }), + ); + await beneath.staging.verifyReach({ + importingFile: beneath.importingFile, + placement: beneath.placement, + project: "commonjs", + alone: true, + }); + const unrelated = await reachStaging({ kind: "no-manifest" }); + await unrelated.staging.writeFile( + "package.json", + JSON.stringify({ name: "unrelated" }), + ); + const nearestAbove = { + importingFile: unrelated.importingFile, + placement: unrelated.placement, + }; + await unrelated.staging.verifyReach({ + ...nearestAbove, + project: "commonjs", + alone: true, + }); + await expectRefused( + unrelated.staging.verifyReach({ ...nearestAbove, project: "no-manifest" }), + "a project beneath an ancestor manifest declared to have none", + "is declared", + ); +}); + +/** One nothing-nearer vector: a Reach staging, and the entries it adds. */ +interface NearerVector { + readonly label: string; + readonly name?: string; + readonly importingDir?: string; + readonly holdingDir?: string; + /** Files written, staging-relative; `<N>` stands for the placement's N. */ + readonly occupy: readonly string[]; +} + +/** The nothing-nearer vectors Reach bars (SPEC 7.6 Reach). */ +const NEARER_REFUSED: readonly NearerVector[] = [ + { + label: "N.js beside node_modules/N", + occupy: ["project/node_modules/<N>.js"], + }, + { + label: "N.d.ts beside node_modules/N", + occupy: ["project/node_modules/<N>.d.ts"], + }, + { + label: "a.ts beside node_modules/a.js (S is a)", + name: "a.js", + occupy: ["project/node_modules/a.ts"], + }, + { + label: "@scope/a.ts beside node_modules/@scope/a.b", + name: "@scope/a.b", + occupy: ["project/node_modules/@scope/a.ts"], + }, + { + label: + "node_modules/N in the importing file's directory, the holding directory a strict ancestor", + importingDir: "project/sub", + holdingDir: "project", + occupy: ["project/sub/node_modules/<N>/index.js"], + }, + { + label: "node_modules/@types/N (D) between", + importingDir: "project/sub", + holdingDir: "project", + occupy: ["project/sub/node_modules/@types/<N>/index.d.ts"], + }, + { + label: "node_modules/N.x (S.) between", + importingDir: "project/sub/deeper", + holdingDir: "project", + occupy: ["project/sub/node_modules/<N>.x"], + }, + { + label: "node_modules/@types/N.x (T.) between", + importingDir: "project/sub", + holdingDir: "project", + occupy: ["project/sub/node_modules/@types/<N>.x"], + }, + { + label: "node_modules/@types/scope__a.b (D of @scope/a.b) between", + name: "@scope/a.b", + importingDir: "project/sub", + holdingDir: "project", + occupy: ["project/sub/node_modules/@types/scope__a.b/index.d.ts"], + }, + { + label: "node_modules/@types/scope__a.x (T of @scope/a.b) between", + name: "@scope/a.b", + importingDir: "project/sub", + holdingDir: "project", + occupy: ["project/sub/node_modules/@types/scope__a.x"], + }, +]; + +/** The nothing-nearer vectors Reach leaves open (T7.6-4(c), (d), (e)). */ +const NEARER_ADMITTED: readonly NearerVector[] = [ + { label: "the placement alone", occupy: [] }, + { + label: "an unrelated package at node_modules/a beside a.js", + name: "a.js", + occupy: ["project/node_modules/a/index.js"], + }, + { + label: "an unrelated package at node_modules/a beside a.b", + name: "a.b", + occupy: ["project/node_modules/a/index.js"], + }, + { + label: + "an unrelated package in the importing file's directory, the holding directory a strict ancestor", + importingDir: "project/sub", + holdingDir: "project", + occupy: ["project/sub/node_modules/unrelated/index.js"], + }, + { + label: "another name's @types package between", + importingDir: "project/sub", + holdingDir: "project", + occupy: ["project/sub/node_modules/@types/other/index.d.ts"], + }, + { + label: + "node_modules/N above the holding directory, farther than the placement", + importingDir: "project/sub", + holdingDir: "project/sub", + occupy: ["project/node_modules/<N>/index.js"], + }, +]; + +test("Reach's nothing-nearer condition: in the holding directory no entry but the placement begins node_modules/S., and from the importing file's directory up to, excluding, the holding directory none occupies node_modules/N or node_modules/D or begins node_modules/S. or node_modules/T. — each such entry refused, while an unrelated package at node_modules/a beside a.js or a.b, another package or another name's @types package between, and a farther node_modules/N are admitted (SPEC 7.6 Reach; TEST-SPEC T7.6-4(c)-(e))", async () => { + for (const vector of [...NEARER_REFUSED, ...NEARER_ADMITTED]) { + const { staging, placement, importingFile } = await reachStaging(vector); + for (const entry of vector.occupy) { + await staging.writeFile(entry.replace("<N>", placement.name), ""); + } + const verified = staging.verifyReach({ importingFile, placement }); + if (NEARER_REFUSED.includes(vector)) { + await expectRefused( + verified, + vector.label, + "fails Reach's nothing-nearer condition", + ); + } else { + await verified; + } + } +}); + +test("Reach's no-self-reference condition: a manifest in the importing file's directory or an ancestor giving a name read as N or a leading part of it — empty, N, or N's scope, with or without one trailing /, each backslash read as / — is refused; unrelated names, and names N only begins, are admitted (SPEC 7.6 Reach; TEST-SPEC T7.6-5(a))", async () => { + const vectors: readonly { + readonly name?: string; + readonly refused: readonly string[]; + readonly admitted: readonly string[]; + }[] = [ + { + refused: ["", "<N>", "<N>/", `<N>${BACKSLASH}`], + admitted: ["unrelated", "<N>-other", "/", "@<N>"], + }, + { + name: "@scope/a.b", + refused: [ + "", + "@scope/a.b", + "@scope/a.b/", + "@scope", + "@scope/", + `@scope${BACKSLASH}a.b`, + `@scope${BACKSLASH}`, + ], + admitted: [ + "unrelated", + "@scope/a", + "@scope/a.b/x", + "scope", + "@scope/a.bc", + ], + }, + ]; + expect(vectors[0]!.refused[3]!.length).toBe("<N>".length + 1); + for (const vector of vectors) { + for (const where of ["", "project"] as const) { + for (const given of [...vector.refused, ...vector.admitted]) { + const { staging, placement, importingFile } = await reachStaging({ + ...(vector.name === undefined ? {} : { name: vector.name }), + kind: "no-manifest", + }); + const name = given.replace("<N>", placement.name); + await staging.writeFile( + where === "" ? "package.json" : "project/package.json", + JSON.stringify({ name }), + ); + const verified = staging.verifyReach({ importingFile, placement }); + if (vector.refused.includes(given)) { + await expectRefused( + verified, + `a manifest at ${where || "the staging root"} named ${JSON.stringify(name)}`, + "fails Reach's no-self-reference condition", + ); + } else { + await verified; + } + } + } + } +}); + +test("physical naming and the holding directory: an importing file reached through a symbolically linked directory, or itself a symbolic link, is refused, as is a placement whose holding directory is not the file's own or an ancestor; a holding directory that is an ancestor of the file's physical path alone, the file's directory also reachable through a link elsewhere, is admitted given the physical path (SPEC 7.6 Package and installation, Reach; TEST-SPEC T7.6-4(d))", async () => { + const { staging, placement } = await reachStaging({ + importingDir: "project/real", + }); + await staging.link("project/alias", "project/real"); + await staging.link("project/linked.ts", "project/real/config.ts"); + await staging.verifyReach({ + importingFile: "project/real/config.ts", + placement, + }); + for (const importingFile of [ + "project/alias/config.ts", + "project/linked.ts", + ]) { + await expectRefused( + staging.verifyReach({ importingFile, placement }), + `the importing file named as ${importingFile}`, + "fails physical naming", + ); + } + const elsewhere = await staging.place({ + name: "elsewhere-placed", + holdingDir: "elsewhere", + arm: TYPE_CHECKING_ARM, + }); + await expectRefused( + staging.verifyReach({ + importingFile: "project/real/config.ts", + placement: elsewhere, + }), + "a holding directory beside the importing file's", + "neither the importing file's directory nor one of its ancestors", + ); + const ancestral = await reachStaging({ + importingDir: "a/b", + holdingDir: "a", + }); + await ancestral.staging.link("elsewhere/b", "a/b"); + await ancestral.staging.verifyReach({ + importingFile: ancestral.importingFile, + placement: ancestral.placement, + }); + await expectRefused( + ancestral.staging.verifyReach({ + importingFile: "elsewhere/b/config.ts", + placement: ancestral.placement, + }), + "the importing file named through the link elsewhere", + "fails physical naming", + ); +}); + +test("Reach's well-formed-manifests condition: a manifest that is not UTF-8, begins with a byte-order mark, is not JSON, is no JSON object, repeats a member name in any object it holds (compared as decoded, __proto__ among them), holds a non-string name or type, or escapes a lone surrogate in any string, member names included, is refused, and so is an ancestor package.json that is a directory or a dangling symbolic link; a paired surrogate escape and a link to a well-formed manifest are admitted (SPEC 7.6 Reach)", async () => { + const u = (hex: string): string => `${BACKSLASH}u${hex}`; + const refused: readonly [string, Uint8Array | string, string][] = [ + ["not UTF-8", Uint8Array.of(0x7b, 0xff, 0x7d), "is not UTF-8"], + ["a byte-order mark", `${BYTE_ORDER_MARK}{}`, "byte-order mark"], + ["not JSON", "{", "is not JSON"], + ["an array", "[]", "an array, not a JSON object"], + ["a string", '"x"', "a string, not a JSON object"], + ["null", "null", "null, not a JSON object"], + [ + "a repeated name", + '{"name": "a", "name": "b"}', + 'repeats the member name "name"', + ], + [ + "a repeated nested member", + '{"a": {"b": 1, "b": 2}}', + 'repeats the member name "b"', + ], + [ + "a member repeated as decoded", + `{"name": "a", "n${u("0061")}me": "b"}`, + 'repeats the member name "name"', + ], + [ + "a repeated __proto__", + '{"__proto__": 1, "__proto__": 2}', + 'repeats the member name "__proto__"', + ], + [ + "a non-string name", + '{"name": 1}', + 'holds a "name" member that is a number', + ], + [ + "a non-string type", + '{"type": true}', + 'holds a "type" member that is a boolean', + ], + [ + "a lone high surrogate", + `{"description": "${u("d800")}"}`, + "lone surrogate U+D800", + ], + [ + "a lone low surrogate", + `{"description": "${u("dc00")}"}`, + "lone surrogate U+DC00", + ], + [ + "a high surrogate before another escape", + `{"description": "${u("d800")}${u("0041")}"}`, + "lone surrogate U+D800", + ], + [ + "a lone surrogate in a member name", + `{"${u("dbff")}": 1}`, + "lone surrogate U+DBFF", + ], + ]; + const admitted: readonly [string, string][] = [ + ["an empty object", "{}"], + ["a name and a type", '{"name": "unrelated", "type": "module"}'], + [ + "a paired surrogate escape", + `{"description": "${u("d83d")}${u("de00")}"}`, + ], + ["repeated names in two objects", '{"a": {"b": 1}, "c": {"b": 2}}'], + ["one __proto__", '{"__proto__": {"name": 1}, "name": "x"}'], + ]; + expect(u("d800")).toHaveLength(6); + expect(u("d800").codePointAt(0)).toBe(0x5c); + for (const [label, text, holding] of refused) { + const bytes = typeof text === "string" ? Buffer.from(text, "utf8") : text; + const judged = judgeManifestBytes(bytes); + expect(judged.wellFormed, label).toBe(false); + if (!judged.wellFormed) expect(judged.problem, label).toContain(holding); + } + for (const [label, text] of admitted) { + expect( + judgeManifestBytes(Buffer.from(text, "utf8")).wellFormed, + label, + ).toBe(true); + } + const stagings: readonly [ + string, + (staging: ModuleStaging) => Promise<unknown>, + boolean, + ][] = [ + [ + "a malformed ancestor manifest", + (staging) => staging.writeFile("package.json", "{"), + false, + ], + [ + "an ancestor manifest with a lone surrogate", + (staging) => + staging.writeFile("package.json", `{"description": "${u("d800")}"}`), + false, + ], + [ + "an ancestor package.json that is a directory", + (staging) => staging.makeDirectory("package.json"), + false, + ], + [ + "an ancestor package.json that is a dangling link", + (staging) => staging.link("package.json", "absent.json"), + false, + ], + [ + "an ancestor package.json linking to a well-formed manifest", + async (staging) => { + await staging.writeFile("manifests/real.json", '{"type": "commonjs"}'); + await staging.link("package.json", "manifests/real.json"); + }, + true, + ], + ]; + for (const [label, stage, holds] of stagings) { + const { staging, placement, importingFile } = await reachStaging({ + kind: "no-manifest", + }); + await stage(staging); + const verified = staging.verifyReach({ importingFile, placement }); + if (holds) await verified; + else + await expectRefused( + verified, + label, + "fails Reach's well-formed-manifests condition", + ); + } +}); + +test("nothing else installed: the canonical placement alone in the staging — a copy or a symbolic link, unscoped or scoped — is confirmed, and an unrelated package beside it, TypeScript's package at node_modules/typescript, or a node_modules directory elsewhere in the staging is refused where the staging declares its placement alone (TEST-SPEC §7.6 Placement, T7.6-4(e))", async () => { + for (const options of [ + {}, + { form: "symlink" as const }, + { name: "@scope/name" }, + ]) { + const { staging, placement, importingFile } = await reachStaging(options); + await staging.verifyReach({ importingFile, placement, alone: true }); + } + const others: readonly string[] = [ + "project/node_modules/unrelated/index.js", + "project/node_modules/typescript/package.json", + "tools/node_modules/x/index.js", + "project/sub/node_modules/x.js", + ]; + for (const other of others) { + const { staging, placement, importingFile } = await reachStaging(); + await staging.writeFile(other, "{}"); + await staging.verifyReach({ importingFile, placement }); + await expectRefused( + staging.verifyReach({ importingFile, placement, alone: true }), + `the canonical placement beside ${other}`, + "is declared to have nothing but its placement", + ); + } + const scoped = await reachStaging({ name: "@scope/name" }); + await scoped.staging.writeFile( + "project/node_modules/@scope/other/index.js", + "", + ); + await expectRefused( + scoped.staging.verifyReach({ + importingFile: scoped.importingFile, + placement: scoped.placement, + alone: true, + }), + "a scoped placement beside another package of its scope", + "is declared to have nothing but its placement", + ); +}); + +test("no staging write lands in a placed copy: a file, a directory, a link, a copied directory, or a project at or below a placement or the copy a symbolic-link placement reaches is refused, the copies left byte-equal to the package directory (TEST-SPEC H-2: nothing installed into it afterwards); a directory copied elsewhere in the staging — another package installed beside a placement (T7.6-4(e)) — is byte-equal to its source, its own mode, modes, and links kept, and an occupied destination fails", async () => { + const staging = await stagingBeside(); + const copied = await staging.placeCanonical("", TYPE_CHECKING_ARM); + const linked = await staging.place({ + name: "linked", + holdingDir: "other", + arm: TYPE_CHECKING_ARM, + form: "symlink", + }); + const inside = [ + `node_modules/${copied.name}/extra.js`, + `node_modules/${copied.name}/lib/extra.js`, + path.relative(staging.root, linked.copy).split(path.sep).join("/") + + "/extra.js", + ]; + for (const rel of inside) { + await expectRefused( + staging.writeFile(rel, ""), + `a write at ${rel}`, + "lies in the placed copy", + ); + await expectRefused( + staging.makeDirectory(rel), + `a directory at ${rel}`, + "lies in the placed copy", + ); + await expectRefused( + staging.link(rel, "other"), + `a link at ${rel}`, + "lies in the placed copy", + ); + await expectRefused( + staging.stageProject(rel, "commonjs"), + `a project at ${rel}`, + "lies in the placed copy", + ); + await expectRefused( + staging.copyDirectory(rel, STANDIN_PACKAGE_DIR), + `a copied directory at ${rel}`, + "lies in the placed copy", + ); + } + const refused = (detail: string): HarnessStagingError => + new HarnessStagingError("module-channel", STANDIN_PACKAGE_DIR, detail); + const source = await readPackageTree( + STANDIN_PACKAGE_DIR, + "the source", + refused, + ); + for (const copy of [copied.copy, linked.copy]) { + expect( + describeTreeDifference( + source, + await readPackageTree(copy, "a copy", refused), + ), + copy, + ).toBeNull(); + } + const varied = await variedPackage(); + const variedTree = await readPackageTree(varied, "the source", refused); + const other = await staging.copyDirectory( + "other/node_modules/typescript", + varied, + ); + expect(other).toBe( + path.join(staging.root, "other", "node_modules", "typescript"), + ); + const otherTree = await readPackageTree( + other, + "the copied directory", + refused, + ); + expect(describeTreeDifference(variedTree, otherTree)).toBeNull(); + expect(otherTree.mode, "the copy keeps the directory's own mode").toBe(0o750); + expect(entriesOf(otherTree)).toContain("lib/alias.js -> helper.js"); + await expect( + staging.copyDirectory("other/node_modules/typescript", varied), + "an occupied destination", + ).rejects.toThrow(/EEXIST/); +}); diff --git a/test/self/module-channel-ts.test.ts b/test/self/module-channel-ts.test.ts new file mode 100644 index 00000000..d23cf2f9 --- /dev/null +++ b/test/self/module-channel-ts.test.ts @@ -0,0 +1,1232 @@ +// Self-checks for the module channel's TypeScript driver (TEST-SPEC 17 +// preamble: internal self-tests cover harness machinery certification does +// not exercise; §7.6 Covered setups, Verdict, Pairing, Placement; SPEC 7.6 +// Covered setups; helpers/module-channel-ts.ts). No test of 7.6 is +// registered yet, so the driver every type-checking arm will judge through +// is pinned here on its own, before any product exists, over hand-written +// non-xspec stand-in packages: +// - the matrix: 173 setups, each project and extension with exactly the +// option sets covering it, each set exactly as TEST-SPEC §7.6 lists it +// (the initialized-project set also as release 5.9.3's own `tsc --init` +// writer writes it), and every program carrying exactly its set's +// options and nothing else, read back from the program; +// - the verdicts: a conforming stand-in's valid file type-checks and its +// unknown-key twin fails to type-check, paired, in all 173 setups, the +// declaration file TypeScript resolves varying across the matrix as it +// should; an error only in the package's declaration file fails "type- +// checks" with no error located in the configuration file (and, with +// `skipLibCheck` on, the initialized set admits it); +// - the pairing: a shape-violation arm fails diagnosed where its twin does +// not type-check (an error in the package, S-7's stub package) and where +// it does not fail to type-check itself (a permissive package); +// - the sharing the driver's header argues, against its reference reading +// (one root, nothing shared but parsed libraries) on a sample of setups, +// a package whose global augmentation puts errors inside a library among +// them, each file's export listing read alike, and batches the driver +// must judge file by file instead (a file augmenting a module among +// them); +// - the program condition, from TypeScript's include reasons: an `@types` +// package included automatically, a library an installed package +// replaces, and a module TypeScript imports implicitly are refused where +// they enter the program, and admitted where they do not; +// - the export listing (TEST-SPEC T7.6-1): each name with its meanings as +// TypeScript resolves them, through each entry — a value merged with a +// namespace, a declared default, values reached only through `export +// type` and `export type *`, an export assignment's members merged with +// its value's exports, a member keyed by a symbol left out, a value typed +// as a class instance, a stand-in exporting `defineConfig` alone, and +// S-7's stub package resolving to no module. S-4's own detections of the +// listing are test/self/s4-module-channel.test.ts's. +// +// The stand-ins, test/fixtures/module-channel-ts/, documented here since +// JSON holds no comment: each a package in the dual-entry layout AGENTS.md's +// scaffold note describes — `package.json` (`"type": "module"`, the +// top-level `types` for `node10`, and `exports` serving `import` an ES +// module typed by `index.d.ts` and `require` a CommonJS module typed by +// `index.d.cts`), the two declaration files identical, and `index.js` and +// `index.cjs` returning their argument — exporting `defineConfig` alone +// (`export {}` keeps every other declaration unexported): +// - `conforming`: `defineConfig(settings: Settings): Settings`, `Settings` +// an unexported type alias of an exact object type (`groups`, a record of +// string lists; `output`, optionally `{ enabled: boolean }`), which +// declaration emit inlines; +// - `declaration-error`: `conforming` beside an unexported declaration +// naming a type that does not exist, an error located in the declaration +// file alone; +// - `permissive`: `defineConfig(settings: any): any`; +// - `global-augmenting`: `conforming` beside a global augmentation giving +// `RangeError` a `name` of type `number`, which TypeScript reports inside +// its own `lib.es5.d.ts` (`RangeError` incorrectly extends `Error`). +// Two more serve the export listing alone: +// - `listing-meanings`: the dual-entry layout, its declaration files +// differing. `index.d.ts` declares `defineConfig` merged with a namespace +// holding a constant, exports it as itself and, type-only, as +// `typeOnlyFunction`, re-exports `star.d.ts`'s constant `starValue` +// through `export type *`, and declares a default export; `index.d.cts` +// assigns (`export =`) a constant whose type carries `defineConfig` and a +// member keyed by a unique symbol, merged with a namespace declaring a +// type `defineConfig` and an interface `Options`. +// - `listing-instance`: a CommonJS package (no `type`, its top-level +// `types` and `main` alone) whose `index.d.ts` assigns a constant typed +// by a class declaring `defineConfig`. +// S-7's stub package (test/fixtures/empty-stub-package/, a manifest alone) +// serves as the stub. + +import * as path from "node:path"; +import { fileURLToPath } from "node:url"; +import ts from "typescript-5.9.3"; +import { expect, onTestFinished, test } from "vitest"; +import { HarnessAssertionError } from "../helpers/assertions.js"; +import { + ModuleStaging, + PROJECT_KINDS, + TYPE_CHECKING_ARM, +} from "../helpers/module-channel.js"; +import type { Placement, ProjectKind } from "../helpers/module-channel.js"; +import { + assertShapeViolation, + assertTypeChecks, + compilesAsEsModule, + COVERED_EXTENSIONS, + COVERED_OPTION_SETS, + COVERED_SETUP_COUNT, + COVERED_SETUPS, + coveredSetupsOf, + describeErrors, + describeExportListing, + INITIALIZED_PROJECT_OPTION_SET, + stageCoveredFiles, + STRICT_DEFAULT_OPTION_SETS, +} from "../helpers/module-channel-ts.js"; +import type { + CoveredFile, + CoveredFiles, + CoveredOptionSet, + CoveredSetup, + CoveredVerdict, + ExportListing, + ListedExport, +} from "../helpers/module-channel-ts.js"; +import { HarnessStagingError } from "../helpers/permissions.js"; +import type { ProductBinding } from "../helpers/subprocess.js"; + +const LF = String.fromCodePoint(0x0a); + +/** The committed stand-ins (module header), resolved like fixtures. */ +const STAND_INS = { + conforming: fixture("module-channel-ts/conforming"), + declarationError: fixture("module-channel-ts/declaration-error"), + permissive: fixture("module-channel-ts/permissive"), + globalAugmenting: fixture("module-channel-ts/global-augmenting"), + listingMeanings: fixture("module-channel-ts/listing-meanings"), + listingInstance: fixture("module-channel-ts/listing-instance"), + stub: fixture("empty-stub-package"), +} as const; + +function fixture(rel: string): string { + return fileURLToPath(new URL(`../fixtures/${rel}`, import.meta.url)); +} + +/** TypeScript 5.9.3's library directory, as TypeScript names its files. */ +const LIBRARY_DIRECTORY = path.posix.dirname( + ts.getDefaultLibFilePath({}).split(path.sep).join("/"), +); + +/** The project directory every staging here holds, staging-relative. */ +const PROJECT_DIR = "project"; + +/** + * A binding of the certification fixtures' shape beside `packageDir`: its + * executable is never run here. + */ +function standInBinding(packageDir: string): ProductBinding { + return { + label: "module-channel TypeScript driver stand-in binding", + command: process.execPath, + requiredFiles: [process.execPath], + packageDir, + }; +} + +/** A staging of one project beside its canonical placement of `packageDir`. */ +interface StagedProject { + readonly staging: ModuleStaging; + readonly placement: Placement; +} + +/** Stage `project` with `packageDir` placed canonically; disposed at the end. */ +async function stagedProject( + packageDir: string, + project: ProjectKind, + context: string, +): Promise<StagedProject> { + const staging = await ModuleStaging.create( + standInBinding(packageDir), + context, + ); + onTestFinished(() => staging.dispose()); + await staging.stageProject(PROJECT_DIR, project); + const placement = await staging.placeCanonical( + PROJECT_DIR, + TYPE_CHECKING_ARM, + ); + return { staging, placement }; +} + +/** Lines joined by LF, the last one terminated. */ +function lines(...all: string[]): string { + return all.join(LF) + LF; +} + +/** The stand-ins' valid configuration file, importing from `name`. */ +function validFile(name: string): CoveredFile { + return { + label: "the valid file", + text: lines( + `import { defineConfig } from ${JSON.stringify(name)};`, + "", + "export default defineConfig({", + ' groups: { product: ["specs/*.mdx"] },', + " output: { enabled: true },", + "});", + ), + }; +} + +/** The valid file with one unknown key: its shape-violation twin. */ +function unknownKeyFile(name: string): CoveredFile { + return { + label: "its unknown-key twin", + text: lines( + `import { defineConfig } from ${JSON.stringify(name)};`, + "", + "export default defineConfig({", + ' groups: { product: ["specs/*.mdx"] },', + " output: { enabled: true },", + " unknown: true,", + "});", + ), + }; +} + +/** A valid file with an aliased binding and string-literal keys. */ +function aliasedFile(name: string): CoveredFile { + return { + label: "the aliased, string-keyed file", + text: lines( + `import { defineConfig as define } from ${JSON.stringify(name)};`, + "", + "// A comment before the export.", + "export default define({", + ' "groups": { "product": ["specs/*.mdx"], "other": [] },', + "});", + ), + }; +} + +/** The valid file with a string where the stand-in admits a boolean. */ +function wrongKindFile(name: string): CoveredFile { + return { + label: "its wrong-kind twin", + text: lines( + `import { defineConfig } from ${JSON.stringify(name)};`, + "", + "export default defineConfig({", + ' groups: { product: ["specs/*.mdx"] },', + ' output: { enabled: "yes" },', + "});", + ), + }; +} + +/** The strict defaults as TEST-SPEC §7.6 lists them: resolution, module. */ +const STRICT_LISTING: readonly (readonly [string, string | undefined])[] = [ + ["node10", undefined], + ["node16", "node16"], + ["node16", "node18"], + ["node16", "node20"], + ["node16", "nodenext"], + ["nodenext", "node16"], + ["nodenext", "node18"], + ["nodenext", "node20"], + ["nodenext", "nodenext"], + ["bundler", "es2015"], + ["bundler", "es2020"], + ["bundler", "es2022"], + ["bundler", "esnext"], + ["bundler", "preserve"], +]; + +/** The initialized-project set as SPEC 7.6 lists it. */ +const INITIALIZED_LISTING = { + module: "nodenext", + target: "esnext", + types: [], + jsx: "react-jsx", + moduleDetection: "force", + strict: true, + declaration: true, + declarationMap: true, + sourceMap: true, + verbatimModuleSyntax: true, + isolatedModules: true, + exactOptionalPropertyTypes: true, + noUncheckedIndexedAccess: true, + noUncheckedSideEffectImports: true, + skipLibCheck: true, +}; + +const RESOLUTION_KINDS: Readonly<Record<string, ts.ModuleResolutionKind>> = { + node10: ts.ModuleResolutionKind.Node10, + node16: ts.ModuleResolutionKind.Node16, + nodenext: ts.ModuleResolutionKind.NodeNext, + bundler: ts.ModuleResolutionKind.Bundler, +}; + +const MODULE_KINDS: Readonly<Record<string, ts.ModuleKind>> = { + node16: ts.ModuleKind.Node16, + node18: ts.ModuleKind.Node18, + node20: ts.ModuleKind.Node20, + nodenext: ts.ModuleKind.NodeNext, + es2015: ts.ModuleKind.ES2015, + es2020: ts.ModuleKind.ES2020, + es2022: ts.ModuleKind.ES2022, + esnext: ts.ModuleKind.ESNext, + preserve: ts.ModuleKind.Preserve, +}; + +/** + * The compiler options a set's program must carry, written out here apart + * from the driver's own conversion: exactly the listed options. + */ +function expectedOptions(set: CoveredOptionSet): ts.CompilerOptions { + if (set === INITIALIZED_PROJECT_OPTION_SET) { + return { + module: ts.ModuleKind.NodeNext, + target: ts.ScriptTarget.ESNext, + types: [], + jsx: ts.JsxEmit.ReactJSX, + moduleDetection: ts.ModuleDetectionKind.Force, + strict: true, + declaration: true, + declarationMap: true, + sourceMap: true, + verbatimModuleSyntax: true, + isolatedModules: true, + exactOptionalPropertyTypes: true, + noUncheckedIndexedAccess: true, + noUncheckedSideEffectImports: true, + skipLibCheck: true, + }; + } + const index = STRICT_DEFAULT_OPTION_SETS.indexOf(set); + const listed = STRICT_LISTING[index]; + if (listed === undefined) throw new Error(`no listing for ${set.name}`); + const [resolution, module] = listed; + const options: ts.CompilerOptions = { + strict: true, + moduleResolution: RESOLUTION_KINDS[resolution], + }; + if (module !== undefined) options.module = MODULE_KINDS[module]; + return options; +} + +/** + * Which of the stand-in's declaration files TypeScript resolves in `setup`: + * under `node10`, which reads no `exports`, the top-level `types`; under + * `node16` and `nodenext` (the initialized set's mode), the `require` + * entry's for a file TypeScript compiles as CommonJS — by its extension and + * its project's `type` — and the `import` entry's otherwise; under + * `bundler`, the `require` entry's for a `.cts` file alone, the one name it + * compiles as CommonJS. + */ +function resolvedDeclaration( + setup: CoveredSetup, +): "index.d.ts" | "index.d.cts" { + const resolution = setup.optionSet.tsconfig["moduleResolution"]; + if (resolution === "node10") return "index.d.ts"; + if (resolution === "bundler") { + return setup.extension === ".cts" ? "index.d.cts" : "index.d.ts"; + } + return compilesAsEsModule(setup.project, setup.extension) + ? "index.d.ts" + : "index.d.cts"; +} + +/** Whether a program file is one of TypeScript 5.9.3's own libraries. */ +function isLibrary(file: string): boolean { + return path.posix.dirname(file) === LIBRARY_DIRECTORY; +} + +/** A placement's copy, as TypeScript names the files inside it. */ +function insideCopy(placement: Placement, file: string): boolean { + return file.startsWith(`${placement.copy.split(path.sep).join("/")}/`); +} + +/** A verdict's comparable reading: everything but how it was reached. */ +function reading(verdict: CoveredVerdict): unknown { + return { + typeChecks: verdict.typeChecks, + failsToTypeCheck: verdict.failsToTypeCheck, + errors: verdict.errors.map((error) => [ + error.origin, + error.file, + error.line, + error.column, + error.code, + ]), + programFiles: verdict.programFiles, + compilerOptions: verdict.compilerOptions, + exportListing: verdict.exportListing, + }; +} + +/** The one covered setup of `project` with `extension` under `set`. */ +function setupOf( + project: ProjectKind, + extension: CoveredSetup["extension"], + set: CoveredOptionSet, +): CoveredSetup { + const found = COVERED_SETUPS.find( + (setup) => + setup.project === project && + setup.extension === extension && + setup.optionSet === set, + ); + if (found === undefined) { + throw new Error(`no covered setup: ${project}, ${extension}, ${set.name}`); + } + return found; +} + +/** The strict defaults with `resolution` and `module`, from the listing. */ +function strictSet(resolution: string, module?: string): CoveredOptionSet { + const index = STRICT_LISTING.findIndex( + ([r, m]) => r === resolution && m === module, + ); + const set = STRICT_DEFAULT_OPTION_SETS[index]; + if (set === undefined) + throw new Error(`no strict set ${resolution} ${String(module)}`); + return set; +} + +/** Judge one setup, expecting the files in request order. */ +function judgedPair( + files: CoveredFiles, + setup: CoveredSetup, +): readonly [CoveredVerdict, CoveredVerdict] { + const [first, second] = files.judge(setup); + if (first === undefined || second === undefined) { + throw new Error(`expected two verdicts in ${setup.label}`); + } + return [first, second]; +} + +test("the matrix: 173 covered setups, each project and extension with exactly the option sets covering it, each set as TEST-SPEC §7.6 lists it and as release 5.9.3's tsc --init writes the initialized set (TEST-SPEC §7.6 Covered setups)", () => { + expect(COVERED_SETUP_COUNT).toBe(173); + expect(COVERED_SETUPS).toHaveLength(173); + expect(STRICT_DEFAULT_OPTION_SETS.map((set) => set.tsconfig)).toStrictEqual( + STRICT_LISTING.map(([moduleResolution, module]) => + module === undefined + ? { strict: true, moduleResolution } + : { strict: true, moduleResolution, module }, + ), + ); + expect( + STRICT_DEFAULT_OPTION_SETS.every((set) => set.kind === "strict defaults"), + ).toBe(true); + expect(INITIALIZED_PROJECT_OPTION_SET.tsconfig).toStrictEqual( + INITIALIZED_LISTING, + ); + expect(INITIALIZED_PROJECT_OPTION_SET.kind).toBe( + "initialized-project options", + ); + const initWriter = ( + ts as unknown as { + generateTSConfig(options: ts.CompilerOptions, newLine: string): string; + } + ).generateTSConfig({}, LF); + const written = ts.parseConfigFileTextToJson("tsconfig.json", initWriter); + expect(written.error).toBeUndefined(); + expect( + (written.config as { compilerOptions: unknown }).compilerOptions, + ).toStrictEqual(INITIALIZED_LISTING); + expect(COVERED_OPTION_SETS).toStrictEqual([ + ...STRICT_DEFAULT_OPTION_SETS, + INITIALIZED_PROJECT_OPTION_SET, + ]); + for (const set of COVERED_OPTION_SETS) { + expect(set.compilerOptions, set.name).toStrictEqual(expectedOptions(set)); + } + const esModule: Record<ProjectKind, readonly string[]> = { + "es-module": [".ts", ".mts", ".tsx"], + commonjs: [".mts"], + "no-manifest": [".mts"], + }; + for (const project of PROJECT_KINDS) { + for (const extension of COVERED_EXTENSIONS) { + const covering = esModule[project].includes(extension) + ? COVERED_OPTION_SETS + : STRICT_DEFAULT_OPTION_SETS; + expect(compilesAsEsModule(project, extension)).toBe( + esModule[project].includes(extension), + ); + expect( + COVERED_SETUPS.filter( + (setup) => setup.project === project && setup.extension === extension, + ).map((setup) => setup.optionSet), + `${project} ${extension}`, + ).toStrictEqual(covering); + } + expect(coveredSetupsOf(project)).toStrictEqual( + COVERED_SETUPS.filter((setup) => setup.project === project), + ); + } + expect(new Set(COVERED_SETUPS.map((setup) => setup.label)).size).toBe(173); +}); + +test("every covered setup's program carries exactly its set's options, read back from the program; a conforming stand-in's valid file type-checks and its unknown-key twin fails to type-check, paired, in all 173 setups, through the declaration file each setup resolves (TEST-SPEC §7.6 Covered setups, Verdict, Pairing)", async () => { + let judged = 0; + for (const project of PROJECT_KINDS) { + const context = `the conforming stand-in in the ${project} project`; + const { staging, placement } = await stagedProject( + STAND_INS.conforming, + project, + context, + ); + const files = await stageCoveredFiles({ + staging, + directory: PROJECT_DIR, + project, + placement, + alone: true, + files: [validFile(placement.name), unknownKeyFile(placement.name)], + context, + }); + expect(files.setups).toStrictEqual(coveredSetupsOf(project)); + for (const setup of files.setups) { + const [valid, arm] = judgedPair(files, setup); + expect(valid.judged, setup.label).toBe("batched"); + expect(valid.compilerOptions, setup.label).toStrictEqual( + expectedOptions(setup.optionSet), + ); + expect(valid.file.endsWith(setup.extension), setup.label).toBe(true); + assertTypeChecks(valid, context); + assertShapeViolation(valid, arm, context); + expect( + arm.errors.every((error) => error.origin === "configuration file"), + setup.label, + ).toBe(true); + const packageFiles = valid.programFiles.filter((file) => + insideCopy(placement, file), + ); + expect(packageFiles, setup.label).toStrictEqual([ + `${placement.copy.split(path.sep).join("/")}/${resolvedDeclaration(setup)}`, + ]); + expect( + valid.programFiles.filter( + (file) => + file !== valid.file && + !isLibrary(file) && + !insideCopy(placement, file), + ), + setup.label, + ).toStrictEqual([]); + expect(valid.programFiles.some(isLibrary), setup.label).toBe(true); + judged += 1; + } + } + expect(judged).toBe(COVERED_SETUP_COUNT); +}); + +test("an error only in the package's declaration file: the valid file does not type-check under the strict defaults, yet no error is located in the configuration file; the initialized set, skipLibCheck on, admits it (TEST-SPEC §7.6 Verdict)", async () => { + const project: ProjectKind = "es-module"; + const context = "the declaration-error stand-in"; + const { staging, placement } = await stagedProject( + STAND_INS.declarationError, + project, + context, + ); + const files = await stageCoveredFiles({ + staging, + directory: PROJECT_DIR, + project, + placement, + alone: true, + files: [validFile(placement.name), unknownKeyFile(placement.name)], + context, + }); + for (const setup of files.setups) { + const [valid] = judgedPair(files, setup); + if (setup.optionSet === INITIALIZED_PROJECT_OPTION_SET) { + assertTypeChecks(valid, context); + continue; + } + expect(valid.typeChecks, setup.label).toBe(false); + expect(valid.failsToTypeCheck, setup.label).toBe(false); + expect(valid.errors.length, setup.label).toBeGreaterThan(0); + for (const error of valid.errors) { + expect(error.origin, setup.label).toBe("another file"); + expect( + error.file !== undefined && insideCopy(placement, error.file), + setup.label, + ).toBe(true); + } + expect(() => { + assertTypeChecks(valid, context); + }).toThrow(HarnessAssertionError); + } +}); + +test("the paired verdict fails diagnosed where the valid twin does not type-check (an error in the package's declaration file, S-7's stub package) and where the arm does not fail to type-check (a permissive package); verdicts of different setups pair as a misuse (TEST-SPEC §7.6 Pairing)", async () => { + const project: ProjectKind = "es-module"; + const strictSetup = setupOf(project, ".ts", strictSet("node10")); + const requireSetup = setupOf( + project, + ".cts", + strictSet("nodenext", "nodenext"), + ); + const setups = [ + strictSetup, + requireSetup, + setupOf(project, ".mts", INITIALIZED_PROJECT_OPTION_SET), + ]; + const judgeIn = async ( + packageDir: string, + context: string, + ): Promise<{ + readonly files: CoveredFiles; + readonly placement: Placement; + }> => { + const { staging, placement } = await stagedProject( + packageDir, + project, + context, + ); + const files = await stageCoveredFiles({ + staging, + directory: PROJECT_DIR, + project, + placement, + alone: true, + files: [validFile(placement.name), unknownKeyFile(placement.name)], + setups, + context, + }); + return { files, placement }; + }; + const broken = await judgeIn(STAND_INS.declarationError, "declaration error"); + const [brokenValid, brokenArm] = judgedPair(broken.files, strictSetup); + expect(brokenArm.failsToTypeCheck).toBe(true); + expect(() => { + assertShapeViolation(brokenValid, brokenArm, "declaration error"); + }).toThrow(/Pairing/); + expect(() => { + assertShapeViolation(brokenValid, brokenArm, "declaration error"); + }).toThrow(HarnessAssertionError); + const permissive = await judgeIn(STAND_INS.permissive, "permissive"); + const stub = await judgeIn(STAND_INS.stub, "stub"); + for (const setup of setups) { + const [valid, arm] = judgedPair(permissive.files, setup); + assertTypeChecks(valid, "permissive"); + expect(arm.typeChecks, setup.label).toBe(true); + expect(() => { + assertShapeViolation(valid, arm, "permissive"); + }).toThrow(/does not fail to type-check/); + const [stubValid, stubArm] = judgedPair(stub.files, setup); + expect(stubValid.failsToTypeCheck, setup.label).toBe(true); + expect(() => { + assertTypeChecks(stubValid, "stub"); + }).toThrow(HarnessAssertionError); + expect(() => { + assertShapeViolation(stubValid, stubArm, "stub"); + }).toThrow(/Pairing/); + } + const [first] = judgedPair(permissive.files, strictSetup); + const [, second] = judgedPair(permissive.files, requireSetup); + let misuse: unknown; + try { + assertShapeViolation(first, second, "across setups"); + } catch (error) { + misuse = error; + } + expect(misuse).toBeInstanceOf(Error); + expect(misuse).not.toBeInstanceOf(HarnessAssertionError); +}); + +/** The sample of setups the sharing is compared on (module header). */ +const SAMPLE: readonly CoveredSetup[] = [ + setupOf("es-module", ".ts", strictSet("node10")), + setupOf("es-module", ".tsx", INITIALIZED_PROJECT_OPTION_SET), + setupOf("es-module", ".cts", strictSet("nodenext", "nodenext")), + setupOf("commonjs", ".mts", strictSet("node16", "node18")), + setupOf("commonjs", ".ts", strictSet("nodenext", "node20")), + setupOf("no-manifest", ".cts", strictSet("bundler", "es2015")), + setupOf("no-manifest", ".tsx", strictSet("bundler", "preserve")), + setupOf("no-manifest", ".mts", INITIALIZED_PROJECT_OPTION_SET), +]; + +test("the driver's sharing reads every verdict its reference reading does, each file's export listing included — one root, nothing shared but parsed libraries — on a sample of setups, a package whose global augmentation puts errors inside a library among them (helpers/module-channel-ts.ts header)", async () => { + for (const project of PROJECT_KINDS) { + const setups = SAMPLE.filter((setup) => setup.project === project); + for (const packageDir of [ + STAND_INS.conforming, + STAND_INS.globalAugmenting, + ]) { + const context = `${path.basename(packageDir)} in the ${project} project`; + const { staging, placement } = await stagedProject( + packageDir, + project, + context, + ); + const staged = [ + validFile(placement.name), + unknownKeyFile(placement.name), + aliasedFile(placement.name), + wrongKindFile(placement.name), + ]; + const files = await stageCoveredFiles({ + staging, + directory: PROJECT_DIR, + project, + placement, + alone: true, + listExports: true, + files: staged, + setups, + context, + }); + for (const setup of setups) { + const verdicts = files.judge(setup); + expect( + verdicts.map((verdict) => verdict.judged), + setup.label, + ).toStrictEqual(staged.map(() => "batched")); + for (const verdict of verdicts) { + expect( + verdict.exportListing?.exports.map((entry) => entry.name), + `${context}, ${verdict.label}, ${setup.label}: ` + + describeExportListing(verdict.exportListing), + ).toStrictEqual(["defineConfig"]); + } + for (const verdict of verdicts) { + const reference = files.judgeUnshared(setup, verdict.label); + expect(reference.judged).toBe("unshared"); + expect( + reading(verdict), + `${context}, ${verdict.label}, ${setup.label}`, + ).toStrictEqual(reading(reference)); + } + const [valid, arm, aliased, wrongKind] = verdicts; + if ( + valid === undefined || + arm === undefined || + aliased === undefined || + wrongKind === undefined + ) { + throw new Error("four verdicts expected"); + } + const augmentedLibraries = + packageDir === STAND_INS.globalAugmenting && + setup.optionSet !== INITIALIZED_PROJECT_OPTION_SET; + if (augmentedLibraries) { + expect(valid.typeChecks, setup.label).toBe(false); + expect(valid.failsToTypeCheck, setup.label).toBe(false); + expect( + valid.errors.some( + (error) => error.file !== undefined && isLibrary(error.file), + ), + setup.label, + ).toBe(true); + } else { + assertTypeChecks(valid, context); + assertTypeChecks(aliased, context); + assertShapeViolation(valid, arm, context); + assertShapeViolation(valid, wrongKind, context); + } + } + } + } +}); + +test("a batch whose files' imports bring in different files, or one of whose files contributes to the global scope or augments a module, is judged file by file, each verdict its reference reading's, a module augmentation reaching its own file's export listing alone (helpers/module-channel-ts.ts header)", async () => { + const project: ProjectKind = "es-module"; + const context = "file-by-file batches"; + const { staging, placement } = await stagedProject( + STAND_INS.conforming, + project, + context, + ); + await staging.writeFile( + `${PROJECT_DIR}/covered-helper.ts`, + lines('export const pattern = "specs/*.mdx";'), + ); + const importing: CoveredFile = { + label: "a file importing a helper beside it", + text: lines( + `import { defineConfig } from ${JSON.stringify(placement.name)};`, + 'import { pattern } from "./covered-helper.js";', + "", + "export default defineConfig({ groups: { product: [pattern] } });", + ), + }; + const script: CoveredFile = { + label: "a file importing nothing", + text: lines("declare const scriptGlobal: number;"), + }; + const augmenting: CoveredFile = { + label: "a file augmenting the global scope", + text: lines( + `import { defineConfig } from ${JSON.stringify(placement.name)};`, + "", + "declare global {", + " var augmentedGlobal: number;", + "}", + "", + "export default defineConfig({ groups: { product: [] } });", + ), + }; + const moduleAugmenting: CoveredFile = { + label: "a file augmenting the package's module", + text: lines( + `import { defineConfig } from ${JSON.stringify(placement.name)};`, + "", + `declare module ${JSON.stringify(placement.name)} {`, + " export const augmentedExport: number;", + "}", + "", + "export default defineConfig({ groups: { product: [] } });", + ), + }; + const setups = [ + setupOf(project, ".ts", strictSet("node10")), + setupOf(project, ".ts", INITIALIZED_PROJECT_OPTION_SET), + ]; + for (const [label, extra] of [ + ["imports", importing], + ["script", script], + ["augmenting", augmenting], + ["augmenting a module", moduleAugmenting], + ] as const) { + const files = await stageCoveredFiles({ + staging, + directory: PROJECT_DIR, + project, + placement, + listExports: label === "augmenting a module", + files: [validFile(placement.name), extra], + setups, + context: `${context}, ${label}`, + }); + for (const setup of setups) { + const verdicts = files.judge(setup); + expect( + verdicts.map((verdict) => verdict.judged), + `${label}, ${setup.label}`, + ).toStrictEqual(["own program", "own program"]); + for (const verdict of verdicts) { + expect( + reading(verdict), + `${verdict.label}, ${setup.label}`, + ).toStrictEqual(reading(files.judgeUnshared(setup, verdict.label))); + } + const [valid, other] = verdicts; + if (valid === undefined || other === undefined) + throw new Error("two verdicts"); + assertTypeChecks(valid, context); + expect( + valid.programFiles.some((file) => file.endsWith("/covered-helper.ts")), + ).toBe(false); + assertTypeChecks(other, context); + expect( + other.programFiles.some((file) => file.endsWith("/covered-helper.ts")), + ).toBe(label === "imports"); + expect( + other.programFiles.some((file) => insideCopy(placement, file)), + ).toBe(label !== "script"); + if (label === "augmenting a module") { + expect( + [valid, other].map((verdict) => + verdict.exportListing?.exports.map((entry) => entry.name), + ), + `${label}, ${setup.label}: the augmentation reaches its own ` + + `program's listing alone`, + ).toStrictEqual([ + ["defineConfig"], + ["augmentedExport", "defineConfig"], + ]); + } + } + } +}); + +/** A staged program-condition vector: extra files beside the placement. */ +async function conditionVector( + extra: Readonly<Record<string, string>>, + context: string, +): Promise<CoveredFiles> { + const project: ProjectKind = "es-module"; + const { staging, placement } = await stagedProject( + STAND_INS.conforming, + project, + context, + ); + for (const [rel, text] of Object.entries(extra)) { + await staging.writeFile(`${PROJECT_DIR}/${rel}`, text); + } + return stageCoveredFiles({ + staging, + directory: PROJECT_DIR, + project, + placement, + files: [validFile(placement.name), unknownKeyFile(placement.name)], + setups: [ + setupOf(project, ".ts", strictSet("node10")), + setupOf(project, ".ts", INITIALIZED_PROJECT_OPTION_SET), + ], + context, + }); +} + +/** Expect `judge` to refuse the setup as a program-condition violation. */ +function expectRefused( + files: CoveredFiles, + setup: CoveredSetup, + reason: RegExp, +): void { + let refused: unknown; + try { + files.judge(setup); + } catch (error) { + refused = error; + } + expect(refused, setup.label).toBeInstanceOf(HarnessStagingError); + expect(String(refused), setup.label).toMatch( + /program condition does not hold/, + ); + expect(String(refused), setup.label).toMatch(reason); + let unshared: unknown; + try { + files.judgeUnshared(setup, "the valid file"); + } catch (error) { + unshared = error; + } + expect(unshared, setup.label).toBeInstanceOf(HarnessStagingError); +} + +test("SPEC 7.6's program condition, read from TypeScript's include reasons: an @types package included automatically, a library an installed package replaces, and a module TypeScript imports implicitly are refused as harness errors where they enter the program, and admitted where they do not (TEST-SPEC §7.6 Placement; SPEC 7.6 Covered setups, Program)", async () => { + const [strict, initialized] = [ + setupOf("es-module", ".ts", strictSet("node10")), + setupOf("es-module", ".ts", INITIALIZED_PROJECT_OPTION_SET), + ]; + const automatic = await conditionVector( + { + "node_modules/@types/stray/index.d.ts": lines( + "declare var strayGlobal: number;", + ), + }, + "an automatic @types package", + ); + expectRefused( + automatic, + strict, + /included automatically as the type package stray/, + ); + const [kept] = automatic.judge(initialized); + if (kept === undefined) throw new Error("a verdict expected"); + assertTypeChecks(kept, "types [] keeps the @types package out"); + expect(kept.programFiles.some((file) => file.includes("/@types/"))).toBe( + false, + ); + const replaced = await conditionVector( + { + "node_modules/@typescript/lib-es5/package.json": lines( + JSON.stringify({ + name: "@typescript/lib-es5", + version: "1.0.0", + types: "./index.d.ts", + }), + ), + "node_modules/@typescript/lib-es5/index.d.ts": lines( + "interface Array<T> { length: number }", + ), + }, + "a replaced library", + ); + expectRefused(replaced, strict, /an installed package replaces it/); + expectRefused(replaced, initialized, /an installed package replaces it/); + const implicit = await conditionVector( + { + "node_modules/react/package.json": lines( + JSON.stringify({ + name: "react", + version: "1.0.0", + types: "./index.d.ts", + exports: { + ".": { types: "./index.d.ts" }, + "./jsx-runtime": { types: "./jsx-runtime.d.ts" }, + }, + }), + ), + "node_modules/react/index.d.ts": lines("export {};"), + "node_modules/react/jsx-runtime.d.ts": lines( + "export declare const jsx: unknown;", + ), + }, + "a module imported implicitly", + ); + expectRefused(implicit, initialized, /import TypeScript synthesizes/); + const [admitted] = implicit.judge(strict); + if (admitted === undefined) throw new Error("a verdict expected"); + assertTypeChecks(admitted, "no jsx: nothing imported implicitly"); +}); + +test("misuses are plain errors: no file, a duplicate label, a setup of another project, a setup the files were not staged for, and an export listing asked of a file holding no import declaration (helpers/module-channel-ts.ts)", async () => { + const project: ProjectKind = "commonjs"; + const context = "misuses"; + const { staging, placement } = await stagedProject( + STAND_INS.conforming, + project, + context, + ); + const request = { + staging, + directory: PROJECT_DIR, + project, + placement, + context, + }; + const misuse = async (run: () => Promise<unknown>): Promise<unknown> => { + try { + await run(); + } catch (error) { + return error; + } + return undefined; + }; + for (const error of [ + await misuse(() => stageCoveredFiles({ ...request, files: [] })), + await misuse(() => + stageCoveredFiles({ + ...request, + files: [validFile(placement.name), validFile(placement.name)], + }), + ), + await misuse(() => + stageCoveredFiles({ + ...request, + files: [validFile(placement.name)], + setups: [setupOf("es-module", ".ts", strictSet("node10"))], + }), + ), + ]) { + expect(error).toBeInstanceOf(Error); + expect(error).not.toBeInstanceOf(HarnessAssertionError); + expect(error).not.toBeInstanceOf(HarnessStagingError); + } + const files = await stageCoveredFiles({ + ...request, + files: [validFile(placement.name)], + setups: [setupOf(project, ".ts", strictSet("node10"))], + }); + expect(() => + files.judge(setupOf(project, ".mts", strictSet("node10"))), + ).toThrow(/not among the setups/); + const unlisted = await stageCoveredFiles({ + ...request, + listExports: true, + files: [ + { + label: "a file holding no import declaration", + text: lines("export default 1;"), + }, + ], + setups: [setupOf(project, ".ts", strictSet("node10"))], + }); + let listingMisuse: unknown; + try { + unlisted.judge(setupOf(project, ".ts", strictSet("node10"))); + } catch (error) { + listingMisuse = error; + } + expect(listingMisuse).toBeInstanceOf(Error); + expect(listingMisuse).not.toBeInstanceOf(HarnessAssertionError); + expect(listingMisuse).not.toBeInstanceOf(HarnessStagingError); + expect(String(listingMisuse)).toMatch(/one import declaration/); +}); + +test(`a CommonJS project whose nearest package.json holds "type": "commonjs" is staged with that type declared beside its kind: Reach confirms it for each written file and the valid file type-checks in a CommonJS project's setup; declared without it, the staging is refused before any program exists (TEST-SPEC T7.6-5(c); helpers/module-channel.ts ReachStaging.nearestType)`, async () => { + const project: ProjectKind = "commonjs"; + const context = "a nearest manifest typed commonjs"; + const { staging, placement } = await stagedProject( + STAND_INS.conforming, + "no-manifest", + context, + ); + await staging.writeFile( + `${PROJECT_DIR}/package.json`, + lines(JSON.stringify({ type: "commonjs" })), + ); + const setup = setupOf(project, ".ts", strictSet("node16", "node16")); + const request = { + staging, + directory: PROJECT_DIR, + project, + placement, + alone: true, + files: [validFile(placement.name)], + setups: [setup], + context, + }; + const files = await stageCoveredFiles({ + ...request, + nearestType: "commonjs", + }); + const [verdict] = files.judge(setup); + expect(verdict?.typeChecks, describeErrors(verdict?.errors ?? [])).toBe(true); + let refusal: unknown; + try { + await stageCoveredFiles(request); + } catch (error) { + refusal = error; + } + expect(refusal).toBeInstanceOf(HarnessStagingError); + expect(String(refusal)).toContain("is declared"); +}); + +/** A listed export written out: its meanings, and where it is listed. */ +function listedExport( + name: string, + meanings: { + readonly value?: boolean; + readonly typeOnlyValue?: boolean; + readonly type?: boolean; + readonly namespace?: boolean; + }, + listedIn: ListedExport["listedIn"], +): ListedExport { + return { + name, + value: meanings.value === true, + typeOnlyValue: meanings.typeOnlyValue === true, + type: meanings.type === true, + namespace: meanings.namespace === true, + listedIn, + }; +} + +/** A listing expected, its module named by its path in the package. */ +type ExpectedListing = Omit<ExportListing, "module"> & { + readonly module: string | undefined; +}; + +test("the export listing reads each name with its meanings as TypeScript resolves the file's import, through each entry: a value merged with a namespace, a declared default, values reached only through export type and export type *, an export assignment's members merged with its value's exports and a symbol-keyed member left out, a value typed as a class instance, a stand-in exporting defineConfig alone, and S-7's stub package resolving to no module — each listing its reference reading's (helpers/module-channel-ts.ts header; TEST-SPEC T7.6-1)", async () => { + const project: ProjectKind = "es-module"; + const importEntry = setupOf( + project, + ".mts", + strictSet("nodenext", "nodenext"), + ); + const requireEntry = setupOf( + project, + ".cts", + strictSet("nodenext", "nodenext"), + ); + const cases: readonly (readonly [ + string, + (setup: CoveredSetup) => ExpectedListing, + ])[] = [ + [ + STAND_INS.listingMeanings, + (setup) => + setup === importEntry + ? { + module: "index.d.ts", + exportAssignment: false, + exports: [ + listedExport("default", { value: true }, ["exports"]), + listedExport("defineConfig", { value: true, namespace: true }, [ + "exports", + ]), + listedExport("starValue", { typeOnlyValue: true }, ["exports"]), + listedExport( + "typeOnlyFunction", + { typeOnlyValue: true, namespace: true }, + ["exports"], + ), + ], + } + : { + module: "index.d.cts", + exportAssignment: true, + exports: [ + listedExport("Options", { type: true }, ["exports"]), + listedExport("defineConfig", { value: true, type: true }, [ + "exports", + "export assignment", + ]), + ], + }, + ], + [ + STAND_INS.listingInstance, + () => ({ + module: "index.d.ts", + exportAssignment: true, + exports: [ + listedExport("defineConfig", { value: true }, ["export assignment"]), + ], + }), + ], + [ + STAND_INS.conforming, + (setup) => ({ + module: setup === importEntry ? "index.d.ts" : "index.d.cts", + exportAssignment: false, + exports: [listedExport("defineConfig", { value: true }, ["exports"])], + }), + ], + [ + STAND_INS.stub, + () => ({ module: undefined, exportAssignment: false, exports: [] }), + ], + ]; + for (const [packageDir, expected] of cases) { + const context = `the export listing of ${path.basename(packageDir)}`; + const { staging, placement } = await stagedProject( + packageDir, + project, + context, + ); + const files = await stageCoveredFiles({ + staging, + directory: PROJECT_DIR, + project, + placement, + alone: true, + listExports: true, + files: [validFile(placement.name)], + setups: [importEntry, requireEntry], + context, + }); + const copy = placement.copy.split(path.sep).join("/"); + for (const setup of [importEntry, requireEntry]) { + const [verdict] = files.judge(setup); + const want = expected(setup); + const listing: ExportListing = { + ...want, + module: + want.module === undefined ? undefined : `${copy}/${want.module}`, + }; + expect( + verdict?.exportListing, + `${context}, ${setup.label}: the driver lists ` + + describeExportListing(verdict?.exportListing), + ).toStrictEqual(listing); + expect( + files.judgeUnshared(setup, "the valid file").exportListing, + `${context}, ${setup.label}: the reference reading's listing`, + ).toStrictEqual(listing); + } + } +}); diff --git a/test/self/node-releases.test.ts b/test/self/node-releases.test.ts new file mode 100644 index 00000000..d92fb219 --- /dev/null +++ b/test/self/node-releases.test.ts @@ -0,0 +1,401 @@ +// Self-checks for E-1's Node.js releases, read on the harness side (TEST-SPEC +// 17 preamble: internal self-tests cover harness machinery certification +// does not exercise; E-1, H-11, H-9, S-10; helpers/node-releases.ts). The +// module channel's runtime arms (T7.6-6, T7.6-7, P-17) run on the releases +// E-1 lists, which the environment provisions before the run and the +// harness finds under XSPEC_NODE_RELEASES_DIR; a listed release left +// unprovisioned is a harness error for every run needing it, never a skip +// or a product failure. Asserted here, on stand-in directories alone, so +// the file passes alike with the variable set (CI's harness-self job, +// which provisions the releases) and unset: +// - test/node-releases.json, the one copy CI's provisioning and the harness +// both read, found relative to the module, lists exactly the releases +// E-1's rule yielded when set on 2026-10-29, in order — pinned, so a +// change goes through the normal change process, with E-1; +// - the list is read strictly: anything but a JSON object holding a +// `releases` array of exact versions, at least one and none twice, beside +// at most a string `comment`, is refused, naming the list; +// - the variable is read by the call resolving a release, never at import +// (this file imports the module whatever the environment holds): unset, +// empty, relative, or naming no directory, it is the harness error naming +// the variable; a stand-in directory missing one listed release, or +// holding one whose executable is no file or is not executable, fails the +// whole list's resolution and that release's own, naming the release and +// the path looked at, while every provisioned release still resolves; a +// version the list does not hold is refused even where a directory holds +// it; every such error is a `NodeReleaseError`, never a +// `HarnessAssertionError` (a diagnosed product failure) and never an +// empty answer; +// - a directory of stand-in executables resolves every release in list +// order, each at `<directory>/v<version>/bin/node`. +// Whether a provisioned executable is the release it names — the version +// the running process reports — is S-10's check, made by running it. + +import * as fsp from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; +import { fileURLToPath } from "node:url"; +import { expect, onTestFinished, test, vi } from "vitest"; +import { HarnessAssertionError } from "../helpers/assertions.js"; +import { + NODE_RELEASE_LIST_PATH, + NODE_RELEASES_DIR_VARIABLE, + NodeReleaseError, + parseNodeReleaseList, + readNodeReleaseList, + resolveNodeRelease, + resolveNodeReleases, +} from "../helpers/node-releases.js"; +import type { NodeReleaseFault } from "../helpers/node-releases.js"; + +/** + * E-1's list as its rule yielded it, set on 2026-10-29 (TEST-SPEC E-1): + * 22.0.0, the 22 line's first release; 22.11.0, the last on which + * `require` cannot load an ES module without a flag; 22.12.0, the first on + * which it can; 22.23.4, the line's newest; and the newest of each later + * line still supported upstream, 24 and 26. + */ +const E1_RELEASES = [ + "22.0.0", + "22.11.0", + "22.12.0", + "22.23.4", + "24.22.2", + "26.13.0", +] as const; + +/** A stand-in release executable: a script that does nothing. */ +const STAND_IN_EXECUTABLE = `#!/bin/sh +exit 0 +`; + +/** A fresh, empty directory of this test's own, removed once it ends. */ +async function freshDirectory(): Promise<string> { + const directory = await fsp.mkdtemp( + path.join(os.tmpdir(), "xspec-node-releases-"), + ); + onTestFinished(() => fsp.rm(directory, { recursive: true, force: true })); + return directory; +} + +/** Where a release's executable lies under `directory`. */ +function executableUnder(directory: string, version: string): string { + return path.join(directory, `v${version}`, "bin", "node"); +} + +/** + * A directory — `into`, else a fresh one — holding a stand-in executable, + * mode 0755, for each of `versions` where the provisioning script installs + * it. + */ +async function standInReleases( + versions: readonly string[], + into?: string, +): Promise<string> { + const directory = into ?? (await freshDirectory()); + for (const version of versions) { + const executable = executableUnder(directory, version); + await fsp.mkdir(path.dirname(executable), { recursive: true }); + await fsp.writeFile(executable, STAND_IN_EXECUTABLE); + await fsp.chmod(executable, 0o755); + } + return directory; +} + +/** The environment naming `directory` as the releases' directory. */ +function naming(directory: string): Record<string, string> { + return { [NODE_RELEASES_DIR_VARIABLE]: directory }; +} + +/** What `run` threw (a test failure naming `what` where it threw nothing). */ +function thrownBy(run: () => unknown, what: string): unknown { + try { + run(); + } catch (error) { + return error; + } + throw new Error(`expected ${what} to throw, got a return`); +} + +/** What `pending` rejected with (a test failure where it resolved). */ +async function rejectionOf(pending: Promise<unknown>): Promise<unknown> { + try { + await pending; + } catch (error) { + return error; + } + throw new Error("expected a rejection, got a resolution"); +} + +/** + * `error` is the harness error of `fault` (never a diagnosed product + * failure) whose message matches `pattern` and names every one of `names`. + */ +function expectReleaseError( + error: unknown, + fault: NodeReleaseFault, + pattern: RegExp, + names: readonly string[] = [], +): NodeReleaseError { + expect(error).toBeInstanceOf(NodeReleaseError); + expect(error).not.toBeInstanceOf(HarnessAssertionError); + const releaseError = error as NodeReleaseError; + expect(releaseError.fault, releaseError.message).toBe(fault); + expect(releaseError.message).toMatch(/^harness error [(]H-11[)]: /); + expect(releaseError.message).toMatch(pattern); + for (const name of names) expect(releaseError.message).toContain(name); + return releaseError; +} + +test("E-1's release list: test/node-releases.json, found relative to the harness module, lists exactly the releases E-1's rule yielded when set on 2026-10-29 — 22.0.0, 22.11.0, 22.12.0, 22.23.4, 24.22.2, 26.13.0 — in order", async () => { + expect(NODE_RELEASE_LIST_PATH).toBe( + fileURLToPath(new URL("../node-releases.json", import.meta.url)), + ); + expect(path.isAbsolute(NODE_RELEASE_LIST_PATH)).toBe(true); + expect(await readNodeReleaseList()).toEqual(E1_RELEASES); +}); + +test("E-1's release list is read strictly: anything but one JSON object holding a `releases` array of exact major.minor.patch versions, at least one and none twice, beside at most a string `comment`, is the harness error naming the list — never a shorter list", async () => { + const source = "/stand-in/node-releases.json"; + expect(parseNodeReleaseList('{"releases":["1.2.3"]}', source)).toEqual([ + "1.2.3", + ]); + expect( + parseNodeReleaseList( + '{"comment":"a note","releases":["0.0.0","10.20.30","22.0.0"]}', + source, + ), + ).toEqual(["0.0.0", "10.20.30", "22.0.0"]); + const refusals: readonly (readonly [string, RegExp])[] = [ + ["", /is not JSON/], + ['{"releases":["22.0.0"]', /is not JSON/], + ["[]", /not a JSON object/], + ["null", /not a JSON object/], + ['"22.0.0"', /not a JSON object/], + ["{}", /holds no "releases"/], + ['{"comment":"a note"}', /holds no "releases"/], + ['{"releases":"22.0.0"}', /as its "releases", not an array/], + ['{"releases":{"0":"22.0.0"}}', /as its "releases", not an array/], + ['{"releases":[]}', /lists no release/], + ['{"releases":[22]}', /lists 22 as release 1, not an exact/], + ['{"releases":[null]}', /lists null as release 1, not an exact/], + ['{"releases":["22.0.0","22"]}', /lists "22" as release 2, not an exact/], + ['{"releases":["22.0"]}', /not an exact/], + ['{"releases":["22.0.0.1"]}', /not an exact/], + ['{"releases":["v22.0.0"]}', /not an exact/], + ['{"releases":["22.0.0-rc.1"]}', /not an exact/], + ['{"releases":["22.x.0"]}', /not an exact/], + ['{"releases":["022.0.0"]}', /not an exact/], + ['{"releases":["22.00.0"]}', /not an exact/], + ['{"releases":[" 22.0.0"]}', /not an exact/], + ['{"releases":["22.0.0 "]}', /not an exact/], + [ + '{"releases":["22.0.0","24.0.0","22.0.0"]}', + /lists the release 22[.]0[.]0 twice/, + ], + ['{"releases":["22.0.0"],"release":["24.0.0"]}', /holds the key "release"/], + ['{"releases":["22.0.0"],"comment":1}', /holds 1 as its "comment"/], + ]; + for (const [text, pattern] of refusals) { + const error = expectReleaseError( + thrownBy( + () => parseNodeReleaseList(text, source), + `reading the list ${JSON.stringify(text)}`, + ), + "list", + pattern, + [source], + ); + expect(error.releases).toEqual([]); + } + // A list that cannot be read is the same harness error. + const directory = await freshDirectory(); + const absent = path.join(directory, "node-releases.json"); + expectReleaseError( + await rejectionOf(readNodeReleaseList(absent)), + "list", + /cannot be read [(]ENOENT/, + [absent], + ); + expectReleaseError( + await rejectionOf(resolveNodeReleases({ listPath: absent })), + "list", + /cannot be read [(]ENOENT/, + [absent], + ); +}); + +test("XSPEC_NODE_RELEASES_DIR unset, empty, relative, or naming no directory is the harness error naming the variable, for one release's resolution and the whole list's alike — never a skip, an empty answer, or a diagnosed failure", async () => { + const scratch = await freshDirectory(); + const absent = path.join(scratch, "absent"); + const file = path.join(scratch, "file"); + await fsp.writeFile(file, ""); + const cases: readonly (readonly [ + Readonly<Record<string, string | undefined>>, + RegExp, + readonly string[], + ])[] = [ + [{}, /XSPEC_NODE_RELEASES_DIR is unset/, []], + [ + { [NODE_RELEASES_DIR_VARIABLE]: undefined }, + /XSPEC_NODE_RELEASES_DIR is unset/, + [], + ], + [naming(""), /XSPEC_NODE_RELEASES_DIR is empty/, []], + [ + naming("node-releases"), + /XSPEC_NODE_RELEASES_DIR is "node-releases", not an absolute path/, + [], + ], + [naming(absent), /names no directory [(]ENOENT/, [absent]], + [naming(file), /names a file, not a directory/, [file]], + ]; + for (const [environment, pattern, names] of cases) { + const whole = expectReleaseError( + await rejectionOf(resolveNodeReleases({ environment })), + "directory", + pattern, + [NODE_RELEASES_DIR_VARIABLE, ...names, ...E1_RELEASES], + ); + expect(whole.releases).toEqual([]); + expectReleaseError( + await rejectionOf(resolveNodeRelease("22.11.0", { environment })), + "directory", + pattern, + [NODE_RELEASES_DIR_VARIABLE, "the Node.js release 22.11.0", ...names], + ); + } +}); + +test("the variable is read from the process environment by the call resolving a release, never at import: unset there, the call fails naming it; set there, the call resolves under it", async () => { + onTestFinished(() => { + vi.unstubAllEnvs(); + }); + vi.stubEnv(NODE_RELEASES_DIR_VARIABLE, undefined); + expectReleaseError( + await rejectionOf(resolveNodeReleases()), + "directory", + /XSPEC_NODE_RELEASES_DIR is unset/, + ); + expectReleaseError( + await rejectionOf(resolveNodeRelease("26.13.0")), + "directory", + /XSPEC_NODE_RELEASES_DIR is unset/, + ); + const directory = await standInReleases(E1_RELEASES); + vi.stubEnv(NODE_RELEASES_DIR_VARIABLE, directory); + expect(await resolveNodeRelease("26.13.0")).toEqual({ + version: "26.13.0", + executable: executableUnder(directory, "26.13.0"), + }); + expect( + (await resolveNodeReleases()).map((release) => release.version), + ).toEqual(E1_RELEASES); +}); + +test("a stand-in directory missing one listed release is the harness error naming that release and the path looked at, for the whole list's resolution and that release's own, while each provisioned release still resolves", async () => { + const missing = "22.12.0"; + const provisioned = E1_RELEASES.filter((version) => version !== missing); + const directory = await standInReleases(provisioned); + const environment = naming(directory); + const lookedAt = executableUnder(directory, missing); + const whole = expectReleaseError( + await rejectionOf(resolveNodeReleases({ environment })), + "release", + /the Node.js release 22[.]12[.]0 is not provisioned under XSPEC_NODE_RELEASES_DIR=/, + [directory, `${lookedAt} is absent (ENOENT`], + ); + expect(whole.releases).toEqual([missing]); + const own = expectReleaseError( + await rejectionOf(resolveNodeRelease(missing, { environment })), + "release", + /the Node.js release 22[.]12[.]0 is not provisioned/, + [lookedAt], + ); + expect(own.releases).toEqual([missing]); + for (const version of provisioned) { + expect(await resolveNodeRelease(version, { environment })).toEqual({ + version, + executable: executableUnder(directory, version), + }); + } +}); + +test("a listed release whose executable is no file, or a file not executable, is not provisioned: the harness error names each such release and the path looked at", async () => { + const directory = await standInReleases( + E1_RELEASES.filter( + (version) => version !== "22.0.0" && version !== "24.22.2", + ), + ); + const environment = naming(directory); + // 22.0.0's bin/node is a directory; 24.22.2's a file of mode 0644. + const directoryInstead = executableUnder(directory, "22.0.0"); + await fsp.mkdir(directoryInstead, { recursive: true }); + const notExecutable = executableUnder(directory, "24.22.2"); + await fsp.mkdir(path.dirname(notExecutable), { recursive: true }); + await fsp.writeFile(notExecutable, STAND_IN_EXECUTABLE); + await fsp.chmod(notExecutable, 0o644); + const whole = expectReleaseError( + await rejectionOf(resolveNodeReleases({ environment })), + "release", + /the Node.js releases 22[.]0[.]0, 24[.]22[.]2 are not provisioned/, + [ + `${directoryInstead} is a directory, not a file`, + `${notExecutable} is not executable by this process (EACCES`, + ], + ); + expect(whole.releases).toEqual(["22.0.0", "24.22.2"]); + expectReleaseError( + await rejectionOf(resolveNodeRelease("22.0.0", { environment })), + "release", + /is a directory, not a file/, + [directoryInstead], + ); + expectReleaseError( + await rejectionOf(resolveNodeRelease("24.22.2", { environment })), + "release", + /is not executable by this process/, + [notExecutable], + ); +}); + +test("a version E-1's list does not hold is refused, naming it, even where the directory holds it: no run exercises an unlisted release", async () => { + const directory = await standInReleases([...E1_RELEASES, "22.1.0"]); + const environment = naming(directory); + for (const version of ["22.1.0", "v22.0.0", "22"]) { + const error = expectReleaseError( + await rejectionOf(resolveNodeRelease(version, { environment })), + "list", + /is not listed in E-1's release list/, + [`the Node.js release ${version}`, NODE_RELEASE_LIST_PATH], + ); + expect(error.releases).toEqual([version]); + } +}); + +test("a directory of stand-in executables resolves every release E-1 lists, in list order, each at <directory>/v<version>/bin/node", async () => { + const directory = await standInReleases(E1_RELEASES); + const releases = await resolveNodeReleases({ + environment: naming(directory), + }); + expect(releases).toEqual( + E1_RELEASES.map((version) => ({ + version, + executable: executableUnder(directory, version), + })), + ); + // Named through a symbolic link to it, a directory still: each executable + // as spelled through the link. Link and directory share a fresh directory. + const scratch = await freshDirectory(); + const target = path.join(scratch, "provisioned"); + await fsp.mkdir(target); + await standInReleases(E1_RELEASES, target); + const link = path.join(scratch, "releases"); + await fsp.symlink(target, link); + expect(await resolveNodeReleases({ environment: naming(link) })).toEqual( + E1_RELEASES.map((version) => ({ + version, + executable: executableUnder(link, version), + })), + ); +}); diff --git a/test/self/p17-fixed-seed-draws.test.ts b/test/self/p17-fixed-seed-draws.test.ts new file mode 100644 index 00000000..7d4584d4 --- /dev/null +++ b/test/self/p17-fixed-seed-draws.test.ts @@ -0,0 +1,248 @@ +// P-17's fixed-seed draw guard (TEST-SPEC §16 P-17; §18 E-5; §0 H-10; +// §17 S-9). CI runs P-17 over the fixed seed set (E-5), so the names and +// placements it stages are a pure function of its generator, the seed set, +// and its registered runs per seed (`P17_RUNS_PER_SEED`; P-17 passes no +// `seeds`). They are replayed here exactly as `checkProperty` draws them — +// `drawFixedSeedTrials`, one sequential PRNG stream per seed — with no +// property body, no package, and no release run (H-8's ordering: the guard +// holds before any product exists). No certification serves the module +// channel, so nothing but this guard keeps a generator change from dropping +// a class P-17 searches silently; it pins, over those draws, each name +// classified by a scanner of its own over N's characters — never by what +// the generator says it drew: +// +// 1. the classes TEST-SPEC P-17 weights the names toward: a `.` in the +// last segment (S then differing from N), an extension TypeScript and +// Node.js read in a specifier after it, a scoped name and an unscoped +// one, a digit-first segment, and a name of 7.6's bound of 214 +// characters; +// 2. the placements and setups each name is crossed with: both placement +// forms, every holding directory (the importing files' own and each of +// its three ancestors up to the staging root), each project kind, each +// covered extension, both option-set kinds, each release E-1 lists, +// and each of Node.js's four routes; +// 3. that every drawn N is a name of 7.6's grammar outside its +// exclusions — no `@types` name, no `@typescript/lib-` name, none of +// the built-in names the generator mends — and that those names cover +// every name of the grammar this harness's own Node.js resolves to a +// built-in module (the drawn release itself confirms each draw, as +// P-17 places N on its runtime arm); +// 4. that every fixed-seed draw passes S-9's per-draw check before any +// product exists, through P-17's own code path (`checkProperty` with +// its `drawSources`), each draw's three files named with its setup's +// extension — P-17 itself stops at its first falsified draw, so its +// later draws reach that check only here. +// +// Should the fixed seeds miss a class, raise `P17_RUNS_PER_SEED` or the +// class's weight; never weaken this. + +import { builtinModules } from "node:module"; +import { expect, test } from "vitest"; +import { + MODULE_NAME_MAX_LENGTH, + moduleNameExclusion, + moduleNameGrammarProblem, + PROJECT_KINDS, +} from "../helpers/module-channel.js"; +import { + COVERED_EXTENSIONS, + COVERED_SETUPS, +} from "../helpers/module-channel-ts.js"; +import { MODULE_ROUTES } from "../helpers/module-channel-node.js"; +import { + checkProperty, + DEFAULT_PROPERTY_SEEDS, + drawFixedSeedTrials, +} from "../helpers/property.js"; +import type { P17Draw } from "../suite/registry/section-16-p17.js"; +import { + genP17Draw, + P17_EXTENSION_SUFFIXES, + P17_IMPORTING_DEPTH, + P17_NODE_BUILT_IN_NAMES, + P17_RELEASE_VERSIONS, + P17_RUNS_PER_SEED, + p17Setup, + stagedP17Sources, +} from "../suite/registry/section-16-p17.js"; + +const DIGITS = "0123456789"; + +/** One replayed draw, labelled with its seed and 1-based trial number. */ +interface Replayed { + readonly label: string; + readonly draw: P17Draw; +} + +const REPLAYED: readonly Replayed[] = drawFixedSeedTrials( + genP17Draw, + P17_RUNS_PER_SEED, +).map((draw, index) => ({ + label: + `seed ${String(DEFAULT_PROPERTY_SEEDS[Math.floor(index / P17_RUNS_PER_SEED)])} ` + + `trial ${String((index % P17_RUNS_PER_SEED) + 1)}`, + draw, +})); + +/** N's segments, as the scanner reads them: its scope, then its name. */ +function segmentsOf(name: string): readonly string[] { + if (!name.startsWith("@")) return [name]; + const slash = name.indexOf("/"); + return [name.slice(1, slash), name.slice(slash + 1)]; +} + +/** N's last segment. */ +function lastSegmentOf(name: string): string { + const segments = segmentsOf(name); + return segments[segments.length - 1] ?? ""; +} + +/** S (SPEC 7.6 Reach): N cut before the first `.` of its last segment. */ +function cutAtLastSegmentDot(name: string): string { + const slash = name.lastIndexOf("/"); + const dot = name.indexOf(".", slash + 1); + return dot < 0 ? name : name.slice(0, dot); +} + +/** The labels of the draws `matches` accepts. */ +function drawsWhere(matches: (draw: P17Draw) => boolean): string[] { + return REPLAYED.filter(({ draw }) => matches(draw)).map(({ label }) => label); +} + +/** Each named class no draw reaches, with the draws reaching the others. */ +function unreached( + classes: Readonly<Record<string, (draw: P17Draw) => boolean>>, +): { readonly missing: string[]; readonly reach: Record<string, number> } { + const reach: Record<string, number> = {}; + for (const [name, matches] of Object.entries(classes)) { + reach[name] = drawsWhere(matches).length; + } + return { + missing: Object.entries(reach) + .filter(([, n]) => n === 0) + .map(([name]) => name), + reach, + }; +} + +test("P-17's fixed-seed draws reach each class TEST-SPEC P-17 weights its names toward: a dotted last segment (S differing from N), an extension-like suffix after it, a scoped and an unscoped name, a digit-first segment, and a 214-character name", () => { + const { missing, reach } = unreached({ + dottedLastSegment: (draw) => + lastSegmentOf(draw.name).includes(".") && + cutAtLastSegmentDot(draw.name) !== draw.name, + undottedLastSegment: (draw) => !lastSegmentOf(draw.name).includes("."), + extensionLikeSuffix: (draw) => + P17_EXTENSION_SUFFIXES.some((suffix) => + lastSegmentOf(draw.name).endsWith(`.${suffix}`), + ), + scoped: (draw) => draw.name.startsWith("@"), + unscoped: (draw) => !draw.name.startsWith("@"), + digitFirstSegment: (draw) => + segmentsOf(draw.name).some((segment) => DIGITS.includes(segment[0]!)), + digitFirstScope: (draw) => + draw.name.startsWith("@") && + DIGITS.includes(segmentsOf(draw.name)[0]![0]!), + boundUnscoped: (draw) => + !draw.name.startsWith("@") && draw.name.length === MODULE_NAME_MAX_LENGTH, + boundScoped: (draw) => + draw.name.startsWith("@") && draw.name.length === MODULE_NAME_MAX_LENGTH, + }); + expect( + missing, + `name classes P-17's fixed seeds never reach; reach: ${JSON.stringify(reach)}`, + ).toEqual([]); +}); + +test("P-17's fixed-seed draws cross the names with both placement forms, every holding directory, each project kind, covered extension, and option-set kind, each release E-1 lists, and each of Node.js's four routes", () => { + const classes: Record<string, (draw: P17Draw) => boolean> = { + copy: (draw) => draw.form === "copy", + symlink: (draw) => draw.form === "symlink", + }; + for (let level = 0; level <= P17_IMPORTING_DEPTH; level += 1) { + classes[`holding ${String(level)} levels up`] = (draw) => + draw.holdingLevel === level; + } + for (const project of PROJECT_KINDS) { + classes[`project ${project}`] = (draw) => + p17Setup(draw).project === project; + } + for (const extension of COVERED_EXTENSIONS) { + classes[`extension ${extension}`] = (draw) => + p17Setup(draw).extension === extension; + } + for (const kind of ["strict defaults", "initialized-project options"]) { + classes[`option set ${kind}`] = (draw) => + p17Setup(draw).optionSet.kind === kind; + } + for (const release of P17_RELEASE_VERSIONS) { + classes[`release ${release}`] = (draw) => draw.release === release; + } + for (const route of MODULE_ROUTES) { + classes[`route ${route}`] = (draw) => draw.route === route; + } + const { missing, reach } = unreached(classes); + expect( + missing, + `placements and setups P-17's fixed seeds never reach; reach: ${JSON.stringify(reach)}`, + ).toEqual([]); + expect(P17_RELEASE_VERSIONS.length).toBeGreaterThan(0); + expect( + REPLAYED.every(({ draw }) => COVERED_SETUPS[draw.setup] !== undefined), + ).toBe(true); +}); + +test("every name P-17 draws at the fixed seeds is a name of 7.6's grammar outside its exclusions — no @types name, no @typescript/lib- name, none of the built-in names it mends — and those names cover every name of the grammar this harness's Node.js resolves to a built-in module", () => { + const violations: string[] = []; + for (const { label, draw } of REPLAYED) { + const shown = `${label}: ${JSON.stringify(draw.name)}`; + const problem = + moduleNameGrammarProblem(draw.name) ?? moduleNameExclusion(draw.name); + if (problem !== null) violations.push(`${shown} ${problem}`); + if (P17_NODE_BUILT_IN_NAMES.includes(draw.name)) { + violations.push(`${shown} is a built-in name`); + } + if (draw.name.length > MODULE_NAME_MAX_LENGTH) { + violations.push(`${shown} is past 7.6's bound`); + } + } + expect(violations).toEqual([]); + const ownBuiltIns = builtinModules.filter( + (name) => moduleNameGrammarProblem(name) === null, + ); + expect(ownBuiltIns.length).toBeGreaterThan(0); + expect( + ownBuiltIns.filter((name) => !P17_NODE_BUILT_IN_NAMES.includes(name)), + "built-in names of 7.6's grammar the generator would draw", + ).toEqual([]); +}); + +test("every fixed-seed P-17 draw passes S-9's per-draw check before any product exists, through P-17's own code path (TEST-SPEC §16 P-17, §17 S-9; E-5 replay at P-17's registered runs per seed)", async () => { + // P-17 as its registration runs it — the generator, the fixed seed set + // (no `seeds`; `env: {}`, so no replay variable intervenes), the + // registered runs per seed, and `drawSources: stagedP17Sources` — with a + // body that only records: checkProperty judges each draw's three files + // before the body runs on it, and a draw failing S-9 rejects the run as a + // harness error naming its seed. + const names: string[] = []; + await checkProperty( + "P-17 installation names (S-9 per-draw replay, no product)", + genP17Draw, + (draw) => { + names.push(draw.name); + }, + { runs: P17_RUNS_PER_SEED, env: {}, drawSources: stagedP17Sources }, + ); + expect(names).toEqual(REPLAYED.map(({ draw }) => draw.name)); + for (const { draw } of REPLAYED) { + const sources = stagedP17Sources(draw); + expect(sources.map(([path]) => path)).toEqual( + Array.from( + { length: 3 }, + () => `covered-file${p17Setup(draw).extension}`, + ), + ); + for (const [, text] of sources) { + expect(String(text)).toContain(`from ${JSON.stringify(draw.name)}`); + } + } +}); diff --git a/test/self/p18-fixed-seed-draws.test.ts b/test/self/p18-fixed-seed-draws.test.ts new file mode 100644 index 00000000..a661fe3c --- /dev/null +++ b/test/self/p18-fixed-seed-draws.test.ts @@ -0,0 +1,467 @@ +// P-18's fixed-seed draw guard (TEST-SPEC §16 P-18; §18 E-5; §0 H-10; +// §17 S-9). CI runs P-18 over the fixed seed set (E-5), so the +// configurations, mutants, and setups it stages are a pure function of its +// generator, the seed set, and its registered runs per seed +// (`P18_RUNS_PER_SEED`; P-18 passes no `seeds`). They are replayed here +// exactly as `checkProperty` draws them — `drawFixedSeedTrials`, one +// sequential PRNG stream per seed — with no property body and no package +// (H-8's ordering: the guard holds before any product exists). No +// certification serves the module channel, so nothing but this guard keeps +// a generator change from dropping a class P-18 searches silently; it pins, +// over those draws, each file classified by reading its rendered text back +// with the harness's TypeScript — the keys, names, comments, binding, and +// data as TypeScript reads them, and the mutant's violation as the +// harness's reading of the type-error class finds it — never by what the +// generator says it drew: +// +// 1. the spellings TEST-SPEC P-18 draws: string-literal and identifier +// keys, a group name spelled each way, keys out of 7's order, each of +// the global `Object` interface's members and `__proto__` as a group +// name, non-identifier group names, an `Object` member or `__proto__` +// as a profile's and as a rule's name, an aliased and an unaliased +// binding, and line and block comments, inside the import declaration +// and inside the argument; +// 2. the forms it draws: an empty glob list; a repeated element in each +// set-read list (`targetTags`, `edgeKinds`, a rule's `kinds`, a +// selector's `tags`); each optional key and field present and absent; +// each selector form; and a kind given for a name of both kinds; +// 3. each member of 7.6's type-error class among the mutants, a violation +// added at a field the draw omits among them, and each project kind, +// covered extension, and option-set kind among the setups; +// 4. that every draw reads back valid under 7 with no violation of the +// class, and its mutant with exactly the drawn one; +// 5. that every fixed-seed draw passes S-9's per-draw check before any +// product exists, through P-18's own code path (`checkProperty` with +// its `drawSources`) — P-18 itself stops at its first falsified draw, +// so its later draws reach that check only here. +// +// Should the fixed seeds miss a class, raise `P18_RUNS_PER_SEED` or the +// class's weight; never weaken this. + +import ts from "typescript-5.9.3"; +import { expect, test } from "vitest"; +import { + CANONICAL_MODULE_NAMES, + PROJECT_KINDS, +} from "../helpers/module-channel.js"; +import { COVERED_EXTENSIONS } from "../helpers/module-channel-ts.js"; +import { + checkProperty, + DEFAULT_PROPERTY_SEEDS, + drawFixedSeedTrials, +} from "../helpers/property.js"; +import type { P18Draw } from "../suite/registry/section-16-p18.js"; +import { + genP18Draw, + isIdentifierName, + P18_RUNS_PER_SEED, + p18Setup, + p18Texts, + stagedP18Sources, +} from "../suite/registry/section-16-p18.js"; +import { + classViolations, + isConfigList, + isConfigObject, + OBJECT_MEMBER_NAMES, + problemsUnder7, + readBack, + scanComments, +} from "../suite/registry/section-7.6.js"; +import type { + ConfigObject, + ConfigValue, + ReadBack, +} from "../suite/registry/section-7.6.js"; + +/** 7's top-level keys, in its order. */ +const TOP_LEVEL_ORDER = ["specs", "code", "markdown", "coverage", "policy"]; + +/** One file read back: its data, keys, comments, and where they stand. */ +interface ReadFile { + readonly read: ReadBack; + readonly aliased: boolean; + readonly commentsInImport: readonly string[]; + readonly commentsInArgument: readonly string[]; + readonly comments: readonly string[]; +} + +/** A replayed draw, labelled with its seed and 1-based trial number. */ +interface Replayed { + readonly label: string; + readonly draw: P18Draw; + readonly valid: ReadFile; + readonly mutant: ReadFile; +} + +/** `text` read back with the harness's TypeScript (section-7.6.ts). */ +function readFile(text: string, label: string): ReadFile { + const read = readBack(text, (detail) => { + throw new Error(`${label}: the rendered file ${detail}`); + }); + const [declaration, exported] = read.source.statements; + if ( + declaration === undefined || + exported === undefined || + !ts.isImportDeclaration(declaration) || + !ts.isExportAssignment(exported) || + !ts.isCallExpression(exported.expression) + ) { + throw new Error(`${label}: no import and default export read back`); + } + const argument = exported.expression.arguments[0]!; + const named = declaration.importClause?.namedBindings; + const specifier = + named !== undefined && ts.isNamedImports(named) + ? named.elements[0] + : undefined; + const scanned = scanComments(text); + const within = (node: ts.Node): string[] => + scanned + .filter( + (comment) => + comment.start > node.getStart(read.source) && comment.end <= node.end, + ) + .map((comment) => comment.text); + return { + read, + aliased: specifier?.propertyName !== undefined, + commentsInImport: within(declaration), + commentsInArgument: within(argument), + comments: scanned.map((comment) => comment.text), + }; +} + +const [NAME] = CANONICAL_MODULE_NAMES; + +const REPLAYED: readonly Replayed[] = drawFixedSeedTrials( + genP18Draw, + P18_RUNS_PER_SEED, +).map((draw, index) => { + const label = + `seed ${String(DEFAULT_PROPERTY_SEEDS[Math.floor(index / P18_RUNS_PER_SEED)])} ` + + `trial ${String((index % P18_RUNS_PER_SEED) + 1)}`; + const texts = p18Texts(draw, NAME); + return { + label, + draw, + valid: readFile(texts.valid, `${label}, the draw`), + mutant: readFile(texts.mutant, `${label}, its mutant`), + }; +}); + +/** The object at `key` of `object`, or an empty one. */ +function objectAt(object: ConfigObject, key: string): ConfigObject { + const value = object.get(key); + return value !== undefined && isConfigObject(value) ? value : new Map(); +} + +/** The objects listed at `key` of `object`. */ +function objectsAt(object: ConfigObject, key: string): ConfigObject[] { + const value = object.get(key); + return value !== undefined && isConfigList(value) + ? value.filter((element) => isConfigObject(element)) + : []; +} + +/** Every rule's two selectors. */ +function selectorsOf(config: ConfigObject): ConfigObject[] { + return objectsAt(config, "policy").flatMap((rule) => + ["from", "to"].map((end) => objectAt(rule, end)), + ); +} + +/** Whether `value` is a list holding some element twice. */ +function repeats(value: ConfigValue | undefined): boolean { + if (value === undefined || !isConfigList(value)) return false; + const strings = value.filter((element) => typeof element === "string"); + return new Set(strings).size < strings.length; +} + +/** The group names of one kind. */ +function groupsOf(config: ConfigObject, key: "specs" | "code"): string[] { + return [...objectAt(config, key).keys()]; +} + +/** Whether `name` is both a spec and a code group's in `config`. */ +function bothKinds( + config: ConfigObject, + name: ConfigValue | undefined, +): boolean { + return ( + typeof name === "string" && + groupsOf(config, "specs").includes(name) && + groupsOf(config, "code").includes(name) + ); +} + +/** Whether `path` names a value or key `config` holds. */ +function holds( + config: ConfigValue, + path: readonly (string | number)[], +): boolean { + let at: ConfigValue | undefined = config; + for (const segment of path) { + if (at === undefined) return false; + if (typeof segment === "number") { + at = isConfigList(at) ? at[segment] : undefined; + } else { + at = isConfigObject(at) ? at.get(segment) : undefined; + } + } + return at !== undefined; +} + +/** Each named class no draw reaches, with the draws reaching each. */ +function unreached( + classes: Readonly<Record<string, (replayed: Replayed) => boolean>>, +): { readonly missing: string[]; readonly reach: Record<string, number> } { + const reach: Record<string, number> = {}; + for (const [name, matches] of Object.entries(classes)) { + reach[name] = REPLAYED.filter(matches).length; + } + return { + missing: Object.entries(reach) + .filter(([, n]) => n === 0) + .map(([name]) => name), + reach, + }; +} + +test("P-18's fixed-seed draws reach each spelling TEST-SPEC P-18 draws: string-literal and identifier keys, a group name spelled each way, keys out of 7's order, each Object member and __proto__ as a group name, non-identifier group names, an Object member or __proto__ as a profile's and a rule's name, an aliased and an unaliased binding, and line and block comments in the import declaration and in the argument", () => { + const config = ({ valid }: Replayed): ConfigObject => valid.read.argument; + const groupKeys = ({ valid }: Replayed) => + valid.read.keys.filter( + (key) => + key.path.length === 1 && + (key.path[0] === "specs" || key.path[0] === "code"), + ); + const classes: Record<string, (replayed: Replayed) => boolean> = { + stringLiteralKey: ({ valid }) => + valid.read.keys.some((key) => key.stringLiteral), + identifierKey: ({ valid }) => + valid.read.keys.some((key) => !key.stringLiteral), + fixedKeyAsStringLiteral: ({ valid }) => + valid.read.keys.some((key) => key.path.length === 0 && key.stringLiteral), + groupNameAsIdentifier: (replayed) => + groupKeys(replayed).some((key) => !key.stringLiteral), + groupNameAsStringLiteral: (replayed) => + groupKeys(replayed).some( + (key) => key.stringLiteral && isIdentifierName(key.key), + ), + topLevelKeysOutOfOrder: (replayed) => { + const keys = [...config(replayed).keys()]; + const sorted = [...keys].sort( + (a, b) => TOP_LEVEL_ORDER.indexOf(a) - TOP_LEVEL_ORDER.indexOf(b), + ); + return keys.join() !== sorted.join(); + }, + nonIdentifierGroupName: (replayed) => + groupKeys(replayed).some((key) => !isIdentifierName(key.key)), + nonAsciiGroupName: (replayed) => + groupKeys(replayed).some((key) => /[^ -~]/.test(key.key)), + objectMemberProfileName: (replayed) => + objectsAt(config(replayed), "coverage").some((profile) => + OBJECT_MEMBER_NAMES.includes(String(profile.get("name"))), + ), + objectMemberRuleName: (replayed) => + objectsAt(config(replayed), "policy").some((rule) => + OBJECT_MEMBER_NAMES.includes(String(rule.get("name"))), + ), + aliased: ({ valid }) => valid.aliased, + unaliased: ({ valid }) => !valid.aliased, + aliasOtherThanDefineConfig: ({ valid }) => + valid.aliased && valid.read.binding !== "defineConfig", + lineComment: ({ valid }) => + valid.comments.some((comment) => comment.startsWith("//")), + blockComment: ({ valid }) => + valid.comments.some((comment) => comment.startsWith("/*")), + commentInImportDeclaration: ({ valid }) => + valid.commentsInImport.length > 0, + commentInArgument: ({ valid }) => valid.commentsInArgument.length > 0, + }; + for (const member of OBJECT_MEMBER_NAMES) { + classes[`group name ${member}`] = (replayed) => + groupKeys(replayed).some((key) => key.key === member); + } + const { missing, reach } = unreached(classes); + expect( + missing, + `spellings P-18's fixed seeds never reach; reach: ${JSON.stringify(reach)}`, + ).toEqual([]); +}); + +test("P-18's fixed-seed draws reach each form TEST-SPEC P-18 draws: an empty glob list, a repeated element in each set-read list, each optional key and field present and absent, each selector form, and a kind given for a name of both kinds", () => { + const config = ({ valid }: Replayed): ConfigObject => valid.read.argument; + const profiles = (replayed: Replayed) => + objectsAt(config(replayed), "coverage"); + const rules = (replayed: Replayed) => objectsAt(config(replayed), "policy"); + const selectors = (replayed: Replayed) => selectorsOf(config(replayed)); + const classes: Record<string, (replayed: Replayed) => boolean> = { + emptyGlobList: (replayed) => + (["specs", "code"] as const).some((key) => + [...objectAt(config(replayed), key).values()].some( + (globs) => isConfigList(globs) && globs.length === 0, + ), + ), + repeatedTargetTags: (replayed) => + profiles(replayed).some((profile) => repeats(profile.get("targetTags"))), + repeatedEdgeKinds: (replayed) => + profiles(replayed).some((profile) => repeats(profile.get("edgeKinds"))), + repeatedRuleKinds: (replayed) => + rules(replayed).some((rule) => repeats(rule.get("kinds"))), + repeatedSelectorTags: (replayed) => + selectors(replayed).some((selector) => repeats(selector.get("tags"))), + profileBoundaryKindForBothKinds: (replayed) => + profiles(replayed).some( + (profile) => + bothKinds(config(replayed), profile.get("boundary")) && + profile.has("boundaryKind"), + ), + selectorKindForBothKinds: (replayed) => + selectors(replayed).some( + (selector) => + bothKinds(config(replayed), selector.get("group")) && + selector.has("kind"), + ), + selectorKindWhereUnambiguous: (replayed) => + selectors(replayed).some( + (selector) => + selector.has("group") && + selector.has("kind") && + !bothKinds(config(replayed), selector.get("group")), + ), + selectorGroupWithoutKind: (replayed) => + selectors(replayed).some( + (selector) => selector.has("group") && !selector.has("kind"), + ), + selectorFiles: (replayed) => + selectors(replayed).some((selector) => selector.has("files")), + selectorTags: (replayed) => + selectors(replayed).some((selector) => selector.has("tags")), + noSpecGroup: (replayed) => groupsOf(config(replayed), "specs").length === 0, + }; + for (const key of ["code", "markdown", "coverage", "policy"]) { + classes[`top-level ${key} present`] = (replayed) => + config(replayed).has(key); + classes[`top-level ${key} absent`] = (replayed) => + !config(replayed).has(key); + } + classes["markdown outDir present"] = (replayed) => + objectAt(config(replayed), "markdown").has("outDir"); + classes["markdown outDir absent"] = (replayed) => + config(replayed).has("markdown") && + !objectAt(config(replayed), "markdown").has("outDir"); + for (const field of ["targetTags", "targets", "boundaryKind", "edgeKinds"]) { + classes[`profile ${field} present`] = (replayed) => + profiles(replayed).some((profile) => profile.has(field)); + classes[`profile ${field} absent`] = (replayed) => + profiles(replayed).some((profile) => !profile.has(field)); + } + classes["rule kinds present"] = (replayed) => + rules(replayed).some((rule) => rule.has("kinds")); + classes["rule kinds absent"] = (replayed) => + rules(replayed).some((rule) => !rule.has("kinds")); + const { missing, reach } = unreached(classes); + expect( + missing, + `forms P-18's fixed seeds never reach; reach: ${JSON.stringify(reach)}`, + ).toEqual([]); +}); + +test("P-18's fixed-seed mutants reach each member of 7.6's type-error class, one added at a field its draw omits among them, and its setups each project kind, covered extension, and option-set kind", () => { + const found = ({ mutant }: Replayed) => classViolations(mutant.read.argument); + const classes: Record<string, (replayed: Replayed) => boolean> = { + addedAtAnOmittedField: (replayed) => + found(replayed).some( + (violation) => + violation.category !== "unknown key" && + violation.category !== "missing required key" && + !holds(replayed.valid.read.argument, violation.path), + ), + }; + for (const category of [ + "unknown key", + "missing required key", + "kind", + "enumeration", + "selector form", + "empty list", + ]) { + classes[`violation ${category}`] = (replayed) => + found(replayed).some((violation) => violation.category === category); + } + for (const project of PROJECT_KINDS) { + classes[`project ${project}`] = ({ draw }) => + p18Setup(draw).project === project; + } + for (const extension of COVERED_EXTENSIONS) { + classes[`extension ${extension}`] = ({ draw }) => + p18Setup(draw).extension === extension; + } + for (const kind of ["strict defaults", "initialized-project options"]) { + classes[`option set ${kind}`] = ({ draw }) => + p18Setup(draw).optionSet.kind === kind; + } + const { missing, reach } = unreached(classes); + expect( + missing, + `violations and setups P-18's fixed seeds never reach; reach: ${JSON.stringify(reach)}`, + ).toEqual([]); +}); + +test("every fixed-seed P-18 draw reads back valid under 7 with no violation of 7.6's type-error class, and its mutant with exactly the one drawn", () => { + const deviations: string[] = []; + for (const { label, draw, valid, mutant } of REPLAYED) { + const problems = problemsUnder7(valid.read.argument); + const inDraw = classViolations(valid.read.argument); + const inMutant = classViolations(mutant.read.argument); + if (problems.length > 0) { + deviations.push(`${label}: the draw is invalid: ${problems.join("; ")}`); + } + if (inDraw.length > 0) { + deviations.push(`${label}: the draw holds ${JSON.stringify(inDraw)}`); + } + if ( + JSON.stringify(inMutant) !== JSON.stringify([draw.mutation.violation]) + ) { + deviations.push( + `${label}: the mutant holds ${JSON.stringify(inMutant)}, not ` + + JSON.stringify([draw.mutation.violation]), + ); + } + } + expect(deviations).toEqual([]); +}); + +test("every fixed-seed P-18 draw passes S-9's per-draw check before any product exists, through P-18's own code path (TEST-SPEC §16 P-18, §17 S-9; E-5 replay at P-18's registered runs per seed)", async () => { + // P-18 as its registration runs it — the generator, the fixed seed set + // (no `seeds`; `env: {}`, so no replay variable intervenes), the + // registered runs per seed, and `drawSources: stagedP18Sources` — with a + // body that only records: checkProperty judges each draw's four files + // (the draw and its mutant beside each candidate N) before the body runs + // on it, and a draw failing S-9 rejects the run as a harness error + // naming its seed. + const labels: string[] = []; + await checkProperty( + "P-18 type contract over generated configurations (S-9 per-draw replay, no product)", + genP18Draw, + (draw) => { + labels.push(draw.mutation.label); + }, + { runs: P18_RUNS_PER_SEED, env: {}, drawSources: stagedP18Sources }, + ); + expect(labels).toEqual(REPLAYED.map(({ draw }) => draw.mutation.label)); + for (const { draw } of REPLAYED) { + const sources = stagedP18Sources(draw); + expect(sources.map(([path]) => path)).toEqual( + Array.from( + { length: 4 }, + () => `covered-file${p18Setup(draw).extension}`, + ), + ); + for (const [index, name] of CANONICAL_MODULE_NAMES.entries()) { + expect(String(sources[index * 2]?.[1])).toContain(`"${name}"`); + } + } +}); diff --git a/test/self/p19-fixed-seed-draws.test.ts b/test/self/p19-fixed-seed-draws.test.ts new file mode 100644 index 00000000..a0c9693c --- /dev/null +++ b/test/self/p19-fixed-seed-draws.test.ts @@ -0,0 +1,405 @@ +// P-19's fixed-seed draw guard (TEST-SPEC §16 P-19; §18 E-5; §0 H-10; +// CERTIFICATIONS.md §CONF-IMPORT, §VIOL-IMPORT-BRACED, §VIOL-IMPORT-SINGLE). +// CI runs P-19 over the fixed seed set (E-5), so the specifiers it stages +// are a pure function of its generator, the seed set, and its registered +// runs per seed (`P19_RUNS_PER_SEED`; P-19 passes no `seeds`). They are +// replayed here exactly as `checkProperty` draws them — +// `drawFixedSeedTrials`, one sequential PRNG stream per seed — with no +// property body and no product (H-8's ordering: the guard holds before any +// product exists). Each CONF-IMPORT violator fails P-19 only on a draw +// reaching the form its deviation refuses, as spelled, and P-19 passes +// against it exactly when no fixed-seed draw reaches that form (C-1 judges +// P-19 at the fixed seeds; §CONF-IMPORT's justification: criterion (a)'s +// reachability case), so the guard pins, over those draws, each classified +// by a scanner of its own over the literal's characters — never by what +// the generator says it drew: +// +// 1. the certified forms: a single-quoted specifier (VIOL-IMPORT-SINGLE), +// and a braced Unicode escape of a code point at or below U+FFFF begun +// by a backslash that itself begins an escape (VIOL-IMPORT-BRACED; +// leading zeros and surrogates count, and both are reached); +// 2. the rest of P-19's search space, so that a generator change cannot +// drop a class silently: double quotes; each text shape and the empty +// string itself; the hexadecimal escape, the four-digit Unicode escape, +// the braced one above U+FFFF, each single-character escape, an escaped +// non-escape character (one beyond ASCII among them), and the NUL +// escape before a non-digit; a line continuation after each line +// terminator the generator draws; a raw U+FFFD and other raw +// non-ASCII code points; the other quote +// character, raw; and an escaped backslash before `u{`, which begins +// no braced escape; +// 3. that each draw's staged configuration — the workspace P-19's body +// creates from it (`p19DrawDecl`), read back — holds the drawn +// spelling's exact UTF-8 bytes, between the shared builder's head and +// tail (helpers/config-import.ts): no decoding, no re-quoting, no +// printer (CONF-IMPORT's staging hazards); +// 4. that every fixed-seed draw passes S-9's per-draw check before any +// product exists, through P-19's own code path (`checkProperty` with +// its `drawSources`) — P-19 itself stops at its first falsified draw, +// so its later draws reach that check only here. +// +// Should the fixed seeds miss a class, raise `P19_RUNS_PER_SEED` or the +// class's weight; never weaken this. + +import { Buffer } from "node:buffer"; +import { expect, test } from "vitest"; +import { + BACKSLASH, + CONFIG_IMPORT_CONFIG_PATH, + CONFIG_IMPORT_HEAD, + CONFIG_IMPORT_TAIL, +} from "../helpers/config-import.js"; +import { + checkProperty, + DEFAULT_PROPERTY_SEEDS, + drawFixedSeedTrials, +} from "../helpers/property.js"; +import { TestWorkspace } from "../helpers/workspace.js"; +import type { P19Draw } from "../suite/registry/section-16-p19.js"; +import { + genP19Draw, + P19_RUNS_PER_SEED, + P19_SHAPES, + P19_SINGLE_ESCAPES, + P19_TERMINATORS, + p19DrawDecl, + spellP19Literal, + stagedP19Sources, +} from "../suite/registry/section-16-p19.js"; + +const cp = (...codes: number[]): string => String.fromCodePoint(...codes); +const LINE_FEED = cp(0x0a); +const CARRIAGE_RETURN = cp(0x0d); +const LINE_SEPARATOR = cp(0x2028); +const PARAGRAPH_SEPARATOR = cp(0x2029); +const REPLACEMENT = cp(0xfffd); +const DOUBLE_QUOTE = '"'; +const SINGLE_QUOTE = "'"; +const HEX = "0123456789abcdefABCDEF"; +const DIGITS = "0123456789"; + +/** Whether `character` is one character among `set` (never the empty string). */ +function isOneOf(character: string | undefined, set: string): boolean { + return ( + character !== undefined && + [...character].length === 1 && + set.includes(character) + ); +} + +/** One replayed draw, labelled with its seed and 1-based trial number. */ +interface Replayed { + readonly label: string; + readonly draw: P19Draw; + readonly literal: string; + readonly scanned: Scanned; +} + +/** One unit of a literal's body as the scanner reads it. */ +type Token = + | { readonly kind: "raw" | "replacement" | "non-ascii" | "other-quote" } + | { readonly kind: "hex" | "nul" } + | { readonly kind: "unicode4"; readonly codePoint: number } + | { + readonly kind: "braced"; + readonly codePoint: number; + /** Digits beyond the code point's shortest spelling. */ + readonly leadingZeros: boolean; + } + | { + readonly kind: "single" | "identity"; + /** The character after the backslash. */ + readonly escaped: string; + /** For an escaped backslash: the two characters after it. */ + readonly next: string; + } + | { readonly kind: "continuation"; readonly terminator: string }; + +interface Scanned { + readonly quote: string; + readonly empty: boolean; + readonly tokens: readonly Token[]; +} + +/** + * The scanner (module header): a literal's quote and body, its body read + * as TypeScript's grammar for a string literal reads it — every backslash + * beginning one escape sequence, each recognized by its first character + * after the backslash — and anything else that grammar rejects, or no + * draw may spell, thrown: a backslash ending the body, a malformed or + * out-of-range escape, a decimal digit after a backslash (but the NUL + * escape before a non-digit), an unescaped delimiter, a raw line feed or + * carriage return. + */ +function scanLiteral(literal: string): Scanned { + const characters = [...literal]; + const quote = characters[0]; + if ( + (quote !== DOUBLE_QUOTE && quote !== SINGLE_QUOTE) || + characters.length < 2 || + characters[characters.length - 1] !== quote + ) { + throw new Error(`no quoted literal: ${JSON.stringify(literal)}`); + } + const body = characters.slice(1, -1); + const tokens: Token[] = []; + const hexRun = (from: number, count: number): number => { + const digits = body.slice(from, from + count); + if (digits.length !== count || !digits.every((d) => isOneOf(d, HEX))) { + throw new Error(`malformed escape in ${JSON.stringify(literal)}`); + } + return Number.parseInt(digits.join(""), 16); + }; + for (let i = 0; i < body.length; i += 1) { + const character = body[i]!; + if (character !== BACKSLASH) { + if (character === quote) { + throw new Error(`unescaped delimiter in ${JSON.stringify(literal)}`); + } + if (character === LINE_FEED || character === CARRIAGE_RETURN) { + throw new Error(`raw line break in ${JSON.stringify(literal)}`); + } + const code = character.codePointAt(0)!; + tokens.push({ + kind: + character === REPLACEMENT + ? "replacement" + : code > 0x7f + ? "non-ascii" + : character === DOUBLE_QUOTE || character === SINGLE_QUOTE + ? "other-quote" + : "raw", + }); + continue; + } + const next = body[i + 1]; + if (next === undefined) { + throw new Error(`a backslash ends ${JSON.stringify(literal)}`); + } + if (next === "x") { + hexRun(i + 2, 2); + tokens.push({ kind: "hex" }); + i += 3; + } else if (next === "u" && body[i + 2] === "{") { + let end = i + 3; + while (end < body.length && body[end] !== "}") end += 1; + const count = end - (i + 3); + if (end >= body.length || count === 0) { + throw new Error( + `malformed braced escape in ${JSON.stringify(literal)}`, + ); + } + const codePoint = hexRun(i + 3, count); + if (codePoint > 0x10ffff) { + throw new Error(`out-of-range escape in ${JSON.stringify(literal)}`); + } + tokens.push({ + kind: "braced", + codePoint, + leadingZeros: count > codePoint.toString(16).length, + }); + i = end; + } else if (next === "u") { + tokens.push({ kind: "unicode4", codePoint: hexRun(i + 2, 4) }); + i += 5; + } else if (next === "0" && !isOneOf(body[i + 2], DIGITS)) { + tokens.push({ kind: "nul" }); + i += 1; + } else if (isOneOf(next, DIGITS)) { + throw new Error(`a digit escape in ${JSON.stringify(literal)}`); + } else if (next === LINE_FEED) { + tokens.push({ kind: "continuation", terminator: "LF" }); + i += 1; + } else if (next === CARRIAGE_RETURN) { + const crlf = body[i + 2] === LINE_FEED; + tokens.push({ kind: "continuation", terminator: crlf ? "CRLF" : "CR" }); + i += crlf ? 2 : 1; + } else if (next === LINE_SEPARATOR || next === PARAGRAPH_SEPARATOR) { + tokens.push({ + kind: "continuation", + terminator: next === LINE_SEPARATOR ? "LS" : "PS", + }); + i += 1; + } else { + tokens.push({ + kind: P19_SINGLE_ESCAPES.includes(next) ? "single" : "identity", + escaped: next, + next: body.slice(i + 2, i + 4).join(""), + }); + i += 1; + } + } + return { quote, empty: body.length === 0, tokens }; +} + +const REPLAYED: readonly Replayed[] = drawFixedSeedTrials( + genP19Draw, + P19_RUNS_PER_SEED, +).map((draw, index) => { + const literal = spellP19Literal(draw); + return { + label: + `seed ${String(DEFAULT_PROPERTY_SEEDS[Math.floor(index / P19_RUNS_PER_SEED)])} ` + + `trial ${String((index % P19_RUNS_PER_SEED) + 1)}`, + draw, + literal, + scanned: scanLiteral(literal), + }; +}); + +/** The labels of the draws `matches` accepts. */ +function drawsWhere(matches: (replayed: Replayed) => boolean): string[] { + return REPLAYED.filter(matches).map(({ label }) => label); +} + +/** The labels of the draws holding a token `matches` accepts. */ +function drawsHolding(matches: (token: Token) => boolean): string[] { + return drawsWhere(({ scanned }) => scanned.tokens.some(matches)); +} + +/** The class names `reach` maps to no draw. */ +function unreached( + reach: Readonly<Record<string, readonly string[]>>, +): string[] { + return Object.entries(reach) + .filter(([, labels]) => labels.length === 0) + .map(([name]) => name); +} + +const isBraced = (token: Token): token is Extract<Token, { kind: "braced" }> => + token.kind === "braced"; + +test("P-19's fixed-seed draws reach, as spelled, each form a CONF-IMPORT violator refuses: a single-quoted specifier, and a braced Unicode escape of a code point at or below U+FFFF begun by a backslash that begins an escape — with leading zeros, and of a surrogate, among them", () => { + const reach = { + singleQuoted: drawsWhere(({ scanned }) => scanned.quote === SINGLE_QUOTE), + bracedAtOrBelowFFFF: drawsHolding( + (token) => isBraced(token) && token.codePoint <= 0xffff, + ), + bracedAtOrBelowFFFFWithLeadingZeros: drawsHolding( + (token) => + isBraced(token) && token.codePoint <= 0xffff && token.leadingZeros, + ), + bracedSurrogate: drawsHolding( + (token) => + isBraced(token) && + token.codePoint >= 0xd800 && + token.codePoint <= 0xdfff, + ), + }; + expect( + unreached(reach), + `forms P-19's fixed seeds never reach as spelled — a violator ` + + `refusing one would pass P-19 (criterion (a)'s reachability case); ` + + `reach: ${JSON.stringify(reach)}`, + ).toEqual([]); +}); + +test("P-19's fixed-seed draws reach the rest of its search space: double quotes, every text shape and the empty string, every escape form, a line continuation after each line terminator, raw U+FFFD and other non-ASCII code points, the other quote character, and an escaped backslash before u{", () => { + const reach: Record<string, string[]> = { + doubleQuoted: drawsWhere(({ scanned }) => scanned.quote === DOUBLE_QUOTE), + theEmptyString: drawsWhere(({ scanned }) => scanned.empty), + hex: drawsHolding((token) => token.kind === "hex"), + unicode4: drawsHolding((token) => token.kind === "unicode4"), + bracedAboveFFFF: drawsHolding( + (token) => isBraced(token) && token.codePoint > 0xffff, + ), + identity: drawsHolding((token) => token.kind === "identity"), + identityBeyondAscii: drawsHolding( + (token) => + token.kind === "identity" && token.escaped.codePointAt(0)! > 0x7f, + ), + nulBeforeNonDigit: drawsHolding((token) => token.kind === "nul"), + replacement: drawsHolding((token) => token.kind === "replacement"), + otherNonAscii: drawsHolding((token) => token.kind === "non-ascii"), + otherQuote: drawsHolding((token) => token.kind === "other-quote"), + escapedBackslashBeforeBrace: drawsHolding( + (token) => + token.kind === "single" && + token.escaped === BACKSLASH && + token.next === "u{", + ), + }; + for (const shape of P19_SHAPES) { + reach[`shape:${shape}`] = drawsWhere(({ draw }) => draw.shape === shape); + } + for (const escaped of P19_SINGLE_ESCAPES) { + reach[`single:${JSON.stringify(escaped)}`] = drawsHolding( + (token) => token.kind === "single" && token.escaped === escaped, + ); + } + for (const [terminator] of P19_TERMINATORS) { + reach[`continuation:${terminator}`] = drawsHolding( + (token) => + token.kind === "continuation" && token.terminator === terminator, + ); + } + expect( + unreached(reach), + `classes of P-19's search space its fixed seeds never reach; reach: ` + + JSON.stringify(reach), + ).toEqual([]); +}); + +test("each fixed-seed P-19 draw's staged configuration holds the drawn spelling's exact UTF-8 bytes between the shared builder's head and tail — no decoding, no re-quoting, no printer", async () => { + const mismatches: string[] = []; + for (const { label, draw, literal } of REPLAYED) { + const workspace = await TestWorkspace.create(p19DrawDecl(draw)); + try { + const staged = Buffer.from( + await workspace.readBytes(CONFIG_IMPORT_CONFIG_PATH), + ); + const expected = Buffer.concat([ + Buffer.from(CONFIG_IMPORT_HEAD, "utf8"), + Buffer.from(literal, "utf8"), + Buffer.from(CONFIG_IMPORT_TAIL, "utf8"), + ]); + // The spelling's backslashes are its pieces', every one staged. + const backslashes = draw.pieces + .map((piece) => [...piece.spelling].filter((c) => c === BACKSLASH)) + .flat().length; + const stagedBackslashes = [...staged].filter((b) => b === 0x5c).length; + if (!staged.equals(expected) || stagedBackslashes !== backslashes) { + mismatches.push( + `${label}: staged ${staged.toString("hex")}, drawn ` + + `${expected.toString("hex")} (${String(stagedBackslashes)} ` + + `backslashes staged, ${String(backslashes)} drawn)`, + ); + } + } finally { + await workspace.dispose(); + } + } + expect(mismatches).toEqual([]); + // Not vacuous: the draws stage backslashes, both quote styles, and code + // points beyond ASCII. + const all = REPLAYED.map(({ literal }) => literal).join(""); + expect(all.includes(BACKSLASH)).toBe(true); + expect([...all].some((c) => c.codePointAt(0)! > 0x7f)).toBe(true); +}); + +test("every fixed-seed P-19 draw passes S-9's per-draw check before any product exists, through P-19's own code path (TEST-SPEC §16 P-19, §17 S-9; E-5 replay at P-19's registered runs per seed)", async () => { + // P-19 as its registration runs it — the generator, the fixed seed set + // (no `seeds`; `env: {}`, so no replay variable intervenes), the + // registered runs per seed, and `drawSources: stagedP19Sources` — with a + // body that only counts: checkProperty judges each draw's configuration + // and sources before the body runs on it, and a draw failing S-9 rejects + // the run as a harness error naming its seed. + const literals: string[] = []; + await checkProperty( + "P-19 configuration import spellings (S-9 per-draw replay, no product)", + genP19Draw, + (draw) => { + literals.push(spellP19Literal(draw)); + }, + { runs: P19_RUNS_PER_SEED, env: {}, drawSources: stagedP19Sources }, + ); + expect(literals).toEqual(REPLAYED.map(({ literal }) => literal)); + // Every draw stages its configuration and the two sources. + for (const { draw } of REPLAYED) { + expect(stagedP19Sources(draw).map(([path]) => path)).toEqual([ + CONFIG_IMPORT_CONFIG_PATH, + "specs/A.mdx", + "specs/B.mdx", + ]); + } +}); diff --git a/test/self/s1-traceability.test.ts b/test/self/s1-traceability.test.ts index 115ede95..0893acf9 100644 --- a/test/self/s1-traceability.test.ts +++ b/test/self/s1-traceability.test.ts @@ -36,12 +36,12 @@ const PREAMBLE_KEY = "preamble"; // The universe SPEC.md currently defines. H-7's section lists (the body-text // sections above; sections covered through their subsections) enumerate over -// exactly sections 1–15, and the full universe is preamble + 70 subsections +// exactly sections 1–15, and the full universe is preamble + 71 subsections // + 10 body keys. The detail is derived from the document below; these pins // force a deliberate visit when SPEC.md's structure changes and guard // against a parser regression losing headings wholesale. const EXPECTED_SECTION_COUNT = 15; -const EXPECTED_KEY_COUNT = 81; +const EXPECTED_KEY_COUNT = 82; // Heading shapes exactly as SPEC.md writes them: a section heading is // `## <n>. <title>`, a subsection heading `### <n>.<m> <title>`, numbers diff --git a/test/self/s10-node-release-driver.test.ts b/test/self/s10-node-release-driver.test.ts new file mode 100644 index 00000000..4b135a06 --- /dev/null +++ b/test/self/s10-node-release-driver.test.ts @@ -0,0 +1,1391 @@ +// S-10, the module channel's Node.js release driver (TEST-SPEC S-10, E-1, +// H-9, H-11; T7.6-6's run conditions, T7.6-7(a) and (c); the driver, +// helpers/module-channel-node.ts, its bootstrap, +// helpers/module-channel-bootstrap.cjs, and E-1's releases, +// helpers/node-releases.ts). 7.6's runtime arms (T7.6-6, T7.6-7, P-17) rest +// on a driver certification cannot check: every fixture's module answers +// alike on every release and route, so a driver serving one release or one +// route for all of them would pass conformer and violators alike and leave +// the arm on 22.0–22.11's `require` vacuous. So the driver is checked here +// directly, before any product exists, on each release E-1 provisions — +// XSPEC_NODE_RELEASES_DIR must name them, as CI's harness-self job and +// AGENTS.md's recipe do (unset, every test here fails as the harness error +// NodeReleaseError naming the variable, never a skip) — each stand-in placed +// at the canonical placement in a CommonJS project and run exactly as the +// tests run it (`runModuleRoute`, `prepareModuleRun`): +// - releases: each run's process reports the listed version, running the +// provisioned executable's physical path with no option, and a run whose +// provisioned executable is another release is refused as a harness error +// naming both versions; a listed release left unprovisioned is a harness +// error (NodeReleaseError) for every run needing it — the whole list's +// resolution and its own — never a skip or a diagnosed failure, and so is +// the releases' directory left unnamed; +// - run conditions: each run, on each release and along each route, carries +// no option, an environment of exactly HOME, TMPDIR, and PATH — no +// NODE_OPTIONS or NODE_PATH — and no user condition, loader, or hook, and +// has a fresh HOME (and TMPDIR and working directory): its own, empty, +// outside the staging, and removed afterwards. A stray NODE_OPTIONS — +// carrying a user condition the dual stand-in's exports map answers and a +// preloaded hook announcing itself through a process warning — and a +// stray NODE_PATH, naming a folder that holds a decoy under N, each +// answered by the release given it directly, stand in the harness's own +// environment and reach no run; +// - routes: each importing module runs as its route's own kind, and the dual +// stand-in, whose entries each report their own format when loaded, +// answers the import routes from its ES-module entry and the require route +// from its CommonJS one; the ES-module-only stand-in loads along each +// import route on every release, and its require route fails, refused as +// an ES module's load (ERR_REQUIRE_ESM), on each release before 22.12.0 +// and loads on each later one, each class holding at least one of E-1's +// releases; +// - the runtime's own loading output: the two minimal stand-ins leave +// T7.6-7(c)'s observed state unchanged along each route that loads them, +// on each release, and their loading output there passes T7.6-7(a)'s +// output oracle; so does the output of the stand-ins whose manifests draw +// the release's own deprecations — an invalid main beside an index.js +// along require (DEP0128), an ES-module package's main lookup along each +// import route (DEP0151) — wherever the release prints one, their state +// unchanged likewise. Which release prints which of its own warnings is +// not pinned, nor is any warning's spelling: the minimal ES-module +// stand-in and each deprecation stand-in must draw a warning on at least +// one release, so that no admission is vacuous; +// - each observation catches what it exists for, one test per effect: a +// stand-in otherwise conforming — its entry for the route exporting +// exactly `defineConfig` and returning its argument — but for one effect +// is caught, on each release and along each route the effect can take +// (each of the four, but where a layout drawing a warning of the +// release's own fixes the route), by the observation that exists for +// that effect, read where the driver reports it, so that no absence +// passes through a blind observer. T7.6-7(a)'s output oracle +// (`outputProblems`) catches a line on standard output; a line on +// standard error outside the release's warning form; one in that form, +// byte for byte the release's printed form of a first warning, its hint +// line included, which no warning stands behind; such a line after a +// warning the release prints (DEP0128 along require, DEP0151 along each +// import route, each printed by at least one release); and a warning the +// module emits through `process.emitWarning`, which the release prints in +// its own form, so that only its stack, beginning in the package's +// files, gives it away. T7.6-7(c)'s comparison (`report.state.changes`, +// read by `stateProblems`) catches, each under its own observation and +// no other, a global added, an own property added to `Array` and to +// `Math`, `String.prototype.trim` replaced, the global object made +// non-extensible, `Date.prototype`'s prototype changed, +// `process.emitWarning` replaced, a variable set in `process.env`, the +// process title set (under `process` as well, the title being a native +// data property of `process`), the working directory changed, each +// standard stream's `write` replaced, `process.exitCode` set, an `exit` +// listener registered, and a timer started — every other observation +// finding nothing. T7.6-6(b) and (c) catch a copy returned +// (`identityProblems`, `examinationProblems`), and (c) a trap of an +// argument's Proxy touched. T7.6-7(b) catches a file written into each of +// the four places a run with effects compares (`writeProblems`). And +// T7.6-7(e) catches each of the three FIFOs opened by the run's guard: the +// run, its guard lowered, ends at it with the driver's hang-guard kill +// (`ProductRunTimeoutError`), its partial standard output showing each +// open begun and none returned, each FIFO still a FIFO. +// +// The stand-ins, test/fixtures/s10-stand-ins/, documented here since JSON +// holds no comment: small hand-written, non-xspec packages, each exporting +// `defineConfig`, an identity function, and nothing else — but for the +// catches' `copies-argument` and `touches-proxy`, whose `defineConfig` is +// the effect. +// - `dual`: no `type`; an `exports` map whose one entry lists, first, the +// user condition `xspec-s10-user-condition` (`condition.cjs`), then +// `import` (`index.mjs`) and `require` (`index.cjs`). Each of the three +// files, when loaded, writes one line to standard output naming itself and +// the kind of module it ran as, read from its own top-level `this` +// (undefined in an ES module, `module.exports` in a CommonJS one): +// `index.mjs: an ES module`, say. +// - `module-only`: `"type": "module"` and an `exports` string naming +// `index.js`: the minimal ES-module stand-in, and the ES-module-only one. +// - `commonjs`: no `type`, its `main` naming `index.js`: the minimal +// CommonJS stand-in. +// - `invalid-main`: `commonjs`'s layout, its `main` naming `./missing.js`, +// which does not exist, beside `index.js` (DEP0128 along require). +// - `main-lookup`: `"type": "module"`, its `main` naming the directory +// `./lib`, whose `index.js` an ES module's index lookup finds (DEP0151 +// along import). +// The catches' stand-ins are each a dual package unless stated: no `type`, +// and an `exports` map whose one entry lists `import` (`index.mjs`, an ES +// module) and `require` (`index.cjs`, a CommonJS module), each entry having +// the stand-in's one effect itself as it loads: +// - `prints-stdout`, `prints-stderr`: write one line, `<its name>: a line +// the module writes`, to standard output, or to standard error. +// - `prints-warning-form`: writes to standard error, through no warning +// facility, the release's printed form of a first warning, +// `(node:<pid>) [XSPEC_S10_FORGED] Warning: a line the module writes in +// the warning form`, then the hint line the release appends to a first +// warning that is no deprecation, naming the executable as the release +// does (`path.basename(process.argv0, ".exe")`). +// - `prints-after-dep0128`: `invalid-main`'s layout, its `index.js` a +// CommonJS module, loaded along require; on the tick after it loads — so +// after the release's DEP0128, delivered on an earlier one — it writes to +// standard error the release's printed form of a warning after the +// first, `(node:<pid>) [XSPEC_S10_FORGED] Warning: a line the module +// writes after the release's own warning`. +// - `prints-after-dep0151`: `main-lookup`'s layout, its `lib/index.js` an +// ES module, loaded along each import route, writing that line likewise +// after the release's DEP0151. +// - `emits-warning`: emits a warning through `process.emitWarning`, its +// type `XspecS10Warning` and its code `XSPEC_S10_EMITTED`. +// - `adds-global`, `adds-array-property`, `adds-math-property`: add the own +// property `xspecS10Global` to the global object, or `xspecS10Property` +// to `Array` or to `Math`. +// - `alters-prototype`: replaces `String.prototype.trim` with a function +// forwarding to it. +// - `prevents-global-extensions`: makes the global object non-extensible. +// - `reparents-prototype`: changes `Date.prototype`'s prototype to a new +// object inheriting from the old one. +// - `replaces-emit-warning`: replaces `process.emitWarning` with a function +// forwarding to it. +// - `sets-env`: sets `process.env.XSPEC_S10_VARIABLE` to `set`. +// - `sets-title`: sets `process.title` to `xspec-s10-title`. +// - `changes-directory`: `process.chdir("..")`, from the run's working +// directory to the run's own directory. +// - `replaces-write`: replaces the `write` of `process.stdout` and of +// `process.stderr`, each with a function forwarding to the one it +// replaces. +// - `sets-exit-code`: sets `process.exitCode` to 0, so the run still exits +// 0 on its own. +// - `adds-listener`: registers an `exit` listener on `process`. +// - `starts-timer`: starts a 100 ms timer. +// - `copies-argument`: its `defineConfig` returns a copy of an object or an +// array argument (`Object.assign`, `slice`), touching no Proxy, and any +// other argument itself. +// - `touches-proxy`: its `defineConfig` reads a property of a function +// argument — the first recording Proxy's `get` trap — and returns the +// argument. +// - `writes-file`: writes a plain file, `writes-file-<pid>-<time>`, into its +// working directory, `HOME`, `TMPDIR`, and its own package directory (the +// placement, in the staging). +// - `opens-fifos`: for each of T7.6-7(e)'s places — its working directory, +// the importing module's directory (its own directory's path up to the +// last `node_modules`), and `HOME` — writes `opens-fifos: opening <path>` +// to standard output and opens `xspec.config.ts` there for reading, +// asynchronously, writing `opens-fifos: opened <path>` or `opens-fifos: +// failed to open (<code>) <path>` once the open returns, which for a FIFO +// no writer holds it never does. +// The strays — the preloaded hook, and the decoy under NODE_PATH, named N — +// and the stand-in executables of the releases tests are written at run +// time into fresh directories under the OS temporary directory, outside +// every staging. + +import * as fsp from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { expect, onTestFinished, test } from "vitest"; +import { HarnessAssertionError } from "../helpers/assertions.js"; +import { ModuleStaging, runtimeArm } from "../helpers/module-channel.js"; +import type { Placement } from "../helpers/module-channel.js"; +import { + assertModuleLoaded, + describeCallCase, + examinationProblems, + exportsProblems, + fifoProblems, + identityProblems, + importingModuleKind, + learnWarningForm, + MODULE_ROUTES, + moduleRunEnvironment, + outputProblems, + packageFrame, + pairingProblem, + prepareModuleRun, + renderWarnings, + runModuleRoute, + runtimeOutputProblems, + stateProblems, + writeProblems, +} from "../helpers/module-channel-node.js"; +import type { + CapturedWarning, + ImportingModuleNote, + LoadedModuleRun, + ModuleRoute, + ModuleRunRequest, + OwnKey, + PreparedModuleRun, + StateObservationName, +} from "../helpers/module-channel-node.js"; +import { + NODE_RELEASES_DIR_VARIABLE, + NodeReleaseError, + readNodeReleaseList, + resolveNodeRelease, + resolveNodeReleases, +} from "../helpers/node-releases.js"; +import type { NodeRelease } from "../helpers/node-releases.js"; +import { ProductRunTimeoutError, runProduct } from "../helpers/subprocess.js"; +import type { ProductBinding, RunResult } from "../helpers/subprocess.js"; + +const LF = String.fromCodePoint(0x0a); + +/** The committed stand-ins (module header), by their directories' names. */ +type StandIn = + | "dual" + | "module-only" + | "commonjs" + | "invalid-main" + | "main-lookup" + | "prints-stdout" + | "prints-stderr" + | "prints-warning-form" + | "prints-after-dep0128" + | "prints-after-dep0151" + | "emits-warning" + | "adds-global" + | "adds-array-property" + | "adds-math-property" + | "alters-prototype" + | "prevents-global-extensions" + | "reparents-prototype" + | "replaces-emit-warning" + | "sets-env" + | "sets-title" + | "changes-directory" + | "replaces-write" + | "sets-exit-code" + | "adds-listener" + | "starts-timer" + | "copies-argument" + | "touches-proxy" + | "writes-file" + | "opens-fifos"; + +/** A committed stand-in's package directory. */ +function standInDirectory(standIn: StandIn): string { + return fileURLToPath( + new URL(`../fixtures/s10-stand-ins/${standIn}`, import.meta.url), + ); +} + +/** The user condition the dual stand-in's exports map lists first. */ +const USER_CONDITION = "xspec-s10-user-condition"; + +/** The line each of the dual stand-in's entries writes when loaded. */ +const ENTRY_LINES = { + module: `index.mjs: an ES module${LF}`, + commonJs: `index.cjs: a CommonJS module${LF}`, + condition: `condition.cjs: a CommonJS module${LF}`, +} as const; + +/** The line the decoy under the stray NODE_PATH writes when loaded. */ +const DECOY_LINE = `NODE_PATH decoy${LF}`; + +/** The code of the warning the stray hook emits wherever it runs. */ +const STRAY_HOOK_CODE = "XSPEC_S10_STRAY_HOOK"; + +/** + * The first release on which `require` loads an ES module without a flag + * (TEST-SPEC E-1: 22.11.0 the last on which it cannot). + */ +const REQUIRE_MODULE_RELEASE = "22.12.0"; + +/** The import routes: each but `require`. */ +const IMPORT_ROUTES: readonly ModuleRoute[] = MODULE_ROUTES.filter( + (route) => route !== "require", +); + +/** A loaded value's own `defineConfig` key, as the report lists it. */ +const DEFINE_CONFIG_KEY: OwnKey = { + kind: "string", + name: "defineConfig", + enumerable: true, +}; + +/** A module namespace's own `Symbol.toStringTag` key, likewise. */ +const TO_STRING_TAG_KEY: OwnKey = { + kind: "symbol", + name: "Symbol.toStringTag", + enumerable: false, +}; + +/** A module's text, from its lines. */ +function lines(...text: string[]): string { + return `${text.join(LF)}${LF}`; +} + +/** A fresh, empty directory of this test's own, removed once it ends. */ +async function freshDirectory(prefix: string): Promise<string> { + const directory = await fsp.realpath( + await fsp.mkdtemp(path.join(os.tmpdir(), prefix)), + ); + onTestFinished(() => fsp.rm(directory, { recursive: true, force: true })); + return directory; +} + +/** + * A binding of the certification fixtures' shape beside `packageDir`: its + * executable is never run here. + */ +function standInBinding(packageDir: string): ProductBinding { + return { + label: "S-10 release-driver stand-in binding", + command: process.execPath, + requiredFiles: [process.execPath], + packageDir, + }; +} + +/** A stand-in staged at the canonical placement in a CommonJS project. */ +interface StagedStandIn { + readonly staging: ModuleStaging; + readonly placement: Placement; +} + +/** + * Stage the committed stand-in `standIn` at the canonical placement in a + * CommonJS project, for runs on `releases`; disposed of once the test ends. + */ +async function stageStandIn( + standIn: StandIn, + releases: readonly NodeRelease[], + context: string, +): Promise<StagedStandIn> { + const staging = await ModuleStaging.create( + standInBinding(standInDirectory(standIn)), + context, + ); + onTestFinished(() => staging.dispose()); + await staging.stageProject("project", "commonjs"); + const placement = await staging.placeCanonical( + "project", + runtimeArm(releases), + ); + return { staging, placement }; +} + +/** One run's request over `staged`, the project declared and alone. */ +function request( + staged: StagedStandIn, + release: NodeRelease, + route: ModuleRoute, + context: string, +): ModuleRunRequest { + return { + staging: staged.staging, + placement: staged.placement, + route, + release, + project: "commonjs", + alone: true, + context, + }; +} + +/** One loaded run of a stand-in the harness expects to load. */ +async function loadedRun( + staged: StagedStandIn, + release: NodeRelease, + route: ModuleRoute, + context: string, +): Promise<LoadedModuleRun> { + return assertModuleLoaded( + await runModuleRoute(request(staged, release, route, context)), + "stand-in", + ); +} + +/** Whether the exact version `version` precedes the exact version `other`. */ +function precedes(version: string, other: string): boolean { + const left = version.split(".").map(Number); + const right = other.split(".").map(Number); + for (let index = 0; index < 3; index += 1) { + const mine = left[index] ?? 0; + const theirs = right[index] ?? 0; + if (mine !== theirs) return mine < theirs; + } + return false; +} + +/** + * The note `route`'s importing module, at the physical path + * `importingModule`, gives of its own kind and location: its top-level + * `this` undefined and its location its file URL in an ES module, an object + * and its path in a CommonJS one. + */ +function kindNote( + route: ModuleRoute, + importingModule: string, +): ImportingModuleNote { + return importingModuleKind(route) === "module" + ? { + topLevelThis: "undefined", + location: pathToFileURL(importingModule).href, + } + : { topLevelThis: "object", location: importingModule }; +} + +/** Whether `inner` is `outer` or lies under it. */ +function within(inner: string, outer: string): boolean { + return inner === outer || inner.startsWith(`${outer}${path.sep}`); +} + +async function exists(entry: string): Promise<boolean> { + return fsp.lstat(entry).then( + () => true, + () => false, + ); +} + +/** What `work` rejects with, which it must. */ +async function rejectionOf(work: () => Promise<unknown>): Promise<unknown> { + return work().then( + () => { + throw new Error("expected a rejection, and the work resolved"); + }, + (error: unknown) => error, + ); +} + +/** A shell script running `commands`. */ +function shellScript(...commands: string[]): string { + return `#!/bin/sh${LF}${commands.join(LF)}${LF}`; +} + +/** `text` single-quoted for the shell; it may hold no single quote. */ +function shellQuoted(text: string): string { + if (text.includes("'")) { + throw new Error( + `S-10 self-test: ${JSON.stringify(text)} holds a single quote, which ` + + `this file's shell scripts do not quote`, + ); + } + return `'${text}'`; +} + +/** Write `text` at `file`, a new file every user may execute, its parents made. */ +async function writeExecutable(file: string, text: string): Promise<void> { + await fsp.mkdir(path.dirname(file), { recursive: true }); + await fsp.writeFile(file, text, { flag: "wx" }); + await fsp.chmod(file, 0o755); +} + +/** The strays (module header), written for the placement name N. */ +interface Strays { + /** NODE_OPTIONS and NODE_PATH, as they stand in the harness's environment. */ + readonly environment: Readonly<Record<string, string>>; + /** A fresh, empty directory outside every staging, no node_modules above it. */ + readonly outside: string; +} + +/** + * Write the strays for N `name` into a fresh directory: the preloaded hook, + * emitting a process warning of code {@link STRAY_HOOK_CODE}; and the decoy + * under NODE_PATH, a CommonJS package at `<folder>/N` writing + * {@link DECOY_LINE} when loaded. + */ +async function writeStrays(name: string): Promise<Strays> { + const directory = await freshDirectory("xspec-s10-strays-"); + const hook = path.join(directory, "hook.cjs"); + await fsp.writeFile( + hook, + lines( + 'process.emitWarning("xspec S-10: a stray preloaded hook ran", {', + ' type: "XspecS10StrayHook",', + ` code: ${JSON.stringify(STRAY_HOOK_CODE)},`, + "});", + ), + { flag: "wx" }, + ); + const folder = path.join(directory, "node-path"); + const decoy = path.join(folder, ...name.split("/")); + await fsp.mkdir(decoy, { recursive: true }); + await fsp.writeFile( + path.join(decoy, "package.json"), + `${JSON.stringify({ name: "s10-node-path-decoy", version: "1.0.0", main: "./index.js" }, null, 2)}${LF}`, + { flag: "wx" }, + ); + await fsp.writeFile( + path.join(decoy, "index.js"), + lines( + 'process.stdout.write("NODE_PATH decoy" + String.fromCharCode(10));', + "exports.defineConfig = function defineConfig(settings) {", + " return settings;", + "};", + ), + { flag: "wx" }, + ); + const outside = path.join(directory, "outside"); + await fsp.mkdir(outside); + return { + environment: { + NODE_OPTIONS: `--conditions=${USER_CONDITION} --require=${JSON.stringify(hook)}`, + NODE_PATH: folder, + }, + outside, + }; +} + +/** + * Run `release` directly, outside the driver, from `cwd` under the + * harness's environment with `environment` set over it, requiring `name`. + */ +async function requireDirectly( + release: NodeRelease, + cwd: string, + environment: Readonly<Record<string, string>>, + name: string, +): Promise<RunResult> { + return runProduct( + { + label: `the Node.js release ${release.version}, given the strays directly`, + command: release.executable, + requiredFiles: [release.executable], + }, + { + cwd, + argv: ["--eval", `require(${JSON.stringify(name)});`], + env: { ...environment }, + }, + ); +} + +/** + * Run `work` with `values` standing in the harness's own environment, + * restoring each variable afterwards. + */ +async function withAmbient( + values: Readonly<Record<string, string>>, + work: () => Promise<void>, +): Promise<void> { + const saved = Object.keys(values).map( + (name): [string, string | undefined] => [name, process.env[name]], + ); + Object.assign(process.env, values); + try { + await work(); + } finally { + for (const [name, value] of saved) { + if (value === undefined) { + delete process.env[name]; + } else { + process.env[name] = value; + } + } + } +} + +/** The code each forged warning line of the catches carries (module header). */ +const FORGED_CODE = "XSPEC_S10_FORGED"; + +/** The message of `prints-warning-form`'s forged first warning. */ +const FORGED_FIRST_MESSAGE = "a line the module writes in the warning form"; + +/** The message of the forged line the prints-after stand-ins write. */ +const FORGED_AFTER_MESSAGE = + "a line the module writes after the release's own warning"; + +/** + * The lowered guard of each of `opens-fifos`' runs, every one of which ends + * at it: about a hundred times a run's own time here, so that each run + * reaches its opens well before it. + */ +const FIFO_RUN_GUARD_MS = 5_000; + +/** The entry of a dual stand-in that answers `route` (module header). */ +function dualEntry(route: ModuleRoute): string { + return route === "require" ? "index.cjs" : "index.mjs"; +} + +/** + * A warning of type `Warning` carrying {@link FORGED_CODE} and `message`, + * as the bootstrap would have captured it had the module emitted it. + */ +function forgedWarning(message: string): CapturedWarning { + return { + type: "object", + name: "Warning", + code: FORGED_CODE, + message, + detail: null, + stack: null, + }; +} + +/** + * Stage the committed stand-in `standIn` once, run it along each of + * `routes` on each of E-1's releases, each run expected to load, and hand + * each loaded run to `check` with its context. + */ +async function checkEachRun( + standIn: StandIn, + routes: readonly ModuleRoute[], + check: (run: LoadedModuleRun, context: string) => Promise<void> | void, +): Promise<void> { + const releases = await resolveNodeReleases(); + const staged = await stageStandIn( + standIn, + releases, + `S-10 catches: ${standIn}`, + ); + for (const release of releases) { + for (const route of routes) { + const context = `S-10 catches: ${standIn}, ${release.version}, ${route}`; + await check(await loadedRun(staged, release, route, context), context); + } + } +} + +/** One of T7.6-7(c)'s catches (module header). */ +interface StateCatch { + readonly standIn: StandIn; + /** What the stand-in does as it loads, for the test's title. */ + readonly effect: string; + /** + * Each difference it must be caught as, in the bootstrap's order: the + * observation, the subject, and a part of the detail. + */ + readonly changes: readonly (readonly [ + StateObservationName, + string, + string, + ])[]; +} + +/** T7.6-7(c)'s catches, one test each. */ +const STATE_CATCHES: readonly StateCatch[] = [ + { + standIn: "adds-global", + effect: "adds a global", + changes: [ + [ + "global-object", + "the global object", + 'an own property "xspecS10Global" was added', + ], + ], + }, + { + standIn: "adds-array-property", + effect: "adds an own property to a built-in constructor (Array)", + changes: [ + ["built-ins", "Array", 'an own property "xspecS10Property" was added'], + ], + }, + { + standIn: "adds-math-property", + effect: "adds an own property to a namespace object (Math)", + changes: [ + ["built-ins", "Math", 'an own property "xspecS10Property" was added'], + ], + }, + { + standIn: "alters-prototype", + effect: "alters a built-in prototype (String.prototype.trim replaced)", + changes: [ + ["built-ins", "String.prototype", 'its own property "trim" changed'], + ], + }, + { + standIn: "prevents-global-extensions", + effect: "makes the global object non-extensible", + changes: [ + [ + "extensibility", + "the global object", + "it was extensible and no longer is", + ], + ], + }, + { + standIn: "reparents-prototype", + effect: "changes the prototype of a built-in prototype (Date.prototype)", + changes: [ + [ + "prototype", + "Date.prototype", + "its prototype changed from Object.prototype to an object", + ], + ], + }, + { + standIn: "replaces-emit-warning", + effect: "replaces a property of process (process.emitWarning)", + changes: [["process", "process", 'its own property "emitWarning" changed']], + }, + { + standIn: "sets-env", + effect: "sets a variable in process.env", + changes: [ + [ + "environment", + "process.env", + 'a variable "XSPEC_S10_VARIABLE" was set to "set"', + ], + ], + }, + { + standIn: "sets-title", + effect: "sets the process title", + changes: [ + ["process", "process", 'its own property "title" changed'], + ["title", "the process title", 'to "xspec-s10-title"'], + ], + }, + { + standIn: "changes-directory", + effect: "changes the working directory (process.chdir)", + changes: [ + ["working-directory", "the working directory", "it changed from "], + ], + }, + { + standIn: "replaces-write", + effect: "replaces the write of each standard stream", + changes: [ + [ + "stream-write", + "process.stdout.write", + "it now resolves to another function", + ], + [ + "stream-write", + "process.stderr.write", + "it now resolves to another function", + ], + ], + }, + { + standIn: "sets-exit-code", + effect: "sets process.exitCode (to 0)", + changes: [ + ["exit-code", "process.exitCode", "it changed from undefined to 0"], + ], + }, + { + standIn: "adds-listener", + effect: "registers a process listener (for exit)", + changes: [ + [ + "listeners", + "the listeners registered on process", + 'the event "exit" had ', + ], + ], + }, + { + standIn: "starts-timer", + effect: "starts a timer", + changes: [ + [ + "timers-and-handles", + "the pending timers and handles", + "0 timer(s) were pending (Timeout), and 1 are", + ], + ], + }, +]; + +test("S-10, releases: on each of E-1's releases, the release in effect is the one provisioned — each run's process reports the listed version, running the provisioned executable's physical path with no option — and a run whose provisioned executable is another release is refused as a harness error naming both versions; a listed release left unprovisioned is a harness error (NodeReleaseError) for every run needing it, the whole list's resolution and its own, each provisioned release still resolving, and so is the releases' directory left unnamed — never a skip or a diagnosed failure (TEST-SPEC S-10, E-1, H-11, H-9)", async () => { + const releases = await resolveNodeReleases(); + const listed = await readNodeReleaseList(); + expect(releases.map((release) => release.version)).toEqual([...listed]); + const staged = await stageStandIn( + "commonjs", + releases, + "S-10 releases: commonjs", + ); + for (const release of releases) { + const context = `S-10 releases: commonjs, ${release.version}`; + const run = await loadedRun(staged, release, "require", context); + expect(run.report.release, context).toEqual({ + version: `v${release.version}`, + execPath: await fsp.realpath(release.executable), + execArgv: [], + }); + } + + // A release provisioned under another's name: the first listed release's + // executable runs the last's. + const first = releases[0]; + const other = releases[releases.length - 1]; + if (first === undefined || other === undefined || first === other) { + throw new Error("S-10 self-test: E-1 lists fewer than two releases"); + } + const impostors = await freshDirectory("xspec-s10-impostor-releases-"); + const impostorPath = path.join(impostors, `v${first.version}`, "bin", "node"); + await writeExecutable( + impostorPath, + shellScript(`exec ${shellQuoted(other.executable)} "$@"`), + ); + const impostor = await resolveNodeRelease(first.version, { + environment: { [NODE_RELEASES_DIR_VARIABLE]: impostors }, + }); + expect(impostor).toEqual({ + version: first.version, + executable: impostorPath, + }); + const refused = await rejectionOf(() => + runModuleRoute( + request(staged, impostor, "require", "S-10 releases: impostor"), + ), + ); + expect(refused).toBeInstanceOf(Error); + expect(refused).not.toBeInstanceOf(HarnessAssertionError); + const message = (refused as Error).message; + expect(message.startsWith("harness error (H-11): ")).toBe(true); + expect(message).toContain( + `the release in effect reports v${other.version}, not v${first.version}`, + ); + + // A listed release left unprovisioned. + const partial = await freshDirectory("xspec-s10-partial-releases-"); + const missing = listed[Math.floor(listed.length / 2)]; + if (missing === undefined) throw new Error("E-1 lists no release"); + const executableIn = (version: string): string => + path.join(partial, `v${version}`, "bin", "node"); + const provisioned = listed.filter((version) => version !== missing); + for (const version of provisioned) { + await writeExecutable(executableIn(version), shellScript("exit 0")); + } + const lookup = { environment: { [NODE_RELEASES_DIR_VARIABLE]: partial } }; + for (const resolve of [ + () => resolveNodeReleases(lookup), + () => resolveNodeRelease(missing, lookup), + ]) { + const error = await rejectionOf(resolve); + expect(error).toBeInstanceOf(NodeReleaseError); + expect(error).not.toBeInstanceOf(HarnessAssertionError); + expect((error as NodeReleaseError).fault).toBe("release"); + expect((error as NodeReleaseError).releases).toEqual([missing]); + expect((error as Error).message).toContain(executableIn(missing)); + } + for (const version of provisioned) { + expect(await resolveNodeRelease(version, lookup)).toEqual({ + version, + executable: executableIn(version), + }); + } + const unnamed = await rejectionOf(() => + resolveNodeReleases({ environment: {} }), + ); + expect(unnamed).toBeInstanceOf(NodeReleaseError); + expect(unnamed).not.toBeInstanceOf(HarnessAssertionError); + expect((unnamed as NodeReleaseError).fault).toBe("directory"); + expect((unnamed as Error).message).toContain( + `${NODE_RELEASES_DIR_VARIABLE} is unset`, + ); +}); + +test("S-10, run conditions: on each of E-1's releases and along each of Node.js's four routes, each run carries no option, an environment of exactly HOME, TMPDIR, and PATH — no NODE_OPTIONS or NODE_PATH — and no user condition, loader, or hook, and has a fresh HOME, TMPDIR, and working directory, each its own, empty, outside the staging, and removed afterwards: a stray NODE_OPTIONS carrying a user condition the dual stand-in's exports map answers and a preloaded hook announcing itself through a process warning, and a stray NODE_PATH naming a folder that holds a decoy under N — each answered by the release given it directly — stand in the harness's own environment and reach no run, which loads the dual stand-in's conditionless entry for its route, with no warning and nothing on standard error (TEST-SPEC S-10, T7.6-6's run conditions, T7.6-7)", async () => { + const releases = await resolveNodeReleases(); + const staged = await stageStandIn( + "dual", + releases, + "S-10 run conditions: dual", + ); + const name = staged.placement.name; + const strays = await writeStrays(name); + // The vectors are live: each release given the strays directly answers + // the user condition, runs the hook, and finds the decoy through + // NODE_PATH where no node_modules holds N. + for (const release of releases) { + const context = `S-10 run conditions: the strays given to ${release.version} directly`; + const answered = await requireDirectly( + release, + staged.placement.holdingDir, + strays.environment, + name, + ); + expect(answered.stdout, context).toBe(ENTRY_LINES.condition); + expect(answered.stderr, context).toContain(STRAY_HOOK_CODE); + const decoy = await requireDirectly( + release, + strays.outside, + strays.environment, + name, + ); + expect(decoy.stdout, context).toBe(DECOY_LINE); + } + const places = new Set<string>(); + await withAmbient(strays.environment, async () => { + for (const release of releases) { + for (const route of MODULE_ROUTES) { + const context = `S-10 run conditions: dual, ${release.version}, ${route}`; + const prepared = await prepareModuleRun( + request(staged, release, route, context), + ); + let run: LoadedModuleRun; + try { + for (const place of [prepared.home, prepared.tmp, prepared.cwd]) { + expect(await fsp.readdir(place), context).toEqual([]); + expect(within(place, staged.staging.root), context).toBe(false); + expect(places.has(place), context).toBe(false); + places.add(place); + } + run = assertModuleLoaded(await prepared.launch(), "stand-in"); + } finally { + await prepared.dispose(); + } + expect(await exists(prepared.root), context).toBe(false); + const { report } = run; + expect(report.release.execArgv, context).toEqual([]); + expect(report.environment, context).toEqual( + moduleRunEnvironment(prepared.home, prepared.tmp), + ); + for (const variable of ["NODE_OPTIONS", "NODE_PATH"]) { + expect(report.environment[variable], context).toBeUndefined(); + } + expect(report.environment["HOME"], context).toBe(prepared.home); + expect(report.cwd, context).toBe(prepared.cwd); + expect(run.result.stdout, context).toBe( + route === "require" ? ENTRY_LINES.commonJs : ENTRY_LINES.module, + ); + expect(report.warnings, context).toEqual([]); + expect(run.result.stderr, context).toBe(""); + } + } + }); + expect(places.size).toBe(releases.length * MODULE_ROUTES.length * 3); +}); + +test("S-10, routes: on each of E-1's releases, each of Node.js's four routes is the one exercised — the importing module runs as its route's own kind from its physical path, an ES module for static import and dynamic import from a module, a CommonJS module for dynamic import from CommonJS and require — and the dual stand-in, whose entries each report their own format when loaded, answers the import routes from its ES-module entry, a namespace of exactly defineConfig, and the require route from its CommonJS one, an object of exactly defineConfig; the ES-module-only stand-in loads along each import route on every release, and its require route fails, refused as an ES module's load (ERR_REQUIRE_ESM), on each release before 22.12.0 and loads on each later one, each class holding at least one of E-1's releases (TEST-SPEC S-10, T7.6-6, E-1)", async () => { + const releases = await resolveNodeReleases(); + const dual = await stageStandIn("dual", releases, "S-10 routes: dual"); + const moduleOnly = await stageStandIn( + "module-only", + releases, + "S-10 routes: ES-module only", + ); + const refusedOn: string[] = []; + const loadedOn: string[] = []; + for (const release of releases) { + for (const route of MODULE_ROUTES) { + const context = `S-10 routes: dual, ${release.version}, ${route}`; + const run = await loadedRun(dual, release, route, context); + expect(run.report.release.version, context).toBe(`v${release.version}`); + expect(run.report.importingModule, context).toEqual( + kindNote(route, run.importingModule), + ); + expect(run.result.stdout, context).toBe( + route === "require" ? ENTRY_LINES.commonJs : ENTRY_LINES.module, + ); + expect(run.report.load.value, context).toEqual({ + type: "object", + ownKeys: + route === "require" + ? [DEFINE_CONFIG_KEY] + : [DEFINE_CONFIG_KEY, TO_STRING_TAG_KEY], + }); + expect(exportsProblems(run), context).toEqual([]); + expect(run.result.stderr, context).toBe(""); + } + for (const route of IMPORT_ROUTES) { + const context = `S-10 routes: ES-module only, ${release.version}, ${route}`; + const run = await loadedRun(moduleOnly, release, route, context); + expect(run.report.importingModule, context).toEqual( + kindNote(route, run.importingModule), + ); + expect(run.report.load.value, context).toEqual({ + type: "object", + ownKeys: [DEFINE_CONFIG_KEY, TO_STRING_TAG_KEY], + }); + } + const context = `S-10 routes: ES-module only, ${release.version}, require`; + const run = await runModuleRoute( + request(moduleOnly, release, "require", context), + ); + if (precedes(release.version, REQUIRE_MODULE_RELEASE)) { + refusedOn.push(release.version); + expect(run.outcome, context).toBe("load-failed"); + const load = run.report?.load; + expect(load?.outcome === "failed" ? load.error.code : null, context).toBe( + "ERR_REQUIRE_ESM", + ); + } else { + loadedOn.push(release.version); + const loaded = assertModuleLoaded(run, "stand-in"); + expect(loaded.report.importingModule, context).toEqual( + kindNote("require", loaded.importingModule), + ); + expect(exportsProblems(loaded), context).toEqual([]); + } + } + expect(refusedOn.length).toBeGreaterThan(0); + expect(loadedOn.length).toBeGreaterThan(0); +}); + +test("S-10, the runtime's own loading output: on each of E-1's releases, the two minimal stand-ins — one with an ES-module entry, one with a CommonJS entry — leave T7.6-7(c)'s observed state unchanged along each route that loads them, and their loading output there passes T7.6-7(a)'s output oracle, the warning a release prints for the ES-module entry's load through require admitted; and so does the loading output of the stand-ins whose manifests draw the release's own deprecations — an invalid main beside an index.js along require (DEP0128) and an ES-module package's main lookup along each import route (DEP0151) — wherever the release prints one, their state unchanged likewise, the minimal ES-module stand-in and each deprecation stand-in drawing a warning on at least one release, so the oracle admits the runtime's own loading output (TEST-SPEC S-10, T7.6-7(a), (c))", async () => { + const releases = await resolveNodeReleases(); + const families: readonly { + readonly standIn: StandIn; + readonly routes: readonly ModuleRoute[]; + /** Whether it must draw a warning of the release's own on some release. */ + readonly draws: boolean; + }[] = [ + { standIn: "module-only", routes: MODULE_ROUTES, draws: true }, + { standIn: "commonjs", routes: MODULE_ROUTES, draws: false }, + { standIn: "invalid-main", routes: ["require"], draws: true }, + { standIn: "main-lookup", routes: IMPORT_ROUTES, draws: true }, + ]; + const staged = new Map<StandIn, StagedStandIn>(); + for (const family of families) { + staged.set( + family.standIn, + await stageStandIn( + family.standIn, + releases, + `S-10 own output: ${family.standIn}`, + ), + ); + } + const drawn = new Map<StandIn, number>(); + for (const release of releases) { + for (const family of families) { + const placed = staged.get(family.standIn); + if (placed === undefined) throw new Error("a family went unstaged"); + for (const route of family.routes) { + const context = `S-10 own output: ${family.standIn}, ${release.version}, ${route}`; + const run = await runModuleRoute( + request(placed, release, route, context), + ); + if ( + family.standIn === "module-only" && + route === "require" && + precedes(release.version, REQUIRE_MODULE_RELEASE) + ) { + // Refused on these releases, as the routes test pins. + expect(run.outcome, context).toBe("load-failed"); + continue; + } + const loaded = assertModuleLoaded(run, "stand-in"); + expect(loaded.report.state.changes, context).toEqual([]); + expect(loaded.report.state.omitted, context).toBe(0); + expect(stateProblems(loaded), context).toEqual([]); + expect(await runtimeOutputProblems(loaded), context).toEqual([]); + if (loaded.report.warnings.length > 0) { + drawn.set(family.standIn, (drawn.get(family.standIn) ?? 0) + 1); + } + } + } + } + for (const family of families) { + if (family.draws) { + expect(drawn.get(family.standIn) ?? 0, family.standIn).toBeGreaterThan(0); + } + } +}); + +test("S-10, catches: a stand-in writing a line to standard output as it loads, along each of Node.js's four routes on each of E-1's releases, is caught by T7.6-7(a)'s output oracle — standard output not empty — and by nothing else of it, standard error empty and no warning captured (TEST-SPEC S-10, T7.6-7(a))", async () => { + await checkEachRun("prints-stdout", MODULE_ROUTES, async (run, context) => { + expect(run.result.stdout, context).toBe( + `prints-stdout: a line the module writes${LF}`, + ); + expect(run.result.stderr, context).toBe(""); + expect(run.report.warnings, context).toEqual([]); + const problems = await runtimeOutputProblems(run); + expect(problems, context).toHaveLength(1); + expect(problems[0], context).toContain("standard output is not empty"); + }); +}); + +test("S-10, catches: a stand-in writing a line to standard error outside the release's warning form as it loads, along each of Node.js's four routes on each of E-1's releases, is caught by T7.6-7(a)'s output oracle — standard error not exactly the printed forms of the run's warnings, of which it captured none — and by nothing else of it (TEST-SPEC S-10, T7.6-7(a))", async () => { + await checkEachRun("prints-stderr", MODULE_ROUTES, async (run, context) => { + expect(run.result.stdout, context).toBe(""); + expect(run.result.stderr, context).toBe( + `prints-stderr: a line the module writes${LF}`, + ); + expect(run.report.warnings, context).toEqual([]); + const problems = await runtimeOutputProblems(run); + expect(problems, context).toHaveLength(1); + expect(problems[0], context).toContain( + "standard error is not exactly the release's printed forms of the 0 " + + "warning(s) the run emits", + ); + }); +}); + +test("S-10, catches: a stand-in writing to standard error, as it loads and through no warning facility, text byte for byte the release's printed form of a first warning — its process identifier, bracketed code, type, and message, and the hint line the release appends — along each of Node.js's four routes on each of E-1's releases, is caught by T7.6-7(a)'s output oracle, no captured warning standing behind it, and by nothing else of it (TEST-SPEC S-10, T7.6-7(a))", async () => { + await checkEachRun( + "prints-warning-form", + MODULE_ROUTES, + async (run, context) => { + const form = await learnWarningForm(run.release); + const forged = renderWarnings( + [forgedWarning(FORGED_FIRST_MESSAGE)], + run.report.pid, + form, + ); + expect(forged.ok, context).toBe(true); + if (!forged.ok) return; + expect(run.result.stdout, context).toBe(""); + expect(run.result.stderr, context).toBe(forged.text); + expect(run.report.warnings, context).toEqual([]); + const problems = outputProblems(run, form); + expect(problems, context).toHaveLength(1); + expect(problems[0], context).toContain( + "standard error is not exactly the release's printed forms of the 0 " + + "warning(s) the run emits", + ); + }, + ); +}); + +test("S-10, catches: a stand-in writing to standard error a line of its own in the release's warning form after a warning the release prints — DEP0128 along require (an invalid main beside an index.js), DEP0151 along each import route (an ES-module package's main lookup) — on each of E-1's releases, is caught by T7.6-7(a)'s output oracle, standard error being the release's printed forms of the run's warnings with that line after them, and by nothing else of it; each release warning, where printed, the layout's deprecation, and each layout's printed by at least one release, so the line follows one (TEST-SPEC S-10, T7.6-7(a))", async () => { + const layouts = [ + { + standIn: "prints-after-dep0128", + routes: ["require"], + code: "DEP0128", + }, + { + standIn: "prints-after-dep0151", + routes: IMPORT_ROUTES, + code: "DEP0151", + }, + ] as const satisfies readonly { + readonly standIn: StandIn; + readonly routes: readonly ModuleRoute[]; + readonly code: string; + }[]; + for (const layout of layouts) { + let drawn = 0; + await checkEachRun(layout.standIn, layout.routes, async (run, context) => { + const { warnings, pid } = run.report; + expect( + warnings.map((warning) => [warning.name, warning.code]), + context, + ).toEqual(warnings.map(() => ["DeprecationWarning", layout.code])); + expect(warnings.length, context).toBeLessThanOrEqual(1); + const form = await learnWarningForm(run.release); + if (warnings.length > 0) { + drawn += 1; + const printed = renderWarnings( + [...warnings, forgedWarning(FORGED_AFTER_MESSAGE)], + pid, + form, + ); + expect(printed.ok, context).toBe(true); + if (!printed.ok) return; + expect(run.result.stderr, context).toBe(printed.text); + } else { + expect(run.result.stderr, context).toBe( + `(node:${String(pid)}) [${FORGED_CODE}] Warning: ` + + `${FORGED_AFTER_MESSAGE}${LF}`, + ); + } + expect(run.result.stdout, context).toBe(""); + const problems = outputProblems(run, form); + expect(problems, context).toHaveLength(1); + expect(problems[0], context).toContain( + `standard error is not exactly the release's printed forms of the ` + + `${String(warnings.length)} warning(s) the run emits`, + ); + }); + expect(drawn, layout.standIn).toBeGreaterThan(0); + } +}); + +test("S-10, catches: a stand-in emitting a warning through the runtime's warning facility (process.emitWarning) as it loads, along each of Node.js's four routes on each of E-1's releases, is caught by T7.6-7(a)'s output oracle by the warning's stack alone — its first frame naming the stand-in's entry for the route, by file URL from the ES-module entry and by path from the CommonJS one — the release printing the warning in its own form, so standard error matches it, and nothing else of the oracle failing (TEST-SPEC S-10, T7.6-7(a))", async () => { + await checkEachRun("emits-warning", MODULE_ROUTES, async (run, context) => { + expect( + run.report.warnings.map((warning) => [ + warning.name, + warning.code, + warning.message, + ]), + context, + ).toEqual([ + [ + "XspecS10Warning", + "XSPEC_S10_EMITTED", + "a warning the module emits while it loads", + ], + ]); + const [warning] = run.report.warnings; + if (warning === undefined) return; + const entry = path.join(run.placement.path, dualEntry(run.route)); + expect(packageFrame(warning, run.placement), context).toContain( + run.route === "require" ? `(${entry}:` : `${pathToFileURL(entry).href}:`, + ); + expect(run.result.stdout, context).toBe(""); + const problems = await runtimeOutputProblems(run); + expect(problems, context).toHaveLength(1); + expect(problems[0], context).toContain( + "begins its stack in the package's files", + ); + }); +}); + +for (const caught of STATE_CATCHES) { + const observations = [ + ...new Set(caught.changes.map(([observation]) => observation)), + ]; + test(`S-10, catches: a stand-in that ${caught.effect} as it loads, along each of Node.js's four routes on each of E-1's releases, is caught by T7.6-7(c)'s comparison of the process state under ${observations.map((name) => `the ${name} observation`).join(" and ")} — each difference listed with its subject, none other, and none omitted — every other observation of T7.6-6 and T7.6-7(a) finding nothing (TEST-SPEC S-10, T7.6-7(c))`, async () => { + await checkEachRun(caught.standIn, MODULE_ROUTES, async (run, context) => { + const { changes, omitted } = run.report.state; + expect( + changes.map((change) => [change.observation, change.subject]), + context, + ).toEqual( + caught.changes.map(([observation, subject]) => [observation, subject]), + ); + expect(omitted, context).toBe(0); + caught.changes.forEach(([, , detail], index) => { + expect(changes[index]?.detail, context).toContain(detail); + }); + const problems = stateProblems(run); + expect(problems, context).toHaveLength(caught.changes.length); + for (const problem of problems) { + expect(problem, context).toContain("TEST-SPEC T7.6-7(c)"); + } + expect(exportsProblems(run), context).toEqual([]); + expect(identityProblems(run), context).toEqual([]); + expect(examinationProblems(run), context).toEqual([]); + expect(await runtimeOutputProblems(run), context).toEqual([]); + }); + }); +} + +test("S-10, catches: a stand-in whose defineConfig returns a copy of an object or array argument, along each of Node.js's four routes on each of E-1's releases, is caught by T7.6-6(b)'s identity observation — the object, the array, and the first of two arguments each returned as another object, compared by SameValue — and by (c)'s, the frozen object likewise, no Proxy's trap touched; so the pairing fails (TEST-SPEC S-10, T7.6-6(b), (c))", async () => { + await checkEachRun("copies-argument", MODULE_ROUTES, (run, context) => { + const { results, traps } = run.report.calls; + expect( + results + .filter((result) => result.outcome !== "returned-argument") + .map((result) => [result.case, result.outcome, result.returned]), + context, + ).toEqual( + ["object", "array", "further-arguments", "frozen"].map((name) => [ + name, + "returned-other", + { type: "object", text: null }, + ]), + ); + expect(traps, context).toEqual([]); + const identity = identityProblems(run); + expect(identity, context).toHaveLength(3); + for (const problem of identity) { + expect(problem, context).toContain( + "it returned another object instead, compared by SameValue", + ); + } + const examination = examinationProblems(run); + expect(examination, context).toHaveLength(1); + expect(examination[0], context).toContain( + `${describeCallCase("frozen")}: it returned another object instead`, + ); + expect(pairingProblem(run), context).not.toBeNull(); + }); +}); + +test("S-10, catches: a stand-in whose defineConfig reads a property of a function argument — the get trap of the first recording Proxy — and returns its argument, along each of Node.js's four routes on each of E-1's releases, is caught by T7.6-6(c)'s observation of the Proxies' traps through the run's end, and by nothing else, every call returning its argument (TEST-SPEC S-10, T7.6-6(c))", async () => { + await checkEachRun("touches-proxy", MODULE_ROUTES, (run, context) => { + expect(run.report.calls.traps, context).toEqual([ + { proxy: "first", trap: "get" }, + ]); + const problems = examinationProblems(run); + expect(problems, context).toHaveLength(1); + expect(problems[0], context).toContain("get on the first Proxy"); + expect(identityProblems(run), context).toEqual([]); + expect(pairingProblem(run), context).toBeNull(); + }); +}); + +test("S-10, catches: a stand-in writing a file as it loads into each of the four places T7.6-7(b) compares — its working directory, HOME, TMPDIR, and the staging, there inside its own placement — along each of Node.js's four routes on each of E-1's releases, in a run observing its effects, is caught by T7.6-7(b)'s comparison in each place, the entry created there named and described, and by nothing else of (b), (c), or (e) (TEST-SPEC S-10, T7.6-7(b))", async () => { + const releases = await resolveNodeReleases(); + const staged = await stageStandIn( + "writes-file", + releases, + "S-10 catches: writes-file", + ); + const own = path + .relative(staged.staging.root, staged.placement.path) + .split(path.sep) + .join("/"); + for (const release of releases) { + for (const route of MODULE_ROUTES) { + const context = `S-10 catches: writes-file, ${release.version}, ${route}`; + const run = assertModuleLoaded( + await runModuleRoute({ + ...request(staged, release, route, context), + effects: true, + }), + "stand-in", + ); + const writes = run.effects?.writes ?? []; + expect( + writes.map((place) => [ + place.place, + place.changes.map((change) => [change.change, change.detail]), + ]), + context, + ).toEqual( + ["staging", "working directory", "HOME", "TMPDIR"].map((place) => [ + place, + [["created", "it is a plain file of 7 byte(s)"]], + ]), + ); + const names = writes.map((place) => { + const written = place.changes[0]?.path ?? ""; + const prefix = place.place === "staging" ? `${own}/` : ""; + expect(written.startsWith(`${prefix}writes-file-`), context).toBe(true); + return written.slice(prefix.length); + }); + expect(new Set(names).size, context).toBe(1); + const problems = writeProblems(run); + expect(problems, context).toHaveLength(4); + problems.forEach((problem, index) => { + expect(problem, context).toContain(`(${writes[index]?.root ?? ""})`); + expect(problem, context).toContain("TEST-SPEC T7.6-7(b)"); + }); + expect(fifoProblems(run), context).toEqual([]); + expect(stateProblems(run), context).toEqual([]); + } + } +}); + +test("S-10, catches: a stand-in opening, as it loads, each of T7.6-7(e)'s FIFOs — xspec.config.ts in its working directory, in the importing module's directory, and in HOME — for reading, along each of Node.js's four routes on each of E-1's releases, in runs observing their effects with a lowered guard (each route's runs launched side by side once all are prepared), is caught by the run's guard: each run ends at it with the driver's hang-guard kill (ProductRunTimeoutError), its partial standard output showing each open begun and none returned, nothing on standard error, and each FIFO still a FIFO (TEST-SPEC S-10, T7.6-7(e), S-3)", async () => { + const releases = await resolveNodeReleases(); + const staged = await stageStandIn( + "opens-fifos", + releases, + "S-10 catches: opens-fifos", + ); + for (const route of MODULE_ROUTES) { + const prepared: PreparedModuleRun[] = []; + try { + for (const release of releases) { + prepared.push( + await prepareModuleRun({ + ...request( + staged, + release, + route, + `S-10 catches: opens-fifos, ${release.version}, ${route}`, + ), + effects: true, + guards: { timeoutMs: FIFO_RUN_GUARD_MS }, + }), + ); + } + const settled = await Promise.allSettled( + prepared.map((run) => run.launch()), + ); + for (const [index, outcome] of settled.entries()) { + const run = prepared[index]; + if (run === undefined) throw new Error("a prepared run went missing"); + const context = run.description; + expect(outcome.status, context).toBe("rejected"); + if (outcome.status !== "rejected") continue; + const reason: unknown = outcome.reason; + expect(reason, context).toBeInstanceOf(ProductRunTimeoutError); + const opening = run.fifos + .map((fifo) => `opens-fifos: opening ${fifo}${LF}`) + .join(""); + expect((reason as Error).message, context).toContain( + `Partial stdout: ${opening}; partial stderr: <empty>`, + ); + expect(run.fifos, context).toHaveLength(3); + for (const fifo of run.fifos) { + expect((await fsp.lstat(fifo)).isFIFO(), context).toBe(true); + } + } + } finally { + for (const run of prepared) await run.dispose(); + } + } +}); diff --git a/test/self/s3-subprocess-driver.test.ts b/test/self/s3-subprocess-driver.test.ts index 5f7c8867..ebbc0c40 100644 --- a/test/self/s3-subprocess-driver.test.ts +++ b/test/self/s3-subprocess-driver.test.ts @@ -104,6 +104,7 @@ import { VoidedTrialsExhaustedError, } from "../helpers/kill-discipline.js"; import type * as MdxDerivabilityModule from "../helpers/mdx-derivability.js"; +import { NodeReleaseError } from "../helpers/node-releases.js"; import { HarnessStagingError, stageDirectoryMode, @@ -113,6 +114,7 @@ import { builtProductBindingAt, createHoldFile, HarnessEvaluationError, + PACKAGE_DIR_VARIABLE, pathExists, productEnvironment, ProductRunOutputOverflowError, @@ -648,8 +650,13 @@ test("the built product's missing artifact fails every run diagnosed — a `Harn expect(await fsp.readdir(absentRoot)).toEqual([]); }); -test("builtProductBinding names the built executable absolutely, independent of the process cwd, its missing artifact marked the missing product; builtProductBindingAt is that shape at another path (C-2 default binding; H-8)", () => { - const binding = builtProductBinding(); +test("builtProductBinding names the built executable absolutely, independent of the process cwd, its missing artifact marked the missing product; builtProductBindingAt is that shape at another path, with no package directory (C-2 default binding; H-8)", () => { + // An environment naming no package directory, so this pins the shape + // alike where the ambient one names one (CI's full-suite job sets + // XSPEC_PACKAGE_DIR) and where it does not; the variable's reading is + // the next test's. + const binding = builtProductBinding({}); + expect("packageDir" in binding).toBe(false); expect(binding.label).toBe("built xspec product"); expect(binding.command).toBe(process.execPath); expect(binding.prefixArgs).toHaveLength(1); @@ -676,6 +683,66 @@ test("builtProductBinding names the built executable absolutely, independent of expect(builtProductBindingAt(binJs)).toStrictEqual(binding); }); +test("builtProductBinding carries, as its packageDir, the package directory XSPEC_PACKAGE_DIR names — exactly as spelled, read from the process environment when the binding is made — and none where the variable is unset or empty; builtProductBindingAt carries none, whatever the environment names (C-2, H-2's module channel; H-8)", () => { + onTestFinished(() => { + vi.unstubAllEnvs(); + }); + expect(PACKAGE_DIR_VARIABLE).toBe("XSPEC_PACKAGE_DIR"); + const bare = builtProductBinding({}); + expect("packageDir" in bare).toBe(false); + // Exactly as spelled: never normalized, and never resolved against the + // working directory — whether the path is usable is for the module + // channel to check where a test of 7.6 reaches for the module. + // (The last two are joined by hand: `path.join` would normalize the `..` + // and `.` segments and the trailing separator away.) + for (const spelled of [ + path.join(os.tmpdir(), "xspec-package", "package"), + [os.tmpdir(), "a", "..", "b", ".", "package", ""].join(path.sep), + ["relative", "package"].join(path.sep), + ]) { + expect( + builtProductBinding({ [PACKAGE_DIR_VARIABLE]: spelled }), + spelled, + ).toStrictEqual({ ...bare, packageDir: spelled }); + } + // Unset or empty, none; nor does another variable stand in for it, the + // module channel's other input included. + for (const environment of [ + {}, + { [PACKAGE_DIR_VARIABLE]: undefined }, + { [PACKAGE_DIR_VARIABLE]: "" }, + { XSPEC_NODE_RELEASES_DIR: path.join(os.tmpdir(), "releases") }, + ]) { + expect(builtProductBinding(environment)).toStrictEqual(bare); + } + + // The default environment is the process's, read by the call making the + // binding — never when the driver was imported. + const ambient = path.join(os.tmpdir(), "xspec-ambient-package", "package"); + vi.stubEnv(PACKAGE_DIR_VARIABLE, ambient); + expect(builtProductBinding()).toStrictEqual({ ...bare, packageDir: ambient }); + vi.stubEnv(PACKAGE_DIR_VARIABLE, ""); + expect(builtProductBinding()).toStrictEqual(bare); + vi.stubEnv(PACKAGE_DIR_VARIABLE, undefined); + expect(builtProductBinding()).toStrictEqual(bare); + + // The no-product shape gives the module channel nothing, whatever the + // environment names (H-8: the module channel counts as part of the + // product). + vi.stubEnv(PACKAGE_DIR_VARIABLE, ambient); + const elsewhere = path.join( + os.tmpdir(), + "xspec-s3-elsewhere", + "dist", + "cli", + "bin.js", + ); + expect("packageDir" in builtProductBindingAt(elsewhere)).toBe(false); + expect("packageDir" in builtProductBindingAt(bare.prefixArgs![0]!)).toBe( + false, + ); +}); + test("background start with hold-file choreography: await creation, hold, release, completion (13.5 seam support)", async () => { const { workspace, binding } = await standin(); const holdPath = path.join(workspace.tempRoot, "hold"); @@ -982,7 +1049,7 @@ test("waitForFile surfaces a capture-limit kill as the driver's ProductRunOutput expect(settled).toBe(error); }); -test("rethrowHarnessError rethrows exactly the harness errors — the capture-limit error, a failed in-run evaluation, a group kill that could not confirm its group gone, an exhausted voidable trial, and a harness step's tripped guard — unchanged, and returns for every other rejection a helper converts (H-11; TEST-SPEC S-3)", () => { +test("rethrowHarnessError rethrows exactly the harness errors — the capture-limit error, a failed in-run evaluation, a group kill that could not confirm its group gone, an exhausted voidable trial, a harness step's tripped guard, and a Node.js release E-1 lists left unprovisioned — unchanged, and returns for every other rejection a helper converts (H-11; TEST-SPEC S-3, E-1)", () => { for (const harnessError of [ new ProductRunOutputOverflowError("capture limit"), new ProcessGroupLingerError("stand-in", 4242, "listed", 30_000, [], [4243]), @@ -998,6 +1065,15 @@ test("rethrowHarnessError rethrows exactly the harness errors — the capture-li "prepare", new RangeError("parser limit"), ), + new NodeReleaseError( + "release", + "the Node.js release 22.12.0 is not provisioned under a stand-in", + ["22.12.0"], + ), + new NodeReleaseError( + "directory", + "XSPEC_NODE_RELEASES_DIR is unset in a stand-in", + ), ]) { let rethrown: unknown = null; try { diff --git a/test/self/s4-module-channel.test.ts b/test/self/s4-module-channel.test.ts new file mode 100644 index 00000000..ce8c995c --- /dev/null +++ b/test/self/s4-module-channel.test.ts @@ -0,0 +1,1171 @@ +// S-4's detections of 7.6's covered setups (TEST-SPEC 17 S-4, from "7.6's +// covered setups are detected in effect likewise"; §7.6 Covered setups, +// Verdict; SPEC 7.6 Covered setups). Every type-checking arm of 7.6 judges +// its files through the module channel's TypeScript driver +// (helpers/module-channel-ts.ts) in each of the 173 covered setups. A driver +// serving one setup's settings for another's would make that setup's arms a +// rerun of the other's, one dropping a setup or a setting would leave it +// unjudged, and a verdict blind to a diagnostic kind would miss what that +// kind reports, each passing conformer and violator alike. So, before any +// product exists, each setting is detected in effect here through that same +// driver (`stageCoveredFiles`, `CoveredFiles.judge`), over hand-written +// non-xspec stand-in packages placed as the tests place a package +// (helpers/module-channel.ts: a fresh staging, the canonical placement, +// Reach verified, nothing else installed but the one `@types` stand-in the +// `types` detection needs), in each setup whose verdict the setting decides, +// both sides: rejected where the setting rejects the construct, admitted +// where it admits it. T7.6-1's export listing, which the same driver reads, +// is detected last (below). +// +// The detections, each with the setups it is judged in and those that +// reject it (release 5.9.3's verdicts, wherever it gives a value an effect +// of its own; TypeScript's error code is a diagnostic aid, never pinned). +// First, the fourteen strict defaults' `moduleResolution` and `module` +// values, which spell every value the matrix holds, each judged in +// strict-default setups alone: +// - `moduleResolution`: an `exports`-only stand-in, which `node10` alone does +// not resolve — every strict-default setup, rejected under `node10` (an +// error at the import's specifier, TS2307), admitted under `node16`, +// `nodenext`, and `bundler`. +// - `module` under the `node16` and `nodenext` modes, each file TypeScript +// compiles as CommonJS (`.cts` in every project, `.ts` and `.tsx` in the +// two CommonJS ones): an ES-module-only stand-in, rejected under `node16` +// and `node18` (an error at the specifier, TS1479), admitted under `node20` +// and `nodenext`, which let `require` load an ES module. +// - `module` under those modes, each file TypeScript compiles as an ES +// module (`.mts` in every project, `.ts` and `.tsx` in the ES-module one): +// import attributes on an import of a JavaScript module, rejected under +// `node16` (an error at the attributes, TS2823), admitted under `node18`, +// `node20`, and `nodenext`. +// - `module`'s default target under those modes, every file: `Object.groupBy`, +// which the library of `nodenext`'s default target (`esnext`) brings and +// those of `node16`'s and `node18`'s (`es2022`) and `node20`'s (`es2023`) +// do not — rejected under those three (an error at `groupBy`, TS2550), +// admitted under `nodenext`. +// - `module` under `bundler`: `import.meta`, rejected by `es2015` alone (an +// error at `import.meta`, TS1343); a string-literal import name, rejected +// by `es2015` and `es2020` (an error at the name, TS18057); an import +// assignment, rejected by every value but `preserve` (an error at the +// declaration, TS1202) — each in every file; and import attributes, +// rejected by `es2015`, `es2020`, and `es2022` (TS2823) and admitted by +// `esnext` and `preserve`, in each file TypeScript compiles as an ES module +// there: every one but a `.cts` file, which `bundler` compiles as CommonJS +// and where attributes compile to `require` calls, rejected whatever the +// value (TS2856). +// Each pair of neighboring values in a chain — `node10` and the other modes; +// `module` `node16`, `node18`, `node20`, `nodenext`; `es2015`, `es2020`, +// `es2022`, `esnext`, `preserve` — is told apart by one detection. Release +// 5.9.3's `node16` and `nodenext` resolvers share one feature set, so beside +// a common `module` value those two `moduleResolution` values have no effect +// of their own to detect. +// +// Then the initialized-project set's own options, the strict defaults' +// `strict`, the module format, and the verdict's reach, each but the module +// format judged in all 173 setups: +// - `verbatimModuleSyntax`: a type imported without a `type` modifier +// (`Settings`, from the `typed` stand-in), rejected under the initialized +// set alone (an error at the type's name, TS1484). +// - `exactOptionalPropertyTypes`: a variable whose type holds an optional +// property, initialized with that property `undefined`, rejected under the +// initialized set alone (an error at the variable, TS2375). +// - `noUncheckedIndexedAccess`: a list's element read by index into a +// variable typed `string`, rejected under the initialized set alone (an +// error at the variable, TS2322). +// - `noUncheckedSideEffectImports`: a side-effect import of a module that +// does not exist, rejected under the initialized set alone (an error at +// its specifier, TS2307). +// - `skipLibCheck`: the `declaration-error` stand-in, whose declaration files +// name a type that does not exist, rejected under the strict defaults (an +// error at that name in the declaration file TypeScript resolves, TS2304) +// and admitted under the initialized set, which skips declaration files. +// - `types` `[]`: an `@types` stand-in installed beside the placement, which +// TypeScript includes automatically under the strict defaults — there the +// driver refuses the staging before any verdict, SPEC 7.6's program +// condition failing — and keeps out of the program under the initialized +// set, where the file type-checks. +// - `strict`, the strict defaults': the `implicit-any` stand-in, whose +// declaration files leave a parameter implicitly typed, rejected under the +// strict defaults (an error at the parameter, TS7006, which `strict` alone +// raises there, `skipLibCheck` being off) and admitted under the +// initialized set, which skips declaration files. The initialized set's +// own `strict` needs no stand-in: dropped, it surfaces as an options error +// (TS5052, `exactOptionalPropertyTypes` requiring `strictNullChecks`), +// which fails every admission under that set here. +// - The module format the project and the extension imply: `import.meta`, +// judged under the `node16` and `nodenext` modes and the initialized set +// (101 setups), rejected in each file TypeScript compiles as CommonJS +// there (an error at `import.meta`, TS1470) and admitted in each it +// compiles as an ES module. +// - The verdict's reach into declaration diagnostics: the +// `unexported-return` stand-in, whose `defineConfig` returns an interface +// the stand-in does not export, its call's valid default export rejected +// under the initialized set alone, which turns `declaration` on (an error +// at the export, TS4082, a declaration diagnostic, every other kind +// empty). Its twin, calling the stand-in's `defineVisible`, alike but for +// returning an interface the stand-in exports, type-checks in every setup, +// so the rejection is declaration emit's alone. +// +// Last, T7.6-1's export listing, which the driver reads from each file's +// own program where a request asks for it (`listExports`): a listing blind +// to an implicit export or to an export assignment's members would pass a +// package declaring more than `defineConfig`. Each detection judges a plain +// import in all 173 setups and pins the listing whole — the declaration +// file TypeScript resolves, whether it declares an export assignment, and +// every name with its meanings and where TypeScript lists it: +// - an interface a declaration module never marks `export`, with no export +// list (`export {}`): the `implicit-export` stand-in lists, beside +// `defineConfig` (a value), its interface (a type), both among the +// module's exports, through the declaration file each setup resolves — +// the `import` entry's in 102 setups and the `require` entry's in 71, +// each entry's interface named for it, so a listing read from another +// file than the one TypeScript resolves fails too; +// - an export assignment's members: the `export-assignment` stand-in, whose +// declaration file assigns a value carrying `defineConfig` and one other +// member, `other`, lists both, each a value among the assignment's +// members, the module's exports proper empty, in every setup. +// +// A rejection is pinned by its effect: TypeScript reports at least one +// error for the file's program and every one of them lies where the +// construct begins — in the configuration file, or, for `skipLibCheck` and +// `strict`, in the stand-in's declaration file TypeScript resolves — its line +// and column computed from that file's own text, the construct occurring +// there once, so a setup rejecting the file for any other reason fails here +// as surely as one admitting it. An admission is the driver's verdict that +// the file type-checks: no error anywhere in its program (TEST-SPEC §7.6 +// Verdict). The ES-module and CommonJS files are written out here apart from +// the driver's own reading, and each detection's count of setups judged and +// rejecting is pinned, so a matrix dropping a setup fails here too. Every +// mismatch of a detection is collected and reported at once, naming its +// setup. +// +// The stand-ins, test/fixtures/s4-module-channel/, documented here since +// JSON holds no comment: each a package declaring `defineConfig<T>(value: +// T): T` where not said otherwise, its runtime files returning their +// argument, and nothing else. +// - `exports-only`: an `exports` map and nothing else naming an entry — no +// top-level `types` or `main`, no root `index` — serving `import` an ES +// module typed by `entry.d.ts` and `require` a CommonJS module typed by +// `entry.d.cts` (`"type": "module"`), so every mode reading `exports` +// resolves it from every file, and `node10`, which reads none, does not. +// - `esm-only`: `"type": "module"`, its `exports` map's one entry an ES +// module typed by `index.d.ts`, so a file TypeScript compiles as CommonJS +// reaches an ES module through `require`. +// - `dual`: the dual-entry layout AGENTS.md's scaffold note describes (the +// top-level `types` for `node10`; `exports` serving `import` an ES module +// typed by `index.d.ts` and `require` a CommonJS module typed by +// `index.d.cts`), resolved in every setup, for the constructs judged on +// their own. +// - `typed`, `declaration-error`, `implicit-any`, and `unexported-return`: +// `dual`'s layout, the two declaration files of each identical. `typed` +// exports an interface `Settings` beside `defineConfig`; +// `declaration-error` declares, unexported (`export {}`), a constant of a +// type that does not exist; `implicit-any` exports a function `loosely` +// whose parameter is left untyped; `unexported-return` declares +// `defineConfig(value: Hidden): Hidden`, `Hidden` an interface it leaves +// unexported (`export {}` keeps it so), and `defineVisible(value: +// Visible): Visible`, `Visible` an exported interface of the same members. +// - `ambient-types`: no module-channel stand-in but an `@types` package +// (`@types/s4-ambient`, its `index.d.ts` declaring a global variable), +// which the `types` detection installs at `node_modules/@types/s4-ambient` +// beside the placement. +// - `implicit-export`: `dual`'s layout, its declaration files differing: +// each declares `defineConfig` and an interface it never marks `export`, +// with no `export {}` — `ImportEntryInterface` in `index.d.ts`, +// `RequireEntryInterface` in `index.d.cts`. +// - `export-assignment`: a CommonJS package — no `type`, no `exports` map, +// its top-level `types` and `main` alone, so every setup resolves its one +// declaration file — whose `index.d.ts` assigns (`export =`) a constant +// typed with `defineConfig` and a number `other`, and whose `index.js` +// exports such an object. + +import * as fsp from "node:fs/promises"; +import * as path from "node:path"; +import { fileURLToPath } from "node:url"; +import { isDeepStrictEqual } from "node:util"; +import { expect, onTestFinished, test } from "vitest"; +import { + ModuleStaging, + PROJECT_KINDS, + TYPE_CHECKING_ARM, +} from "../helpers/module-channel.js"; +import type { Placement, ProjectKind } from "../helpers/module-channel.js"; +import { + COVERED_SETUPS, + describeErrors, + describeExportListing, + stageCoveredFiles, +} from "../helpers/module-channel-ts.js"; +import type { + CoveredExtension, + CoveredSetup, + CoveredVerdict, + ExportListing, + ExportSource, + ListedExport, + ProgramError, +} from "../helpers/module-channel-ts.js"; +import { HarnessStagingError } from "../helpers/permissions.js"; +import { guardStep } from "../helpers/step-guards.js"; +import type { ProductBinding } from "../helpers/subprocess.js"; + +const LF = String.fromCodePoint(0x0a); + +/** The committed stand-ins (module header), resolved like fixtures. */ +const STAND_INS = { + exportsOnly: fixture("s4-module-channel/exports-only"), + esmOnly: fixture("s4-module-channel/esm-only"), + dual: fixture("s4-module-channel/dual"), + typed: fixture("s4-module-channel/typed"), + declarationError: fixture("s4-module-channel/declaration-error"), + implicitAny: fixture("s4-module-channel/implicit-any"), + unexportedReturn: fixture("s4-module-channel/unexported-return"), + ambientTypes: fixture("s4-module-channel/ambient-types"), + implicitExport: fixture("s4-module-channel/implicit-export"), + exportAssignment: fixture("s4-module-channel/export-assignment"), +} as const; + +function fixture(rel: string): string { + return fileURLToPath(new URL(`../fixtures/${rel}`, import.meta.url)); +} + +/** The project directory every staging here holds, staging-relative. */ +const PROJECT_DIR = "project"; + +/** + * A binding of the certification fixtures' shape beside `packageDir`: its + * executable is never run here. + */ +function standInBinding(packageDir: string): ProductBinding { + return { + label: "S-4 module-channel stand-in binding", + command: process.execPath, + requiredFiles: [process.execPath], + packageDir, + }; +} + +/** A staging of one project beside its canonical placement of `packageDir`. */ +interface StagedProject { + readonly staging: ModuleStaging; + readonly placement: Placement; +} + +/** Stage `project` with `packageDir` placed canonically; disposed at the end. */ +async function stagedProject( + packageDir: string, + project: ProjectKind, + context: string, +): Promise<StagedProject> { + const staging = await ModuleStaging.create( + standInBinding(packageDir), + context, + ); + onTestFinished(() => staging.dispose()); + await staging.stageProject(PROJECT_DIR, project); + const placement = await staging.placeCanonical( + PROJECT_DIR, + TYPE_CHECKING_ARM, + ); + return { staging, placement }; +} + +/** Lines joined by LF, the last one terminated. */ +function lines(...all: string[]): string { + return all.join(LF) + LF; +} + +/** + * The files TypeScript compiles as ES modules under the `node16` and + * `nodenext` modes (SPEC 7.6: a name ending in `.mts`, or in `.ts` or `.tsx` + * in an ES-module project), written out here apart from the driver's own + * reading; every other file it compiles as CommonJS there. + */ +const ES_MODULE_FILES: Readonly< + Record<ProjectKind, readonly CoveredExtension[]> +> = { + "es-module": [".ts", ".mts", ".tsx"], + commonjs: [".mts"], + "no-manifest": [".mts"], +}; + +/** Whether TypeScript compiles `setup`'s file as an ES module there. */ +function compiledAsEsModule(setup: CoveredSetup): boolean { + return ES_MODULE_FILES[setup.project].includes(setup.extension); +} + +/** A strict-default setup's `moduleResolution`, as its set spells it. */ +function resolutionOf(setup: CoveredSetup): string { + const value = setup.optionSet.tsconfig["moduleResolution"]; + if (typeof value !== "string") { + throw new Error(`${setup.label} spells no moduleResolution`); + } + return value; +} + +/** A setup's `module`, as its set spells it: undefined at its default. */ +function moduleOf(setup: CoveredSetup): string | undefined { + const value = setup.optionSet.tsconfig["module"]; + if (value !== undefined && typeof value !== "string") { + throw new Error(`${setup.label} spells module as no string`); + } + return value; +} + +/** The two modes whose `module` values run `node16` to `nodenext`. */ +const NODE_MODES: ReadonlySet<string> = new Set(["node16", "nodenext"]); + +/** Whether `setup` is one of the fourteen strict defaults'. */ +function strictDefault(setup: CoveredSetup): boolean { + return setup.optionSet.kind === "strict defaults"; +} + +/** Whether `setup` is the initialized-project set's. */ +function initializedSet(setup: CoveredSetup): boolean { + return setup.optionSet.kind === "initialized-project options"; +} + +/** One detection (module header). */ +interface Detection { + /** How every diagnosis names it. */ + readonly name: string; + /** The stand-in package placed canonically for it. */ + readonly standIn: string; + /** The covered file, importing from `name` (N). */ + readonly text: (name: string) => string; + /** + * The construct a rejection is located at: its first characters, which + * occur once in the file holding it, where TypeScript's error begins. + */ + readonly construct: (name: string) => string; + /** + * The stand-in's files holding the construct, by their paths in the + * package, where a rejection lies in whichever of them TypeScript + * resolves; where none are named, the configuration file holds it. + */ + readonly constructIn?: readonly string[]; + /** A twin file judged beside it, which type-checks wherever it is judged. */ + readonly twin?: (name: string) => string; + /** Whether it is judged in a covered setup. */ + readonly judgedIn: (setup: CoveredSetup) => boolean; + /** Whether the setting rejects the construct there. */ + readonly rejectedIn: (setup: CoveredSetup) => boolean; + /** The setups it is judged in, and the rejecting ones among them. */ + readonly counts: { readonly judged: number; readonly rejected: number }; +} + +/** A file importing `defineConfig` from N, then exporting its call. */ +function plainImport(name: string): string { + return lines( + `import { defineConfig } from ${JSON.stringify(name)};`, + "", + "export default defineConfig({ checked: true });", + ); +} + +/** A file importing from N with import attributes. */ +function attributedImport(name: string): string { + return lines( + `import { defineConfig } from ${JSON.stringify(name)} with { note: "stand-in" };`, + "", + "export default defineConfig({ checked: true });", + ); +} + +/** A file exporting `defineConfig`'s call on an object holding `import.meta`. */ +function importMetaFile(name: string): string { + return lines( + `import { defineConfig } from ${JSON.stringify(name)};`, + "", + "export default defineConfig({ meta: import.meta });", + ); +} + +const EXPORTS_ONLY: Detection = { + name: "an exports-only stand-in imported", + standIn: STAND_INS.exportsOnly, + text: plainImport, + construct: (name) => JSON.stringify(name), + judgedIn: strictDefault, + rejectedIn: (setup) => resolutionOf(setup) === "node10", + counts: { judged: 168, rejected: 12 }, +}; + +const ESM_ONLY_FROM_COMMONJS: Detection = { + name: "an ES-module-only stand-in imported from a file TypeScript compiles as CommonJS", + standIn: STAND_INS.esmOnly, + text: plainImport, + construct: (name) => JSON.stringify(name), + judgedIn: (setup) => + strictDefault(setup) && + NODE_MODES.has(resolutionOf(setup)) && + !compiledAsEsModule(setup), + rejectedIn: (setup) => ["node16", "node18"].includes(moduleOf(setup) ?? ""), + counts: { judged: 56, rejected: 28 }, +}; + +const NODE_IMPORT_ATTRIBUTES: Detection = { + name: "import attributes on an import of a JavaScript module, in a file TypeScript compiles as an ES module", + standIn: STAND_INS.dual, + text: attributedImport, + construct: () => "with {", + judgedIn: (setup) => + strictDefault(setup) && + NODE_MODES.has(resolutionOf(setup)) && + compiledAsEsModule(setup), + rejectedIn: (setup) => moduleOf(setup) === "node16", + counts: { judged: 40, rejected: 10 }, +}; + +const GROUP_BY: Detection = { + name: "Object.groupBy", + standIn: STAND_INS.dual, + text: (name) => + lines( + `import { defineConfig } from ${JSON.stringify(name)};`, + "", + "export default defineConfig({", + ' groups: Object.groupBy(["a", "bc"], (item: string) => String(item.length)),', + "});", + ), + construct: () => "groupBy", + judgedIn: (setup) => + strictDefault(setup) && NODE_MODES.has(resolutionOf(setup)), + rejectedIn: (setup) => moduleOf(setup) !== "nodenext", + counts: { judged: 96, rejected: 72 }, +}; + +const BUNDLER_IMPORT_META: Detection = { + name: "import.meta under bundler", + standIn: STAND_INS.dual, + text: importMetaFile, + construct: () => "import.meta", + judgedIn: (setup) => + strictDefault(setup) && resolutionOf(setup) === "bundler", + rejectedIn: (setup) => moduleOf(setup) === "es2015", + counts: { judged: 60, rejected: 12 }, +}; + +const BUNDLER_STRING_IMPORT_NAME: Detection = { + name: "a string-literal import name under bundler", + standIn: STAND_INS.dual, + text: (name) => + lines( + `import { "defineConfig" as define } from ${JSON.stringify(name)};`, + "", + "export default define({ checked: true });", + ), + construct: () => '"defineConfig"', + judgedIn: (setup) => + strictDefault(setup) && resolutionOf(setup) === "bundler", + rejectedIn: (setup) => ["es2015", "es2020"].includes(moduleOf(setup) ?? ""), + counts: { judged: 60, rejected: 24 }, +}; + +const BUNDLER_IMPORT_ATTRIBUTES: Detection = { + name: "import attributes under bundler, in a file TypeScript compiles as an ES module there", + standIn: STAND_INS.dual, + text: attributedImport, + construct: () => "with {", + judgedIn: (setup) => + strictDefault(setup) && + resolutionOf(setup) === "bundler" && + setup.extension !== ".cts", + rejectedIn: (setup) => + ["es2015", "es2020", "es2022"].includes(moduleOf(setup) ?? ""), + counts: { judged: 45, rejected: 27 }, +}; + +const BUNDLER_IMPORT_ASSIGNMENT: Detection = { + name: "an import assignment under bundler", + standIn: STAND_INS.dual, + text: (name) => + lines( + `import config = require(${JSON.stringify(name)});`, + "", + "export default config.defineConfig({ checked: true });", + ), + construct: () => "import config = require(", + judgedIn: (setup) => + strictDefault(setup) && resolutionOf(setup) === "bundler", + rejectedIn: (setup) => moduleOf(setup) !== "preserve", + counts: { judged: 60, rejected: 48 }, +}; + +/** The declaration files of a stand-in in `dual`'s layout. */ +const DECLARATION_FILES: readonly string[] = ["index.d.ts", "index.d.cts"]; + +const VERBATIM_MODULE_SYNTAX: Detection = { + name: "verbatimModuleSyntax: a type imported without a type modifier", + standIn: STAND_INS.typed, + text: (name) => + lines( + `import { defineConfig, Settings } from ${JSON.stringify(name)};`, + "", + "export default defineConfig({ checked: true });", + ), + construct: () => "Settings", + judgedIn: () => true, + rejectedIn: initializedSet, + counts: { judged: 173, rejected: 5 }, +}; + +const EXACT_OPTIONAL_PROPERTY_TYPES: Detection = { + name: "exactOptionalPropertyTypes: an optional property initialized undefined", + standIn: STAND_INS.dual, + text: (name) => + lines( + `import { defineConfig } from ${JSON.stringify(name)};`, + "", + "const options: { note?: string } = { note: undefined };", + "", + "export default defineConfig(options);", + ), + construct: () => "options: {", + judgedIn: () => true, + rejectedIn: initializedSet, + counts: { judged: 173, rejected: 5 }, +}; + +const NO_UNCHECKED_INDEXED_ACCESS: Detection = { + name: "noUncheckedIndexedAccess: a list's element read by index into a string variable", + standIn: STAND_INS.dual, + text: (name) => + lines( + `import { defineConfig } from ${JSON.stringify(name)};`, + "", + 'const list: string[] = ["a"];', + "const first: string = list[0];", + "", + "export default defineConfig({ first });", + ), + construct: () => "first: string", + judgedIn: () => true, + rejectedIn: initializedSet, + counts: { judged: 173, rejected: 5 }, +}; + +const NO_UNCHECKED_SIDE_EFFECT_IMPORTS: Detection = { + name: "noUncheckedSideEffectImports: a side-effect import of a module that does not exist", + standIn: STAND_INS.dual, + text: (name) => + lines( + `import { defineConfig } from ${JSON.stringify(name)};`, + 'import "./absent-module.js";', + "", + "export default defineConfig({ checked: true });", + ), + construct: () => '"./absent-module.js"', + judgedIn: () => true, + rejectedIn: initializedSet, + counts: { judged: 173, rejected: 5 }, +}; + +const SKIP_LIB_CHECK: Detection = { + name: "skipLibCheck: a stand-in whose declaration files name a type that does not exist", + standIn: STAND_INS.declarationError, + text: plainImport, + construct: () => "UndeclaredType", + constructIn: DECLARATION_FILES, + judgedIn: () => true, + rejectedIn: strictDefault, + counts: { judged: 173, rejected: 168 }, +}; + +const STRICT: Detection = { + name: "the strict defaults' strict: a stand-in whose declaration files leave a parameter implicitly typed", + standIn: STAND_INS.implicitAny, + text: plainImport, + construct: () => "untyped", + constructIn: DECLARATION_FILES, + judgedIn: () => true, + rejectedIn: strictDefault, + counts: { judged: 173, rejected: 168 }, +}; + +const MODULE_FORMAT: Detection = { + name: "the module format the project and the extension imply: import.meta", + standIn: STAND_INS.dual, + text: importMetaFile, + construct: () => "import.meta", + judgedIn: (setup) => + initializedSet(setup) || NODE_MODES.has(resolutionOf(setup)), + rejectedIn: (setup) => !compiledAsEsModule(setup), + counts: { judged: 101, rejected: 56 }, +}; + +const DECLARATION_DIAGNOSTICS: Detection = { + name: "declaration diagnostics: a default export of a stand-in's unexported interface", + standIn: STAND_INS.unexportedReturn, + text: plainImport, + construct: () => "export default", + twin: (name) => + lines( + `import { defineVisible } from ${JSON.stringify(name)};`, + "", + "export default defineVisible({ checked: true });", + ), + judgedIn: () => true, + rejectedIn: initializedSet, + counts: { judged: 173, rejected: 5 }, +}; + +/** A 1-based position in a file, as the driver reports an error's. */ +interface Position { + readonly line: number; + readonly column: number; +} + +/** + * Where `construct` begins in `text`, which holds it once; a construct + * missing or repeated is a defect of this file's own tables. + */ +function locate(text: string, construct: string, context: string): Position { + const at = text.indexOf(construct); + if (at < 0 || text.indexOf(construct, at + 1) >= 0) { + throw new Error( + `${context}: the construct ${JSON.stringify(construct)} occurs ` + + `${at < 0 ? "nowhere" : "more than once"} in its file`, + ); + } + const before = text.slice(0, at).split(LF); + return { + line: before.length, + column: (before[before.length - 1] ?? "").length + 1, + }; +} + +/** Where a detection's rejection lies (module header). */ +type Site = + | { + /** In the configuration file, at `position`. */ + readonly in: "configuration file"; + readonly construct: string; + readonly position: Position; + } + | { + /** + * In the stand-in's declaration file TypeScript resolves: each such + * file by the name TypeScript reads it under, in the placed copy, with + * the construct's position there. + */ + readonly in: "declaration files"; + readonly construct: string; + readonly positions: ReadonlyMap<string, Position>; + }; + +/** A path with `/` separators, as TypeScript spells file names. */ +function slashed(file: string): string { + return file.split(path.sep).join("/"); +} + +/** + * Where `detection`'s rejection lies once its stand-in is placed at + * `placement` and its file holds `text`: the construct's position in the + * configuration file, or in each named file of the stand-in, read from the + * fixture the placed copy equals byte for byte. + */ +async function siteOf( + detection: Detection, + text: string, + placement: Placement, + context: string, +): Promise<Site> { + const construct = detection.construct(placement.name); + if (detection.constructIn === undefined) { + return { + in: "configuration file", + construct, + position: locate(text, construct, context), + }; + } + const positions = new Map<string, Position>(); + for (const rel of detection.constructIn) { + const source = path.join(detection.standIn, ...rel.split("/")); + const held = await guardStep(`reading ${source} (${context})`, () => + fsp.readFile(source, "utf8"), + ); + positions.set( + `${slashed(placement.copy)}/${rel}`, + locate(held, construct, `${context}, the stand-in's ${rel}`), + ); + } + return { in: "declaration files", construct, positions }; +} + +/** How a diagnosis names a site. */ +function describeSite(site: Site): string { + const at = (position: Position): string => + `${String(position.line)}:${String(position.column)}`; + const where = + site.in === "configuration file" + ? `${at(site.position)} of the configuration file` + : [...site.positions] + .map(([file, position]) => `${at(position)} of ${file}`) + .join(", or "); + return `${JSON.stringify(site.construct)} (${where})`; +} + +/** Whether `error` lies at `site`. */ +function atSite(error: ProgramError, site: Site): boolean { + let position: Position | undefined; + if (site.in === "configuration file") { + if (error.origin === "configuration file") position = site.position; + } else if (error.origin === "another file" && error.file !== undefined) { + position = site.positions.get(error.file); + } + return ( + position !== undefined && + error.line === position.line && + error.column === position.column + ); +} + +/** Why a verdict is no rejection at `site`, or undefined where it is. */ +function rejectionProblem( + verdict: CoveredVerdict, + site: Site, +): string | undefined { + if (verdict.errors.length === 0) { + return ( + `admitted — TypeScript 5.9.3 reports no error — where the setting ` + + `rejects the file, an error expected at ${describeSite(site)}` + ); + } + if (verdict.errors.every((error) => atSite(error, site))) return undefined; + return ( + `rejected otherwise than at ${describeSite(site)}: ` + + describeErrors(verdict.errors) + ); +} + +/** Why a verdict is no admission, or undefined where it is one. */ +function admissionProblem(verdict: CoveredVerdict): string | undefined { + if (verdict.typeChecks) return undefined; + return ( + `rejected where the setting admits the file: ` + + describeErrors(verdict.errors) + ); +} + +/** + * Judge `detection` in each covered setup it is judged in, project by + * project, each project a fresh staging of its stand-in (module header), and + * expect every verdict the setting decides, and its twin's admission where + * it has one, together with the counts. + */ +async function expectDetected(detection: Detection): Promise<void> { + const mismatches: string[] = []; + let judged = 0; + let rejected = 0; + for (const project of PROJECT_KINDS) { + const setups = COVERED_SETUPS.filter( + (setup) => setup.project === project && detection.judgedIn(setup), + ); + if (setups.length === 0) continue; + const context = `S-4, ${detection.name}, in the ${project} project`; + const { staging, placement } = await stagedProject( + detection.standIn, + project, + context, + ); + const text = detection.text(placement.name); + const site = await siteOf(detection, text, placement, context); + const twin = detection.twin?.(placement.name); + const files = await stageCoveredFiles({ + staging, + directory: PROJECT_DIR, + project, + placement, + alone: true, + files: [ + { label: detection.name, text }, + ...(twin === undefined + ? [] + : [{ label: `${detection.name}, its twin`, text: twin }]), + ], + setups, + context, + }); + for (const setup of setups) { + const [verdict, twinVerdict] = files.judge(setup); + if ( + verdict === undefined || + (twin !== undefined && twinVerdict === undefined) + ) { + throw new Error(`${context}: no verdict in ${setup.label}`); + } + judged += 1; + const rejects = detection.rejectedIn(setup); + if (rejects) rejected += 1; + const problem = rejects + ? rejectionProblem(verdict, site) + : admissionProblem(verdict); + if (problem !== undefined) { + mismatches.push(`${setup.label}: ${problem}`); + } + const twinProblem = + twinVerdict === undefined ? undefined : admissionProblem(twinVerdict); + if (twinProblem !== undefined) { + mismatches.push(`${setup.label}, the twin: ${twinProblem}`); + } + } + } + expect( + { mismatches, judged, rejected }, + `${detection.name}: each setup's verdict as its setting decides it, ` + + `and the setups judged and rejecting`, + ).toStrictEqual({ mismatches: [], ...detection.counts }); +} + +/** The `@types` stand-in's name, and its files (module header). */ +const AMBIENT_TYPES_NAME = "s4-ambient"; +const AMBIENT_TYPES_FILES: readonly string[] = ["package.json", "index.d.ts"]; + +/** Why an outcome is no refused automatic inclusion, or undefined where it is. */ +function inclusionProblem( + verdict: CoveredVerdict | undefined, + refusal: HarnessStagingError | undefined, +): string | undefined { + if (refusal === undefined) { + const judged = + verdict === undefined ? "no verdict" : describeErrors(verdict.errors); + return ( + `judged (${judged}) where TypeScript, types at its default, includes ` + + `the @types stand-in automatically, so the driver refuses the staging, ` + + `SPEC 7.6's program condition failing` + ); + } + if ( + refusal.message.includes("program condition does not hold") && + refusal.message.includes( + `included automatically as the type package ${AMBIENT_TYPES_NAME}`, + ) + ) { + return undefined; + } + return ( + `refused otherwise than for the @types stand-in's automatic inclusion: ` + + refusal.message + ); +} + +/** Why an outcome is no admission with the stand-in kept out, or undefined. */ +function exclusionProblem( + verdict: CoveredVerdict | undefined, + refusal: HarnessStagingError | undefined, + typesDirectory: string, +): string | undefined { + if (refusal !== undefined) { + return ( + `refused where types [] keeps the @types stand-in out of the ` + + `program: ${refusal.message}` + ); + } + if (verdict === undefined) return "no verdict"; + const entered = verdict.programFiles.filter((file) => + file.startsWith(`${typesDirectory}/`), + ); + if (entered.length > 0) { + return `the @types stand-in entered the program: ${entered.join(", ")}`; + } + return admissionProblem(verdict); +} + +/** + * The `types` detection (module header): a plain file judged in every + * covered setup, project by project, beside an `@types` stand-in installed + * next to the canonical placement, each project a fresh staging — each + * strict-default setup refused, TypeScript including the stand-in + * automatically, and each initialized-set setup type-checking with the + * stand-in out of its program — together with the counts. + */ +async function expectTypesKeptOut(): Promise<void> { + const mismatches: string[] = []; + let judged = 0; + let included = 0; + for (const project of PROJECT_KINDS) { + const setups = COVERED_SETUPS.filter((setup) => setup.project === project); + const context = + `S-4, types [] keeping an @types stand-in out of the program, in ` + + `the ${project} project`; + const { staging, placement } = await stagedProject( + STAND_INS.dual, + project, + context, + ); + const installed = `${PROJECT_DIR}/node_modules/@types/${AMBIENT_TYPES_NAME}`; + for (const name of AMBIENT_TYPES_FILES) { + const source = path.join(STAND_INS.ambientTypes, name); + const bytes = await guardStep(`reading ${source} (${context})`, () => + fsp.readFile(source), + ); + await staging.writeFile(`${installed}/${name}`, bytes); + } + const files = await stageCoveredFiles({ + staging, + directory: PROJECT_DIR, + project, + placement, + files: [ + { + label: "a plain import beside an @types stand-in", + text: plainImport(placement.name), + }, + ], + setups, + context, + }); + const typesDirectory = slashed(staging.path(installed)); + for (const setup of setups) { + judged += 1; + const includes = strictDefault(setup); + if (includes) included += 1; + let verdict: CoveredVerdict | undefined; + let refusal: HarnessStagingError | undefined; + try { + [verdict] = files.judge(setup); + } catch (error) { + if (!(error instanceof HarnessStagingError)) throw error; + refusal = error; + } + const problem = includes + ? inclusionProblem(verdict, refusal) + : exclusionProblem(verdict, refusal, typesDirectory); + if (problem !== undefined) { + mismatches.push(`${setup.label}: ${problem}`); + } + } + } + expect( + { mismatches, judged, included }, + `types []: each setup's outcome as the option decides it, and the ` + + `setups judged and including the @types stand-in automatically`, + ).toStrictEqual({ mismatches: [], judged: 173, included: 168 }); +} + +/** The declaration files a listing detection's stand-ins hold. */ +type DeclarationFile = "index.d.ts" | "index.d.cts"; + +/** One detection of T7.6-1's export listing (module header). */ +interface ListingDetection { + /** How every diagnosis names it. */ + readonly name: string; + /** The stand-in package placed canonically for it. */ + readonly standIn: string; + /** The stand-in's declaration file TypeScript resolves in `setup`. */ + readonly declarationIn: (setup: CoveredSetup) => DeclarationFile; + /** The listing expected where TypeScript resolves `declaration`. */ + readonly listed: ( + declaration: DeclarationFile, + ) => Omit<ExportListing, "module">; + /** How many of the 173 setups resolve each declaration file. */ + readonly resolved: Partial<Readonly<Record<DeclarationFile, number>>>; +} + +/** A listed export written out: one meaning, found in one place. */ +function listedExport( + name: string, + meaning: "value" | "type", + listedIn: ExportSource, +): ListedExport { + return { + name, + value: meaning === "value", + typeOnlyValue: false, + type: meaning === "type", + namespace: false, + listedIn: [listedIn], + }; +} + +/** + * Which of a `dual`-layout stand-in's declaration files TypeScript resolves + * in `setup`, written out here apart from the driver: under `node10`, which + * reads no `exports`, the top-level `types`; under `bundler`, the `require` + * entry's for a `.cts` file alone; under the `node16` and `nodenext` modes + * (the initialized set's among them), the `require` entry's for each file + * TypeScript compiles as CommonJS there, and the `import` entry's otherwise. + */ +function dualDeclaration(setup: CoveredSetup): DeclarationFile { + const resolution = setup.optionSet.tsconfig["moduleResolution"]; + if (resolution === "node10") return "index.d.ts"; + if (resolution === "bundler") { + return setup.extension === ".cts" ? "index.d.cts" : "index.d.ts"; + } + return compiledAsEsModule(setup) ? "index.d.ts" : "index.d.cts"; +} + +const IMPLICIT_EXPORT: ListingDetection = { + name: "an interface a declaration module never marks export, with no export {}", + standIn: STAND_INS.implicitExport, + declarationIn: dualDeclaration, + listed: (declaration) => ({ + exportAssignment: false, + exports: [ + listedExport( + declaration === "index.d.ts" + ? "ImportEntryInterface" + : "RequireEntryInterface", + "type", + "exports", + ), + listedExport("defineConfig", "value", "exports"), + ], + }), + resolved: { "index.d.ts": 102, "index.d.cts": 71 }, +}; + +const EXPORT_ASSIGNMENT: ListingDetection = { + name: "an export assignment whose value carries defineConfig and one other member", + standIn: STAND_INS.exportAssignment, + declarationIn: () => "index.d.ts", + listed: () => ({ + exportAssignment: true, + exports: [ + listedExport("defineConfig", "value", "export assignment"), + listedExport("other", "value", "export assignment"), + ], + }), + resolved: { "index.d.ts": 173 }, +}; + +/** + * Judge a plain import of `detection`'s stand-in in every covered setup, + * project by project, each project a fresh staging, the driver listing the + * import's exports, and expect each setup's listing whole (module header), + * together with the counts of setups judged and resolving each declaration + * file. + */ +async function expectListed(detection: ListingDetection): Promise<void> { + const mismatches: string[] = []; + let judged = 0; + const resolved: Partial<Record<DeclarationFile, number>> = {}; + for (const project of PROJECT_KINDS) { + const setups = COVERED_SETUPS.filter((setup) => setup.project === project); + const context = + `S-4, T7.6-1's export listing: ${detection.name}, in the ${project} ` + + `project`; + const { staging, placement } = await stagedProject( + detection.standIn, + project, + context, + ); + const files = await stageCoveredFiles({ + staging, + directory: PROJECT_DIR, + project, + placement, + alone: true, + listExports: true, + files: [{ label: detection.name, text: plainImport(placement.name) }], + setups, + context, + }); + for (const setup of setups) { + const [verdict] = files.judge(setup); + if (verdict === undefined) { + throw new Error(`${context}: no verdict in ${setup.label}`); + } + judged += 1; + const declaration = detection.declarationIn(setup); + resolved[declaration] = (resolved[declaration] ?? 0) + 1; + const expected: ExportListing = { + module: `${slashed(placement.copy)}/${declaration}`, + ...detection.listed(declaration), + }; + if (!isDeepStrictEqual(verdict.exportListing, expected)) { + mismatches.push( + `${setup.label}: the driver lists ` + + `${describeExportListing(verdict.exportListing)}, where ` + + `the stand-in's declarations give ${describeExportListing(expected)}`, + ); + } + } + } + expect( + { mismatches, judged, resolved }, + `T7.6-1's export listing, ${detection.name}: each setup's listing as ` + + `TypeScript's own resolution gives it, and the setups judged and ` + + `resolving each declaration file`, + ).toStrictEqual({ + mismatches: [], + judged: 173, + resolved: detection.resolved, + }); +} + +test("moduleResolution: an exports-only stand-in, which node10 alone does not resolve, is rejected in each of the 12 node10 setups — an error at the import's specifier and nowhere else — and type-checks in each of the 156 other strict-default setups (TEST-SPEC S-4; §7.6 Covered setups)", async () => { + await expectDetected(EXPORTS_ONLY); +}); + +test("module under the node16 and nodenext modes: an ES-module-only stand-in imported from a file TypeScript compiles as CommonJS is rejected under module node16 and node18 — an error at the import's specifier and nowhere else — and type-checks under node20 and nodenext, in each of the 56 setups of such a file (TEST-SPEC S-4; §7.6 Covered setups)", async () => { + await expectDetected(ESM_ONLY_FROM_COMMONJS); +}); + +test("module under the node16 and nodenext modes: import attributes on an import of a JavaScript module, in a file TypeScript compiles as an ES module, are rejected under module node16 — an error at the attributes and nowhere else — and type-check under node18, node20, and nodenext, in each of the 40 setups of such a file (TEST-SPEC S-4)", async () => { + await expectDetected(NODE_IMPORT_ATTRIBUTES); +}); + +test("module's default target under the node16 and nodenext modes: Object.groupBy, which the library of nodenext's default target brings and those of node16's, node18's, and node20's do not, is rejected under module node16, node18, and node20 — an error at groupBy and nowhere else — and type-checks under nodenext, in each of the 96 setups of those modes (TEST-SPEC S-4; §7.6 Covered setups)", async () => { + await expectDetected(GROUP_BY); +}); + +test("module under bundler: import.meta is rejected by es2015 alone — an error at import.meta and nowhere else — and type-checks under es2020, es2022, esnext, and preserve, in each of the 60 bundler setups (TEST-SPEC S-4)", async () => { + await expectDetected(BUNDLER_IMPORT_META); +}); + +test("module under bundler: a string-literal import name is rejected by es2015 and es2020 — an error at the name and nowhere else — and type-checks under es2022, esnext, and preserve, in each of the 60 bundler setups (TEST-SPEC S-4)", async () => { + await expectDetected(BUNDLER_STRING_IMPORT_NAME); +}); + +test("module under bundler: import attributes are rejected by es2015, es2020, and es2022 — an error at the attributes and nowhere else — and type-check under esnext and preserve, in each of the 45 bundler setups of a file TypeScript compiles as an ES module there (TEST-SPEC S-4)", async () => { + await expectDetected(BUNDLER_IMPORT_ATTRIBUTES); +}); + +test("module under bundler: an import assignment type-checks under preserve alone and is rejected by es2015, es2020, es2022, and esnext — an error at the declaration and nowhere else — in each of the 60 bundler setups (TEST-SPEC S-4)", async () => { + await expectDetected(BUNDLER_IMPORT_ASSIGNMENT); +}); + +test("the initialized set's verbatimModuleSyntax: a type imported without a type modifier is rejected in each of the 5 initialized-project setups — an error at the type's name and nowhere else — and type-checks in each of the 168 strict-default setups (TEST-SPEC S-4; §7.6 Covered setups)", async () => { + await expectDetected(VERBATIM_MODULE_SYNTAX); +}); + +test("the initialized set's exactOptionalPropertyTypes: a variable whose optional property is initialized undefined is rejected in each of the 5 initialized-project setups — an error at the variable and nowhere else — and type-checks in each of the 168 strict-default setups (TEST-SPEC S-4)", async () => { + await expectDetected(EXACT_OPTIONAL_PROPERTY_TYPES); +}); + +test("the initialized set's noUncheckedIndexedAccess: a list's element read by index into a variable typed string is rejected in each of the 5 initialized-project setups — an error at the variable and nowhere else — and type-checks in each of the 168 strict-default setups (TEST-SPEC S-4)", async () => { + await expectDetected(NO_UNCHECKED_INDEXED_ACCESS); +}); + +test("the initialized set's noUncheckedSideEffectImports: a side-effect import of a module that does not exist is rejected in each of the 5 initialized-project setups — an error at its specifier and nowhere else — and type-checks in each of the 168 strict-default setups (TEST-SPEC S-4)", async () => { + await expectDetected(NO_UNCHECKED_SIDE_EFFECT_IMPORTS); +}); + +test("the initialized set's skipLibCheck: a stand-in whose declaration files name a type that does not exist is rejected in each of the 168 strict-default setups — an error at that name in the declaration file TypeScript resolves and nowhere else — and type-checks in each of the 5 initialized-project setups, which skip declaration files (TEST-SPEC S-4; §7.6 Covered setups)", async () => { + await expectDetected(SKIP_LIB_CHECK); +}); + +test("the initialized set's types []: an @types stand-in installed beside the placement stays out of the program in each of the 5 initialized-project setups, the file type-checking, and is included automatically in each of the 168 strict-default setups, where the driver refuses the staging as SPEC 7.6's program condition fails (TEST-SPEC S-4; §7.6 Placement)", async () => { + await expectTypesKeptOut(); +}); + +test("the strict defaults' strict: a stand-in whose declaration files leave a parameter implicitly typed is rejected in each of the 168 strict-default setups — an error at the parameter in the declaration file TypeScript resolves and nowhere else, skipLibCheck being off — and type-checks in each of the 5 initialized-project setups, which skip declaration files (TEST-SPEC S-4; §7.6 Covered setups)", async () => { + await expectDetected(STRICT); +}); + +test("the module format the project and the extension imply: import.meta is rejected in each of the 56 setups of a file TypeScript compiles as CommonJS under the node16 and nodenext modes — an error at import.meta and nowhere else — and type-checks in each of the 45 setups of a file it compiles as an ES module there or under the initialized-project set (TEST-SPEC S-4; §7.6 Covered setups)", async () => { + await expectDetected(MODULE_FORMAT); +}); + +test("the verdict's reach into declaration diagnostics: a valid default export of a stand-in's defineConfig, which returns an interface the stand-in does not export, is rejected in each of the 5 initialized-project setups, which turn declaration on — an error at the export and nowhere else — and type-checks in each of the 168 strict-default setups, while its twin, returning an interface the stand-in exports, type-checks in all 173 (TEST-SPEC S-4; §7.6 Verdict)", async () => { + await expectDetected(DECLARATION_DIAGNOSTICS); +}); + +test("T7.6-1's export listing: a stand-in whose declaration files each declare, beside defineConfig, an interface never marked export, with no export {}, lists both — defineConfig a value, the interface a type, each among the module's exports — read through TypeScript's own resolution in each of the 173 covered setups, the import entry's declaration file in 102 and the require entry's in 71 (TEST-SPEC S-4; T7.6-1)", async () => { + await expectListed(IMPLICIT_EXPORT); +}); + +test("T7.6-1's export listing: a stand-in whose export assignment assigns a value carrying defineConfig and one other member lists both, each a value among the assignment's members, the module's exports proper empty, in each of the 173 covered setups (TEST-SPEC S-4; T7.6-1)", async () => { + await expectListed(EXPORT_ASSIGNMENT); +}); diff --git a/test/self/s4-typescript-tooling.test.ts b/test/self/s4-typescript-tooling.test.ts index 9348accc..e2732b6a 100644 --- a/test/self/s4-typescript-tooling.test.ts +++ b/test/self/s4-typescript-tooling.test.ts @@ -8,12 +8,14 @@ // driver, in each configuration, against a hand-written, non-xspec fixture // project (test/fixtures/s4-tooling/) compiled and served in that // configuration from a copy in a fresh workspace under the OS temporary -// directory, as a consumer workspace is compiled — no `node_modules` above -// it, so the release's default `types` brings no `@types` package of this -// repository into the program (H-2: every option H-2 does not name at the -// release's default), and H-2's isolation holds: a known type error, a known -// definition location, and a known hover text must all be detected, so -// section 4's consumer assertions cannot pass vacuously — among the type +// directory, as a consumer workspace is compiled — no `package.json` or +// `node_modules` above it, so the release's default `types` brings no +// `@types` package of this repository into the program (H-2: every option +// H-2 does not name at the release's default) and no manifest of this +// repository decides its module kind, and H-1's isolation of a consumer +// program holds: a known type error, a known definition location, and a +// known hover text must all be detected, so section 4's consumer +// assertions cannot pass vacuously — among the type // errors one located in a declaration module the consumer imports, outside // the consumer file (`companion-error.d.ts`, in a product companion's // shape), which only a clean verdict covering the whole program reports and @@ -48,10 +50,14 @@ // and never the ES-module configuration's; an import nothing makes // resolvable is a diagnosed compile error (the red path for section 4 tests // against the stub product, H-8); marker addressing and project loading -// fail loudly rather than vacuously green; H-2's isolation is a staging -// error, never a verdict; and a project is loaded under one of H-2's two -// configurations exactly, with no compiler option of its own, any other -// load a harness misuse — so no other configuration is reachable. The +// fail loudly rather than vacuously green; H-1's isolation of a consumer +// program — nothing installed in its project root or above it or its +// runtime output, nothing in Node.js's global module folders under a run's +// environment, and each run under a fresh, empty `HOME` with no `NODE_PATH` +// — is verified before TypeScript or Node.js reads it, an unmet isolation a +// staging error, never a verdict; and a project is loaded under one of +// H-2's two configurations exactly, with no compiler option of its own, any +// other load a harness misuse — so no other configuration is reachable. The // skeleton reader T1.1-2 compares two generated modules through // (`moduleSkeleton`, `skeletonChains`, `diffModuleSkeletons`) is pinned, in // each configuration, against a hand-written module in the generated @@ -67,6 +73,7 @@ import ts from "typescript-5.9.3"; import { describe, expect, onTestFinished, test } from "vitest"; import { HarnessAssertionError } from "../helpers/assertions.js"; import { HarnessStagingError } from "../helpers/permissions.js"; +import { verifyStagingIsolation } from "../helpers/staging-isolation.js"; import { assertTypeChecksClean, assertTypeErrorsAt, @@ -101,7 +108,7 @@ async function makeWorkspace(decl?: WorkspaceDecl): Promise<TestWorkspace> { /** * The S-4 fixture project, copied byte for byte into a fresh workspace under * the OS temporary directory, where it is compiled as a consumer workspace - * is (module header): no `node_modules` above it. + * is (module header): no `package.json` or `node_modules` above it. */ async function stageFixtureProject(): Promise<TestWorkspace> { const files: Record<string, Uint8Array> = {}; @@ -1171,35 +1178,119 @@ test("H-2's runtime refuses the ES-module configuration and an output directory expect(await workspace.readdirNames()).not.toContain("out"); }); -test("H-2's isolation: a project whose root has a node_modules entry above it is refused as a staging error — the fixture directory in this repository among them", async () => { - for (const [kind, decl] of [ - ["a directory", { dirs: ["node_modules"] }], - ["a plain file", { files: { node_modules: "" } }], - ["a symbolic link", { symlinks: { node_modules: "nowhere" } }], +// H-1's isolation of a consumer program (TEST-SPEC H-1, H-2, T13.1-2; +// helpers/staging-isolation.ts through helpers/tooling.ts). Every staging +// lies in a fresh temporary directory, never under this repository, whose +// own package.json and node_modules lie above it; every symbolic link points +// inside its own workspace. + +/** A text of `lines`, each ended by a line feed (U+000A). */ +function textOf(...lines: readonly string[]): string { + const lineFeed = String.fromCodePoint(0x0a); + return lines.map((line) => line + lineFeed).join(""); +} + +/** + * An entry named `name`, in the workspace directory `at` ("" for the root), + * of each kind H-1's examination judges by `lstat`: a directory, a plain + * file, and a dangling symbolic link pointing inside the workspace. + */ +function entryOfEachKind( + name: string, + at: string, +): readonly (readonly [string, WorkspaceDecl])[] { + const rel = at === "" ? name : `${at}/${name}`; + return [ + ["a directory", { dirs: [rel] }], + ["a plain file", { files: { [rel]: "" } }], + ["a symbolic link", { symlinks: { [rel]: "nowhere" } }], + ]; +} + +/** + * A consumer that writes the marker file its first argument names, if any, + * and prints `ran` — so a run refused before the consumer starts leaves no + * marker. H-2 supplies no `@types/node`: it declares what it reads. + */ +const MARKING_CONSUMER = textOf( + "declare const process: { readonly argv: readonly string[] };", + "declare const module: {", + ' require(id: "node:fs"): {', + " writeFileSync(path: string, data: string): void;", + " };", + "};", + "", + "const marker = process.argv[2];", + "if (marker !== undefined) {", + ' module.require("node:fs").writeFileSync(marker, "ran");', + "}", + 'console.log("ran");', + "", + "export {};", +); + +/** + * A consumer reporting, as one JSON line, the `HOME` and `NODE_PATH` it + * runs under and the entries of that `HOME`. + */ +const HOME_REPORTING_CONSUMER = textOf( + "declare const process: {", + " readonly env: Readonly<Record<string, string | undefined>>;", + "};", + "declare const module: {", + ' require(id: "node:fs"): { readdirSync(path: string): string[] };', + "};", + "", + "const home = process.env.HOME;", + "console.log(", + " JSON.stringify({", + " home: home ?? null,", + " entries:", + " home === undefined", + " ? null", + ' : module.require("node:fs").readdirSync(home),', + " nodePath: process.env.NODE_PATH ?? null,", + " }),", + ");", + "", + "export {};", +); + +test("H-1's isolation of a consumer program: a project whose root has a package.json or node_modules entry above it, or a node_modules entry in it, is refused as a staging error — the fixture directory in this repository among them (TEST-SPEC H-1, T13.1-2)", async () => { + for (const [name, at] of [ + ["package.json", ""], + ["node_modules", ""], + ["node_modules", "project"], ] as const) { - const workspace = await makeWorkspace({ - ...decl, - files: { - ...("files" in decl ? decl.files : {}), - "project/main.ts": "export const value = 1;\n", - }, - }); - for (const configuration of CONSUMER_CONFIGURATIONS) { - const error: unknown = await ConsumerProject.load({ - rootDir: workspace.path("project"), - rootFiles: ["main.ts"], - configuration, - }).catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(HarnessStagingError); - expect((error as HarnessStagingError).mode).toBe("consumer-isolation"); - expect((error as Error).message).toContain( - `holds an entry named node_modules (${kind}, ` + - `${path.join(workspace.root, "node_modules")})`, - ); + for (const [kind, decl] of entryOfEachKind(name, at)) { + const workspace = await makeWorkspace({ + ...decl, + files: { + ...(decl.files ?? {}), + "project/main.ts": textOf("export const value = 1;"), + }, + }); + const entry = path.join(workspace.root, at, name); + const expected = + at === "" + ? `the ancestor directory ${workspace.root} holds an entry named ` + + `${name} (${kind}, ${entry})` + : `the consumer project root ${workspace.path("project")} itself ` + + `holds an entry named ${name} (${kind}, ${entry})`; + for (const configuration of CONSUMER_CONFIGURATIONS) { + const error: unknown = await ConsumerProject.load({ + rootDir: workspace.path("project"), + rootFiles: ["main.ts"], + configuration, + }).catch((caught: unknown) => caught); + expect(error).toBeInstanceOf(HarnessStagingError); + expect((error as HarnessStagingError).mode).toBe("consumer-isolation"); + expect((error as Error).message).toContain(expected); + } } } // The fixture directory in place lies below this repository's own - // node_modules — hence S-4's copies. + // package.json and node_modules — hence S-4's copies. const inPlace: unknown = await ConsumerProject.load({ rootDir: fixtureRoot, rootFiles: ["greeting.ts", "main.ts"], @@ -1209,87 +1300,254 @@ test("H-2's isolation: a project whose root has a node_modules entry above it is expect((inPlace as HarnessStagingError).mode).toBe("consumer-isolation"); }); -test("H-2's isolation: a runtime output directory with a node_modules entry above it is refused before anything is compiled into it, and removed", async () => { +test("H-1's isolation of a consumer program: a runtime output directory with a package.json or node_modules entry above it is refused before anything is compiled into it, and removed (TEST-SPEC H-1)", async () => { const workspace = await makeWorkspace({ - files: { "main.ts": 'console.log("never run");\n\nexport {};\n' }, + files: { + "main.ts": textOf('console.log("never run");', "", "export {};"), + }, }); const project = await ConsumerProject.load({ rootDir: workspace.root, rootFiles: ["main.ts"], configuration: COMMONJS_CONFIGURATION, }); - // The OS temporary directory, as `os.tmpdir()` reads it at each call, moved - // below a node_modules-holding directory for this one call. - const decoy = await makeWorkspace({ dirs: ["node_modules", "tmp"] }); - const ambient = process.env["TMPDIR"]; - process.env["TMPDIR"] = decoy.path("tmp"); - let entered = false; - let refused: unknown; - try { - refused = await withCompiledConsumer( - project, - "S-4 isolation probe", - async () => { - entered = true; - }, - ).catch((error: unknown) => error); - } finally { - if (ambient === undefined) { - delete process.env["TMPDIR"]; - } else { - process.env["TMPDIR"] = ambient; + for (const [name, kind, decl] of [ + ["node_modules", "a directory", { dirs: ["node_modules", "tmp"] }], + [ + "package.json", + "a plain file", + { dirs: ["tmp"], files: { "package.json": textOf("{}") } }, + ], + ] as const) { + // The OS temporary directory, as `os.tmpdir()` reads it at each call, + // moved below a directory holding the entry for this one call. + const decoy = await makeWorkspace(decl); + const ambient = process.env["TMPDIR"]; + process.env["TMPDIR"] = decoy.path("tmp"); + let entered = false; + let refused: unknown; + try { + refused = await withCompiledConsumer( + project, + "S-4 isolation probe", + async () => { + entered = true; + }, + ).catch((error: unknown) => error); + } finally { + if (ambient === undefined) { + delete process.env["TMPDIR"]; + } else { + process.env["TMPDIR"] = ambient; + } } + expect(entered).toBe(false); + expect(refused).toBeInstanceOf(HarnessStagingError); + expect((refused as HarnessStagingError).mode).toBe("consumer-isolation"); + expect((refused as Error).message).toContain( + `the ancestor directory ${decoy.root} holds an entry named ${name} ` + + `(${kind}, ${path.join(decoy.root, name)})`, + ); + expect(await decoy.readdirNames("tmp")).toEqual([]); } - expect(entered).toBe(false); - expect(refused).toBeInstanceOf(HarnessStagingError); - expect((refused as HarnessStagingError).mode).toBe("consumer-isolation"); - expect((refused as Error).message).toContain( - `holds an entry named node_modules (a directory, ` + - `${path.join(decoy.root, "node_modules")})`, - ); - expect(await decoy.readdirNames("tmp")).toEqual([]); }); -test("H-2's isolation: a run whose environment lets Node.js's resolver find a package named xspec in a global folder is refused before the consumer runs", async () => { - const home = await makeWorkspace({ - dirs: [".node_modules/xspec", "path/xspec"], +test("H-1's isolation of a consumer program: a run whose environment gives Node.js's resolver a global folder holding a package — under any name, xspec's or another — is refused before the consumer runs, and an empty global folder holds none (TEST-SPEC H-1, H-2)", async () => { + const folders = await makeWorkspace({ + dirs: [ + "other/.node_modules/left-pad", + "named/.node_modules/xspec", + "path/@acme/config-kit", + "empty/.node_modules", + "empty/.node_libraries", + ], + files: { "module/.node_libraries/helper.js": textOf("exports.x = 1;") }, }); + const markers = await makeWorkspace(); const workspace = await makeWorkspace({ - files: { "main.ts": 'console.log("ran");\n\nexport {};\n' }, + files: { "main.ts": MARKING_CONSUMER }, }); + const sources = { rootDir: workspace.root, rootFiles: ["main.ts"] }; + await forEachConsumerProject(sources, (project) => + assertTypeChecksClean(project, "marking consumer"), + ); const project = await ConsumerProject.load({ - rootDir: workspace.root, - rootFiles: ["main.ts"], + ...sources, configuration: COMMONJS_CONFIGURATION, }); + const refusals = [ + // `$HOME/.node_modules`, holding a package under another name. + { + marker: "other", + env: { HOME: folders.path("other") }, + folder: folders.path("other/.node_modules"), + holds: 'the entry "left-pad"', + }, + // `$HOME/.node_libraries`, holding a plain-file module. + { + marker: "module", + env: { HOME: folders.path("module") }, + folder: folders.path("module/.node_libraries"), + holds: 'the entry "helper.js"', + }, + // `$HOME/.node_modules`, holding a package named xspec. + { + marker: "named", + env: { HOME: folders.path("named") }, + folder: folders.path("named/.node_modules"), + holds: 'the entry "xspec"', + }, + // A NODE_PATH entry, which a run drops unless its environment sets it, + // holding a scope. + { + marker: "path", + env: { NODE_PATH: folders.path("path") }, + folder: folders.path("path"), + holds: 'the entry "@acme"', + }, + ]; await withCompiledConsumer( project, "S-4 global-folder probe", async (compiled) => { - // `$HOME/.node_modules`, which Node.js's resolver searches. - const viaHome: unknown = await compiled - .run("main.ts", { env: { HOME: home.root } }) - .catch((error: unknown) => error); - expect(viaHome).toBeInstanceOf(HarnessStagingError); - expect((viaHome as HarnessStagingError).mode).toBe("consumer-isolation"); - expect((viaHome as Error).message).toContain( - `holds an entry named xspec (a directory, ` + - `${path.join(home.root, ".node_modules", "xspec")})`, - ); - // A NODE_PATH entry, which a run drops unless its environment sets it. - const viaNodePath: unknown = await compiled - .run("main.ts", { env: { NODE_PATH: home.path("path") } }) - .catch((error: unknown) => error); - expect(viaNodePath).toBeInstanceOf(HarnessStagingError); - expect((viaNodePath as Error).message).toContain( - `${path.join(home.root, "path", "xspec")}`, - ); - // Under the ambient environment the run proceeds. - const ran = await compiled.run("main.ts"); - expect(ran.exitCode).toBe(0); - expect(ran.stdout).toBe("ran\n"); + for (const refusal of refusals) { + const marker = markers.path(`${refusal.marker}.ran`); + const refused: unknown = await compiled + .run("main.ts", { argv: [marker], env: refusal.env }) + .catch((error: unknown) => error); + expect(refused).toBeInstanceOf(HarnessStagingError); + expect((refused as HarnessStagingError).mode).toBe( + "consumer-isolation", + ); + expect((refused as Error).message).toContain( + `the global folder ${refusal.folder}, which Node.js's resolver ` + + `searches for a bare specifier under the run's environment, ` + + `holds ${refusal.holds}`, + ); + } + // Refused before the consumer ran: no marker written. + expect(await markers.readdirNames()).toEqual([]); + // Global folders that exist but hold nothing hold no package, and + // under the ambient environment, with the run's own fresh HOME, the + // run proceeds too. + for (const [name, env] of [ + ["empty", { HOME: folders.path("empty") }], + ["ambient", undefined], + ] as const) { + const ran = await compiled.run("main.ts", { + argv: [markers.path(`${name}.ran`)], + env, + }); + expect(ran.exitCode).toBe(0); + expect(ran.stdout).toBe(textOf("ran")); + expect(ran.stderr).toBe(""); + } + expect((await markers.readdirNames()).sort()).toEqual([ + "ambient.ran", + "empty.ran", + ]); + }, + ); +}); + +test("H-1's isolation of a consumer program: each run gets a fresh, empty HOME of its own — never the ambient one — under the OS temporary directory, outside the workspace and the output directory, with no NODE_PATH, removed once the run ends (TEST-SPEC H-1)", async () => { + const workspace = await makeWorkspace({ + files: { "main.ts": HOME_REPORTING_CONSUMER }, + }); + const sources = { rootDir: workspace.root, rootFiles: ["main.ts"] }; + await forEachConsumerProject(sources, (project) => + assertTypeChecksClean(project, "HOME-reporting consumer"), + ); + const project = await ConsumerProject.load({ + ...sources, + configuration: COMMONJS_CONFIGURATION, + }); + const ambientHome = process.env["HOME"]; + const homes: string[] = []; + await withCompiledConsumer( + project, + "S-4 fresh-HOME probe", + async (compiled) => { + for (let index = 0; index < 2; index += 1) { + const result = await compiled.run("main.ts"); + expect(result.exitCode).toBe(0); + expect(result.stderr).toBe(""); + const report = JSON.parse(result.stdout) as { + readonly home: unknown; + readonly entries: unknown; + readonly nodePath: unknown; + }; + expect(typeof report.home).toBe("string"); + const home = report.home as string; + expect(path.isAbsolute(home)).toBe(true); + expect(home).not.toBe(ambientHome); + expect(liesInside(home, os.tmpdir())).toBe(true); + for (const other of [workspace.root, compiled.dir]) { + expect(home).not.toBe(other); + expect(liesInside(home, other)).toBe(false); + expect(liesInside(other, home)).toBe(false); + } + expect(report.entries).toEqual([]); + expect(report.nodePath).toBeNull(); + // Removed once the run ends. + await expect(fsp.lstat(home)).rejects.toThrowError(/ENOENT/); + homes.push(home); + } }, ); + // Each run its own. + expect(new Set(homes).size).toBe(2); +}); + +test("H-1's isolation: lib/node under the prefix of each Node.js executable that will run — as spelled and along its physical path — is a global module folder too, a folder that is no directory holding none, and an executable whose physical path cannot be read leaving the isolation unverified (helpers/staging-isolation.ts)", async () => { + const staging = await makeWorkspace({ + dirs: ["root", "real/lib/node/some-package", "linked/bin", "plain/lib"], + files: { "real/bin/node": "", "plain/bin/node": "", "plain/lib/node": "" }, + symlinks: { "linked/bin/node": "../../real/bin/node" }, + }); + const isolation = (executable: string): Promise<void> => + verifyStagingIsolation({ + root: staging.path("root"), + role: "the S-4 probe's staging root", + context: "S-4 executable-prefix probe", + mode: "consumer-isolation", + run: { + environment: {}, + cwd: staging.path("root"), + executables: [executable], + }, + }); + const realFolder = path.join( + await fsp.realpath(staging.path("real")), + "lib", + "node", + ); + for (const [executable, folder] of [ + [staging.path("real/bin/node"), staging.path("real/lib/node")], + [staging.path("linked/bin/node"), realFolder], + ] as const) { + const refused: unknown = await isolation(executable).catch( + (error: unknown) => error, + ); + expect(refused).toBeInstanceOf(HarnessStagingError); + expect((refused as HarnessStagingError).mode).toBe("consumer-isolation"); + expect((refused as Error).message).toContain( + `the global folder ${folder}, which Node.js's resolver searches for ` + + `a bare specifier under the run's environment, holds the entry ` + + `"some-package"`, + ); + } + await expect(isolation(staging.path("plain/bin/node"))).resolves.toBe( + undefined, + ); + const unverified: unknown = await isolation( + staging.path("missing/bin/node"), + ).catch((error: unknown) => error); + expect(unverified).toBeInstanceOf(HarnessStagingError); + expect((unverified as Error).message).toContain( + `the physical path of the Node.js executable ` + + `${staging.path("missing/bin/node")} cannot be read`, + ); }); // `moduleSkeleton`'s fixture (T1.1-2: two generated modules expose the same diff --git a/test/self/s7-red-green-sweep.test.ts b/test/self/s7-red-green-sweep.test.ts index 3c910e32..268e9045 100644 --- a/test/self/s7-red-green-sweep.test.ts +++ b/test/self/s7-red-green-sweep.test.ts @@ -1,36 +1,67 @@ // S-7 red-green sweep (TEST-SPEC 17 S-7, §0 H-8). Against an empty stub -// product — every command exits with an unexpected code and no output — every -// product-facing test, the registry's entries and the bodies outside the -// registry alike, must fail with a diagnosed assertion failure (a -// `HarnessAssertionError`, helpers/assertions.ts), and the sweep must -// complete with no harness error, no hang, and no false pass. H-8's other -// half, a run with no product installed, holds the same bodies to the same -// verdict (layer 5). +// product — every command exits with an unexpected code and no output — +// beside an empty stub package (a directory holding only a manifest naming +// no entry; H-2's module channel), and again with no package directory +// given, every product-facing test, the registry's entries and the bodies +// outside the registry alike, must fail with a diagnosed assertion failure +// (a `HarnessAssertionError`, helpers/assertions.ts), and each sweep must +// complete with no harness error, no hang, and no false pass — 7.6's tests +// failing through their pairing (TEST-SPEC §7.6: a shape-violation arm +// counts only where its valid twin type-checks, a runtime absence only +// where the same run saw `defineConfig` return its argument), never passing +// on a negative arm alone. H-8's other half, a run with no product +// installed, holds the same bodies to the same verdict (layer 5). // -// The sweep target is the harness-owned stub fixture -// (test/fixtures/empty-stub/bin.mjs), deliberately not src/'s pre-product -// placeholder: H-8 sanctions "a deliberately empty stub", and a sweep bound -// to the placeholder would lose its subject the moment Phase 10 implements -// the product. This file keeps S-7 green in every phase. +// The sweep targets are two harness-owned fixtures, deliberately not src/'s +// pre-product placeholder or the product's own package directory: H-8 +// sanctions "a deliberately empty stub", and a sweep bound to the product +// would lose its subject the moment Phase 10 implements it. This file keeps +// S-7 green in every phase. +// - The stub product, test/fixtures/empty-stub/bin.mjs (its own comments +// give its contract and its exit code's choice). +// - The stub package, test/fixtures/empty-stub-package/, documented here +// since JSON holds no comment: one file, `package.json`, a manifest +// naming no entry — no `main`, `exports`, `types`, `typings`, `module`, +// `imports`, or `bin` — whose only members are `name`, +// `xspec-empty-stub`, and `version`, `0.0.0`; nothing else is in the +// directory. Wherever a test places it, under whatever name, neither +// TypeScript nor Node.js finds a module there — a specifier naming it +// designates nothing — so every arm of 7.6 fails beside it through its +// pairing. Its `name` is of 7.6's grammar, so that the tests reading the +// manifest's `name` (T7.6-4(a), T7-9(d)) stage under it as they would +// under the product's; and it is unscoped and differs from `xspec`, the +// executable's name, which T7-9(d) stages as a name of its own, so that +// no two of T7-9(d)'s names coincide. The sweep beside it gives every +// body the directory as the binding's `packageDir`, exactly as committed +// here, and afterwards finds it as it was: the harness copies a package +// directory and reads its manifest, never writing into it (H-2). // // Five layers, so the sweep's premise is pinned even while the registry is // still being populated: -// 1. the stub fixture's own contract (unexpected exit code, silence, -// no filesystem effects) is asserted directly; +// 1. the two stub fixtures' own contracts — the stub product's (unexpected +// exit code, silence, no filesystem effects) and the stub package's +// (the directory holds exactly `package.json`, a JSON object naming no +// entry) — are asserted directly; // 2. a registry-convention probe body is run against the stub through the // certification runner, proving end to end that the committed fixture // produces exactly the diagnosed-failure taxonomy the sweep relies on; // 3. the sweep proper runs every entry of the product-test manifest // (test/suite/registry/index.ts) against the stub via the certification // runner — the identical bodies and machinery C-1 certification uses -// (C-2 one code path). While the manifest is empty (no SUITE-*/PROP-* -// task has landed yet) the sweep is vacuously satisfied and layer 2 -// carries the check; suite completeness itself is gated elsewhere (S-1 -// traceability and the phase gate), not here; +// (C-2 one code path) — in two sweeps (`STUB_SWEEPS`): the stub product +// beside the stub package, given as the binding's `packageDir`, and +// the stub product with no package directory given (H-8: a stub +// package and a missing one alike hold every test of 7.6 to a diagnosed +// failure). Each sweep's title and report name it, and the sweep beside +// the stub package ends by finding the directory as it was. While the +// manifest is empty (no SUITE-*/PROP-* task has landed yet) the sweeps +// are vacuously satisfied and layer 2 carries the check; suite +// completeness itself is gated elsewhere (S-1 traceability and the +// phase gate), not here; // 4. the product-facing bodies outside the registry — §18's E-6 // machinery, keyed to no registry entry — run against the stub through -// the same runner, each wrapped as a synthetic entry in the reserved -// section-99 ID space: the representative fixture +// the same runner, in layer 3's two sweeps, each wrapped as a synthetic +// entry in the reserved section-99 ID space: the representative fixture // (`runE6RepresentativeFixture`, helpers/e6.ts), which // test/suite/e6-exchange-writer.test.ts and the Windows leg's // test/windows/e6-byte-identity.test.ts run before they touch the @@ -53,13 +84,18 @@ // full-suite job (the product built), and, like the stub, keeps its // subject in every phase. Each body must fail diagnosed, its diagnosis // naming the absent artifact: the driver's pre-flight refuses the -// body's first product invocation, before anything is spawned. The +// body's first product invocation, before anything is spawned — or, +// for a test of 7.6, which invokes no executable, the module channel +// finds no package directory given (that binding carries none) and +// fails diagnosed, naming the executable beside which none is given +// (helpers/module-channel.ts `modulePackageDirectory`). The // probe also runs against an unflagged binding of the certification // fixtures' shape over the same absent path, which must end a harness // error: an unbuilt fixture is a harness defect, never a certified // failure (C-1). import { expect, onTestFinished, test } from "vitest"; +import type { Stats } from "node:fs"; import * as fsp from "node:fs/promises"; import * as os from "node:os"; import * as path from "node:path"; @@ -101,15 +137,51 @@ const STUB_BIN = fileURLToPath( ); const STUB_EXIT_CODE = 87; -function emptyStubBinding(): ProductBinding { - return { - label: `empty-stub fixture product (exit ${STUB_EXIT_CODE}, no output)`, +// The committed stub package directory (module header), resolved like the +// stub executable: an absolute path, which the sweep beside the stub package +// gives every body exactly as spelled here. +const STUB_PACKAGE_DIR = fileURLToPath( + new URL("../fixtures/empty-stub-package", import.meta.url), +); + +/** + * The stub product's binding: beside the stub package where `packageDir` is + * given — the binding's package directory, as the built product's binding + * carries the product's — and with no package directory otherwise, each + * labelled with what it gives, so that a sweep's report names its sweep. + */ +function emptyStubBinding(packageDir?: string): ProductBinding { + const product = `empty-stub fixture product (exit ${STUB_EXIT_CODE}, no output)`; + const invocation = { command: process.execPath, prefixArgs: [STUB_BIN], requiredFiles: [STUB_BIN], }; + return packageDir === undefined + ? { label: `${product}, no package directory given`, ...invocation } + : { + label: `${product} beside the empty stub package ${packageDir}`, + ...invocation, + packageDir, + }; +} + +/** One of the two stub sweeps layers 3 and 4 run (module header). */ +interface StubSweep { + /** The sweep's name, in its tests' titles and its violation reports. */ + readonly name: string; + /** The stub product's binding for the sweep. */ + readonly binding: ProductBinding; } +const STUB_SWEEPS: readonly StubSweep[] = [ + { + name: "beside the empty stub package", + binding: emptyStubBinding(STUB_PACKAGE_DIR), + }, + { name: "with no package directory given", binding: emptyStubBinding() }, +]; + // No guard of its own per sweep (TEST-SPEC S-3, helpers/hang-guards.ts): a // sweep is a span over the bodies it runs, each stub invocation in them // bounded by its own hang guard — against the stub every one exits at once, @@ -154,6 +226,136 @@ test("the empty-stub fixture exits with an unexpected code and writes nothing, w expect(await workspace.readdirNames()).toEqual([]); }); +// Layer 1, the stub package (module header). The entry members of a +// manifest: the fields through which TypeScript's or Node.js's resolution, +// or a package manager, finds a module or an executable in a package. +const ENTRY_MEMBERS: readonly string[] = [ + "main", + "exports", + "types", + "typings", + "module", + "imports", + "bin", +]; + +// 7.6's grammar for an unscoped name (SPEC.md 7.6, *Package and +// installation*): a non-empty run of lowercase ASCII letters, digits, `-`, +// `.`, and `_` beginning with a letter or digit, at most 214 characters. +const UNSCOPED_NAME = /^[a-z0-9][a-z0-9._-]*$/; +const NAME_LENGTH_LIMIT = 214; + +const LF = String.fromCodePoint(0x0a); +const BYTE_ORDER_MARK = String.fromCodePoint(0xfeff); + +type EntryKind = "file" | "directory" | "symbolic link" | "other"; + +function kindOf(stats: Stats): EntryKind { + if (stats.isFile()) return "file"; + if (stats.isDirectory()) return "directory"; + if (stats.isSymbolicLink()) return "symbolic link"; + return "other"; +} + +/** An entry of the stub package as read, never followed. */ +interface PackageEntryState { + readonly name: string; + readonly kind: EntryKind; + readonly mode: number; + /** A regular file's bytes, base64; null for any other kind. */ + readonly bytes: string | null; +} + +/** + * The stub package directory read afresh: its own kind and mode, and each + * entry, in name order — what layer 1 pins, and what a sweep beside the + * stub package must leave as it found it. + */ +interface StubPackageState { + readonly kind: EntryKind; + readonly mode: number; + readonly entries: readonly PackageEntryState[]; +} + +async function readStubPackage(): Promise<StubPackageState> { + const directory = await fsp.lstat(STUB_PACKAGE_DIR); + const entries: PackageEntryState[] = []; + for (const name of (await fsp.readdir(STUB_PACKAGE_DIR)).sort()) { + const entryPath = path.join(STUB_PACKAGE_DIR, name); + const stats = await fsp.lstat(entryPath); + entries.push({ + name, + kind: kindOf(stats), + mode: stats.mode, + bytes: stats.isFile() + ? (await fsp.readFile(entryPath)).toString("base64") + : null, + }); + } + return { kind: kindOf(directory), mode: directory.mode, entries }; +} + +test("the empty stub package is a directory holding exactly one file, `package.json`: a manifest naming no entry, a JSON object whose only members are a `name` of 7.6's grammar — unscoped, and not `xspec` — and a `version`, in canonical form (the S-7 stub package contract; H-2's module channel)", async () => { + const state = await readStubPackage(); + expect(state.kind, STUB_PACKAGE_DIR).toBe("directory"); + expect( + state.entries.map(({ name, kind }) => `${name} (${kind})`), + "the stub package holds one regular file, its manifest, and nothing else", + ).toEqual(["package.json (file)"]); + const bytes = Buffer.from(state.entries[0]!.bytes!, "base64"); + // UTF-8 (`fatal`: an ill-formed sequence throws), a byte-order mark kept + // (`ignoreBOM`) so that it is seen and refused. + const text = new TextDecoder("utf-8", { + fatal: true, + ignoreBOM: true, + }).decode(bytes); + expect( + text.startsWith(BYTE_ORDER_MARK), + "the stub package's manifest carries no byte-order mark", + ).toBe(false); + const manifest: unknown = JSON.parse(text); + if ( + typeof manifest !== "object" || + manifest === null || + Array.isArray(manifest) + ) { + throw new Error( + `the stub package's manifest is not a JSON object: ${text}`, + ); + } + const members = Object.keys(manifest); + expect( + ENTRY_MEMBERS.filter((member) => members.includes(member)), + "the stub package's manifest names no entry", + ).toEqual([]); + expect( + members, + "the stub package's manifest holds a name and a version, and nothing else", + ).toEqual(["name", "version"]); + const { name, version } = manifest as Record<string, unknown>; + expect( + typeof name === "string" && + UNSCOPED_NAME.test(name) && + name.length <= NAME_LENGTH_LIMIT, + `the manifest's name ${JSON.stringify(name)} is an unscoped name of 7.6's grammar`, + ).toBe(true); + expect( + name, + "the manifest's name differs from `xspec`, the executable's name, which T7-9(d) stages as a name of its own", + ).not.toBe("xspec"); + expect( + typeof version === "string" && version !== "", + `the manifest's version ${JSON.stringify(version)} is a non-empty string`, + ).toBe(true); + // Canonical form — two-space JSON ending in one line feed, Prettier's form + // for a package.json — which also rules out a repeated member name, whose + // earlier value JSON.parse drops silently. + expect( + text, + "the stub package's manifest is in canonical form, no member name repeated", + ).toBe(`${JSON.stringify(manifest, null, 2)}${LF}`); +}); + // A body following the registry conventions exactly (own workspace lifecycle, // rejection only via the diagnosed-assertion helpers): what the runner sees // here is what real suite bodies produce against the stub. Section-99 ID @@ -189,44 +391,101 @@ test("a registry-convention body fails diagnosed against the committed stub via expect(result.diagnosis).toContain(`exit code ${STUB_EXIT_CODE}`); }); -test( - "S-7: every product-facing test in the registry fails as a diagnosed assertion failure against the empty stub — the sweep completes with no false pass, harness error, or hang (H-8)", - { timeout: NO_SPAN_GUARD }, - async () => { - const entries = productTestSuite.all(); - if (entries.length === 0) { - // Vacuously satisfied: no SUITE-*/PROP-* task has populated the - // manifest yet. This is not a false pass — "every product-facing test - // fails" holds over the empty set, the stub premise is pinned by the - // two tests above, and suite completeness is enforced by the S-1 - // traceability self-check and the phase gate, not by S-7. - return; - } - // Bodies are H-1-isolated and exit fast against the stub (every product - // invocation terminates immediately), so a higher lane count than the - // runner's conservative default is safe and keeps the sweep short. - const report = await runProductTests(emptyStubBinding(), entries, { - concurrency: 8, - }); - const offenders = report.results.filter( - (result) => result.outcome !== "fail", +/** + * The stub package's state before a sweep beside it, read afresh (H-2: the + * harness never writes into a package directory); null for a sweep with no + * package directory given. + */ +async function stubPackageBefore( + sweep: StubSweep, +): Promise<StubPackageState | null> { + return sweep.binding.packageDir === undefined + ? null + : await readStubPackage(); +} + +/** + * A sweep beside the stub package found it as it was before the sweep: its + * kind and mode, and each entry's kind, mode, and bytes (H-2: the harness + * copies a package directory and reads its manifest, never writing into it). + */ +async function expectStubPackageAsBefore( + sweep: StubSweep, + before: StubPackageState | null, +): Promise<void> { + if (before === null) { + return; + } + expect( + await readStubPackage(), + `S-7's sweep ${sweep.name} left the stub package ${STUB_PACKAGE_DIR} ` + + `as it found it (H-2: the harness never writes into a package directory)`, + ).toStrictEqual(before); +} + +/** The words a test title adds for a sweep beside the stub package. */ +function packageClause(sweep: StubSweep): string { + return sweep.binding.packageDir === undefined + ? "" + : ", the stub package left as the sweep found it (H-2)"; +} + +/** + * Layer 3's verdict (H-8): every registered body failed as a diagnosed + * assertion failure in `sweep`. Any other outcome is named by count, with + * the sweep's name and the runner's report. + */ +function expectEveryEntryFailed( + report: FixtureRunReport, + sweep: StubSweep, +): void { + const offenders = report.results.filter( + (result) => result.outcome !== "fail", + ); + if (offenders.length > 0) { + throw new Error( + `S-7 red-green sweep ${sweep.name} violated: ${offenders.length} of ${report.results.length} ` + + `product-facing test(s) did not fail as a diagnosed assertion failure against the ` + + `empty stub (H-8: a pass here is a false pass; an error or hang is a harness ` + + `defect).\n${renderFixtureReport(report)}`, ); - if (offenders.length > 0) { - throw new Error( - `S-7 red-green sweep violated: ${offenders.length} of ${report.results.length} ` + - `product-facing test(s) did not fail as a diagnosed assertion failure against the ` + - `empty stub (H-8: a pass here is a false pass; an error or hang is a harness ` + - `defect).\n${renderFixtureReport(report)}`, - ); - } - expect(report.counts).toEqual({ - pass: 0, - fail: entries.length, - error: 0, - hang: 0, - }); - }, -); + } + expect(report.counts).toEqual({ + pass: 0, + fail: report.results.length, + error: 0, + hang: 0, + }); +} + +for (const sweep of STUB_SWEEPS) { + test( + `S-7, ${sweep.name}: every product-facing test in the registry fails as a diagnosed assertion failure against the empty stub — the sweep completes with no false pass, harness error, or hang (H-8)${packageClause(sweep)}`, + { timeout: NO_SPAN_GUARD }, + async () => { + const entries = productTestSuite.all(); + if (entries.length === 0) { + // Vacuously satisfied: no SUITE-*/PROP-* task has populated the + // manifest yet. This is not a false pass — "every product-facing + // test fails" holds over the empty set, the stub premise is pinned + // by layers 1 and 2, and suite completeness is enforced by the S-1 + // traceability self-check and the phase gate, not by S-7. + return; + } + const before = await stubPackageBefore(sweep); + // Bodies are H-1-isolated and exit fast against the stub (every + // product invocation terminates immediately), so a higher lane count + // than the runner's conservative default is safe and keeps the sweep + // short. + const report = await runProductTests(sweep.binding, entries, { + concurrency: 8, + }); + expectEveryEntryFailed(report, sweep); + expect(report.results).toHaveLength(entries.length); + await expectStubPackageAsBefore(sweep, before); + }, + ); +} // Layer 4 (module header): the product-facing bodies outside the registry, // each wrapped as a synthetic entry in the reserved section-99 ID space @@ -287,13 +546,17 @@ const BODIES_OUTSIDE_THE_REGISTRY: readonly ProductTestEntry[] = [ ]; /** - * Layer 4's verdict (H-8): every body failed as a diagnosed assertion - * failure, and each diagnosis names the stub's exit code — the body reached - * the stub and was rejected for its answer (H-5: every test asserts the - * exact exit code), not by a harness-side check before any invocation. Any - * other outcome is named by test ID, with the runner's report. + * Layer 4's verdict (H-8): in `sweep`, every body failed as a diagnosed + * assertion failure, and each diagnosis names the stub's exit code — the + * body reached the stub and was rejected for its answer (H-5: every test + * asserts the exact exit code), not by a harness-side check before any + * invocation. Any other outcome is named by test ID, with the sweep's name + * and the runner's report. */ -function expectEveryBodyFailedAtTheStub(report: FixtureRunReport): void { +function expectEveryBodyFailedAtTheStub( + report: FixtureRunReport, + sweep: StubSweep, +): void { const stubAnswer = `exit code ${STUB_EXIT_CODE}`; const offenders = report.results.filter( (result) => @@ -312,7 +575,7 @@ function expectEveryBodyFailedAtTheStub(report: FixtureRunReport): void { ) .join(", "); throw new Error( - `S-7 red-green sweep violated outside the registry: ${named} — every ` + + `S-7 red-green sweep ${sweep.name} violated outside the registry: ${named} — every ` + `product-facing body must fail as a diagnosed assertion failure at ` + `the empty stub's answer (H-8: a pass here is a false pass; an error ` + `or hang is a harness defect).\n${renderFixtureReport(report)}`, @@ -326,20 +589,24 @@ function expectEveryBodyFailedAtTheStub(report: FixtureRunReport): void { }); } -test( - "S-7: every product-facing body outside the registry — the E-6 representative fixture, the Windows leg's five single-casing probes (T7-1, T7-4, T10.1-2, T10.1-3, T12.0-6), and T11.6-1's drive-mismatch arm — fails as a diagnosed assertion failure at the empty stub's answer, with no false pass, harness error, or hang (H-8)", - { timeout: NO_SPAN_GUARD }, - async () => { - // Seven bodies, each exiting at its first invocation against the stub: - // one lane apiece. - const report = await runProductTests( - emptyStubBinding(), - BODIES_OUTSIDE_THE_REGISTRY, - { concurrency: BODIES_OUTSIDE_THE_REGISTRY.length }, - ); - expectEveryBodyFailedAtTheStub(report); - }, -); +for (const sweep of STUB_SWEEPS) { + test( + `S-7, ${sweep.name}: every product-facing body outside the registry — the E-6 representative fixture, the Windows leg's five single-casing probes (T7-1, T7-4, T10.1-2, T10.1-3, T12.0-6), and T11.6-1's drive-mismatch arm — fails as a diagnosed assertion failure at the empty stub's answer, with no false pass, harness error, or hang (H-8)${packageClause(sweep)}`, + { timeout: NO_SPAN_GUARD }, + async () => { + const before = await stubPackageBefore(sweep); + // Seven bodies, each exiting at its first invocation against the + // stub: one lane apiece. + const report = await runProductTests( + sweep.binding, + BODIES_OUTSIDE_THE_REGISTRY, + { concurrency: BODIES_OUTSIDE_THE_REGISTRY.length }, + ); + expectEveryBodyFailedAtTheStub(report, sweep); + await expectStubPackageAsBefore(sweep, before); + }, + ); +} // Layer 5 (module header): H-8's no-product half — the same bodies against // the built product's binding shape at an artifact path guaranteed absent, diff --git a/test/self/s9-typescript-well-formedness.test.ts b/test/self/s9-typescript-well-formedness.test.ts index e2883eba..922cd05e 100644 --- a/test/self/s9-typescript-well-formedness.test.ts +++ b/test/self/s9-typescript-well-formedness.test.ts @@ -9,19 +9,22 @@ // release-pin arms, language-level arms, and whitespace arm; T4-2's // relative-name and undeclared module declarations and its other // module-linking forms (their diagnostics are post-parse); T7-2's -// modifier-bearing configuration imports (the declarative form of 7 decides -// them); plain configuration files; a `.tsx` file holding JSX; and the -// fixed vector set of the forms the §16 generators compose — every +// modifier-bearing configuration imports, string-literal import names (the +// escape-spelled twin's too), and export and import assignments (the +// declarative form of 7 decides them); plain configuration files; a `.tsx` +// file holding JSX; and the fixed vector set of the forms the §16 +// generators compose — every // property's configuration file, P-7's capture sources, P-13's `c0/U.ts` // and `c1/V.ts`, P-14's code sources, and the fuzz base code source (each // draw's own are judged // per draw by the property runner, helpers/property.ts `drawSources`). // Every one it declares unparseable is rejected both ways: `010`, `09`, -// U+1C89 in an identifier, the T7-2 syntax error, and T14-12's staged code -// arms. And the top-level `await` forms 14.20 names, accepted read one way -// only, are a harness error whatever the declaration. Every non-ASCII or -// control character this file's own vectors hold is built from its code -// point. +// U+1C89 in an identifier, the T7-2 syntax error, T7-9(b)'s four +// scanner-rejected specifier escapes (each that release's scanning error, +// located at its escape), and T14-12's staged code arms. And the top-level +// `await` forms 14.20 names, accepted read one way only, are a harness error +// whatever the declaration. Every non-ASCII or control character and every +// backslash this file's own vectors hold is built from its code point. import { Buffer } from "node:buffer"; import { describe, expect, test } from "vitest"; @@ -45,6 +48,9 @@ import { P13_TS_FORM_VECTORS } from "../suite/registry/section-16-p13.js"; import { P14_TS_FORM_VECTORS } from "../suite/registry/section-16-p14.js"; import { P15_TS_FORM_VECTORS } from "../suite/registry/section-16-p15.js"; import { P16_TS_FORM_VECTORS } from "../suite/registry/section-16-p16.js"; +import { P17_TS_FORM_VECTORS } from "../suite/registry/section-16-p17.js"; +import { P18_TS_FORM_VECTORS } from "../suite/registry/section-16-p18.js"; +import { P19_TS_FORM_VECTORS } from "../suite/registry/section-16-p19.js"; import { P2_P3_TS_FORM_VECTORS } from "../suite/registry/section-16-p2-p3.js"; import { P4_TS_FORM_VECTORS } from "../suite/registry/section-16-p4.js"; import { P5_P6_TS_FORM_VECTORS } from "../suite/registry/section-16-p5-p6.js"; @@ -64,18 +70,27 @@ const NEL = cp(0x0085); const BOM = cp(0xfeff); const CR = cp(0x000d); const LF = cp(0x000a); +/** U+005C, so that no vector's escape is spelled in this file's source. */ +const BACKSLASH = cp(0x5c); /** Lines joined by U+000A, the last one terminated. */ const lines = (...parts: readonly string[]): string => parts.join(LF) + LF; const CODE_IMPORT = 'import A from "../specs/A.xspec"'; -/** A configuration over one spec group, its import line and callee given. */ -const configWith = (importLine: string, callee = "defineConfig"): string => +/** + * A configuration over one spec group, its import line, callee, and export + * form given (`export default`, or T7-2's export assignment `export =`). + */ +const configWith = ( + importLine: string, + callee = "defineConfig", + exportForm = "export default", +): string => lines( importLine, "", - `export default ${callee}({`, + `${exportForm} ${callee}({`, " specs: {", ' main: ["specs/**/*.mdx"]', " }", @@ -287,8 +302,12 @@ const WELL_FORMED: readonly Vector[] = [ "}", ), ], - // T7-2's modifier-bearing configuration imports: the declarative form of - // 7 refuses each (14.14), never a parse failure. + // T7-2's modifier-bearing configuration imports, string-literal import + // names, and export and import assignments, each named by S-9: the + // declarative form of 7 decides each, never a parse failure — refusing + // the modifier-bearing imports, the escape-spelled import name (read + // verbatim, 2.4, it spells no `defineConfig`), and both assignments + // (14.14), and loading `"defineConfig"` as that import, aliased. [ 'T7-2: `import type { defineConfig } from "xspec"`', "xspec.config.ts", @@ -309,6 +328,33 @@ const WELL_FORMED: readonly Vector[] = [ "xspec.config.ts", configWith('import { defineConfig } from "xspec" with { type: "json" }'), ], + [ + 'T7-2: a string-literal import name, `import { "defineConfig" as d } from "xspec"` with `export default d({…})`', + "xspec.config.ts", + configWith('import { "defineConfig" as d } from "xspec"', "d"), + ], + [ + "T7-2: its escape-spelled twin, the import name `defineConfig` with its `C` written as a hexadecimal escape, with `export default d({…})`", + "xspec.config.ts", + configWith( + `import { "define${BACKSLASH}x43onfig" as d } from "xspec"`, + "d", + ), + ], + [ + 'T7-2: an export assignment, `export = defineConfig({…})` beside `import { defineConfig } from "xspec"`', + "xspec.config.ts", + configWith( + 'import { defineConfig } from "xspec"', + "defineConfig", + "export =", + ), + ], + [ + 'T7-2: an import assignment, `import defineConfig = require("xspec")` beside `export default defineConfig({…})`', + "xspec.config.ts", + configWith('import defineConfig = require("xspec")'), + ], // Plain configuration files. [ "a plain `xspec.config.ts`", @@ -361,6 +407,43 @@ const WELL_FORMED: readonly Vector[] = [ ["top-level `await x;`, accepted both ways", "src/app.ts", lines("await x;")], ]; +/** + * T7-9(b)'s scanner-rejected specifiers, each the double-quoted literal as + * TEST-SPEC spells it, its one backslash built from U+005C: with the + * scanning error TypeScript 5.9.3 reports for it under both readings — its + * code, and its start counted in code units from the backslash. + */ +const T7_9_B_SPECIFIERS: readonly (readonly [ + name: string, + literal: string, + code: number, + fromBackslash: number, +])[] = [ + // "Hexadecimal digit expected.", where the escape's second digit is due. + [ + "a hexadecimal escape with one hex digit (backslash, `x`, `4`)", + `"${BACKSLASH}x4"`, + 1125, + 3, + ], + // "An extended Unicode escape value must be between 0x0 and 0x10FFFF + // inclusive.", at the value's first digit. + [ + "a braced Unicode escape of the code point 110000 hexadecimal (backslash, `u`, `{110000}`)", + `"${BACKSLASH}u{110000}"`, + 1198, + 3, + ], + // "Octal escape sequences are not allowed. …", at the backslash. + ["an octal escape (backslash, `0`, `1`)", `"${BACKSLASH}01"`, 1487, 0], + // "Escape sequence … is not allowed.", at the backslash. + ["a backslash before `8`", `"${BACKSLASH}8"`, 1488, 0], +]; + +/** A configuration importing `defineConfig` from `literal`, spelled as given. */ +const configImportingFrom = (literal: string): string => + configWith(`import { defineConfig } from ${literal}`); + const UNPARSEABLE: readonly Vector[] = [ [ "`010` in a `.ts` file — a legacy octal literal (T14-12)", @@ -393,6 +476,13 @@ const UNPARSEABLE: readonly Vector[] = [ ' main: ["specs/**/*.mdx"]', ), ], + // T7-9(b)'s specifier escapes, each a scanning error of the release under + // both readings (S-9), leaving the file not well-formed (14.20). + ...T7_9_B_SPECIFIERS.map(([name, literal]): Vector => [ + `T7-9(b): a configuration whose specifier holds ${name}`, + "xspec.config.ts", + configImportingFrom(literal), + ]), // The grammar the name selects. [ "JSX in a `.ts` file — the name selects plain TypeScript", @@ -532,6 +622,36 @@ describe("S-9 (TypeScript): every declared-unparseable code source and configura }); } }); + + test.each(T7_9_B_SPECIFIERS)( + "T7-9(b): a specifier holding %s draws one scanning error of the release, at its escape, in both readings", + (name, literal, code, fromBackslash) => { + // The vector holds the escape as spelled: one backslash, the + // literal's second code unit, and none elsewhere in the file. + expect(literal.split(BACKSLASH).length - 1).toBe(1); + expect(literal.indexOf(BACKSLASH)).toBe(1); + const source = configImportingFrom(literal); + expect(source.split(BACKSLASH).length - 1).toBe(1); + // The error lies inside the literal, its quotes included. + const start = source.indexOf(literal); + const at = source.indexOf(BACKSLASH) + fromBackslash; + expect(at).toBeGreaterThan(start); + expect(at).toBeLessThan(start + literal.length); + // An ASCII prefix, so the release's UTF-16 position is the byte offset. + const verdict = expectUnparseable(judged(source, "xspec.config.ts")); + for (const reading of TS_READINGS) { + expect(verdict.errors[reading], `${name}, read as ${reading}`).toEqual([ + expect.objectContaining({ + code, + index: at, + offset: at, + line: 1, + column: at + 1, + }), + ]); + } + }, + ); }); describe("S-9 (TypeScript): T14-12's staged code arms are rejected both ways", () => { @@ -596,9 +716,18 @@ describe("S-9 (TypeScript): every code source and configuration T14-12's positiv // included, is judged before any product exists; the §16 preamble: every // generated workspace is valid by construction, no draw declared // unparseable). The fixed vector set: every registered property's -// configuration file (the coverage check below reads the registry) — P-7's -// and P-13's composed per draw, the rest fixed records also judged -// by test/self/s9-staged-sources.test.ts — P-7's capture sources, P-13's +// configuration file (the coverage check below reads the registry) — P-7's, +// P-13's, P-17's, P-18's, and P-19's composed per draw (P-17's three files +// beside a name holding every character N may hold, as plain TypeScript and +// as TSX, through the composition its draws are staged with; P-18's vector +// draw — comments of both kinds in every gap, names of each class, keys of +// both spellings — and its mutant, as plain TypeScript and as TSX, through +// the composition and read-back its draws are staged with; P-19's twin a fixed +// record, and its drawn specifiers' families — every shape text raw, every +// escape of their characters, every inserted piece, in each quote style — +// through the shared builder its draws are staged with), the rest fixed +// records also judged by test/self/s9-staged-sources.test.ts — P-7's +// capture sources, P-13's // `c0/U.ts` and `c1/V.ts`, P-14's code sources (top-level markers, // function units, `src/lib/` specifiers), P-16's code sources (imports of // every spec module with their `text` exports aliased, top-level markers and @@ -628,6 +757,9 @@ const GENERATED_TS_FORM_VECTORS: Readonly< "P-14": P14_TS_FORM_VECTORS, "P-15": P15_TS_FORM_VECTORS, "P-16": P16_TS_FORM_VECTORS, + "P-17": P17_TS_FORM_VECTORS, + "P-18": P18_TS_FORM_VECTORS, + "P-19": P19_TS_FORM_VECTORS, }; const GENERATED_TS_VECTORS = Object.entries(GENERATED_TS_FORM_VECTORS).flatMap( @@ -651,7 +783,7 @@ describe("S-9 (TypeScript): every configuration file and code source the §16 ge for (const vectors of Object.values(GENERATED_TS_FORM_VECTORS)) { expect(vectors.some(([, path]) => path === "xspec.config.ts")).toBe(true); } - expect(GENERATED_TS_VECTORS.length).toBe(31); + expect(GENERATED_TS_VECTORS.length).toBe(48); expect(new Set(GENERATED_TS_VECTORS.map(([name]) => name)).size).toBe( GENERATED_TS_VECTORS.length, ); diff --git a/test/suite/declare.ts b/test/suite/declare.ts index 0553b38a..2df449de 100644 --- a/test/suite/declare.ts +++ b/test/suite/declare.ts @@ -1,9 +1,11 @@ // Thin Vitest wrapper over the product-test registry (C-2 "one code path"): // each suite file declares its section's registered entries with // `declareProductTests`, and every body runs here against the default -// binding — the built product (helpers/subprocess.ts, builtProductBinding) — -// byte-for-byte the same body the certification runner executes against -// CERTIFICATIONS.md fixture products. No test hard-codes the product path. +// binding — the built product (helpers/subprocess.ts, builtProductBinding), +// with the package directory `XSPEC_PACKAGE_DIR` names where it is set, the +// binding made as the body starts and handed to it unchanged — byte-for-byte +// the same body the certification runner executes against CERTIFICATIONS.md +// fixture products. No test hard-codes the product path. // // Membership guard: an entry declared to Vitest but absent from the manifest // (test/suite/registry/index.ts) would run in the suite yet be invisible to diff --git a/test/suite/registry/index.ts b/test/suite/registry/index.ts index 639884a5..cb59b5ff 100644 --- a/test/suite/registry/index.ts +++ b/test/suite/registry/index.ts @@ -51,8 +51,12 @@ import { section66Tests } from "./section-6.6.js"; import { section67Tests } from "./section-6.7.js"; import { section7BasicsTests } from "./section-7-basics.js"; import { section7DiscoveryTests } from "./section-7-discovery.js"; +import { section7ImportTests } from "./section-7-import.js"; +import { section7NamesTests } from "./section-7-names.js"; import { section71to73Tests } from "./section-7.1-7.3.js"; import { section74to75Tests } from "./section-7.4-7.5.js"; +import { section76Tests } from "./section-7.6.js"; +import { section76iiTests } from "./section-7.6-ii.js"; import { section8Tests } from "./section-8.js"; import { section9Tests } from "./section-9.js"; import { section93Tests } from "./section-9.3.js"; @@ -107,6 +111,9 @@ import { section16P13Tests } from "./section-16-p13.js"; import { section16P14Tests } from "./section-16-p14.js"; import { section16P15Tests } from "./section-16-p15.js"; import { section16P16Tests } from "./section-16-p16.js"; +import { section16P17Tests } from "./section-16-p17.js"; +import { section16P18Tests } from "./section-16-p18.js"; +import { section16P19Tests } from "./section-16-p19.js"; export const productTestSuite = new ProductTestSuite([ // Section registration modules are spread here as they are implemented. @@ -146,8 +153,12 @@ export const productTestSuite = new ProductTestSuite([ ...section67Tests, ...section7BasicsTests, ...section7DiscoveryTests, + ...section7ImportTests, + ...section7NamesTests, ...section71to73Tests, ...section74to75Tests, + ...section76Tests, + ...section76iiTests, ...section8Tests, ...section9Tests, ...section93Tests, @@ -202,6 +213,9 @@ export const productTestSuite = new ProductTestSuite([ ...section16P14Tests, ...section16P15Tests, ...section16P16Tests, + ...section16P17Tests, + ...section16P18Tests, + ...section16P19Tests, ]); // The staged-source ledger (helpers/staged-mdx.ts, and its TypeScript diff --git a/test/suite/registry/section-1.1-1.2.ts b/test/suite/registry/section-1.1-1.2.ts index f920a0dd..838c84fa 100644 --- a/test/suite/registry/section-1.1-1.2.ts +++ b/test/suite/registry/section-1.1-1.2.ts @@ -739,7 +739,7 @@ const T1_2_2 = defineProductTest({ // program, the generated module and its companions included — then // run under the CommonJS configuration alone: compiled to CommonJS // JavaScript written outside the workspace and run there under plain - // Node, no package named `xspec` resolvable (H-2, SPEC 13.1). + // Node, nothing resolvable by package name (H-2, H-1, SPEC 13.1). await forEachConsumerProject(sources, (project) => assertTypeChecksClean(project, context), ); diff --git a/test/suite/registry/section-1.6-1.7.ts b/test/suite/registry/section-1.6-1.7.ts index e8db3034..5ec62871 100644 --- a/test/suite/registry/section-1.6-1.7.ts +++ b/test/suite/registry/section-1.6-1.7.ts @@ -784,7 +784,7 @@ const T1_6_3 = defineProductTest({ // whole program, the generated module and its companions included — // and runs under the CommonJS configuration alone: compiled to // CommonJS JavaScript written outside the workspace and run there - // under plain Node, no package named `xspec` resolvable (H-2). + // under plain Node, nothing resolvable by package name (H-2, H-1). await workspace.file("main.ts", EXPANSION_CONSUMER); const sources = { rootDir: workspace.root, rootFiles: ["main.ts"] }; const consumerContext = diff --git a/test/suite/registry/section-13.1-13.2.ts b/test/suite/registry/section-13.1-13.2.ts index 5f71f764..26194231 100644 --- a/test/suite/registry/section-13.1-13.2.ts +++ b/test/suite/registry/section-13.1-13.2.ts @@ -60,8 +60,9 @@ // absent). The consumer files are matched by no configured group (the §4 // preamble arrangement), and the compiled program — the compiler's output // alone, written outside the workspace — runs under plain Node with -// NODE_PATH dropped and no package named `xspec` resolvable -// (helpers/tooling.ts): "no xspec runtime dependency", observed +// NODE_PATH dropped, a fresh HOME, and nothing resolvable by package +// name, nothing installed in or above the consumer project +// (helpers/tooling.ts, H-1): "no xspec runtime dependency", observed // structurally. Per-contract negative matrices and edge cases remain with // T4-1…T4.6-4. // - T13.2-1 asserts placement and exact bytes together ("content per section @@ -553,8 +554,9 @@ const T13_1_2 = defineProductTest({ // (d) 4.3–4.5 runtime, under H-2's CommonJS configuration alone: the // consumer program, compiled to CommonJS JavaScript written into a // fresh directory outside the workspace — the compiler's output - // alone — runs there under plain Node (NODE_PATH dropped, no package - // named `xspec` resolvable: no xspec runtime dependency), and the + // alone — runs there under plain Node (NODE_PATH dropped, a fresh + // HOME, nothing resolvable by package name: no xspec runtime + // dependency, its defineConfig module included), and the // program's whole stdout is byte-compared: `text` returns the // subtree texts through both modules (the second via its alias) and // the marker line contributes nothing. The ES-module configuration's diff --git a/test/suite/registry/section-16-p17.ts b/test/suite/registry/section-16-p17.ts new file mode 100644 index 00000000..0fa3aa65 --- /dev/null +++ b/test/suite/registry/section-16-p17.ts @@ -0,0 +1,920 @@ +// TEST-SPEC §16 P-17 (installation names). +// +// One registered product-facing property test (C-2 "one code path") over +// SPEC 7.6's Package and installation and Reach: a package installed under +// a name N — placed, exactly as distributed, at `node_modules/N` in its +// holding directory, the importing file's own or an ancestor, as a copy or +// as a symbolic link to one — is designated by a specifier spelling exactly +// N along TypeScript's route in every covered setup and along Node.js's +// routes on every release the runtime contract covers, wherever Reach's +// four conditions hold; a copy, a symbolic-link install, and an aliased +// install are alike. T7.6-4's placements anchor the property +// (section-7.6-ii.ts: the manifest's own name, a symbolic link, a scoped +// name, a digit-first name, a name holding `-` and `_`, the dotted names +// `a.js` and `a.b`, an unscoped and a scoped 214-character name, two +// ancestor holding directories); this module searches the names and +// placements they never stage. A seeded, reproducible generator +// (helpers/property.ts, H-10; the fixed seed set in CI, E-5) draws, per +// trial (`genP17Draw`): +// +// * N (`genP17Name`), a name of 7.6's grammar: unscoped, or scoped +// (`@scope/name`), each segment a run of lowercase ASCII letters, +// digits, `-`, `.`, and `_` beginning with a letter or a digit, its +// lead weighted toward a digit (digit-first segments); its length drawn +// from four classes (P17_LENGTH_CLASSES), the last 7.6's bound of 214 +// characters itself; and its last segment weighted toward holding a +// `.`, so that S — N cut before the first `.` of its last segment — +// differs from N, what follows that `.` drawn as a run of the alphabet +// (possibly empty: `a.`) or as one of the file extensions TypeScript and +// Node.js read in a specifier (P17_EXTENSION_SUFFIXES: `js`, `d.ts`, +// `json`, `node`, …), the lookups Reach's nothing-nearer condition +// guards. Never an `@types` name, an `@typescript` name beginning +// `lib-`, or a name a release E-1 lists resolves to a built-in module: +// a draw falling there is mended by construction — the scope's leading +// `t` made `u` (`@types/…` drawn as `@uypes/…`), and a `-` appended to +// an unscoped name P17_NODE_BUILT_IN_NAMES holds (`fs` drawn as `fs-`). +// Those names are the 42 that every listed release resolves to its own +// built-in modules without the `node:` scheme (its newer built-ins, +// `node:test` and `node:sqlite` among them, are reached through that +// scheme alone), and the drawn release itself confirms on every draw +// that it resolves N to none (below); +// * the placement form: a copy at `node_modules/N`, or a symbolic link +// there to a copy elsewhere in the staging, under no `node_modules` +// (helpers/module-channel.ts `ModuleStaging.place`); +// * the holding directory: the importing files' own directory, +// P17_IMPORTING_DIR (`outer/inner/project`), or, at even odds, one of +// its three ancestors, the staging root the farthest; +// * a covered setup of 7.6's matrix (helpers/module-channel-ts.ts +// `COVERED_SETUPS`: a project kind, the configuration file's +// extension, and an option set), its option set's kind drawn first — +// the initialized-project set, which covers 5 of the 173 setups, a +// quarter of the time — then one of that kind's setups; and +// * a release E-1 lists (test/node-releases.json, read at module load) +// and one of Node.js's four routes, T7.6-6's (a static `import` and a +// dynamic `import()` from an `.mjs`, a dynamic `import()` and `require` +// from a `.cjs`). +// +// Each draw's files — T7.6-1's covered file (T7.6-2(d)'s), T7.6-2(a)'s +// file, and T7.6-3's unknown-top-level-key arm, beside N, exactly as +// T7.6-4's placements compose them (section-7.6.ts `placementFiles`) — are +// checked well-formed under the grammar their staged name selects before +// anything is staged (S-9; §16's preamble: `drawSources`, a failing draw a +// harness error reported with its seed). The body checks the package +// directory first (none given fails diagnosed before any draw, declining +// shrinking: H-8, S-7) and resolves every release E-1 lists (a missing one +// a harness error, E-1); then each draw runs in two fresh stagings (H-1), +// as T7.6-4's placements run their two halves, each holding the drawn +// setup's project kind in the importing files' directory as +// `ModuleStaging.stageProject` stages it, the drawn placement in the drawn +// holding directory, and nothing else (Reach's conditions verified, and +// nothing but the placement installed, before any tool runs): +// +// * the type-checking half: the three files written under the drawn +// setup's extension and judged in one program in the drawn setup +// (helpers/module-channel-ts.ts, which falls back to a program per file +// where the batch is unsound) — T7.6-1's listing declaring exactly +// `defineConfig` (section-7.6.ts `assertDeclaredExports`), T7.6-2(a)'s +// file type-checking (`assertTypeChecks`), and the arm failing to +// type-check paired with it (`assertShapeViolation`; where (a)'s file +// does not type-check the arm counts nowhere: §7.6 Pairing); +// * the runtime half: the placement made on the drawn release's runtime +// arm — the release itself asked whether it resolves N to a built-in +// module, a yes a harness error (the generator let through a name it +// never draws) — and one run along the drawn route on that release +// (helpers/module-channel-node.ts `runModuleRoute`, under T7.6-6's run +// conditions), which must load the module and end on its own with exit +// code 0 (`assertModuleLoaded`), its exports exactly `defineConfig` and +// `defineConfig` returning its argument (`exportsProblems`, +// `identityProblems`: T7.6-6's (a) and (b), as T7.6-4 reads them). +// +// Both halves run on every draw: their diagnosed failures are collected, +// and the draw fails once, naming each (New-test conventions: many +// stagings); a harness error or a hang-guard kill propagates at once. A +// draw failing where nothing resolves — TypeScript resolving T7.6-1's +// import to no module it reads declarations from, and the load throwing — +// declines shrinking (helpers/assertions.ts): with Reach holding, both +// tools read the package's own manifest and files alone, whatever the +// draw, so no draw is expected to resolve where this one did not, and a +// shrink would only report an arbitrary counterexample, as for H-8's +// missing product (helpers/property.ts). S-7's stub package, whose manifest +// names no entry, so ends P-17 at its first draw. Every other failure +// shrinks, within P17_MAX_SHRINK_EXECUTIONS draws. +// +// No certification serves the module channel (CERTIFICATIONS.md, the +// defineConfig module's tests): P-17's draws reach no class without a +// deterministic anchor whose failure is loud — names, placement forms, +// holding directories, setups, releases, and routes by T7.6-4 and T7.6-6. +// test/self/p17-fixed-seed-draws.test.ts pins what the fixed seeds reach: a +// dotted last segment, an extension-like suffix, a scoped name, a +// digit-first segment, a 214-character name, both placement forms, each +// holding directory, each project kind, covered extension, and option-set +// kind, each release, and each route. + +import * as fs from "node:fs"; +import { fail, HarnessAssertionError } from "../../helpers/assertions.js"; +import { + MODULE_NAME_MAX_LENGTH, + moduleNameExclusion, + moduleNameGrammarProblem, + modulePackageDirectory, + ModuleStaging, + runtimeArm, + TYPE_CHECKING_ARM, +} from "../../helpers/module-channel.js"; +import type { + ModuleArm, + Placement, + PlacementForm, +} from "../../helpers/module-channel.js"; +import { + assertShapeViolation, + assertTypeChecks, + COVERED_SETUPS, + stageCoveredFiles, +} from "../../helpers/module-channel-ts.js"; +import type { + CoveredSetup, + CoveredVerdict, + OptionSetKind, +} from "../../helpers/module-channel-ts.js"; +import { + assertModuleLoaded, + describeRoute, + exportsProblems, + identityProblems, + MODULE_ROUTES, + runModuleRoute, +} from "../../helpers/module-channel-node.js"; +import type { ModuleRoute } from "../../helpers/module-channel-node.js"; +import { + NODE_RELEASE_LIST_PATH, + parseNodeReleaseList, + resolveNodeReleases, +} from "../../helpers/node-releases.js"; +import type { NodeRelease } from "../../helpers/node-releases.js"; +import type { Choices, DrawSource } from "../../helpers/property.js"; +import { checkProperty } from "../../helpers/property.js"; +import { defineProductTest } from "../../helpers/registry.js"; +import type { ProductTestEntry } from "../../helpers/registry.js"; +import { guardSyncStep } from "../../helpers/step-guards.js"; +import type { ProductBinding } from "../../helpers/subprocess.js"; +import { assertDeclaredExports, placementFiles } from "./section-7.6.js"; +import type { PlacementFile, PlacementFiles } from "./section-7.6.js"; + +/** + * Trials per fixed seed (E-5): the default three seeds, each draw two + * stagings, one TypeScript program, and two runs of a release (the + * built-in check and the route's). test/self/p17-fixed-seed-draws.test.ts + * replays exactly these. + */ +export const P17_RUNS_PER_SEED = 25; + +/** + * Shrink budget, in draws (helpers/property.ts): each costs a full draw, + * about a third of a second against a conforming stand-in, so a failure + * found on a long name has room to shrink. + */ +const P17_MAX_SHRINK_EXECUTIONS = 32; + +/** `n` and `word`, pluralized. */ +function count(n: number, word: string): string { + return `${String(n)} ${word}${n === 1 ? "" : "s"}`; +} + +// --------------------------------------------------------------------------- +// N (module header) + +/** A segment's characters (SPEC 7.6): its lead, and the rest of its run. */ +const LETTERS: readonly string[] = [..."abcdefghijklmnopqrstuvwxyz"]; +const DIGITS: readonly string[] = [..."0123456789"]; + +/** N's length classes, simplest first: [least, most] characters. */ +export type P17LengthClass = "short" | "medium" | "long" | "bound"; + +export const P17_LENGTH_CLASSES: Readonly< + Record<P17LengthClass, readonly [number, number]> +> = { + short: [1, 8], + medium: [9, 40], + long: [41, MODULE_NAME_MAX_LENGTH - 1], + bound: [MODULE_NAME_MAX_LENGTH, MODULE_NAME_MAX_LENGTH], +}; + +const LENGTH_WEIGHTS: ReadonlyArray<readonly [number, P17LengthClass]> = [ + [6, "short"], + [3, "medium"], + [1, "long"], + [2, "bound"], +]; + +/** How often N is scoped, and its last segment dotted. */ +const SCOPED_PROBABILITY = 0.4; +const DOTTED_PROBABILITY = 0.5; + +/** + * File extensions TypeScript and Node.js read in a specifier, drawn after + * the last segment's `.` (module header): each a run of 7.6's alphabet. + */ +export const P17_EXTENSION_SUFFIXES: readonly string[] = [ + "js", + "mjs", + "cjs", + "jsx", + "ts", + "mts", + "cts", + "tsx", + "d.ts", + "d.mts", + "d.cts", + "json", + "node", + "wasm", +]; + +/** + * The names every release E-1 lists resolves to its own built-in modules + * without the `node:` scheme and that 7.6's grammar admits (module header: + * each release's `require("node:module").builtinModules`, less the names + * holding a `/` or beginning `_`, which the grammar bars). A draw never + * stages one: an unscoped name drawn among them is mended by a `-` + * appended. + */ +export const P17_NODE_BUILT_IN_NAMES: readonly string[] = [ + "assert", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "diagnostics_channel", + "dns", + "domain", + "events", + "fs", + "http", + "http2", + "https", + "inspector", + "module", + "net", + "os", + "path", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "repl", + "stream", + "string_decoder", + "sys", + "timers", + "tls", + "trace_events", + "tty", + "url", + "util", + "v8", + "vm", + "wasi", + "worker_threads", + "zlib", +]; + +/** A segment's lead: a letter, or — weighted toward it — a digit. */ +function genLead(choices: Choices): string { + return choices.pick( + choices.weightedPick<readonly string[]>([ + [3, LETTERS], + [2, DIGITS], + ]), + ); +} + +/** One character of a segment's run past its lead. */ +function genRunCharacter(choices: Choices): string { + return choices.pick( + choices.weightedPick<readonly string[]>([ + [10, LETTERS], + [4, DIGITS], + [1, ["-"]], + [1, ["_"]], + [1, ["."]], + ]), + ); +} + +/** `length` characters of a segment's run. */ +function genRun(choices: Choices, length: number): string { + let run = ""; + for (let index = 0; index < length; index += 1) { + run += genRunCharacter(choices); + } + return run; +} + +/** A segment of `length` characters (at least one): its lead, then its run. */ +function genSegment(choices: Choices, length: number): string { + return genLead(choices) + genRun(choices, length - 1); +} + +/** + * N's last segment, `length` characters long: where it is at least two, + * weighted toward a `.` after its lead, followed by an extension + * TypeScript or Node.js reads in a specifier or by a run of the alphabet, + * possibly empty (module header). + */ +function genLastSegment(choices: Choices, length: number): string { + if (length < 2 || !choices.boolean(DOTTED_PROBABILITY)) { + return genSegment(choices, length); + } + const room = length - 2; + const extensions = P17_EXTENSION_SUFFIXES.filter( + (suffix) => suffix.length <= room, + ); + const suffix = + extensions.length > 0 && choices.boolean(0.5) + ? choices.pick(extensions) + : genRun(choices, choices.intInclusive(0, room)); + return `${genSegment(choices, length - 1 - suffix.length)}.${suffix}`; +} + +/** + * N (module header): a name of 7.6's grammar outside its exclusions for + * every release E-1 lists — unscoped or scoped, its length drawn from + * P17_LENGTH_CLASSES (a scoped name at least four characters long), a + * draw falling under an exclusion mended by construction. + */ +export function genP17Name(choices: Choices): string { + const scoped = choices.boolean(SCOPED_PROBABILITY); + const [least, most] = + P17_LENGTH_CLASSES[choices.weightedPick(LENGTH_WEIGHTS)]; + const length = Math.max(choices.intInclusive(least, most), scoped ? 4 : 1); + if (!scoped) { + const name = genLastSegment(choices, length); + return P17_NODE_BUILT_IN_NAMES.includes(name) ? `${name}-` : name; + } + const scopeLength = choices.intInclusive(1, length - 3); + const drawnScope = genSegment(choices, scopeLength); + const name = genLastSegment(choices, length - 2 - scopeLength); + const excluded = + drawnScope === "types" || + (drawnScope === "typescript" && name.startsWith("lib-")); + const scope = excluded ? `u${drawnScope.slice(1)}` : drawnScope; + return `@${scope}/${name}`; +} + +// --------------------------------------------------------------------------- +// The draw (module header) + +/** + * The importing files' directory, staging-relative: three levels below the + * staging root, so that the holding directory may be any of its three + * ancestors. + */ +export const P17_IMPORTING_DIR = "outer/inner/project"; + +/** How many ancestors the importing files' directory has in the staging. */ +export const P17_IMPORTING_DEPTH = P17_IMPORTING_DIR.split("/").length; + +/** + * The holding directory `level` levels above the importing files' + * directory, staging-relative: its own at 0, the staging root (`""`) at + * {@link P17_IMPORTING_DEPTH}. + */ +export function holdingDirOf(level: number): string { + if (!Number.isInteger(level) || level < 0 || level > P17_IMPORTING_DEPTH) { + throw new Error( + `P-17: no holding directory lies ${String(level)} levels above ` + + `${P17_IMPORTING_DIR} in the staging`, + ); + } + return P17_IMPORTING_DIR.split("/") + .slice(0, P17_IMPORTING_DEPTH - level) + .join("/"); +} + +/** + * E-1's releases, in list order, read at module load from the one list CI + * and the harness both read (helpers/node-releases.ts): what the generator + * draws from. The body resolves each where the environment provisioned it. + */ +export const P17_RELEASE_VERSIONS: readonly string[] = guardSyncStep( + `reading E-1's release list ${NODE_RELEASE_LIST_PATH} for P-17's draws`, + () => + parseNodeReleaseList( + fs.readFileSync(NODE_RELEASE_LIST_PATH, "utf8"), + NODE_RELEASE_LIST_PATH, + ), +); + +/** One trial (module header). */ +export interface P17Draw { + /** N. */ + readonly name: string; + readonly form: PlacementForm; + /** + * How many levels above the importing files' directory the holding + * directory lies: 0 for that directory itself ({@link holdingDirOf}). + */ + readonly holdingLevel: number; + /** The covered setup, by its index in `COVERED_SETUPS`. */ + readonly setup: number; + /** The release, by its version. */ + readonly release: string; + readonly route: ModuleRoute; +} + +/** The indices in `COVERED_SETUPS` of the setups of one option-set kind. */ +function setupsOfKind(kind: OptionSetKind): readonly number[] { + return COVERED_SETUPS.flatMap((setup, index) => + setup.optionSet.kind === kind ? [index] : [], + ); +} + +/** + * The covered setups by option-set kind (module header): the strict + * defaults' 168, and the initialized-project set's 5, drawn a quarter of + * the time so that the fixed seeds reach it. + */ +export const P17_STRICT_DEFAULT_SETUPS = setupsOfKind("strict defaults"); +export const P17_INITIALIZED_PROJECT_SETUPS = setupsOfKind( + "initialized-project options", +); + +/** The generator (module header): simplest outcomes first, for shrinking. */ +export function genP17Draw(choices: Choices): P17Draw { + const name = genP17Name(choices); + const form: PlacementForm = choices.boolean(0.5) ? "symlink" : "copy"; + const holdingLevel = choices.boolean(0.5) + ? choices.intInclusive(1, P17_IMPORTING_DEPTH) + : 0; + const setup = choices.pick( + choices.weightedPick<readonly number[]>([ + [3, P17_STRICT_DEFAULT_SETUPS], + [1, P17_INITIALIZED_PROJECT_SETUPS], + ]), + ); + const release = choices.pick(P17_RELEASE_VERSIONS); + const route = choices.pick(MODULE_ROUTES); + return { name, form, holdingLevel, setup, release, route }; +} + +/** The drawn covered setup. */ +export function p17Setup(draw: P17Draw): CoveredSetup { + const setup = COVERED_SETUPS[draw.setup]; + if (setup === undefined) { + throw new Error( + `P-17: the draw names the covered setup ${String(draw.setup)}, which ` + + `7.6's matrix of ${String(COVERED_SETUPS.length)} does not hold: a ` + + "harness defect", + ); + } + return setup; +} + +/** The drawn holding directory, in words. */ +function describeHolding(draw: P17Draw): string { + if (draw.holdingLevel === 0) { + return `the importing files' own directory, ${P17_IMPORTING_DIR}`; + } + const holding = holdingDirOf(draw.holdingLevel); + return ( + `${holding === "" ? "the staging root" : holding}, ` + + `${count(draw.holdingLevel, "level")} above the importing files' ` + + `directory ${P17_IMPORTING_DIR}` + ); +} + +/** A draw, in words, for a diagnosis and a counterexample. */ +export function renderP17Draw(draw: P17Draw): string { + const setup = COVERED_SETUPS[draw.setup]; + return ( + `N ${JSON.stringify(draw.name)} (${String(draw.name.length)} ` + + `characters), ${ + draw.form === "copy" + ? "a copy at node_modules/N" + : "node_modules/N a symbolic link to a copy elsewhere in the staging" + }, held in ${describeHolding(draw)}; ${ + setup === undefined + ? `covered setup ${String(draw.setup)} (none such)` + : setup.label + }; the Node.js release ${draw.release} along ${describeRoute(draw.route)}` + ); +} + +// --------------------------------------------------------------------------- +// The draw's files, and S-9 (module header) + +/** The three files beside each N drawn so far, composed once per N. */ +const composed = new Map<string, PlacementFiles>(); + +/** The files beside `name` (section-7.6.ts `placementFiles`). */ +function p17Files(name: string): PlacementFiles { + let files = composed.get(name); + if (files === undefined) { + files = placementFiles(name); + composed.set(name, files); + } + return files; +} + +/** The three files in the order the type-checking half stages them. */ +function filesInOrder(files: PlacementFiles): readonly PlacementFile[] { + return [files.declaredExports, files.valid, files.unknownKey]; +} + +/** + * S-9's per-draw check (module header): the draw's three files, each under + * the name the drawn setup's extension gives it, so that S-9 judges each + * under the grammar its staging selects (TSX for `.tsx`). + */ +export function stagedP17Sources(draw: P17Draw): readonly DrawSource[] { + const { extension } = p17Setup(draw); + return filesInOrder(p17Files(draw.name)).map( + (file) => [`covered-file${extension}`, file.text, file.label] as const, + ); +} + +/** + * A name holding every character N may hold — scoped, one segment led by a + * letter and one by a digit, `-`, `.`, and `_` in each, and an + * extension-like suffix — for S-9's fixed vectors. + */ +const P17_VECTOR_NAME = "@a0-._/9z-_.d.ts"; + +/** + * S-9's fixed TypeScript vectors (test/self/s9-typescript-well-formedness + * .test.ts): the three files beside {@link P17_VECTOR_NAME}, as plain + * TypeScript and as TSX — the files P-17 composes beside any N, through + * the composition its draws are staged with. + */ +export const P17_TS_FORM_VECTORS: ReadonlyArray< + readonly [name: string, path: string, source: string | Uint8Array] +> = filesInOrder(placementFiles(P17_VECTOR_NAME)).flatMap((file) => + ["xspec.config.ts", "xspec.config.tsx"].map( + (path) => + [ + `P-17 configuration (${file.label}, importing ` + + `${JSON.stringify(P17_VECTOR_NAME)}, as ` + + `${path.endsWith(".tsx") ? "TSX" : "plain TypeScript"})`, + path, + file.text, + ] as const, + ), +); + +/** + * The generator's tables (module header), held at module load: each + * built-in name and the suffixes runs of 7.6's alphabet, a mended + * built-in name of the grammar and no built-in name itself, the importing + * directory three levels deep, the vector name of the grammar, and E-1's + * list read. A deviation is a harness defect, thrown at module load. + */ +function checkP17Tables(): void { + const problems: string[] = []; + const need = (held: boolean, problem: string): void => { + if (!held) problems.push(problem); + }; + const alphabet = new Set([...LETTERS, ...DIGITS, "-", ".", "_"]); + for (const name of P17_NODE_BUILT_IN_NAMES) { + need( + moduleNameGrammarProblem(name) === null && !name.startsWith("@"), + `the built-in name ${name} is an unscoped name of 7.6's grammar`, + ); + const mended = `${name}-`; + need( + moduleNameGrammarProblem(mended) === null && + !P17_NODE_BUILT_IN_NAMES.includes(mended), + `the mended name ${mended} is a name of 7.6's grammar and no built-in`, + ); + } + for (const suffix of P17_EXTENSION_SUFFIXES) { + need( + suffix.length > 0 && [...suffix].every((c) => alphabet.has(c)), + `the suffix ${suffix} is a run of 7.6's alphabet`, + ); + } + need( + P17_IMPORTING_DEPTH === 3 && + holdingDirOf(P17_IMPORTING_DEPTH) === "" && + holdingDirOf(0) === P17_IMPORTING_DIR, + `the importing files' directory ${P17_IMPORTING_DIR} lies three levels ` + + "below the staging root", + ); + need( + moduleNameGrammarProblem(P17_VECTOR_NAME) === null && + moduleNameExclusion(P17_VECTOR_NAME) === null, + `the vector name ${P17_VECTOR_NAME} is a name of 7.6's grammar outside ` + + "its exclusions", + ); + need(P17_RELEASE_VERSIONS.length > 0, "E-1's list names a release"); + need( + COVERED_SETUPS.length === 173 && + P17_STRICT_DEFAULT_SETUPS.length === 168 && + P17_INITIALIZED_PROJECT_SETUPS.length === 5, + "7.6's matrix holds 173 covered setups, 168 under the strict defaults " + + `and 5 under the initialized-project options, not ` + + `${String(COVERED_SETUPS.length)}, ${String(P17_STRICT_DEFAULT_SETUPS.length)}, ` + + `and ${String(P17_INITIALIZED_PROJECT_SETUPS.length)}`, + ); + if (problems.length > 0) { + throw new Error( + `P-17: its generator's tables deviate: ${problems.join("; ")}: a ` + + "harness defect", + ); + } +} + +checkP17Tables(); + +// --------------------------------------------------------------------------- +// The body (module header) + +/** Leads every diagnosis. */ +const P17_CONTEXT = "P-17 (installation names)"; + +/** TEST-SPEC P-17's rule, closing a draw's failure. */ +const P17_RULE = + "(TEST-SPEC P-17: N drawn from 7.6's grammar outside its exclusions, " + + "crossed with a drawn placement form, holding directory, covered setup, " + + "release, and route, every condition of Reach holding: T7.6-1's exports " + + "assertion holds, T7.6-2(a)'s file type-checks with T7.6-3's " + + "unknown-top-level-key arm paired to it, and T7.6-6's exports and " + + "identity assertions hold along the drawn route; SPEC 7.6 Package and " + + "installation — a copy, a symbolic-link install, and an aliased install " + + "are alike — and Reach)"; + +/** What one half of a draw found (module header). */ +interface HalfOutcome { + /** Each failing run's diagnosis, in order. */ + readonly failures: readonly string[]; + /** + * Whether nothing resolved there: TypeScript resolving T7.6-1's import + * to no module it reads declarations from, or the load throwing. + */ + readonly nothingResolved: boolean; +} + +/** Each failing assertion's diagnosis, in order: none where all hold. */ +function failuresOf(checks: readonly (() => void)[]): readonly string[] { + const failures: string[] = []; + for (const check of checks) { + try { + check(); + } catch (error) { + if (!(error instanceof HarnessAssertionError)) throw error; + failures.push(error.message); + } + } + return failures; +} + +/** + * Stage `draw` in `staging` for `arm` (module header): the drawn setup's + * project kind in the importing files' directory, then the drawn placement + * in the drawn holding directory. + */ +async function stageDraw( + staging: ModuleStaging, + draw: P17Draw, + setup: CoveredSetup, + arm: ModuleArm, +): Promise<Placement> { + await staging.stageProject(P17_IMPORTING_DIR, setup.project); + return staging.place({ + name: draw.name, + holdingDir: holdingDirOf(draw.holdingLevel), + arm, + form: draw.form, + }); +} + +/** + * A draw's type-checking half (module header): T7.6-1's covered file, + * T7.6-2(a)'s file, and T7.6-3's unknown-top-level-key arm judged in the + * drawn setup, beside the drawn placement. + */ +async function typeCheckingHalf( + product: ProductBinding, + draw: P17Draw, + setup: CoveredSetup, + context: string, +): Promise<HalfOutcome> { + const half = `${context}, its type-checking runs`; + const staging = await ModuleStaging.create(product, half); + try { + const placement = await stageDraw(staging, draw, setup, TYPE_CHECKING_ARM); + const covered = await stageCoveredFiles({ + staging, + directory: P17_IMPORTING_DIR, + project: setup.project, + placement, + alone: true, + files: filesInOrder(p17Files(draw.name)), + setups: [setup], + listExports: true, + context: half, + }); + const verdicts: readonly CoveredVerdict[] = covered.judge(setup); + const [listed, valid, arm] = verdicts; + if (listed === undefined || valid === undefined || arm === undefined) { + throw new Error("unreachable: three verdicts"); + } + const failures = failuresOf([ + () => { + assertDeclaredExports(listed, "T7.6-1's run"); + }, + () => { + assertTypeChecks(valid, "T7.6-2(a)'s run"); + }, + () => { + if (!valid.typeChecks) { + fail( + "T7.6-3's run: its unknown-top-level-key arm counts nowhere " + + "here, its valid twin, T7.6-2(a)'s file, not type-checking " + + "(TEST-SPEC §7.6 Pairing)", + ); + } + assertShapeViolation(valid, arm, "T7.6-3's run"); + }, + ]); + return { + failures, + nothingResolved: listed.exportListing?.module === undefined, + }; + } finally { + await staging.dispose(); + } +} + +/** + * A draw's runtime half (module header): one run along the drawn route on + * the drawn release, beside the drawn placement made on that release's + * runtime arm, read for T7.6-6's exports and identity. + */ +async function runtimeHalf( + product: ProductBinding, + draw: P17Draw, + setup: CoveredSetup, + release: NodeRelease, + context: string, +): Promise<HalfOutcome> { + const half = `${context}, its runtime run`; + const staging = await ModuleStaging.create(product, half); + try { + const placement = await stageDraw( + staging, + draw, + setup, + runtimeArm([release]), + ); + const run = await runModuleRoute({ + staging, + placement, + route: draw.route, + release, + importingDir: P17_IMPORTING_DIR, + project: setup.project, + alone: true, + context: half, + }); + let loaded; + try { + loaded = assertModuleLoaded(run, "product"); + } catch (error) { + if (!(error instanceof HarnessAssertionError)) throw error; + return { + failures: [`T7.6-6's run: ${error.message}`], + nothingResolved: run.outcome === "load-failed", + }; + } + const problems = [...exportsProblems(loaded), ...identityProblems(loaded)]; + return { + failures: + problems.length === 0 + ? [] + : [ + `T7.6-6's run, which loaded the module and ended on its own ` + + `with exit code 0: ${problems.join("; ")}`, + ], + nothingResolved: false, + }; + } finally { + await staging.dispose(); + } +} + +/** + * One draw (module header): both halves, then one diagnosed failure naming + * each failing run, declining shrinking where nothing resolved in either. + */ +async function runP17Draw( + product: ProductBinding, + releases: ReadonlyMap<string, NodeRelease>, + draw: P17Draw, +): Promise<void> { + const setup = p17Setup(draw); + const release = releases.get(draw.release); + if (release === undefined) { + throw new Error( + `P-17: the draw names the release ${draw.release}, which E-1's list ` + + `as resolved does not hold: a harness defect`, + ); + } + const context = + `${P17_CONTEXT}, N ${JSON.stringify(draw.name)}, ` + + `${draw.form === "copy" ? "a copy" : "a symbolic link"} held in ` + + describeHolding(draw); + const typeChecking = await typeCheckingHalf(product, draw, setup, context); + const runtime = await runtimeHalf(product, draw, setup, release, context); + const failures = [...typeChecking.failures, ...runtime.failures]; + if (failures.length === 0) return; + const nothingResolves = + typeChecking.nothingResolved && runtime.nothingResolved; + fail( + `${P17_CONTEXT}: ${String(failures.length)} of the draw's 4 runs — ` + + "T7.6-1's, T7.6-2(a)'s, T7.6-3's arm's, and T7.6-6's — " + + `${failures.length === 1 ? "fails" : "fail"} ${P17_RULE}` + + (nothingResolves + ? ". Nothing resolves here — TypeScript resolves the import to no " + + "module it reads declarations from, and the load throws — a " + + "failure no draw meeting Reach is expected to change, since both " + + "tools then read the package's own manifest and files alone, so " + + "it is reported as drawn, unshrunk" + : "") + + `: ${failures.join(" | ")}`, + { shrinkable: !nothingResolves }, + ); +} + +/** + * P-17's body (module header): the package directory checked and every + * release E-1 lists resolved before any draw, then the property. + */ +async function runP17(product: ProductBinding): Promise<void> { + await modulePackageDirectory(product, P17_CONTEXT); + const resolved = await resolveNodeReleases(); + const versions = resolved.map((release) => release.version); + if (versions.join(", ") !== P17_RELEASE_VERSIONS.join(", ")) { + throw new Error( + `P-17: the releases resolved (${versions.join(", ")}) are not those ` + + `its draws name (${P17_RELEASE_VERSIONS.join(", ")}), though both ` + + "come from E-1's one list: a harness defect", + ); + } + const releases = new Map( + resolved.map((release): [string, NodeRelease] => [ + release.version, + release, + ]), + ); + await checkProperty( + "P-17 installation names", + genP17Draw, + (draw) => runP17Draw(product, releases, draw), + { + runs: P17_RUNS_PER_SEED, + maxShrinkExecutions: P17_MAX_SHRINK_EXECUTIONS, + render: renderP17Draw, + drawSources: stagedP17Sources, + }, + ); +} + +// --------------------------------------------------------------------------- +// Registration + +const P_17 = defineProductTest({ + id: "P-17", + title: + "installation names (TEST-SPEC §16 P-17): seeded draws of N from 7.6's " + + "grammar — unscoped and scoped, each segment a run of lowercase " + + "letters, digits, -, ., and _ beginning with a letter or digit, " + + "weighted toward a . in the last segment (S then differing from N, " + + "what follows it a run or a file extension such as js or d.ts), " + + "digit-first segments, and lengths up to the 214-character bound — " + + "never an @types name, an @typescript/lib- name, or a name the drawn " + + "release resolves to a built-in module, each crossed with a drawn " + + "placement form (a copy, or a symbolic link to a copy elsewhere in the " + + "staging), a drawn holding directory (the importing files' own, or one " + + "of its ancestors up to the staging root), a covered setup drawn from " + + "7.6's matrix, and a release E-1 lists and a route drawn from T7.6-6's, " + + "every condition of Reach holding and each draw's files checked " + + "well-formed before staging (S-9): in the drawn setup, T7.6-1's " + + "covered file's import reaches a module declaring exactly defineConfig, " + + "T7.6-2(a)'s file type-checks, and T7.6-3's unknown-top-level-key arm " + + "fails to type-check paired with it; and along the drawn route on the " + + "drawn release, the module loads, the process ending on its own with " + + "exit code 0, its exports exactly defineConfig and defineConfig " + + "returning its argument (T7.6-6 (a), (b)) (SPEC 7.6 Package and " + + "installation, Reach; E-5)", + run: runP17, +}); + +/** TEST-SPEC §16 P-17. */ +export const section16P17Tests: readonly ProductTestEntry[] = [P_17]; diff --git a/test/suite/registry/section-16-p18.ts b/test/suite/registry/section-16-p18.ts new file mode 100644 index 00000000..09909ab9 --- /dev/null +++ b/test/suite/registry/section-16-p18.ts @@ -0,0 +1,2667 @@ +// TEST-SPEC §16 P-18 (type contract over generated configurations). +// +// One registered product-facing property test (C-2 "one code path") over +// SPEC 7.6's type contract: a covered file valid under 7 type-checks in +// every covered setup, whatever spelling it carries, and one holding a +// violation of 7.6's type-error class does not. T7.6-2 and T7.6-3 anchor +// the property (section-7.6.ts: every key, field, and enumerated value, an +// aliased binding, string-literal keys, comments, the minimal file, the +// global `Object` interface's members and `__proto__` as names, the empty, +// omitted, and repeated forms, and 430 single-violation edits of (a)'s +// file); this module searches the configurations they never stage. A +// seeded, reproducible generator (helpers/property.ts, H-10; the fixed +// seed set in CI, E-5) draws, per trial (`genP18Draw`): +// +// * a configuration valid under 7 by construction (`genP18Argument`): +// zero to three spec groups and, at even odds or so, a `code` map of +// zero to three code groups, a code group's name drawn now and then +// among the spec groups' so that a name is both kinds'; each group's +// glob list empty or not; `markdown`, `coverage`, and `policy` each +// present or absent, `markdown` with `emit` either boolean and `outDir` +// present or absent; up to two profiles, each optional field present or +// absent, and up to three rules, their selectors in each of 7.5's forms, +// `kinds` present or absent; every reference resolving (a profile's +// `target` a spec group, its `boundary` and a selector's `group` any +// group), every kind given where a name is both a spec and a code +// group's and drawn present or absent elsewhere (and then the name's +// own), group names distinct within each map, profile names distinct +// among the profiles and rule names among the rules; each list 7.4 and +// 7.5 read as a set (`targetTags`, `edgeKinds`, a rule's `kinds`, a +// selector's `tags`) drawn with repeated elements or without; +// * group, profile, and rule names (`genP18Name`) drawn from identifier +// spellings (P18_IDENTIFIER_NAMES, reserved words and non-ASCII letters +// among them), from non-identifier spellings (`genNonIdentifierName`: +// runs of ASCII punctuation, spaces, digits, letters, non-ASCII +// characters, an astral one among them, and control characters), and, +// weighted toward them, the seven members of TypeScript's global +// `Object` interface and `__proto__` — never a backslash, a quote, a +// line terminator, or U+FFFD (P18_FORBIDDEN_IN_STRINGS); a name drawn +// twice where 7 requires distinct names is mended by a suffix; +// * every object's key order (a drawn permutation of its keys), and per +// key its spelling: an identifier where the key is an identifier name +// by TypeScript's reading, drawn against a string literal, and a string +// literal otherwise; +// * `defineConfig`'s binding (`genP18Binding`): unaliased, or an alias +// drawn among names strict module code admits as a binding +// (P18_ALIAS_NAMES: contextual keywords, global names, `__`-prefixed +// names, non-ASCII ones, and `defineConfig` itself), never `require`, +// `exports`, or a name SPEC 6.5's first rule bars (section-7.6.ts +// `BARRED_BINDINGS`); +// * comments between tokens: a density per draw — none, sparse, or +// dense — and in each gap between two tokens of the file, before the +// first and after the last included, none, one, or two line or block +// comments, their bodies runs of P18_COMMENT_ALPHABET — no `@`, `/`, +// `*`, backslash, or line terminator — so that none is a directive or +// pragma, none begins `///`, and none closes early; +// * a covered setup of 7.6's matrix (helpers/module-channel-ts.ts +// `COVERED_SETUPS`), its option set's kind drawn first, as P-17 draws +// it (the initialized-project set's 5 setups a quarter of the time); +// * and one violation of 7.6's type-error class (`genP18Mutation`): its +// member drawn among those the draw has a position for, its position +// among the draw's — every fixed-key object for an unknown key, every +// required key present for a missing one, every value at a position 7 +// gives a kind for a kind, every enumerated value for an enumeration, +// every selector for a selector form, every set-read list for an empty +// list, and, for the last three, an optional field the draw omits, +// added (outside a selector, where adding a field changes its form) — +// and its offending value drawn: the unknown key's name +// (P18_UNKNOWN_KEYS, the `Object` members and `__proto__` among them, +// less the object's own fields), value, spelling, and place among the +// object's keys; a value of a kind 7 does not admit there, from T7.6-3's +// kind table (section-7.6.ts `T763_KIND_TABLE`) or drawn; a string +// outside the position's enumeration — near misses, other +// enumerations' members, `"contains"` for an edge kind, the empty +// string; a selector in one of T7.6-3's eight form violations, its +// names resolving; or the empty list. The mutant is the draw with that +// one edit, its spellings and comments elsewhere unchanged. +// +// The generator holds each draw to its premise before returning it: the +// harness's own reading of 7 over the data finds the draw valid +// (section-7.6.ts `problemsUnder7`), its reading of the type-error class +// finds no violation in the draw and exactly the drawn one in the mutant +// (`classViolations`); a deviation is a harness defect, thrown and reported +// with the seed (H-10). Each draw's two files — the draw and its mutant, +// each rendered beside each candidate canonical N (helpers/module-channel.ts +// `CANONICAL_MODULE_NAMES`) — are read back with the harness's TypeScript +// as 7.6's covered-file conditions require (section-7.6.ts `readBack`: an +// import of `defineConfig` by that identifier bound to the drawn binding, +// the specifier exactly N, a default export of one call whose argument +// reads back equal to the data, each key spelled as drawn, no backslash +// anywhere, and exactly the drawn comments, none carrying `@` or beginning +// `///`), and checked well-formed under the grammar the drawn setup's +// extension selects before TypeScript judges them (S-9; §16's preamble: +// `drawSources`, a failing draw a harness error reported with its seed). +// Reading back as its data, which holds no key twice in one object, no +// mutant carries beside its violation an error every `defineConfig` type +// meets (a repeated key, a syntax error): the composition residual +// CERTIFICATIONS.md's exclusions name for T7.6-3's edits and P-18's +// mutants. +// +// The body checks the package directory first (none given fails diagnosed +// before any draw, declining shrinking: H-8, S-7); then each draw runs in a +// fresh staging (H-1) holding the drawn setup's project kind in its project +// directory beside the canonical placement and nothing else (TEST-SPEC §7.6 +// Placement, Reach verified for each written file), where the draw and its +// mutant are written under the drawn setup's extension and judged in one +// program in the drawn setup (helpers/module-channel-ts.ts, which falls +// back to a program per file where the batch is unsound): the draw +// type-checks (`assertTypeChecks`, T7.6-2's assertion) and the mutant fails +// to type-check paired with it (`assertShapeViolation`, T7.6-3's; where the +// draw does not type-check, the mutant counts nowhere: §7.6 Pairing). Both +// are judged on every draw and the draw fails once, naming each failing +// assertion; a harness error or a hang-guard kill propagates at once. A +// draw failing where nothing resolves — TypeScript resolving the import to +// no module it reads declarations from (`listExports`) — declines +// shrinking (helpers/assertions.ts): no configuration is expected to +// resolve where this one did not, and a shrink would only report an +// arbitrary counterexample. S-7's stub package, whose manifest names no +// entry, so ends P-18 at its first draw. Every other failure shrinks, +// within P18_MAX_SHRINK_EXECUTIONS draws. +// +// Conservative operationalizations (noted per H-4): +// - The placement is the canonical one throughout: P-17 searches names and +// placements, so P-18 varies the configuration and the setup alone. +// - Globs, `outDir` values, and tags are drawn from fixed pools that 7 +// admits (P18_SPEC_GLOB_PARTS, P18_CODE_GLOB_PARTS, P18_OUT_DIRS, +// P18_TAGS): globs inside the root and capture-free, spec globs naming +// `.mdx` files and code globs `.ts` and `.tsx` ones, so that no file a +// spec and a code group both match can arise; none is staged, so no +// workspace-bound rule of 7 is reached. +// - A value replaced or added by a mutation carries no comments, its keys +// spelled as identifiers where they can be. +// +// No certification serves the module channel (CERTIFICATIONS.md, the +// defineConfig module's tests): P-18's draws reach no class without a +// deterministic anchor whose failure is loud — T7.6-2 and T7.6-3. +// test/self/p18-fixed-seed-draws.test.ts pins what the fixed seeds reach: +// string-literal and identifier keys, each `Object` member name and +// `__proto__` as a group name, non-identifier names, an aliased binding, +// empty glob lists, repeated elements in each set-read list, line and +// block comments in the import declaration and in the argument, each +// optional key present and absent, a kind given for a name of both kinds, +// each member of the type-error class, and each project kind, covered +// extension, and option-set kind. + +import ts from "typescript-5.9.3"; +import { fail, HarnessAssertionError } from "../../helpers/assertions.js"; +import { + CANONICAL_MODULE_NAMES, + modulePackageDirectory, + ModuleStaging, + TYPE_CHECKING_ARM, +} from "../../helpers/module-channel.js"; +import { + assertShapeViolation, + assertTypeChecks, + COVERED_SETUPS, + stageCoveredFiles, +} from "../../helpers/module-channel-ts.js"; +import type { + CoveredSetup, + OptionSetKind, +} from "../../helpers/module-channel-ts.js"; +import type { Choices, DrawSource } from "../../helpers/property.js"; +import { checkProperty } from "../../helpers/property.js"; +import { defineProductTest } from "../../helpers/registry.js"; +import type { ProductTestEntry } from "../../helpers/registry.js"; +import type { ProductBinding } from "../../helpers/subprocess.js"; +import { + BARRED_BINDINGS, + classViolations, + CONFIG_KINDS, + configObject, + CONTAINS, + describeValue, + EDGE_KINDS, + GROUP_KINDS, + isConfigList, + isConfigObject, + kindOf, + MODES, + nearMisses, + OBJECT_MEMBER_NAMES, + problemsUnder7, + readBack, + RULE_TYPES, + sameValue, + scanComments, + shapeNodes, + T763_KIND_TABLE, + TARGETS, +} from "./section-7.6.js"; +import type { + ClassViolation, + ConfigKind, + ConfigObject, + ConfigPath, + ConfigValue, + ShapeNode, + ShapeSchema, + ViolationCategory, +} from "./section-7.6.js"; + +/** + * Trials per fixed seed (E-5): the default three seeds, each draw one + * staging and one TypeScript program of two files. + * test/self/p18-fixed-seed-draws.test.ts replays exactly these. + */ +export const P18_RUNS_PER_SEED = 30; + +/** + * Shrink budget, in draws (helpers/property.ts): each costs a staging and + * one program, a fraction of a second against a conforming stand-in. + */ +const P18_MAX_SHRINK_EXECUTIONS = 96; + +const LF = String.fromCodePoint(0x0a); +const BACKSLASH = String.fromCodePoint(0x5c); +const INDENT = " "; + +/** `n` and `word`, pluralized. */ +function count(n: number, word: string): string { + return `${String(n)} ${word}${n === 1 ? "" : "s"}`; +} + +/** + * What no string of a draw holds (module header): a backslash, either + * quote, a line terminator TypeScript's scanner ends a string literal at + * (U+000A, U+000D, U+2028, U+2029), and U+FFFD — so that every string reads + * the same as spelled and as TypeScript reads it, delimited by double + * quotes, and every name is one 7 admits. + */ +export const P18_FORBIDDEN_IN_STRINGS: readonly string[] = [ + BACKSLASH, + '"', + "'", + LF, + String.fromCodePoint(0x0d), + String.fromCodePoint(0x2028), + String.fromCodePoint(0x2029), + String.fromCodePoint(0xfffd), +]; + +/** The first forbidden character `text` holds, or undefined. */ +function forbiddenIn(text: string): string | undefined { + return P18_FORBIDDEN_IN_STRINGS.find((character) => text.includes(character)); +} + +/** + * Whether TypeScript 5.9.3 reads `text` as one identifier name at ESNext: + * an identifier start, then identifier parts, code point by code point. + */ +export function isIdentifierName(text: string): boolean { + const [first, ...rest] = [...text].map((character) => + character.codePointAt(0), + ); + return ( + first !== undefined && + ts.isIdentifierStart(first, ts.ScriptTarget.ESNext) && + rest.every( + (codePoint) => + codePoint !== undefined && + ts.isIdentifierPart(codePoint, ts.ScriptTarget.ESNext), + ) + ); +} + +// --------------------------------------------------------------------------- +// The draw's data: values with their spellings and comments (module header) +// --------------------------------------------------------------------------- + +/** A comment drawn between two tokens. */ +export interface P18Comment { + readonly kind: "line" | "block"; + /** Its text, a run of P18_COMMENT_ALPHABET, rendered after a space. */ + readonly body: string; +} + +/** The comments drawn in one gap between two tokens, in order. */ +export type P18Gap = readonly P18Comment[]; + +const NO_COMMENTS: P18Gap = Object.freeze([]); + +/** A value of 7's declarative form, with its spellings and comments. */ +export type P18Value = P18Scalar | P18List | P18Object; + +/** A string or a boolean literal. */ +export interface P18Scalar { + readonly kind: "scalar"; + readonly value: string | boolean; +} + +/** An array literal. */ +export interface P18List { + readonly kind: "list"; + readonly elements: readonly P18Element[]; + /** The gap between `[` and `]` where the list is empty. */ + readonly inner: P18Gap; +} + +/** One element of an array literal, with the gaps on either side of it. */ +export interface P18Element { + readonly before: P18Gap; + readonly value: P18Value; + /** Between the value and the comma, or `]` after the last. */ + readonly after: P18Gap; +} + +/** An object literal, its members in spelling order. */ +export interface P18Object { + readonly kind: "object"; + readonly members: readonly P18Member[]; + /** The gap between `{` and `}` where the object is empty. */ + readonly inner: P18Gap; +} + +/** One key and value of an object literal, with the gaps around them. */ +export interface P18Member { + readonly key: string; + /** Spelled as a string literal; as an identifier otherwise. */ + readonly stringLiteral: boolean; + /** Before the key: after `{`, or after the previous member's comma. */ + readonly before: P18Gap; + /** Between the key and the colon. */ + readonly afterKey: P18Gap; + /** Between the colon and the value. */ + readonly afterColon: P18Gap; + readonly value: P18Value; + /** Between the value and the comma, or `}` after the last. */ + readonly after: P18Gap; +} + +/** + * The gaps of the file outside its argument, in token order: before + * `import`, inside the import declaration (`nameAs` and `asBinding` only + * where the import is aliased), between the declaration and the export, + * inside the export around the argument, and after the closing `)`. + */ +export const P18_STATEMENT_GAPS = [ + "head", + "importBrace", + "braceName", + "nameAs", + "asBinding", + "bindingBrace", + "braceFrom", + "fromSpecifier", + "between", + "exportDefault", + "defaultBinding", + "bindingParen", + "parenArgument", + "argumentParen", + "tail", +] as const; + +export type P18StatementGap = (typeof P18_STATEMENT_GAPS)[number]; + +/** The gaps inside the import declaration (module header). */ +export const P18_IMPORT_GAPS: readonly P18StatementGap[] = [ + "importBrace", + "braceName", + "nameAs", + "asBinding", + "bindingBrace", + "braceFrom", + "fromSpecifier", +]; + +/** A covered file: the import, then the default export of one call. */ +export interface P18File { + /** Whether the import spells `defineConfig as <binding>`. */ + readonly alias: boolean; + /** The name `defineConfig` is bound to: itself where not aliased. */ + readonly binding: string; + readonly gaps: Readonly<Record<P18StatementGap, P18Gap>>; + readonly argument: P18Object; +} + +/** The drawn violation, and the mutant's argument it makes. */ +export interface P18Mutation { + /** The member of the class and where it lies, as `classViolations` reads it. */ + readonly violation: ClassViolation; + /** How a diagnosis names the edit. */ + readonly label: string; + /** The mutant's argument: the draw's with the one edit. */ + readonly argument: P18Object; +} + +/** One trial (module header). */ +export interface P18Draw { + /** The valid configuration, a covered file. */ + readonly file: P18File; + readonly mutation: P18Mutation; + /** The covered setup, by its index in `COVERED_SETUPS`. */ + readonly setup: number; +} + +/** A scalar. */ +function scalar(value: string | boolean): P18Scalar { + return { kind: "scalar", value }; +} + +/** A value of 7's form, as the harness's readings of 7 take it. */ +export function toConfigValue(value: P18Value): ConfigValue { + if (value.kind === "scalar") return value.value; + if (value.kind === "list") { + return value.elements.map((element) => toConfigValue(element.value)); + } + return configObject( + ...value.members.map( + (member) => [member.key, toConfigValue(member.value)] as const, + ), + ); +} + +/** An argument as the harness's readings of 7 take it. */ +export function p18Config(argument: P18Object): ConfigObject { + const config = toConfigValue(argument); + if (!isConfigObject(config)) { + throw new Error("unreachable: an object reads as an object"); + } + return config; +} + +/** + * A plain value of 7's form as a spelled one (a mutation's replacement): + * no comments, each key an identifier where it is an identifier name. + */ +function fromConfigValue(value: ConfigValue): P18Value { + if (typeof value === "string" || typeof value === "boolean") { + return scalar(value); + } + if (isConfigList(value)) { + return { + kind: "list", + elements: value.map((element) => ({ + before: NO_COMMENTS, + value: fromConfigValue(element), + after: NO_COMMENTS, + })), + inner: NO_COMMENTS, + }; + } + return { + kind: "object", + members: [...value].map(([key, member]) => plainMember(key, member)), + inner: NO_COMMENTS, + }; +} + +/** A member with no comments, its key an identifier where it can be. */ +function plainMember(key: string, value: ConfigValue): P18Member { + return { + key, + stringLiteral: !isIdentifierName(key), + before: NO_COMMENTS, + afterKey: NO_COMMENTS, + afterColon: NO_COMMENTS, + value: fromConfigValue(value), + after: NO_COMMENTS, + }; +} + +// --------------------------------------------------------------------------- +// Rendering (module header) +// --------------------------------------------------------------------------- + +/** What separates a piece from the one before it. */ +type Separator = "none" | "space" | "line" | "blank"; + +/** One token or comment of a rendered file. */ +interface Piece { + readonly text: string; + readonly before: Separator; + readonly depth: number; + /** A comment (module header): its kind. */ + readonly comment?: "line" | "block"; +} + +/** A comment as rendered. */ +function commentText(comment: P18Comment): string { + return comment.kind === "line" + ? `// ${comment.body}` + : `/* ${comment.body} */`; +} + +/** The pieces of a file, joined into its text. */ +class Pieces { + readonly #pieces: Piece[] = []; + #forced: Separator | undefined; + + token(text: string, before: Separator, depth: number): void { + this.#pieces.push({ text, before: this.#forced ?? before, depth }); + this.#forced = undefined; + } + + gap(gap: P18Gap, depth: number): void { + for (const comment of gap) { + this.#pieces.push({ + text: commentText(comment), + before: this.#forced ?? "space", + depth, + comment: comment.kind, + }); + this.#forced = undefined; + } + } + + /** The next piece starts on a line of its own. */ + breakNext(separator: "line" | "blank"): void { + this.#forced = separator; + } + + /** Every comment rendered, in order. */ + comments(): readonly string[] { + return this.#pieces + .filter((piece) => piece.comment !== undefined) + .map((piece) => piece.text); + } + + /** + * The text: each piece after its separator, a line comment always ending + * its line; LF line ends, the last line terminated. + */ + text(): string { + let text = ""; + let breakDue = false; + this.#pieces.forEach((piece, index) => { + let separator = ""; + if (index > 0) { + if (piece.before === "blank") separator = LF + LF; + else if (breakDue || piece.before === "line") { + separator = LF + INDENT.repeat(piece.depth); + } else if (piece.before === "space") separator = " "; + } + text += separator + piece.text; + breakDue = piece.comment === "line"; + }); + return text + LF; + } +} + +/** A string literal spelling `value` exactly, in double quotes. */ +function spellString(value: string): string { + const forbidden = forbiddenIn(value); + if (forbidden !== undefined) { + throw new Error( + `P-18: the string ${JSON.stringify(value)} holds ` + + `${JSON.stringify(forbidden)}, which no string of a draw holds ` + + "(P18_FORBIDDEN_IN_STRINGS): a harness defect", + ); + } + return `"${value}"`; +} + +/** A member's key as spelled. */ +function spellKey(member: P18Member): string { + if (member.stringLiteral) return spellString(member.key); + if (!isIdentifierName(member.key)) { + throw new Error( + `P-18: the key ${JSON.stringify(member.key)} is spelled as an ` + + "identifier, which TypeScript does not read it as: a harness defect", + ); + } + return member.key; +} + +/** Push a value: a scalar's token, or a list's or an object's pieces. */ +function pushValue( + pieces: Pieces, + value: P18Value, + depth: number, + before: Separator, +): void { + if (value.kind === "scalar") { + pieces.token( + typeof value.value === "string" + ? spellString(value.value) + : String(value.value), + before, + depth, + ); + } else if (value.kind === "list") pushList(pieces, value, depth, before); + else pushObject(pieces, value, depth, before); +} + +/** Push a list: scalars on its own line, anything else a line each. */ +function pushList( + pieces: Pieces, + list: P18List, + depth: number, + before: Separator, +): void { + pieces.token("[", before, depth); + if (list.elements.length === 0) { + pieces.gap(list.inner, depth + 1); + pieces.token("]", list.inner.length > 0 ? "space" : "none", depth); + return; + } + const multiline = list.elements.some( + (element) => element.value.kind !== "scalar", + ); + list.elements.forEach((element, index) => { + if (multiline) pieces.breakNext("line"); + pieces.gap(element.before, depth + 1); + pushValue( + pieces, + element.value, + depth + 1, + index === 0 && !multiline ? "none" : "space", + ); + pieces.gap(element.after, depth + 1); + if (index < list.elements.length - 1) pieces.token(",", "none", depth + 1); + }); + if (multiline) pieces.breakNext("line"); + pieces.token("]", "none", depth); +} + +/** Push an object: each member on a line of its own. */ +function pushObject( + pieces: Pieces, + object: P18Object, + depth: number, + before: Separator, +): void { + pieces.token("{", before, depth); + if (object.members.length === 0) { + pieces.gap(object.inner, depth + 1); + pieces.token("}", object.inner.length > 0 ? "space" : "none", depth); + return; + } + object.members.forEach((member, index) => { + pieces.breakNext("line"); + pieces.gap(member.before, depth + 1); + pieces.token(spellKey(member), "space", depth + 1); + pieces.gap(member.afterKey, depth + 1); + pieces.token(":", "none", depth + 1); + pieces.gap(member.afterColon, depth + 1); + pushValue(pieces, member.value, depth + 1, "space"); + pieces.gap(member.after, depth + 1); + if (index < object.members.length - 1) { + pieces.token(",", "none", depth + 1); + } + }); + pieces.breakNext("line"); + pieces.token("}", "none", depth); +} + +/** A rendered file, with every comment it renders, in order. */ +export interface P18Rendering { + readonly text: string; + readonly comments: readonly string[]; +} + +/** + * `file` rendered with `argument` as its argument, importing from + * `specifier` (module header): the import declaration, a blank line, the + * default export; every gap's comments where the file draws them. + */ +export function renderP18File( + file: P18File, + argument: P18Object, + specifier: string, +): P18Rendering { + const pieces = new Pieces(); + const gaps = file.gaps; + pieces.gap(gaps.head, 0); + pieces.breakNext("line"); + pieces.token("import", "line", 0); + pieces.gap(gaps.importBrace, 0); + pieces.token("{", "space", 0); + pieces.gap(gaps.braceName, 0); + pieces.token("defineConfig", "space", 0); + if (file.alias) { + pieces.gap(gaps.nameAs, 0); + pieces.token("as", "space", 0); + pieces.gap(gaps.asBinding, 0); + pieces.token(file.binding, "space", 0); + } else if (gaps.nameAs.length > 0 || gaps.asBinding.length > 0) { + throw new Error( + "P-18: an unaliased import draws comments around an alias it does " + + "not spell: a harness defect", + ); + } + pieces.gap(gaps.bindingBrace, 0); + pieces.token("}", "space", 0); + pieces.gap(gaps.braceFrom, 0); + pieces.token("from", "space", 0); + pieces.gap(gaps.fromSpecifier, 0); + pieces.token(spellString(specifier), "space", 0); + pieces.gap(gaps.between, 0); + pieces.breakNext("blank"); + pieces.token("export", "blank", 0); + pieces.gap(gaps.exportDefault, 0); + pieces.token("default", "space", 0); + pieces.gap(gaps.defaultBinding, 0); + pieces.token(file.binding, "space", 0); + pieces.gap(gaps.bindingParen, 0); + pieces.token("(", "none", 0); + pieces.gap(gaps.parenArgument, 0); + pushObject(pieces, argument, 0, "none"); + pieces.gap(gaps.argumentParen, 0); + pieces.token(")", "none", 0); + pieces.gap(gaps.tail, 0); + return { text: pieces.text(), comments: pieces.comments() }; +} + +// --------------------------------------------------------------------------- +// The generator's pools (module header) +// --------------------------------------------------------------------------- + +/** A character from its code point. */ +function cp(codePoint: number): string { + return String.fromCodePoint(codePoint); +} + +/** + * Identifier spellings of names (module header): ASCII identifiers, reserved + * words (identifier names all the same, as keys), and non-ASCII letters + * Unicode has held since its first versions. + */ +export const P18_IDENTIFIER_NAMES: readonly string[] = [ + "app", + "tests", + "product", + "docs", + "a", + "B", + "_x", + "$y", + "a1", + "ab_$9", + "default", + "class", + "new", + "import", + "await", + "yield", + `caf${cp(0xe9)}`, + cp(0x3c0), + `${cp(0x4e2d)}${cp(0x6587)}`, + `${cp(0x416)}x`, +]; + +/** + * A non-identifier name's first character (module header): none an + * identifier's start — ASCII punctuation and the space, digits, non-ASCII + * characters (U+00A0, U+00B7, the astral U+1F600, U+FEFF, U+200B, U+0085), + * and control characters (U+0001, U+0009, U+001F, U+007F, U+0000). + */ +export const P18_NON_IDENTIFIER_LEADS: readonly string[] = [ + ..." -./*@#!?+,;:=<>()[]{}|~^%&`", + ..."0123456789", + cp(0xa0), + cp(0xb7), + cp(0x1f600), + cp(0xfeff), + cp(0x200b), + cp(0x85), + cp(0x01), + cp(0x09), + cp(0x1f), + cp(0x7f), + cp(0x00), +]; + +/** A non-identifier name's later characters, by class. */ +const NON_IDENTIFIER_RUN: ReadonlyArray<readonly [number, readonly string[]]> = + [ + [4, [..."abcxyzABZ"]], + [2, [..."0123456789"]], + [3, P18_NON_IDENTIFIER_LEADS], + [1, ["_", "$", cp(0xe9), cp(0x3c0)]], + ]; + +/** Spec globs' parts (module header): directories, then a file pattern. */ +export const P18_SPEC_GLOB_PARTS = { + directories: ["specs", "docs", "a", "**", "*", "x?", ".hidden", "s-1"], + files: ["*.mdx", "a.mdx", "?.mdx", "*-x.mdx", "index.mdx"], +} as const; + +/** Code globs' parts (module header). */ +export const P18_CODE_GLOB_PARTS = { + directories: ["src", "test", "lib", "**", "*", "y?", ".gen", "c_2"], + files: ["*.ts", "*.tsx", "index.ts", "?.ts", "*.test.ts"], +} as const; + +/** One pool of glob parts. */ +interface GlobParts { + readonly directories: readonly string[]; + readonly files: readonly string[]; +} + +/** `markdown.outDir` values (module header): each of 7.3's form. */ +export const P18_OUT_DIRS: readonly string[] = [ + "docs", + "out/md", + "build", + "a/b/c", + ".site", + "md-out", + "_x", +]; + +/** Tags (module header), for `targetTags` and a selector's `tags`. */ +export const P18_TAGS: readonly string[] = [ + "core", + "edge", + "a", + "b.c", + "x-1", + "ui_2", + "T", +]; + +/** + * An unknown key's names (module header): near misses of 7's keys, keys of + * other objects of 7's, and the `Object` members and `__proto__`; each + * object draws among those that are none of its own fields. + */ +export const P18_UNKNOWN_KEYS: readonly string[] = [ + "extra", + "Specs", + "spec", + "groups", + "name", + "kind", + "group", + "type", + "emits", + "outdir", + "boundarykind", + "edgeKind", + "files", + "tags", + "from", + "to", + "mode", + "markdown", + "version", + "$schema", + "target-tags", + "edge kinds", + ...OBJECT_MEMBER_NAMES, +]; + +/** + * Aliases `defineConfig` may be bound to (module header): names strict + * module code admits as a binding — contextual keywords, global names, + * `__`-prefixed names, non-ASCII ones, `defineConfig` itself — none of + * `BARRED_BINDINGS` (`require`, `exports`, and SPEC 6.5's first rule). + */ +export const P18_ALIAS_NAMES: readonly string[] = [ + "configure", + "d", + "_", + "$", + "defineConfig", + "define", + "undefined", + "string", + "async", + "type", + "as", + "from", + "of", + "get", + "set", + "declare", + "module", + "namespace", + "global", + "Object", + "Promise", + "globalThis", + "React", + "escape", + "Iterator", + "__proto__", + "constructor", + "toString", + "__esModule", + "__awaiter", + cp(0x3c0), + `d${cp(0xe9)}finir`, + "x9", +]; + +/** + * Comment bodies' characters (module header): no `@`, so no directive or + * pragma; no `/` or `*`, so no `///` line and no early close; no backslash + * and no line terminator. + */ +export const P18_COMMENT_ALPHABET: readonly string[] = [ + ..."abcdefghijklmnopqrstuvwxyzABCXYZ0123456789", + " ", + " ", + " ", + ..."-.,;:!?()[]{}<>=+#$%&~^|`", + "'", + '"', + cp(0xe9), + cp(0x3c0), + cp(0x4e2d), +]; + +/** Strings a mutation's free values hold (module header). */ +const LOOSE_STRINGS: readonly string[] = [ + "", + "x", + "true", + "specs/**/*.mdx", + "src/*.ts", + "direct", + "app", + "a b", +]; + +/** Keys a mutation's free objects hold. */ +const LOOSE_KEYS: readonly string[] = [ + "name", + "group", + "x", + "emit", + "glob", + "kind", +]; + +/** Every value 7 enumerates, at any position. */ +const ENUMERATED_VALUES: readonly string[] = [ + ...TARGETS, + ...GROUP_KINDS, + ...MODES, + ...RULE_TYPES, + ...EDGE_KINDS, +]; + +/** + * T7.6-3's selector-form violations (module header), each by the keys it + * carries: each two of `group`, `files`, and `tags`, all three, none, and + * `kind` without `group` beside `files`, beside `tags`, and alone. + */ +const SELECTOR_FORM_VIOLATIONS: ReadonlyArray< + readonly [form: string, keys: readonly string[]] +> = [ + ["group and files", ["group", "files"]], + ["group and tags", ["group", "tags"]], + ["files and tags", ["files", "tags"]], + ["group, files, and tags", ["group", "files", "tags"]], + ["none of group, files, and tags", []], + ["kind beside files", ["files", "kind"]], + ["kind beside tags", ["tags", "kind"]], + ["kind alone", ["kind"]], +]; + +// --------------------------------------------------------------------------- +// The generator (module header): simplest outcomes first, for shrinking +// --------------------------------------------------------------------------- + +/** The draws one trial makes, and its comment density. */ +interface Drawing { + readonly choices: Choices; + /** How likely a gap holds comments: 0 draws none at all. */ + readonly density: number; +} + +/** A comment: its kind, then its body. */ +function genComment(choices: Choices): P18Comment { + const kind = choices.boolean(0.5) ? "line" : "block"; + const length = choices.intInclusive(0, 12); + let body = ""; + for (let index = 0; index < length; index += 1) { + body += choices.pick(P18_COMMENT_ALPHABET); + } + return { kind, body }; +} + +/** A gap's comments: none, one, or two. */ +function genGap(drawing: Drawing): P18Gap { + const { choices, density } = drawing; + if (density === 0 || !choices.boolean(density)) return NO_COMMENTS; + const comments = [genComment(choices)]; + if (choices.boolean(0.3)) comments.push(genComment(choices)); + return comments; +} + +/** `items` in a drawn order, the given order the simplest. */ +function genOrder<T>(choices: Choices, items: readonly T[]): T[] { + const remaining = [...items]; + const ordered: T[] = []; + while (remaining.length > 0) { + const index = + remaining.length === 1 + ? 0 + : choices.intInclusive(0, remaining.length - 1); + ordered.push(remaining.splice(index, 1)[0]!); + } + return ordered; +} + +/** A list of `values`, each element with its gaps. */ +function genListOf(drawing: Drawing, values: readonly P18Value[]): P18List { + const elements = values.map((value) => ({ + before: genGap(drawing), + value, + after: genGap(drawing), + })); + return { + kind: "list", + elements, + inner: elements.length === 0 ? genGap(drawing) : NO_COMMENTS, + }; +} + +/** A list of strings. */ +function genStringList(drawing: Drawing, values: readonly string[]): P18List { + return genListOf(drawing, values.map(scalar)); +} + +/** A member: its key's spelling, then its gaps. */ +function genMember(drawing: Drawing, key: string, value: P18Value): P18Member { + const stringLiteral = isIdentifierName(key) + ? drawing.choices.boolean(0.4) + : true; + return { + key, + stringLiteral, + before: genGap(drawing), + afterKey: genGap(drawing), + afterColon: genGap(drawing), + value, + after: genGap(drawing), + }; +} + +/** An object of `entries`, in a drawn order unless `ordered` is false. */ +function genObjectOf( + drawing: Drawing, + entries: ReadonlyArray<readonly [string, P18Value]>, + ordered = true, +): P18Object { + const members = ( + ordered ? genOrder(drawing.choices, entries) : [...entries] + ).map(([key, value]) => genMember(drawing, key, value)); + return { + kind: "object", + members, + inner: members.length === 0 ? genGap(drawing) : NO_COMMENTS, + }; +} + +/** A non-identifier name: a lead no identifier begins with, then a run. */ +export function genNonIdentifierName(choices: Choices): string { + let name = choices.pick(P18_NON_IDENTIFIER_LEADS); + const length = choices.intInclusive(0, 7); + for (let index = 0; index < length; index += 1) { + name += choices.pick(choices.weightedPick(NON_IDENTIFIER_RUN)); + } + return name; +} + +/** + * A group, profile, or rule name (module header): an identifier spelling, + * an `Object` member or `__proto__` (weighted toward them), or a + * non-identifier spelling. + */ +export function genP18Name(choices: Choices): string { + return choices.weightedPick<(choices: Choices) => string>([ + [3, (c) => c.pick(P18_IDENTIFIER_NAMES)], + [4, (c) => c.pick(OBJECT_MEMBER_NAMES)], + [3, genNonIdentifierName], + ])(choices); +} + +/** A name none of `taken` holds: drawn, mended by a suffix if it is. */ +function genDistinctName(choices: Choices, taken: ReadonlySet<string>): string { + const drawn = genP18Name(choices); + if (!taken.has(drawn)) return drawn; + for (let suffix = 2; ; suffix += 1) { + const mended = `${drawn}-${String(suffix)}`; + if (!taken.has(mended)) return mended; + } +} + +/** `count` distinct names. */ +function genDistinctNames(choices: Choices, count: number): string[] { + const names: string[] = []; + const taken = new Set<string>(); + for (let index = 0; index < count; index += 1) { + const name = genDistinctName(choices, taken); + taken.add(name); + names.push(name); + } + return names; +} + +/** A glob: up to two directory parts, then a file pattern. */ +function genGlob(choices: Choices, parts: GlobParts): string { + const depth = choices.intInclusive(0, 2); + const segments: string[] = []; + for (let index = 0; index < depth; index += 1) { + segments.push(choices.pick(parts.directories)); + } + segments.push(choices.pick(parts.files)); + return segments.join("/"); +} + +/** A group's glob list: empty, or up to three globs. */ +function genGlobList(choices: Choices, parts: GlobParts): string[] { + const length = choices.weightedPick([ + [2, 0], + [4, 1], + [2, 2], + [1, 3], + ]); + return Array.from({ length }, () => genGlob(choices, parts)); +} + +/** + * A list 7.4 or 7.5 reads as a set (module header): one to three distinct + * members of `pool`, then, a third of the time, one or two of them + * repeated at drawn places. + */ +function genSetList(choices: Choices, pool: readonly string[]): string[] { + const remaining = [...pool]; + const distinct: string[] = []; + const size = choices.intInclusive(1, Math.min(3, pool.length)); + for (let index = 0; index < size; index += 1) { + distinct.push( + remaining.splice(choices.intInclusive(0, remaining.length - 1), 1)[0]!, + ); + } + const values = [...distinct]; + if (choices.boolean(0.35)) { + const repeats = choices.intInclusive(1, 2); + for (let index = 0; index < repeats; index += 1) { + values.splice( + choices.intInclusive(0, values.length), + 0, + choices.pick(distinct), + ); + } + } + return values; +} + +/** The configured groups' names, by kind. */ +interface GroupNames { + readonly spec: readonly string[]; + readonly code: readonly string[]; +} + +/** Every configured group's name, each once. */ +function allGroupNames(groups: GroupNames): readonly string[] { + return [...new Set([...groups.spec, ...groups.code])]; +} + +/** The kinds of the groups named `name`. */ +function groupKinds(groups: GroupNames, name: string): readonly string[] { + return GROUP_KINDS.filter((kind) => + (kind === "spec" ? groups.spec : groups.code).includes(name), + ); +} + +/** + * A reference to one of `among` (module header): its name, and its kind — + * given where the name is both kinds', drawn present or absent elsewhere. + */ +function genGroupReference( + choices: Choices, + groups: GroupNames, + among: readonly string[], +): { readonly name: string; readonly kind: string | undefined } { + const name = choices.pick(among); + const kinds = groupKinds(groups, name); + if (kinds.length > 1) return { name, kind: choices.pick(kinds) }; + return { name, kind: choices.boolean(0.3) ? kinds[0] : undefined }; +} + +/** The code groups' names, a third or so shared with the spec groups. */ +function genCodeNames( + choices: Choices, + count: number, + specNames: readonly string[], +): string[] { + const names: string[] = []; + const taken = new Set<string>(); + for (let index = 0; index < count; index += 1) { + const shareable = specNames.filter((name) => !taken.has(name)); + const name = + shareable.length > 0 && choices.boolean(0.35) + ? choices.pick(shareable) + : genDistinctName(choices, taken); + taken.add(name); + names.push(name); + } + return names; +} + +/** `markdown`: `emit`, and `outDir` present or absent. */ +function genMarkdown(drawing: Drawing): P18Object { + const { choices } = drawing; + const entries: [string, P18Value][] = [["emit", scalar(choices.boolean())]]; + if (choices.boolean(0.5)) { + entries.push(["outDir", scalar(choices.pick(P18_OUT_DIRS))]); + } + return genObjectOf(drawing, entries); +} + +/** A profile named `name`, each optional field present or absent. */ +function genProfile( + drawing: Drawing, + groups: GroupNames, + name: string, +): P18Object { + const { choices } = drawing; + const entries: [string, P18Value][] = [ + ["name", scalar(name)], + ["target", scalar(choices.pick(groups.spec))], + ]; + if (choices.boolean(0.5)) { + entries.push([ + "targetTags", + genStringList(drawing, genSetList(choices, P18_TAGS)), + ]); + } + if (choices.boolean(0.5)) { + entries.push(["targets", scalar(choices.pick(TARGETS))]); + } + const boundary = genGroupReference(choices, groups, allGroupNames(groups)); + entries.push(["boundary", scalar(boundary.name)]); + if (boundary.kind !== undefined) { + entries.push(["boundaryKind", scalar(boundary.kind)]); + } + entries.push(["mode", scalar(choices.pick(MODES))]); + if (choices.boolean(0.5)) { + entries.push([ + "edgeKinds", + genStringList(drawing, genSetList(choices, EDGE_KINDS)), + ]); + } + return genObjectOf(drawing, entries); +} + +/** A glob for a `files` selector: a spec or a code glob. */ +function genSelectorGlob(choices: Choices): string { + return genGlob( + choices, + choices.boolean(0.5) ? P18_CODE_GLOB_PARTS : P18_SPEC_GLOB_PARTS, + ); +} + +/** A selector in one of 7.5's forms, its names resolving. */ +function genSelector(drawing: Drawing, groups: GroupNames): P18Object { + const { choices } = drawing; + const names = allGroupNames(groups); + const form = choices.pick( + names.length > 0 ? ["group", "files", "tags"] : ["files", "tags"], + ); + const entries: [string, P18Value][] = []; + if (form === "group") { + const reference = genGroupReference(choices, groups, names); + entries.push(["group", scalar(reference.name)]); + if (reference.kind !== undefined) { + entries.push(["kind", scalar(reference.kind)]); + } + } else if (form === "files") { + entries.push(["files", scalar(genSelectorGlob(choices))]); + } else { + entries.push([ + "tags", + genStringList(drawing, genSetList(choices, P18_TAGS)), + ]); + } + return genObjectOf(drawing, entries); +} + +/** A rule named `name`, `kinds` present or absent. */ +function genRule( + drawing: Drawing, + groups: GroupNames, + name: string, +): P18Object { + const { choices } = drawing; + const entries: [string, P18Value][] = [ + ["name", scalar(name)], + ["type", scalar(choices.pick(RULE_TYPES))], + ["from", genSelector(drawing, groups)], + ["to", genSelector(drawing, groups)], + ]; + if (choices.boolean(0.5)) { + entries.push([ + "kinds", + genStringList(drawing, genSetList(choices, EDGE_KINDS)), + ]); + } + return genObjectOf(drawing, entries); +} + +/** + * The argument (module header): a configuration valid under 7 by + * construction, its top-level keys in a drawn order. + */ +function genP18Argument(drawing: Drawing): P18Object { + const { choices } = drawing; + const specNames = genDistinctNames( + choices, + choices.weightedPick([ + [1, 0], + [3, 1], + [3, 2], + [2, 3], + ]), + ); + const codePresent = choices.boolean(0.6); + const codeNames = codePresent + ? genCodeNames( + choices, + choices.weightedPick([ + [1, 0], + [3, 1], + [2, 2], + [1, 3], + ]), + specNames, + ) + : []; + const groups: GroupNames = { spec: specNames, code: codeNames }; + const groupMap = (names: readonly string[], parts: GlobParts): P18Object => + genObjectOf( + drawing, + names.map( + (name) => + [name, genStringList(drawing, genGlobList(choices, parts))] as const, + ), + false, + ); + const entries: [string, P18Value][] = [ + ["specs", groupMap(specNames, P18_SPEC_GLOB_PARTS)], + ]; + if (codePresent) + entries.push(["code", groupMap(codeNames, P18_CODE_GLOB_PARTS)]); + if (choices.boolean(0.4)) entries.push(["markdown", genMarkdown(drawing)]); + if (choices.boolean(0.5)) { + const profiles = + specNames.length === 0 + ? 0 + : choices.weightedPick([ + [1, 0], + [3, 1], + [2, 2], + ]); + entries.push([ + "coverage", + genListOf( + drawing, + genDistinctNames(choices, profiles).map((name) => + genProfile(drawing, groups, name), + ), + ), + ]); + } + if (choices.boolean(0.5)) { + const rules = choices.weightedPick([ + [1, 0], + [3, 1], + [2, 2], + [1, 3], + ]); + entries.push([ + "policy", + genListOf( + drawing, + genDistinctNames(choices, rules).map((name) => + genRule(drawing, groups, name), + ), + ), + ]); + } + return genObjectOf(drawing, entries); +} + +/** `defineConfig`'s binding: unaliased, or an alias (module header). */ +function genP18Binding(choices: Choices): { + readonly alias: boolean; + readonly binding: string; +} { + if (!choices.boolean(0.6)) return { alias: false, binding: "defineConfig" }; + return { alias: true, binding: choices.pick(P18_ALIAS_NAMES) }; +} + +/** The file around `argument`: its binding, then its statement gaps. */ +function genP18File(drawing: Drawing, argument: P18Object): P18File { + const { alias, binding } = genP18Binding(drawing.choices); + const gaps = {} as Record<P18StatementGap, P18Gap>; + for (const gap of P18_STATEMENT_GAPS) { + gaps[gap] = + !alias && (gap === "nameAs" || gap === "asBinding") + ? NO_COMMENTS + : genGap(drawing); + } + return { alias, binding, gaps, argument }; +} + +/** The indices in `COVERED_SETUPS` of the setups of one option-set kind. */ +function setupsOfKind(kind: OptionSetKind): readonly number[] { + return COVERED_SETUPS.flatMap((setup, index) => + setup.optionSet.kind === kind ? [index] : [], + ); +} + +/** + * The covered setups by option-set kind (module header): the strict + * defaults' 168, and the initialized-project set's 5, drawn a quarter of + * the time so that the fixed seeds reach it. + */ +export const P18_STRICT_DEFAULT_SETUPS = setupsOfKind("strict defaults"); +export const P18_INITIALIZED_PROJECT_SETUPS = setupsOfKind( + "initialized-project options", +); + +/** The drawn covered setup. */ +export function p18Setup(draw: P18Draw): CoveredSetup { + const setup = COVERED_SETUPS[draw.setup]; + if (setup === undefined) { + throw new Error( + `P-18: the draw names the covered setup ${String(draw.setup)}, which ` + + `7.6's matrix of ${String(COVERED_SETUPS.length)} does not hold: a ` + + "harness defect", + ); + } + return setup; +} + +// --------------------------------------------------------------------------- +// The mutation (module header) +// --------------------------------------------------------------------------- + +/** Where a value stands, as a label names it: `coverage[0].mode`. */ +export function describeP18Path(path: ConfigPath): string { + if (path.length === 0) return "the top level"; + let text = ""; + for (const segment of path) { + if (typeof segment === "number") text += `[${String(segment)}]`; + else if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(segment)) { + text += text === "" ? segment : `.${segment}`; + } else text += `[${JSON.stringify(segment)}]`; + } + return text; +} + +/** A kind with its article. */ +function aKind(kind: ConfigKind): string { + return kind === "object" ? "an object" : `a ${kind}`; +} + +/** + * A position a kind, an enumeration, or an empty-list violation may take + * (module header): a value of the draw, or an optional field it omits. + */ +type ValuePosition = + | { + readonly added: false; + readonly path: ConfigPath; + readonly shape: ShapeSchema; + readonly value: ConfigValue; + } + | { + readonly added: true; + /** The fixed-key object the field is added to. */ + readonly objectPath: ConfigPath; + readonly key: string; + readonly shape: ShapeSchema; + /** How many keys the object holds. */ + readonly size: number; + }; + +/** A value of the draw as a position. */ +function present(node: ShapeNode): ValuePosition { + return { + added: false, + path: node.path, + shape: node.shape, + value: node.value, + }; +} + +/** + * The optional fields the draw omits whose shape `keep` admits, in every + * fixed-key object but a selector, where adding a field changes its form. + */ +function addablePositions( + nodes: readonly ShapeNode[], + keep: (shape: ShapeSchema) => boolean, +): ValuePosition[] { + const positions: ValuePosition[] = []; + for (const node of nodes) { + const { shape, value } = node; + if ( + shape.fields === undefined || + shape.selector === true || + !isConfigObject(value) + ) { + continue; + } + for (const [key, field] of shape.fields) { + if ( + value.has(key) || + (shape.required ?? []).includes(key) || + !keep(field) + ) { + continue; + } + positions.push({ + added: true, + objectPath: node.path, + key, + shape: field, + size: value.size, + }); + } + } + return positions; +} + +/** An object of the spelled tree, or a harness defect. */ +function asP18Object(value: P18Value, path: ConfigPath): P18Object { + if (value.kind !== "object") { + throw new Error( + `P-18: ${describeP18Path(path)} is no object to edit: a harness defect`, + ); + } + return value; +} + +/** `value` with the value at `path` replaced by `edit`'s result. */ +function editP18At( + value: P18Value, + path: ConfigPath, + edit: (at: P18Value) => P18Value, + walked: ConfigPath = [], +): P18Value { + const [head, ...rest] = path; + if (head === undefined) return edit(value); + const here = [...walked, head]; + if (typeof head === "number") { + if (value.kind !== "list" || head >= value.elements.length) { + throw new Error( + `P-18: no list element at ${describeP18Path(here)} to edit: a ` + + "harness defect", + ); + } + return { + ...value, + elements: value.elements.map((element, index) => + index === head + ? { ...element, value: editP18At(element.value, rest, edit, here) } + : element, + ), + }; + } + const object = asP18Object(value, walked); + if (!object.members.some((member) => member.key === head)) { + throw new Error( + `P-18: no key at ${describeP18Path(here)} to edit: a harness defect`, + ); + } + return { + ...object, + members: object.members.map((member) => + member.key === head + ? { ...member, value: editP18At(member.value, rest, edit, here) } + : member, + ), + }; +} + +/** The argument with the value at `path` replaced by `value`. */ +function replaceValue( + argument: P18Object, + path: ConfigPath, + value: ConfigValue, +): P18Object { + return asP18Object( + editP18At(argument, path, () => fromConfigValue(value)), + [], + ); +} + +/** + * The argument with `member` inserted as key `index` of the object at + * `objectPath`: an empty object's comments move before it. + */ +function insertMember( + argument: P18Object, + objectPath: ConfigPath, + index: number, + member: P18Member, +): P18Object { + return asP18Object( + editP18At(argument, objectPath, (at) => { + const object = asP18Object(at, objectPath); + const members = [...object.members]; + members.splice( + index, + 0, + members.length === 0 ? { ...member, before: object.inner } : member, + ); + return { kind: "object", members, inner: NO_COMMENTS }; + }), + [], + ); +} + +/** The argument with `key` removed from the object at `objectPath`. */ +function removeMember( + argument: P18Object, + objectPath: ConfigPath, + key: string, +): P18Object { + return asP18Object( + editP18At(argument, objectPath, (at) => { + const object = asP18Object(at, objectPath); + return { + kind: "object", + members: object.members.filter((member) => member.key !== key), + inner: NO_COMMENTS, + }; + }), + [], + ); +} + +/** A free value of `kind` (module header): its contents unconstrained. */ +function genLooseOfKind( + choices: Choices, + kind: ConfigKind, + depth: number, +): ConfigValue { + switch (kind) { + case "boolean": + return choices.boolean(); + case "string": + return choices.boolean(0.7) + ? choices.pick(LOOSE_STRINGS) + : genP18Name(choices); + case "list": { + const length = choices.intInclusive(0, depth > 0 ? 1 : 2); + return Array.from({ length }, () => genLooseValue(choices, depth + 1)); + } + case "object": { + const remaining = [...LOOSE_KEYS]; + const size = choices.intInclusive(0, depth > 0 ? 1 : 2); + const entries: [string, ConfigValue][] = []; + for (let index = 0; index < size; index += 1) { + const key = remaining.splice( + choices.intInclusive(0, remaining.length - 1), + 1, + )[0]!; + entries.push([key, genLooseValue(choices, depth + 1)]); + } + return configObject(...entries); + } + } +} + +/** A free value of any kind, scalars alone two levels down. */ +function genLooseValue(choices: Choices, depth: number): ConfigValue { + return genLooseOfKind( + choices, + choices.pick(depth > 1 ? (["boolean", "string"] as const) : CONFIG_KINDS), + depth, + ); +} + +/** + * A value of a kind 7 does not admit where `shape` stands (module header): + * the kind drawn, then T7.6-3's kind-table value of it there, or a drawn + * one. + */ +function genWrongKindValue(choices: Choices, shape: ShapeSchema): ConfigValue { + const kind = choices.pick( + CONFIG_KINDS.filter((other) => other !== shape.kind), + ); + const tabled = (T763_KIND_TABLE.get(shape.position) ?? []).filter( + (value) => kindOf(value) === kind, + ); + if (tabled.length > 0 && choices.boolean(0.5)) return choices.pick(tabled); + return genLooseOfKind(choices, kind, 0); +} + +/** + * A string outside `values` (module header): near misses of the current + * value, variants of each enumerated one, `"contains"` for an edge kind, + * every other enumeration's members, and the empty string. + */ +function genOutsideEnumeration( + choices: Choices, + values: readonly string[], + current: string | undefined, +): string { + const candidates = [ + ...new Set([ + ...(current === undefined ? [] : nearMisses(current)), + ...values.flatMap((value) => [ + value.toUpperCase(), + `${value}s`, + ` ${value}`, + `${value} `, + ]), + ...(values.includes("depends") ? [CONTAINS] : []), + ...ENUMERATED_VALUES, + "", + "none", + ]), + ].filter((candidate) => !values.includes(candidate)); + return choices.pick(candidates); +} + +/** The configured groups' names, read from the data. */ +function groupNamesOf(config: ConfigObject): GroupNames { + const names = (key: string): string[] => { + const value = config.get(key); + return value !== undefined && isConfigObject(value) + ? [...value.keys()] + : []; + }; + return { spec: names("specs"), code: names("code") }; +} + +/** Where a path stands, in words. */ +function where(path: ConfigPath): string { + return describeP18Path(path); +} + +/** An unknown key in the object `node` holds (module header). */ +function unknownKeyMutation( + choices: Choices, + argument: P18Object, + node: ShapeNode, +): P18Mutation { + const object = node.value; + const fields = node.shape.fields; + if (!isConfigObject(object) || fields === undefined) { + throw new Error("unreachable: an unknown key's object is a fixed-key one"); + } + const key = choices.pick( + P18_UNKNOWN_KEYS.filter((name) => !fields.has(name) && !object.has(name)), + ); + const value = genLooseValue(choices, 0); + const stringLiteral = isIdentifierName(key) ? choices.boolean(0.5) : true; + const index = choices.intInclusive(0, object.size); + return { + violation: { category: "unknown key", path: [...node.path, key] }, + label: + `the unknown key ${JSON.stringify(key)} — spelled as ` + + `${stringLiteral ? "a string literal" : "an identifier"}, valued ` + + `${describeValue(value)} — as key ${String(index + 1)} of ` + + where(node.path), + argument: insertMember(argument, node.path, index, { + ...plainMember(key, value), + stringLiteral, + }), + }; +} + +/** A value of a kind 7 does not admit, replacing or added (module header). */ +function kindMutation( + choices: Choices, + argument: P18Object, + position: ValuePosition, +): P18Mutation { + const value = genWrongKindValue(choices, position.shape); + const offending = + `${aKind(kindOf(value))} where 7 admits ${aKind(position.shape.kind)} ` + + `(${position.shape.position}): ${describeValue(value)}`; + if (!position.added) { + return { + violation: { category: "kind", path: position.path }, + label: `${offending}, at ${where(position.path)}`, + argument: replaceValue(argument, position.path, value), + }; + } + const index = choices.intInclusive(0, position.size); + return { + violation: { + category: "kind", + path: [...position.objectPath, position.key], + }, + label: + `${offending}, as the optional field ${position.key} the draw omits, ` + + `added as key ${String(index + 1)} of ${where(position.objectPath)}`, + argument: insertMember( + argument, + position.objectPath, + index, + plainMember(position.key, value), + ), + }; +} + +/** A string outside an enumeration, replacing or added (module header). */ +function enumerationMutation( + choices: Choices, + argument: P18Object, + position: ValuePosition, +): P18Mutation { + if (!position.added) { + const values = position.shape.values; + if (values === undefined || typeof position.value !== "string") { + throw new Error("unreachable: an enumerated position holds a string"); + } + const value = genOutsideEnumeration(choices, values, position.value); + return { + violation: { category: "enumeration", path: position.path }, + label: + `the string ${JSON.stringify(value)}, outside ${values.join(", ")}, ` + + `replacing ${JSON.stringify(position.value)} at ${where(position.path)}`, + argument: replaceValue(argument, position.path, value), + }; + } + const index = choices.intInclusive(0, position.size); + const field = [...position.objectPath, position.key]; + const values = position.shape.values ?? position.shape.elements?.values; + if (values === undefined) { + throw new Error("unreachable: an added enumerated field enumerates"); + } + const outside = genOutsideEnumeration(choices, values, undefined); + const inList = position.shape.values === undefined; + const value: ConfigValue = inList ? [outside] : outside; + return { + violation: { + category: "enumeration", + path: inList ? [...field, 0] : field, + }, + label: + `the string ${JSON.stringify(outside)}, outside ${values.join(", ")}, ` + + `${inList ? "the one element of " : ""}the optional field ` + + `${position.key} the draw omits, added as key ${String(index + 1)} of ` + + where(position.objectPath), + argument: insertMember( + argument, + position.objectPath, + index, + plainMember(position.key, value), + ), + }; +} + +/** A selector in one of T7.6-3's form violations (module header). */ +function selectorFormMutation( + choices: Choices, + argument: P18Object, + node: ShapeNode, + groups: GroupNames, +): P18Mutation { + const names = allGroupNames(groups); + const [form, keys] = choices.pick( + SELECTOR_FORM_VIOLATIONS.filter( + ([, carried]) => names.length > 0 || !carried.includes("group"), + ), + ); + const entries: [string, ConfigValue][] = []; + for (const key of keys) { + if (key === "group") { + const reference = genGroupReference(choices, groups, names); + entries.push(["group", reference.name]); + if (reference.kind !== undefined) entries.push(["kind", reference.kind]); + } else if (key === "files") { + entries.push(["files", genSelectorGlob(choices)]); + } else if (key === "tags") { + entries.push(["tags", genSetList(choices, P18_TAGS)]); + } else { + entries.push(["kind", choices.pick(GROUP_KINDS)]); + } + } + const selector = configObject(...genOrder(choices, entries)); + return { + violation: { category: "selector form", path: node.path }, + label: + `the selector form ${form}, ${describeValue(selector)}, at ` + + where(node.path), + argument: replaceValue(argument, node.path, selector), + }; +} + +/** An empty set-read list, replacing or added (module header). */ +function emptyListMutation( + choices: Choices, + argument: P18Object, + position: ValuePosition, +): P18Mutation { + if (!position.added) { + return { + violation: { category: "empty list", path: position.path }, + label: `an empty list at ${where(position.path)}`, + argument: replaceValue(argument, position.path, []), + }; + } + const index = choices.intInclusive(0, position.size); + return { + violation: { + category: "empty list", + path: [...position.objectPath, position.key], + }, + label: + `an empty list as the optional field ${position.key} the draw omits, ` + + `added as key ${String(index + 1)} of ${where(position.objectPath)}`, + argument: insertMember( + argument, + position.objectPath, + index, + plainMember(position.key, []), + ), + }; +} + +/** + * One violation of 7.6's type-error class (module header): its member + * drawn among those the draw has a position for, then its position, then + * its offending value. + */ +function genP18Mutation(choices: Choices, argument: P18Object): P18Mutation { + const config = p18Config(argument); + const nodes = shapeNodes(config); + const objects = nodes.filter( + (node) => node.shape.fields !== undefined && isConfigObject(node.value), + ); + const required = objects.flatMap((node) => { + const object = node.value; + return (node.shape.required ?? []) + .filter((key) => isConfigObject(object) && object.has(key)) + .map((key) => ({ node, key })); + }); + const kinds = [ + ...nodes.filter((node) => node.path.length > 0).map(present), + ...addablePositions(nodes, () => true), + ]; + const enumerations = [ + ...nodes + .filter( + (node) => + node.shape.values !== undefined && typeof node.value === "string", + ) + .map(present), + ...addablePositions( + nodes, + (shape) => + shape.values !== undefined || shape.elements?.values !== undefined, + ), + ]; + const selectors = nodes.filter((node) => node.shape.selector === true); + const empties = [ + ...nodes.filter((node) => node.shape.nonEmpty === true).map(present), + ...addablePositions(nodes, (shape) => shape.nonEmpty === true), + ]; + const members = ( + [ + ["unknown key", objects.length], + ["missing required key", required.length], + ["kind", kinds.length], + ["enumeration", enumerations.length], + ["selector form", selectors.length], + ["empty list", empties.length], + ] as const + ) + .filter(([, positions]) => positions > 0) + .map(([category]): ViolationCategory => category); + const category = choices.pick(members); + switch (category) { + case "unknown key": + return unknownKeyMutation(choices, argument, choices.pick(objects)); + case "missing required key": { + const { node, key } = choices.pick(required); + return { + violation: { category, path: [...node.path, key] }, + label: `the required key ${key} removed from ${where(node.path)}`, + argument: removeMember(argument, node.path, key), + }; + } + case "kind": + return kindMutation(choices, argument, choices.pick(kinds)); + case "enumeration": + return enumerationMutation(choices, argument, choices.pick(enumerations)); + case "selector form": + return selectorFormMutation( + choices, + argument, + choices.pick(selectors), + groupNamesOf(config), + ); + case "empty list": + return emptyListMutation(choices, argument, choices.pick(empties)); + } +} + +/** TEST-SPEC P-18's premise for each draw, which a deviation breaks. */ +const P18_PREMISE = + "each draw is valid under 7 and a covered file, and its mutant is the " + + "draw with exactly the one violation of 7.6's type-error class drawn " + + "(TEST-SPEC P-18; SPEC 7, 7.6 Covered files, Type contract)"; + +/** How a check compares violations: member and path. */ +function violationKey(violation: ClassViolation): string { + return `${violation.category} at ${JSON.stringify(violation.path)}`; +} + +/** A violation, in words. */ +function describeViolation(violation: ClassViolation): string { + return `${violation.category} at ${where(violation.path)}`; +} + +/** + * Hold a draw to its premise (module header): valid under 7 by the + * harness's own reading, no violation of the class in the draw, and + * exactly the drawn one in its mutant; a deviation is a harness defect. + */ +function checkP18Draw(file: P18File, mutation: P18Mutation): void { + const config = p18Config(file.argument); + const problems = [ + ...problemsUnder7(config), + ...classViolations(config).map(describeViolation), + ]; + if (problems.length > 0) { + throw new Error( + `P-18: a draw is not valid as drawn (${problems.join("; ")}) — ` + + `${P18_PREMISE}: a harness defect`, + ); + } + const found = classViolations(p18Config(mutation.argument)); + if ( + found.length !== 1 || + violationKey(found[0]!) !== violationKey(mutation.violation) + ) { + throw new Error( + `P-18: the mutant (${mutation.label}) holds ` + + `${found.length === 0 ? "no violation" : found.map(describeViolation).join(", ")} ` + + "by the harness's reading of 7.6's type-error class, not exactly " + + `the one drawn, ${describeViolation(mutation.violation)} — ` + + `${P18_PREMISE}: a harness defect`, + ); + } +} + +/** The generator (module header): simplest outcomes first, for shrinking. */ +export function genP18Draw(choices: Choices): P18Draw { + const density = choices.weightedPick([ + [3, 0], + [2, 0.12], + [1, 0.4], + ]); + const drawing: Drawing = { choices, density }; + const argument = genP18Argument(drawing); + const file = genP18File(drawing, argument); + const setup = choices.pick( + choices.weightedPick<readonly number[]>([ + [3, P18_STRICT_DEFAULT_SETUPS], + [1, P18_INITIALIZED_PROJECT_SETUPS], + ]), + ); + const mutation = genP18Mutation(choices, argument); + checkP18Draw(file, mutation); + return { file, mutation, setup }; +} + +// --------------------------------------------------------------------------- +// The draw's files, read back, and S-9 (module header) +// --------------------------------------------------------------------------- + +/** The keys of `value`, with their spellings, as TypeScript reads them back. */ +function spelledKeys( + value: P18Value, + keys: Array<readonly [string, boolean]> = [], +): Array<readonly [string, boolean]> { + if (value.kind === "list") { + for (const element of value.elements) spelledKeys(element.value, keys); + } else if (value.kind === "object") { + for (const member of value.members) { + keys.push([member.key, member.stringLiteral]); + spelledKeys(member.value, keys); + } + } + return keys; +} + +/** + * `file` rendered with `argument` beside N `name`, then read back with the + * harness's TypeScript (module header); a deviation throws. + */ +function composeP18File( + file: P18File, + argument: P18Object, + name: string, + what: string, +): string { + const problem = (detail: string): never => { + throw new Error( + `P-18: ${what}, rendered importing ${JSON.stringify(name)}, ${detail} ` + + `— ${P18_PREMISE}: a harness defect`, + ); + }; + const rendering = renderP18File(file, argument, name); + const text = rendering.text; + if (text.includes(BACKSLASH)) problem("spells a backslash"); + const scanned = scanComments(text).map((comment) => comment.text); + if ( + scanned.length !== rendering.comments.length || + scanned.some((comment, index) => comment !== rendering.comments[index]) + ) { + problem( + `holds ${count(scanned.length, "comment")} as TypeScript scans it, ` + + `not the ${String(rendering.comments.length)} drawn`, + ); + } + for (const comment of scanned) { + if (comment.includes("@") || comment.startsWith("///")) { + problem( + `carries the comment ${JSON.stringify(comment)}, which TypeScript ` + + "may read as a directive or pragma", + ); + } + } + const read = readBack(text, problem); + if (read.specifier !== name || read.specifierSpelling !== `"${name}"`) { + problem(`spells its specifier ${read.specifierSpelling}, not exactly N`); + } + if (read.binding !== file.binding) { + problem(`binds defineConfig to ${read.binding}, not ${file.binding}`); + } + if (!sameValue(read.argument, p18Config(argument))) { + problem("reads back as another configuration than the one drawn"); + } + const expected = spelledKeys(argument); + if ( + read.keys.length !== expected.length || + read.keys.some( + (key, index) => + key.key !== expected[index]?.[0] || + key.stringLiteral !== expected[index]?.[1], + ) + ) { + problem("spells its keys otherwise than drawn"); + } + return text; +} + +/** A draw's two files beside one N. */ +export interface P18Texts { + readonly valid: string; + readonly mutant: string; +} + +/** Each draw's files, composed once per candidate N. */ +const composedTexts = new WeakMap<P18Draw, Map<string, P18Texts>>(); + +/** The draw's two files beside N `name`, read back (module header). */ +export function p18Texts(draw: P18Draw, name: string): P18Texts { + let byName = composedTexts.get(draw); + if (byName === undefined) { + byName = new Map(); + composedTexts.set(draw, byName); + } + let texts = byName.get(name); + if (texts === undefined) { + texts = { + valid: composeP18File(draw.file, draw.file.argument, name, "the draw"), + mutant: composeP18File( + draw.file, + draw.mutation.argument, + name, + `its mutant (${draw.mutation.label})`, + ), + }; + byName.set(name, texts); + } + return texts; +} + +/** + * S-9's per-draw check (module header): the draw and its mutant beside each + * candidate N, each under the name the drawn setup's extension gives it, + * so that S-9 judges each under the grammar its staging selects. + */ +export function stagedP18Sources(draw: P18Draw): readonly DrawSource[] { + const { extension } = p18Setup(draw); + return CANONICAL_MODULE_NAMES.flatMap((name) => { + const texts = p18Texts(draw, name); + const importing = `importing ${JSON.stringify(name)}`; + return [ + [`covered-file${extension}`, texts.valid, `the draw, ${importing}`], + [ + `covered-file${extension}`, + texts.mutant, + `its mutant (${draw.mutation.label}), ${importing}`, + ], + ] as const; + }); +} + +/** A draw, in words, for a diagnosis and a counterexample. */ +export function renderP18Draw(draw: P18Draw): string { + const setup = COVERED_SETUPS[draw.setup]; + const [name] = CANONICAL_MODULE_NAMES; + let text: string; + try { + text = JSON.stringify( + renderP18File(draw.file, draw.file.argument, name).text, + ); + } catch (error) { + text = `(not rendered: ${error instanceof Error ? error.message : String(error)})`; + } + return ( + `${setup === undefined ? `covered setup ${String(draw.setup)} (none such)` : setup.label}; ` + + `the mutation: ${draw.mutation.label}; the draw, importing ` + + `${JSON.stringify(name)}: ${text}` + ); +} + +// --------------------------------------------------------------------------- +// S-9's fixed vectors, and the tables held at module load (module header) +// --------------------------------------------------------------------------- + +/** A gap holding a block and a line comment, every comment character. */ +const VECTOR_GAP: P18Gap = [ + { kind: "block", body: P18_COMMENT_ALPHABET.join("") }, + { kind: "line", body: P18_COMMENT_ALPHABET.join("") }, +]; + +/** `value` with VECTOR_GAP in every gap, keys alternately spelled. */ +function commentedEverywhere( + value: ConfigValue, + keys: { count: number }, +): P18Value { + if (typeof value !== "object") return scalar(value); + if (isConfigList(value)) { + return { + kind: "list", + elements: value.map((element) => ({ + before: VECTOR_GAP, + value: commentedEverywhere(element, keys), + after: VECTOR_GAP, + })), + inner: value.length === 0 ? VECTOR_GAP : NO_COMMENTS, + }; + } + const members = [...value].map(([key, member]): P18Member => { + keys.count += 1; + return { + key, + stringLiteral: !isIdentifierName(key) || keys.count % 2 === 0, + before: VECTOR_GAP, + afterKey: VECTOR_GAP, + afterColon: VECTOR_GAP, + value: commentedEverywhere(member, keys), + after: VECTOR_GAP, + }; + }); + return { + kind: "object", + members, + inner: members.length === 0 ? VECTOR_GAP : NO_COMMENTS, + }; +} + +/** A name holding every character a non-identifier name may hold. */ +const VECTOR_NAME = [ + ...P18_NON_IDENTIFIER_LEADS, + ...NON_IDENTIFIER_RUN.flatMap(([, characters]) => characters), +].join(""); + +/** + * The vector configuration: names of each class — `__proto__`, `Object` + * members, an identifier, and VECTOR_NAME — one of both kinds, empty glob + * lists, repeated set-read elements, keys out of 7's order, and each kind + * given where a name is both kinds'. + */ +const VECTOR_ARGUMENT: ConfigObject = configObject( + [ + "specs", + configObject( + ["__proto__", ["specs/**/*.mdx", "specs/**/*.mdx"]], + [VECTOR_NAME, []], + ["constructor", ["a/x?/*-x.mdx"]], + ), + ], + [ + "code", + configObject(["constructor", ["src/**/*.ts", ".gen/*.tsx"]], ["app", []]), + ], + ["markdown", configObject(["outDir", "out/md"], ["emit", false])], + [ + "coverage", + [ + configObject( + ["targets", "all"], + ["name", "toString"], + ["target", "__proto__"], + ["targetTags", ["core", "b.c", "core"]], + ["boundary", "constructor"], + ["boundaryKind", "code"], + ["mode", "transitive"], + ["edgeKinds", ["embeds", "depends", "embeds"]], + ), + ], + ], + [ + "policy", + [ + configObject( + ["name", VECTOR_NAME], + ["type", "allowedOnly"], + ["from", configObject(["kind", "spec"], ["group", "constructor"])], + ["to", configObject(["tags", ["x-1", "x-1"]])], + ["kinds", ["references", "references"]], + ), + configObject( + ["name", "valueOf"], + ["type", "forbidden"], + ["from", configObject(["files", "src/*.ts"])], + ["to", configObject(["group", "app"])], + ), + ], + ], +); + +/** The vector file: aliased to `undefined`, VECTOR_GAP in every gap. */ +const VECTOR_FILE: P18File = (() => { + const gaps = {} as Record<P18StatementGap, P18Gap>; + for (const gap of P18_STATEMENT_GAPS) gaps[gap] = VECTOR_GAP; + return { + alias: true, + binding: "undefined", + gaps, + argument: asP18Object( + commentedEverywhere(VECTOR_ARGUMENT, { count: 0 }), + [], + ), + }; +})(); + +/** The vector mutant: an unknown `__proto__` key first at the top level. */ +const VECTOR_MUTATION: P18Mutation = { + violation: { category: "unknown key", path: ["__proto__"] }, + label: 'the unknown key "__proto__" as key 1 of the top level', + argument: insertMember(VECTOR_FILE.argument, [], 0, { + ...plainMember("__proto__", true), + stringLiteral: true, + }), +}; + +/** + * S-9's fixed TypeScript vectors (test/self/s9-typescript-well-formedness + * .test.ts): the vector draw and its mutant, as plain TypeScript and as + * TSX, through the composition P-18's draws are staged with. + */ +export const P18_TS_FORM_VECTORS: ReadonlyArray< + readonly [name: string, path: string, source: string | Uint8Array] +> = (() => { + checkP18Draw(VECTOR_FILE, VECTOR_MUTATION); + const [name] = CANONICAL_MODULE_NAMES; + const files = [ + ["the vector draw", VECTOR_FILE.argument], + ["its mutant", VECTOR_MUTATION.argument], + ] as const; + return files.flatMap(([what, argument]) => { + const text = composeP18File(VECTOR_FILE, argument, name, `P-18's ${what}`); + return ["xspec.config.ts", "xspec.config.tsx"].map( + (path) => + [ + `P-18 configuration (${what}: comments in every gap, names of ` + + `each class, importing ${JSON.stringify(name)}, as ` + + `${path.endsWith(".tsx") ? "TSX" : "plain TypeScript"})`, + path, + text, + ] as const, + ); + }); +})(); + +/** + * The generator's tables (module header), held at module load: names and + * aliases of their classes, none holding a forbidden character, every + * alias reading back as the binding; comment characters none a directive + * or line terminator needs; and 7.6's matrix as P-18 draws from it. A + * deviation is a harness defect, thrown at module load. + */ +function checkP18Tables(): void { + const problems: string[] = []; + const need = (held: boolean, problem: string): void => { + if (!held) problems.push(problem); + }; + const strings = [ + ...P18_IDENTIFIER_NAMES, + ...P18_NON_IDENTIFIER_LEADS, + ...NON_IDENTIFIER_RUN.flatMap(([, characters]) => characters), + ...P18_SPEC_GLOB_PARTS.directories, + ...P18_SPEC_GLOB_PARTS.files, + ...P18_CODE_GLOB_PARTS.directories, + ...P18_CODE_GLOB_PARTS.files, + ...P18_OUT_DIRS, + ...P18_TAGS, + ...P18_UNKNOWN_KEYS, + ...LOOSE_STRINGS, + ...LOOSE_KEYS, + ]; + for (const text of strings) { + need( + forbiddenIn(text) === undefined, + `${JSON.stringify(text)} holds no forbidden character`, + ); + } + for (const name of P18_IDENTIFIER_NAMES) { + need(isIdentifierName(name), `${JSON.stringify(name)} is an identifier`); + } + for (const lead of P18_NON_IDENTIFIER_LEADS) { + const codePoint = lead.codePointAt(0); + need( + [...lead].length === 1 && + codePoint !== undefined && + !ts.isIdentifierStart(codePoint, ts.ScriptTarget.ESNext), + `the lead ${JSON.stringify(lead)} is one character no identifier begins with`, + ); + } + for (const character of P18_COMMENT_ALPHABET) { + need( + [...character].length === 1 && + !["@", "/", "*"].includes(character) && + forbiddenIn(character.replace(/["']/, "")) === undefined, + `the comment character ${JSON.stringify(character)} is one no ` + + "directive, pragma, or comment's end needs", + ); + } + for (const alias of P18_ALIAS_NAMES) { + need( + isIdentifierName(alias) && !BARRED_BINDINGS.has(alias), + `the alias ${JSON.stringify(alias)} is a binding strict module code admits`, + ); + try { + composeP18File( + { + alias: true, + binding: alias, + gaps: VECTOR_FILE.gaps, + argument: asP18Object( + fromConfigValue(configObject(["specs", configObject()])), + [], + ), + }, + asP18Object( + fromConfigValue(configObject(["specs", configObject()])), + [], + ), + CANONICAL_MODULE_NAMES[0], + `the alias ${JSON.stringify(alias)}`, + ); + } catch (error) { + problems.push(error instanceof Error ? error.message : String(error)); + } + } + need( + COVERED_SETUPS.length === 173 && + P18_STRICT_DEFAULT_SETUPS.length === 168 && + P18_INITIALIZED_PROJECT_SETUPS.length === 5, + "7.6's matrix holds 173 covered setups, 168 under the strict defaults " + + "and 5 under the initialized-project options", + ); + need( + P18_TS_FORM_VECTORS.length === 4, + "S-9's vectors are the vector draw and its mutant, each as TypeScript " + + "and as TSX", + ); + if (problems.length > 0) { + throw new Error( + `P-18: its generator's tables deviate: ${problems.join("; ")}: a ` + + "harness defect", + ); + } +} + +checkP18Tables(); + +// --------------------------------------------------------------------------- +// The body (module header) +// --------------------------------------------------------------------------- + +/** Leads every diagnosis. */ +const P18_CONTEXT = "P-18 (type contract over generated configurations)"; + +/** TEST-SPEC P-18's rule, closing a draw's failure. */ +const P18_RULE = + "(TEST-SPEC P-18: each draw, valid under 7 by construction and a " + + "covered file, type-checks in its drawn covered setup (T7.6-2), and its " + + "mutant, holding one violation of 7.6's type-error class, fails to " + + "type-check in the same setup, paired with its draw (T7.6-3); SPEC 7.6 " + + "Type contract: valid configurations, shape violations)"; + +/** The project directory, the importing files' own, in each staging. */ +const PROJECT_DIR = "project"; + +/** What a draw's runs found. */ +interface DrawOutcome { + /** Each failing assertion's diagnosis, in order. */ + readonly failures: readonly string[]; + /** TypeScript resolved the import to no module it reads declarations from. */ + readonly nothingResolved: boolean; +} + +/** Each failing assertion's diagnosis, in order: none where all hold. */ +function failuresOf(checks: readonly (() => void)[]): readonly string[] { + const failures: string[] = []; + for (const check of checks) { + try { + check(); + } catch (error) { + if (!(error instanceof HarnessAssertionError)) throw error; + failures.push(error.message); + } + } + return failures; +} + +/** + * Judge a draw (module header): the draw and its mutant beside the + * canonical placement in a fresh staging of the drawn setup's project + * kind, in one program in the drawn setup. + */ +async function judgeP18Draw( + product: ProductBinding, + draw: P18Draw, + setup: CoveredSetup, + context: string, +): Promise<DrawOutcome> { + const staging = await ModuleStaging.create(product, context); + try { + await staging.stageProject(PROJECT_DIR, setup.project); + const placement = await staging.placeCanonical( + PROJECT_DIR, + TYPE_CHECKING_ARM, + ); + const texts = p18Texts(draw, placement.name); + const covered = await stageCoveredFiles({ + staging, + directory: PROJECT_DIR, + project: setup.project, + placement, + alone: true, + files: [ + { label: "the draw", text: texts.valid }, + { label: `its mutant (${draw.mutation.label})`, text: texts.mutant }, + ], + setups: [setup], + listExports: true, + context, + }); + const [valid, mutant] = covered.judge(setup); + if (valid === undefined || mutant === undefined) { + throw new Error("unreachable: two verdicts"); + } + return { + failures: failuresOf([ + () => { + assertTypeChecks(valid, "T7.6-2's assertion over the draw"); + }, + () => { + if (!valid.typeChecks) { + fail( + "T7.6-3's assertion over its mutant: the mutant counts " + + "nowhere here, the draw, its valid twin, not type-checking " + + "(TEST-SPEC §7.6 Pairing)", + ); + } + assertShapeViolation( + valid, + mutant, + "T7.6-3's assertion over its mutant", + ); + }, + ]), + nothingResolved: valid.exportListing?.module === undefined, + }; + } finally { + await staging.dispose(); + } +} + +/** + * One draw (module header): both assertions, then one diagnosed failure + * naming each failing one, declining shrinking where nothing resolved. + */ +async function runP18Draw( + product: ProductBinding, + draw: P18Draw, +): Promise<void> { + const setup = p18Setup(draw); + const context = `${P18_CONTEXT}, in ${setup.label}`; + const { failures, nothingResolved } = await judgeP18Draw( + product, + draw, + setup, + context, + ); + if (failures.length === 0) return; + fail( + `${P18_CONTEXT}: ${String(failures.length)} of the draw's 2 ` + + "assertions — T7.6-2's over the draw and T7.6-3's over its mutant " + + `(${draw.mutation.label}) — ${failures.length === 1 ? "fails" : "fail"} ` + + `in ${setup.label} ${P18_RULE}` + + (nothingResolved + ? ". Nothing resolves here — TypeScript resolves the import to no " + + "module it reads declarations from — a failure no configuration " + + "is expected to change, so it is reported as drawn, unshrunk" + : "") + + `: ${failures.join(" | ")}`, + { shrinkable: !nothingResolved }, + ); +} + +/** + * P-18's body (module header): the package directory checked before any + * draw, then the property. + */ +async function runP18(product: ProductBinding): Promise<void> { + await modulePackageDirectory(product, P18_CONTEXT); + await checkProperty( + "P-18 type contract over generated configurations", + genP18Draw, + (draw) => runP18Draw(product, draw), + { + runs: P18_RUNS_PER_SEED, + maxShrinkExecutions: P18_MAX_SHRINK_EXECUTIONS, + render: renderP18Draw, + drawSources: stagedP18Sources, + }, + ); +} + +// --------------------------------------------------------------------------- +// Registration + +const P_18 = defineProductTest({ + id: "P-18", + title: + "type contract over generated configurations (TEST-SPEC §16 P-18): " + + "seeded draws of configurations valid under 7 by construction, each a " + + "covered file — each object's key order and each key's identifier or " + + "string-literal spelling drawn; defineConfig's binding drawn among " + + "names strict module code admits, never require or exports; line and " + + "block comments drawn between tokens, their bodies free of @ and never " + + "a /// line; optional keys and fields present or absent; each group's " + + "glob list empty or not; each set-read list (targetTags, edgeKinds, a " + + "rule's kinds, a selector's tags) with repeated elements or without; " + + "group, profile, and rule names drawn from identifier and " + + "non-identifier spellings weighted toward the global Object " + + "interface's members and __proto__; every reference resolving, every " + + "kind given where a name is ambiguous, every name distinct where 7 " + + "requires it — each type-checks in a covered setup drawn from 7.6's " + + "matrix beside the canonical placement (T7.6-2), and each draw given " + + "one violation of 7.6's type-error class — its member, position, and " + + "offending value drawn — fails to type-check in the same setup, paired " + + "with its draw (T7.6-3); draws and mutants checked well-formed before " + + "TypeScript judges them (S-9) (SPEC 7.6 Covered files, Type contract; " + + "E-5)", + run: runP18, +}); + +/** TEST-SPEC §16 P-18. */ +export const section16P18Tests: readonly ProductTestEntry[] = [P_18]; diff --git a/test/suite/registry/section-16-p19.ts b/test/suite/registry/section-16-p19.ts new file mode 100644 index 00000000..4f6a8472 --- /dev/null +++ b/test/suite/registry/section-16-p19.ts @@ -0,0 +1,1068 @@ +// TEST-SPEC §16 P-19 (configuration import spellings). +// +// One registered product-facing property test (C-2 "one code path") over +// SPEC 7's reading of the configuration's import: its module specifier is +// any static string literal (2.4) — either quote style, escape sequences, +// line continuations, and U+FFFD included — read as spelled and never +// interpreted, resolved, or loaded, so that validity and everything xspec +// derives from the configuration are independent of the specifier's +// spelling wherever the file stays well-formed (14.20). T7-9(a)'s fixed +// spellings anchor the property; this module searches the spellings they +// never stage. A seeded, reproducible generator (helpers/property.ts, H-10; +// the fixed seed set in CI, E-5) draws, per trial, one specifier spelling: +// +// * its quote style, double or single; +// * its text's shape — a bare name, a scoped name, a relative path, an +// absolute path, a URL, or the empty string (P19_SHAPE_TEXTS); +// * each character of that text spelled raw or as an escape sequence +// encoding it — the hexadecimal escape, the Unicode escape in its +// four-digit form and in its braced form (code points at or below +// U+FFFF, leading zeros included), or a backslash before a non-escape +// character (`spellTextCharacter`); +// * pieces inserted between those characters (`genInserted`): line +// continuations, each line terminator after the backslash (LF, CR, +// CR LF, U+2028, U+2029); the single-character escapes; the NUL escape, +// never before a decimal digit; escape sequences of other code points +// (surrogates, and braced ones above U+FFFF); backslashes before other +// non-escape characters; a raw U+FFFD and other raw non-ASCII code +// points; the other quote character, raw; and an escaped backslash +// before the ordinary characters of an escape's spelling (`u{41}`, +// which begins no braced escape: the backslash before it is escaped). +// +// Every spelling is one static string literal TypeScript 5.9.3's scanner +// accepts: every backslash drawn begins a complete escape sequence, and no +// raw line feed or carriage return stands in the literal. Each draw is +// checked well-formed before the product is driven on it (S-9, §16's +// preamble: `drawSources`, the configuration judged both as module code and +// as script code), a failing draw a harness error with its seed (H-10). The +// spelling reaches the file exactly as drawn: the literal is concatenated +// into the configuration's text by the shared builder +// (helpers/config-import.ts `configImportText`), never printed, decoded, or +// re-quoted, every backslash built from code point U+005C — CONF-IMPORT's +// two staging hazards (CERTIFICATIONS.md). +// +// Each draw runs over T7-9's workspace (helpers/config-import.ts: one spec +// group `main` globbing `specs/*.mdx` over `specs/A.mdx` and `specs/B.mdx`, +// Markdown emitted next to sources, no code group, `coverage`, `policy`, +// git, or `node_modules`, so that no group discovers the configuration +// file), fresh for each draw (H-1), its configuration differing from its +// twin's in the specifier alone. The twin imports from `"xspec"`; it runs +// once, in a fresh workspace of its own, before any draw (twins are no +// draws), and holds the outcome such a workspace gives (H-5): `build` and +// `check` exit 0 finding-free, `ids` and `inventory` exit 0 with one JSON +// document each. Each draw then runs `build`, `check`, `ids`, and +// `inventory`, each under `--json`, in that order, and loads and answers as +// its twin does, under T7-9's assertions (T7-9's opening and (a)): +// +// * each command's exit code and standard output equal to the twin's — +// `inventory`'s `configuration` byte-identical among them; +// * the generated modules and emitted Markdown byte-identical — every +// file outside `.xspec/` but the configuration file, compared once the +// four commands have run; graph data, whose opaque content a differing +// configuration file may change, not compared (as in T7-8), and the lock +// path with it (H-6). +// +// So P-19 fails a product that refuses a specifier for its spelling — one +// whose spelling is not its value (an escape, a line continuation), one in +// single quotes, or one holding U+FFFD — or for what it designates. +// +// Certification: §CONF-IMPORT (P-19 in scope) and its two violators, +// VIOL-IMPORT-BRACED (refusing the braced Unicode escape of a code point at +// or below U+FFFF) and VIOL-IMPORT-SINGLE (refusing a single-quoted +// specifier), each failing P-19 at the fixed seeds, whose draws reach both +// classes as spelled (CERTIFICATIONS.md's criterion (a) reachability case; +// test/self/p19-fixed-seed-draws.test.ts pins it, with the rest of P-19's +// search space and the staged bytes of every fixed-seed draw). + +import { Buffer } from "node:buffer"; +import { decodeFindingsReport } from "../../helpers/adapters/index.js"; +import { + assertBytesEqual, + assertExitCode, + fail, + parseJsonStdout, +} from "../../helpers/assertions.js"; +import { + BACKSLASH, + CONFIG_IMPORT_CONFIG_PATH, + CONFIG_IMPORT_SOURCES, + CONFIG_IMPORT_TWIN_CONFIG, + CONFIG_IMPORT_TWIN_LITERAL, + configImportText, +} from "../../helpers/config-import.js"; +import type { Choices, DrawSource, Gen } from "../../helpers/property.js"; +import { checkProperty } from "../../helpers/property.js"; +import { defineProductTest } from "../../helpers/registry.js"; +import type { ProductTestEntry } from "../../helpers/registry.js"; +import type { + DirectorySnapshot, + SnapshotOptions, +} from "../../helpers/snapshot.js"; +import { + assertSnapshotsEqual, + snapshotDirectory, +} from "../../helpers/snapshot.js"; +import type { ProductBinding, RunResult } from "../../helpers/subprocess.js"; +import { runProduct, summarizeResult } from "../../helpers/subprocess.js"; +import { TestWorkspace } from "../../helpers/workspace.js"; +import type { WorkspaceDecl } from "../../helpers/workspace.js"; +import { assertSameJson } from "./support.js"; + +/** + * Trials per fixed seed (E-5): the default three seeds, each draw a fresh + * workspace and four invocations. test/self/p19-fixed-seed-draws.test.ts + * replays exactly these. + */ +export const P19_RUNS_PER_SEED = 16; + +/** Shrink budget, in draws (helpers/property.ts): each costs a full draw. */ +const P19_MAX_SHRINK_EXECUTIONS = 24; + +// --------------------------------------------------------------------------- +// Code points and spellings + +const cp = (...codes: number[]): string => String.fromCodePoint(...codes); + +const DOUBLE_QUOTE = '"'; +const SINGLE_QUOTE = "'"; +const LINE_FEED = cp(0x0a); +const CARRIAGE_RETURN = cp(0x0d); +const LINE_SEPARATOR = cp(0x2028); +const PARAGRAPH_SEPARATOR = cp(0x2029); +const REPLACEMENT = cp(0xfffd); + +/** The literal's delimiters. */ +export type P19Quote = "double" | "single"; + +/** The quote character delimiting a literal of `quote` style. */ +export function quoteCharacter(quote: P19Quote): string { + return quote === "double" ? DOUBLE_QUOTE : SINGLE_QUOTE; +} + +/** The quote character a literal of `quote` style holds raw. */ +function otherQuoteCharacter(quote: P19Quote): string { + return quote === "double" ? SINGLE_QUOTE : DOUBLE_QUOTE; +} + +/** + * The shapes of the specifier's text (TEST-SPEC P-19), simplest first: the + * shrinker moves toward the first. + */ +export type P19Shape = + "bare" | "scoped" | "relative" | "absolute" | "url" | "empty"; + +export const P19_SHAPES: readonly P19Shape[] = [ + "bare", + "scoped", + "relative", + "absolute", + "url", + "empty", +]; + +const SHAPE_WEIGHTS: ReadonlyArray<readonly [number, P19Shape]> = [ + [3, "bare"], + [2, "scoped"], + [3, "relative"], + [2, "absolute"], + [2, "url"], + [2, "empty"], +]; + +/** + * Each shape's texts, plain ASCII with no backslash, quote, or line + * terminator (checked at module load): the bare names T7-9(a) stages and + * others, scoped names (the product's own package name among them), + * relative paths (the configuration file itself and a directory among + * them), absolute paths, URLs of several schemes, and the empty string. No + * text is read, resolved, or loaded by a conforming product; none names a + * system file's content. + */ +export const P19_SHAPE_TEXTS: Readonly<Record<P19Shape, readonly string[]>> = { + bare: ["xspec", "XSPEC", "left-pad", "lodash.merge", "define_config"], + scoped: ["@acme/config", "@modularcloud/xspec", "@a/b"], + relative: [ + "./lib/define.js", + "../define.mjs", + "./nowhere.js", + "./xspec.config.ts", + "./specs", + ], + absolute: ["/opt/define.mjs", "/nonexistent/define.js", "/"], + url: [ + "https://example.com/define.js", + "file:///opt/define.mjs", + "node:module", + "http://127.0.0.1:9/define.js", + ], + empty: [""], +}; + +/** How a piece of the literal's body is spelled. */ +export type P19Form = + | "raw" + | "hex" + | "unicode4" + | "braced" + | "identity" + | "single" + | "nul" + | "continuation" + | "replacement" + | "non-ascii" + | "other-quote" + | "escaped-backslash"; + +/** One piece of the literal's body, exactly as staged. */ +export interface P19Piece { + readonly form: P19Form; + /** The characters staged, every backslash among them. */ + readonly spelling: string; +} + +/** One P-19 draw: the specifier's spelling, piece by piece. */ +export interface P19Draw { + readonly quote: P19Quote; + readonly shape: P19Shape; + /** The shape's text the pieces spell, inserted pieces aside. */ + readonly text: string; + /** The literal's body, in order: the delimiters are `quote`'s. */ + readonly pieces: readonly P19Piece[]; +} + +/** The draw's specifier exactly as the configuration holds it, quotes included. */ +export function spellP19Literal(draw: P19Draw): string { + const quote = quoteCharacter(draw.quote); + return quote + draw.pieces.map((piece) => piece.spelling).join("") + quote; +} + +const HEX_UPPER = "0123456789ABCDEF"; +const HEX_LOWER = "0123456789abcdef"; + +/** `code` in hexadecimal, at least `width` digits, in the case drawn. */ +function hexDigits(code: number, width: number, upper: boolean): string { + const digits = upper ? HEX_UPPER : HEX_LOWER; + let out = ""; + let rest = code; + do { + out = digits[rest % 16]! + out; + rest = Math.floor(rest / 16); + } while (rest > 0); + return out.padStart(width, "0"); +} + +/** The hexadecimal escape: backslash, `x`, two hex digits (code <= 0xFF). */ +export function hexEscape(code: number, upper: boolean): string { + if (code > 0xff) + throw new Error(`P-19: no hexadecimal escape of ${String(code)}`); + return `${BACKSLASH}x${hexDigits(code, 2, upper)}`; +} + +/** The four-digit Unicode escape: backslash, `u`, four hex digits. */ +export function unicode4Escape(code: number, upper: boolean): string { + if (code > 0xffff) + throw new Error(`P-19: no four-digit escape of ${String(code)}`); + return `${BACKSLASH}u${hexDigits(code, 4, upper)}`; +} + +/** + * The braced Unicode escape: backslash, `u`, `{`, the code point's hex + * digits after `zeros` leading zeros, `}`. + */ +export function bracedEscape( + code: number, + zeros: number, + upper: boolean, +): string { + if (code > 0x10ffff) + throw new Error(`P-19: no braced escape of ${String(code)}`); + return `${BACKSLASH}u{${"0".repeat(zeros)}${hexDigits(code, 1, upper)}}`; +} + +/** + * The characters TypeScript's grammar gives a meaning after a backslash in a + * string literal (ECMAScript's EscapeCharacter, beside the line + * terminators): the single-character escapes, the decimal digits, `x`, and + * `u`. A backslash before any other character escapes that character alone + * (a NonEscapeCharacter). + */ +const ESCAPE_CHARACTERS = `'"${BACKSLASH}bfnrtv0123456789xu`; + +/** Whether a backslash before `char` escapes it alone (module header). */ +export function isNonEscapeCharacter(char: string): boolean { + return ( + [...char].length === 1 && + !ESCAPE_CHARACTERS.includes(char) && + char !== LINE_FEED && + char !== CARRIAGE_RETURN && + char !== LINE_SEPARATOR && + char !== PARAGRAPH_SEPARATOR + ); +} + +/** A backslash before a non-escape character. */ +export function identityEscape(char: string): string { + if (!isNonEscapeCharacter(char)) { + throw new Error(`P-19: ${JSON.stringify(char)} is an escape character`); + } + return BACKSLASH + char; +} + +/** + * The single-character escapes, after their backslash: the two quote + * characters, the backslash itself, and `b`, `f`, `n`, `r`, `t`, `v`. + */ +export const P19_SINGLE_ESCAPES: readonly string[] = [ + SINGLE_QUOTE, + DOUBLE_QUOTE, + BACKSLASH, + "b", + "f", + "n", + "r", + "t", + "v", +]; + +/** The NUL escape: backslash, `0` — never before a decimal digit. */ +export const NUL_ESCAPE = `${BACKSLASH}0`; + +/** The line terminators a line continuation draws after its backslash. */ +export type P19Terminator = "LF" | "CR" | "CRLF" | "LS" | "PS"; + +export const P19_TERMINATORS: ReadonlyArray< + readonly [name: P19Terminator, sequence: string] +> = [ + ["LF", LINE_FEED], + ["CR", CARRIAGE_RETURN], + ["CRLF", CARRIAGE_RETURN + LINE_FEED], + ["LS", LINE_SEPARATOR], + ["PS", PARAGRAPH_SEPARATOR], +]; + +/** Leading zeros a braced escape draws before its code point's digits. */ +const BRACED_ZEROS: ReadonlyArray<readonly [number, number]> = [ + [4, 0], + [2, 1], + [1, 2], + [1, 4], + [1, 9], +]; + +/** + * Code points an inserted escape sequence spells — controls, a Latin-1 + * letter, the separators, both surrogate halves' bounds, a byte-order mark, + * U+FFFD, a noncharacter, and code points above U+FFFF — each in every + * escape form that reaches it (hexadecimal at or below U+00FF, four-digit + * at or below U+FFFF, braced for all). + */ +export const P19_INSERTED_CODE_POINTS: readonly number[] = [ + 0x0, 0x0a, 0x7f, 0xe9, 0xff, 0x2028, 0xd800, 0xdfff, 0xfeff, 0xfffd, 0xffff, + 0x10000, 0x1f600, 0x10ffff, +]; + +/** Non-escape characters an inserted backslash escapes, ASCII and beyond. */ +export const P19_IDENTITY_CHARACTERS: readonly string[] = [ + "a", + "c", + "s", + "-", + "/", + ".", + "@", + " ", + "%", + cp(0xe9), + REPLACEMENT, + cp(0x1f5c2), +]; + +/** + * Raw non-ASCII text beside U+FFFD: two-, three-, and four-byte forms, a + * combining mark, U+00A0 and U+0085, the two separators U+2028 and U+2029 + * (raw, a string literal's ordinary characters: TypeScript 5.9.3 ends a + * string literal at a raw line feed or carriage return alone), a zero-width + * space, a byte-order mark inside the literal, a private-use code point, + * and the noncharacters U+FFFF and U+10FFFF. + */ +export const P19_NON_ASCII_TEXTS: readonly string[] = [ + cp(0xe9), + cp(0x65e5, 0x672c), + cp(0x1f5c2), + `e${cp(0x301)}`, + cp(0xa0), + cp(0x85), + LINE_SEPARATOR, + PARAGRAPH_SEPARATOR, + cp(0x200b), + cp(0xfeff), + cp(0xe000), + cp(0xffff), + cp(0x10ffff), +]; + +/** + * What follows an escaped backslash as ordinary characters: the spellings + * of escapes, which begin none there (VIOL-IMPORT-BRACED reads `u{41}` + * after an escaped backslash as the conformer does). + */ +export const P19_ESCAPED_BACKSLASH_TAILS: readonly string[] = [ + "u{41}", + "u{0041}", + "u{D800}", + "u{1F600}", + "u0041", + "x41", +]; + +// Module-load self-checks: every text a draw spells raw is ASCII with no +// backslash, quote, or line terminator, so that each spelling is one +// well-formed literal; every identity character escapes itself alone. +for (const texts of Object.values(P19_SHAPE_TEXTS)) { + for (const text of texts) { + for (const char of text) { + const code = char.codePointAt(0)!; + if ( + code < 0x20 || + code > 0x7e || + char === BACKSLASH || + char === DOUBLE_QUOTE || + char === SINGLE_QUOTE + ) { + throw new Error( + `P-19: the shape text ${JSON.stringify(text)} holds ${JSON.stringify(char)}, which no raw piece may spell`, + ); + } + } + } +} +for (const char of P19_IDENTITY_CHARACTERS) identityEscape(char); +for (const tail of P19_ESCAPED_BACKSLASH_TAILS) { + if (tail.includes(BACKSLASH)) { + throw new Error(`P-19: the tail ${JSON.stringify(tail)} holds a backslash`); + } +} + +// --------------------------------------------------------------------------- +// The generator + +const QUOTES: ReadonlyArray<readonly [number, P19Quote]> = [ + [1, "double"], + [1, "single"], +]; + +/** How often a shape text's character is escaped: never, some, most. */ +const ESCAPE_DENSITIES: ReadonlyArray<readonly [number, number]> = [ + [2, 0], + [3, 0.25], + [2, 0.6], +]; + +/** How often a piece is inserted at each position: never, some, often. */ +const INSERT_DENSITIES: ReadonlyArray<readonly [number, number]> = [ + [2, 0], + [3, 0.2], + [3, 0.45], +]; + +/** Pieces inserted at one position, at most. */ +const MAX_INSERTED_PER_POSITION = 2; + +type CharacterEscape = "hex" | "unicode4" | "braced" | "identity"; + +const CHARACTER_ESCAPES: ReadonlyArray<readonly [number, CharacterEscape]> = [ + [2, "hex"], + [2, "unicode4"], + [3, "braced"], + [2, "identity"], +]; + +type InsertedKind = + | "continuation" + | "single" + | "nul" + | "escape" + | "identity" + | "replacement" + | "non-ascii" + | "other-quote" + | "escaped-backslash"; + +const INSERTED_KINDS: ReadonlyArray<readonly [number, InsertedKind]> = [ + [4, "continuation"], + [3, "single"], + [2, "nul"], + [3, "escape"], + [2, "identity"], + [3, "replacement"], + [3, "non-ascii"], + [1, "other-quote"], + [1, "escaped-backslash"], +]; + +/** The inserted kinds where the NUL escape would precede a decimal digit. */ +const INSERTED_KINDS_BEFORE_DIGIT = INSERTED_KINDS.filter( + ([, kind]) => kind !== "nul", +); + +/** Whether `spelling` begins with a decimal digit. */ +function beginsWithDigit(spelling: string | undefined): boolean { + const code = spelling?.codePointAt(0); + return code !== undefined && code >= 0x30 && code <= 0x39; +} + +/** P-19's generator (module header): quote, shape, text, then the pieces. */ +export const genP19Draw: Gen<P19Draw> = (choices) => { + const quote = choices.weightedPick(QUOTES); + const shape = choices.weightedPick(SHAPE_WEIGHTS); + const text = choices.pick(P19_SHAPE_TEXTS[shape]); + const escapeDensity = choices.weightedPick(ESCAPE_DENSITIES); + const insertDensity = choices.weightedPick(INSERT_DENSITIES); + const characters = [...text]; + const pieces: P19Piece[] = []; + for (let index = 0; index <= characters.length; index += 1) { + const character = characters[index]; + // The character's own spelling is drawn first, so that the pieces + // inserted before it know whether it begins with a decimal digit. + const own = + character === undefined + ? undefined + : spellTextCharacter(choices, character, escapeDensity); + pieces.push( + ...genInserted( + choices, + quote, + insertDensity, + beginsWithDigit(own?.spelling), + ), + ); + if (own !== undefined) pieces.push(own); + } + return { quote, shape, text, pieces }; +}; + +/** One character of the shape's text: raw, or an escape encoding it. */ +function spellTextCharacter( + choices: Choices, + character: string, + density: number, +): P19Piece { + if (density === 0 || !choices.boolean(density)) { + return { form: "raw", spelling: character }; + } + const code = character.codePointAt(0)!; + const forms = CHARACTER_ESCAPES.filter( + ([, form]) => form !== "identity" || isNonEscapeCharacter(character), + ); + switch (choices.weightedPick(forms)) { + case "hex": + return { form: "hex", spelling: hexEscape(code, choices.boolean()) }; + case "unicode4": + return { + form: "unicode4", + spelling: unicode4Escape(code, choices.boolean()), + }; + case "braced": + return { + form: "braced", + spelling: bracedEscape( + code, + choices.weightedPick(BRACED_ZEROS), + choices.boolean(), + ), + }; + case "identity": + return { form: "identity", spelling: identityEscape(character) }; + } +} + +/** + * The pieces inserted at one position: none or more, each drawn knowing + * whether it is the last before a piece beginning with a decimal digit, + * where the NUL escape is never drawn: before a digit it would spell a + * legacy octal escape, which TypeScript 5.9.3's scanner rejects. + */ +function genInserted( + choices: Choices, + quote: P19Quote, + density: number, + beforeDigit: boolean, +): P19Piece[] { + if (density === 0) return []; + let count = 0; + while (count < MAX_INSERTED_PER_POSITION && choices.boolean(density)) { + count += 1; + } + const pieces: P19Piece[] = []; + for (let index = 0; index < count; index += 1) { + const last = index === count - 1; + pieces.push( + genInsertedPiece( + choices, + quote, + last && beforeDigit ? INSERTED_KINDS_BEFORE_DIGIT : INSERTED_KINDS, + ), + ); + } + return pieces; +} + +function genInsertedPiece( + choices: Choices, + quote: P19Quote, + kinds: ReadonlyArray<readonly [number, InsertedKind]>, +): P19Piece { + switch (choices.weightedPick(kinds)) { + case "continuation": { + const [, sequence] = choices.pick(P19_TERMINATORS); + return { form: "continuation", spelling: BACKSLASH + sequence }; + } + case "single": + return { + form: "single", + spelling: BACKSLASH + choices.pick(P19_SINGLE_ESCAPES), + }; + case "nul": + return { form: "nul", spelling: NUL_ESCAPE }; + case "escape": + return genInsertedEscape(choices); + case "identity": + return { + form: "identity", + spelling: identityEscape(choices.pick(P19_IDENTITY_CHARACTERS)), + }; + case "replacement": + return { form: "replacement", spelling: REPLACEMENT }; + case "non-ascii": + return { form: "non-ascii", spelling: choices.pick(P19_NON_ASCII_TEXTS) }; + case "other-quote": + return { form: "other-quote", spelling: otherQuoteCharacter(quote) }; + case "escaped-backslash": + return { + form: "escaped-backslash", + spelling: + BACKSLASH + BACKSLASH + choices.pick(P19_ESCAPED_BACKSLASH_TAILS), + }; + } +} + +/** An escape sequence of one of P19_INSERTED_CODE_POINTS, in a form reaching it. */ +function genInsertedEscape(choices: Choices): P19Piece { + const code = choices.pick(P19_INSERTED_CODE_POINTS); + const upper = choices.boolean(); + const forms: ReadonlyArray<readonly [number, CharacterEscape]> = [ + ...(code <= 0xff ? [[1, "hex"] as const] : []), + ...(code <= 0xffff ? [[2, "unicode4"] as const] : []), + [3, "braced"], + ]; + switch (choices.weightedPick(forms)) { + case "hex": + return { form: "hex", spelling: hexEscape(code, upper) }; + case "unicode4": + return { form: "unicode4", spelling: unicode4Escape(code, upper) }; + default: + return { + form: "braced", + spelling: bracedEscape(code, choices.weightedPick(BRACED_ZEROS), upper), + }; + } +} + +// --------------------------------------------------------------------------- +// Rendering (a falsification's counterexample) + +/** A draw as text: its literal, how it was drawn, and its UTF-8 bytes. */ +export function renderP19Draw(draw: P19Draw): string { + const literal = spellP19Literal(draw); + const forms = draw.pieces.map((piece) => piece.form); + return ( + `the specifier ${JSON.stringify(literal)} (${draw.quote}-quoted; the ` + + `${draw.shape} text ${JSON.stringify(draw.text)}; its pieces ` + + `${forms.length === 0 ? "none" : forms.join(", ")}; its UTF-8 bytes ` + + `${Buffer.from(literal, "utf8").toString("hex")})` + ); +} + +// --------------------------------------------------------------------------- +// Staging + +/** + * The files a draw stages, for S-9's per-draw check (helpers/property.ts + * `drawSources`): the configuration its specifier composes — judged + * well-formed TypeScript both ways — and the two sources, judged for + * derivability. The body stages exactly these (`p19DrawDecl`). + */ +export function stagedP19Sources(draw: P19Draw): DrawSource[] { + return [ + [ + CONFIG_IMPORT_CONFIG_PATH, + configImportText(spellP19Literal(draw)), + "the drawn specifier's configuration", + ], + ...Object.entries(CONFIG_IMPORT_SOURCES).map( + ([path, record]): DrawSource => [path, record.source], + ), + ]; +} + +/** + * A draw's workspace: the configuration its specifier composes, declared + * per draw (`ts.perDraw`: the property runner judged it before the body saw + * the draw, and the builder judges it again at staging), beside the two + * source records. + */ +export function p19DrawDecl(draw: P19Draw): WorkspaceDecl { + return { + files: { + [CONFIG_IMPORT_CONFIG_PATH]: configImportText(spellP19Literal(draw)), + ...CONFIG_IMPORT_SOURCES, + }, + ts: { perDraw: [CONFIG_IMPORT_CONFIG_PATH] }, + }; +} + +/** The twin's workspace: the twin's configuration record and the sources. */ +const P19_TWIN_DECL: WorkspaceDecl = { + files: { + [CONFIG_IMPORT_CONFIG_PATH]: CONFIG_IMPORT_TWIN_CONFIG, + ...CONFIG_IMPORT_SOURCES, + }, +}; + +/** + * What P-19 compares with the twin's files (module header): every entry + * outside `.xspec/` but the configuration file — the sources, the generated + * modules with their companions (13.1), and the emitted Markdown (13.2). + * Graph data, the lock path, and everything else under `.xspec/` are pruned. + */ +const P19_COMPARED_FILES: SnapshotOptions = { + exclude: (relPathBytes) => { + const rel = Buffer.from(relPathBytes).toString("latin1"); + return ( + rel === ".xspec" || + rel.startsWith(".xspec/") || + rel === CONFIG_IMPORT_CONFIG_PATH + ); + }, +}; + +// --------------------------------------------------------------------------- +// The commands, the twin, and one draw + +/** + * One of T7-9's four commands, run from the workspace root with JSON output + * in effect, and the outcome the twin's valid workspace gives it (H-5). + */ +interface P19Command { + readonly argv: readonly string[]; + readonly expect: (result: RunResult, context: string) => void; +} + +/** A findings-only surface: exit 0 with exactly `{"findings": []}`. */ +function expectFindingFree( + result: RunResult, + context: string, + rule: string, +): void { + assertExitCode( + result, + 0, + `${context} — on a valid workspace it exits 0 finding-free (${rule}; H-5)`, + ); + assertSameJson( + decodeFindingsReport(parseJsonStdout(result, context), context).findings, + [], + `${context} — the report is exactly {"findings": []}, the ` + + `findings-only form's one member holding the empty array (SPEC 12.7)`, + ); +} + +/** A reading surface: exit 0 with exactly one JSON document (H-5, 12.0). */ +function expectAnswered( + result: RunResult, + context: string, + rule: string, +): void { + assertExitCode( + result, + 0, + `${context} — a valid workspace's answer, exit 0 (${rule}; H-5)`, + ); + parseJsonStdout(result, context); +} + +const P19_COMMANDS: readonly P19Command[] = [ + { + argv: ["build", "--json"], + expect: (result, context) => { + expectFindingFree(result, context, "SPEC 12.1"); + }, + }, + { + argv: ["check", "--json"], + expect: (result, context) => { + expectFindingFree(result, context, "SPEC 12.2: graph data current"); + }, + }, + { + argv: ["ids", "--json"], + expect: (result, context) => { + expectAnswered(result, context, "SPEC 12.3"); + }, + }, + { + argv: ["inventory", "--json"], + expect: (result, context) => { + expectAnswered(result, context, "SPEC 11.6"); + }, + }, +]; + +/** A command as diagnoses name it. */ +function commandLabel(command: P19Command): string { + return "`" + command.argv.join(" ") + "`"; +} + +/** The twin's four runs and its compared files, once they have run. */ +interface P19Twin { + readonly results: readonly RunResult[]; + readonly compared: DirectorySnapshot; +} + +/** + * The twin (module header): the four commands in order on its fresh + * workspace, each holding the outcome that workspace gives it (H-5), then + * its compared files. + */ +async function runP19Twin( + product: ProductBinding, + workspace: TestWorkspace, +): Promise<P19Twin> { + const results: RunResult[] = []; + for (const command of P19_COMMANDS) { + const context = + `P-19's twin (the specifier ${CONFIG_IMPORT_TWIN_LITERAL}): ` + + commandLabel(command); + const result = await runProduct(product, { + cwd: workspace.root, + argv: command.argv, + }); + command.expect(result, context); + results.push(result); + } + return { + results, + compared: await snapshotDirectory(workspace.root, P19_COMPARED_FILES), + }; +} + +/** Why each answer must be the twin's (TEST-SPEC P-19, T7-9; SPEC 7, 2.4). */ +const TWIN_RULE = + "the configuration differs from the twin's in its import's specifier " + + "alone, a static string literal xspec reads as spelled and never " + + "interprets, resolves, or loads, so that validity and everything xspec " + + "derives from the configuration are independent of its spelling (SPEC " + + "7, 2.4; TEST-SPEC P-19, T7-9)"; + +/** + * A draw's run answers exactly as the twin's: the same exit outcome — exit + * code, or death by signal — and byte-equal standard output (for + * `inventory`, its `configuration` byte-identical among it). Standard error + * is not compared: its wording is free (12.0). + */ +function assertAnswersAsTwin( + result: RunResult, + twin: RunResult, + context: string, +): void { + if (result.exitCode !== twin.exitCode || result.signal !== twin.signal) { + fail( + `${context}: it exits exactly as on its twin importing from ` + + `${CONFIG_IMPORT_TWIN_LITERAL} — ${TWIN_RULE}; the draw: ` + + `${summarizeResult(result)}; the twin: ${summarizeResult(twin)}`, + ); + } + assertBytesEqual( + result.stdoutBytes, + twin.stdoutBytes, + `${context}: its standard output is byte-equal to the twin's — ` + + `${TWIN_RULE}`, + ); +} + +/** + * One draw (module header): a fresh workspace staging the drawn specifier, + * the four commands in order, each answering as the twin's did, then the + * compared files byte-identical to the twin's. + */ +async function runP19Draw( + product: ProductBinding, + twin: P19Twin, + draw: P19Draw, +): Promise<void> { + const literal = JSON.stringify(spellP19Literal(draw)); + const workspace = await TestWorkspace.create(p19DrawDecl(draw)); + try { + for (const [index, command] of P19_COMMANDS.entries()) { + const twinResult = twin.results[index]; + if (twinResult === undefined) { + throw new Error(`P-19: no twin run for ${commandLabel(command)}`); + } + const result = await runProduct(product, { + cwd: workspace.root, + argv: command.argv, + }); + assertAnswersAsTwin( + result, + twinResult, + `P-19 ${commandLabel(command)} over the specifier ${literal}`, + ); + } + assertSnapshotsEqual( + twin.compared, + await snapshotDirectory(workspace.root, P19_COMPARED_FILES), + `P-19 over the specifier ${literal}, once its four commands have ` + + `run: the generated modules and emitted Markdown — every file ` + + `outside .xspec/ but the configuration file, the twin's first, the ` + + `draw's second — are byte-identical to the twin's, graph data not ` + + `compared (${TWIN_RULE})`, + ); + } finally { + await workspace.dispose(); + } +} + +// --------------------------------------------------------------------------- +// S-9's fixed TypeScript vectors + +/** + * Every spelling the generator's tables can stage, one literal per family + * and quote style, each family's spellings concatenated (an escape sequence + * is complete wherever it stands, and no piece but the NUL escape cares what + * follows it; the NUL escape stands where a backslash follows it): the + * shape texts raw; every escape the generator spells for their characters; + * and every piece it inserts. + */ +function p19FamilyLiterals( + quote: P19Quote, +): ReadonlyArray<readonly [family: string, literal: string]> { + const characters = [ + ...new Set( + Object.values(P19_SHAPE_TEXTS).flatMap((texts) => [...texts.join("")]), + ), + ].sort(); + const characterEscapes = characters.flatMap((character) => { + const code = character.codePointAt(0)!; + return [true, false].flatMap((upper) => [ + hexEscape(code, upper), + unicode4Escape(code, upper), + ...BRACED_ZEROS.map(([, zeros]) => bracedEscape(code, zeros, upper)), + ...(isNonEscapeCharacter(character) ? [identityEscape(character)] : []), + ]); + }); + const insertedEscapes = P19_INSERTED_CODE_POINTS.flatMap((code) => + [true, false].flatMap((upper) => [ + ...(code <= 0xff ? [hexEscape(code, upper)] : []), + ...(code <= 0xffff ? [unicode4Escape(code, upper)] : []), + ...BRACED_ZEROS.map(([, zeros]) => bracedEscape(code, zeros, upper)), + ]), + ); + const inserted = [ + NUL_ESCAPE, + ...P19_TERMINATORS.map(([, sequence]) => BACKSLASH + sequence), + ...P19_SINGLE_ESCAPES.map((escaped) => BACKSLASH + escaped), + ...insertedEscapes, + ...P19_IDENTITY_CHARACTERS.map(identityEscape), + REPLACEMENT, + ...P19_NON_ASCII_TEXTS, + otherQuoteCharacter(quote), + ...P19_ESCAPED_BACKSLASH_TAILS.map((tail) => BACKSLASH + BACKSLASH + tail), + NUL_ESCAPE, + ]; + const delimiter = quoteCharacter(quote); + return [ + ["every shape text, raw", Object.values(P19_SHAPE_TEXTS).flat().join("")], + ["every escape of the shape texts' characters", characterEscapes.join("")], + ["every inserted piece", inserted.join("")], + ].map(([family, body]) => [family!, delimiter + body! + delimiter] as const); +} + +/** + * S-9's fixed TypeScript vectors (test/self/s9-typescript-well-formedness + * .test.ts): the twin's configuration, and, in each quote style, the + * configuration over each family literal (`p19FamilyLiterals`), every one + * through the shared builder the draws are staged with. + */ +export const P19_TS_FORM_VECTORS: ReadonlyArray< + readonly [name: string, path: string, source: string | Uint8Array] +> = [ + [ + "P-19 configuration (the twin: CONFIG_IMPORT_TWIN_CONFIG)", + CONFIG_IMPORT_CONFIG_PATH, + CONFIG_IMPORT_TWIN_CONFIG.source, + ], + ...(["double", "single"] as const).flatMap((quote) => + p19FamilyLiterals(quote).map( + ([family, literal]) => + [ + `P-19 configuration (${quote}-quoted: ${family})`, + CONFIG_IMPORT_CONFIG_PATH, + configImportText(literal), + ] as const, + ), + ), +]; + +// --------------------------------------------------------------------------- +// Registration + +const P_19 = defineProductTest({ + id: "P-19", + title: + "configuration import spellings (TEST-SPEC §16 P-19): seeded draws of " + + "the configuration's module specifier as a static string literal " + + "TypeScript 5.9.3's scanner accepts — double- or single-quoted; its " + + "text shaped as a bare name, a scoped name, a relative or absolute " + + "path, a URL, or the empty string, each character raw or spelled as a " + + "hexadecimal escape, a four-digit or braced Unicode escape (leading " + + "zeros included), or an escaped non-escape character; with " + + "single-character escapes, the NUL escape before a non-digit, line " + + "continuations after each line terminator, escapes of other code " + + "points (surrogates, and braced ones above U+FFFF), an escaped " + + "backslash before an escape's spelling, U+FFFD, other non-ASCII code " + + "points, and the other quote character inserted — each draw checked " + + "well-formed before the product sees it (S-9) and staged exactly as " + + "spelled, over T7-9's workspace (one spec group globbing specs/*.mdx " + + "over specs/A.mdx and specs/B.mdx, Markdown emitted next to sources, " + + "no group discovering the configuration file): each draw loads and " + + 'answers as its twin importing from "xspec" does — `build`, `check`, ' + + "`ids`, and `inventory`, each under `--json`, exit code and standard " + + "output equal to the twin's (`inventory`'s `configuration` " + + "byte-identical among them), `build` and `check` exiting 0 " + + "finding-free, and the generated modules and emitted Markdown " + + "byte-identical, graph data not compared (SPEC 7, 2.4; T7-9; E-5)", + run: async (product) => { + const twinWorkspace = await TestWorkspace.create(P19_TWIN_DECL); + try { + const twin = await runP19Twin(product, twinWorkspace); + await checkProperty( + "P-19 configuration import spellings", + genP19Draw, + async (draw) => { + await runP19Draw(product, twin, draw); + }, + { + runs: P19_RUNS_PER_SEED, + maxShrinkExecutions: P19_MAX_SHRINK_EXECUTIONS, + render: renderP19Draw, + drawSources: stagedP19Sources, + }, + ); + } finally { + await twinWorkspace.dispose(); + } + }, +}); + +/** TEST-SPEC §16 P-19. */ +export const section16P19Tests: readonly ProductTestEntry[] = [P_19]; diff --git a/test/suite/registry/section-4.ts b/test/suite/registry/section-4.ts index dcc2e315..27d4bf94 100644 --- a/test/suite/registry/section-4.ts +++ b/test/suite/registry/section-4.ts @@ -18,8 +18,8 @@ // the program's diagnostics at the consumer references under test alone — // and runtime behavior is exercised under the CommonJS configuration alone: // the consumer program compiled to CommonJS JavaScript written into a -// fresh directory outside the workspace and run there under plain Node, no -// package named `xspec` resolvable. H-2 supplies no `@types/node`, so a +// fresh directory outside the workspace and run there under plain Node, +// nothing resolvable by package name. H-2 supplies no `@types/node`, so a // consumer writing to standard output declares the one `process` member it // uses itself (module-scoped, the file holding an import). // diff --git a/test/suite/registry/section-7-basics.ts b/test/suite/registry/section-7-basics.ts index 52fd9ad2..f61cee59 100644 --- a/test/suite/registry/section-7-basics.ts +++ b/test/suite/registry/section-7-basics.ts @@ -13,16 +13,20 @@ // `--config <path>` option (a filesystem path resolved against the working // directory, 12.0); the configuration file's directory is the workspace // root. The configuration is declarative — exactly an import of -// `defineConfig` from `"xspec"` (optionally aliased) and a default export of -// one call to that binding with a statically literal argument; anything else -// is a configuration error (14.14), reported by every command at -// configuration load as a usage error (exit 2), before all source analysis. +// `defineConfig` (optionally aliased) whose module specifier is any static +// string literal, and a default export of one call to that binding with a +// statically literal argument; anything else is a configuration error +// (14.14), reported by every command at configuration load as a usage error +// (exit 2), before all source analysis. // `specs` is required; `code`, `markdown`, `coverage`, and `policy` are // optional with defined omission semantics; empty `coverage`/`policy` lists -// equal omission; unknown keys anywhere in the argument are 14.14, as is a -// value of the wrong shape — 14.14's "otherwise invalid group shape" (7.1, -// 7.2, 7.4, 7.5: `specs` and `code` are maps of named groups, each a list -// of glob strings; `coverage` and `policy` are lists). +// equal omission; an empty glob list is valid, its group discovering zero +// sources (7 bars an empty list only for `targetTags`, `edgeKinds`, a +// rule's `kinds`, and a selector's `tags`, 7.4, 7.5); unknown keys anywhere +// in the argument are 14.14, as is a value of the wrong shape — 14.14's +// "otherwise invalid group shape" (7.1, 7.2, 7.4, 7.5: `specs` and `code` +// are maps of named groups, each a list of glob strings; `coverage` and +// `policy` are lists). // // Conservative operationalizations (noted per H-3/H-4): // - 14.14 contract: `expectConfigurationError` (shared, ./support.ts) — run @@ -97,6 +101,27 @@ // the Windows leg reruns it (E-6, test/windows/e6-subset.test.ts), where // no case-sensitive filesystem masks a product resolving the name through // filesystem lookups. +// - T7-1 configuration file names (SPEC 7: `--config` names any path, the +// file judged by the grammar its name selects, 14.20 — a name ending +// `.tsx` parses as TSX, any other as plain TypeScript): three arms in +// TEST-SPEC's order, `--config xspec.config.mts`, `--config +// xspec.config.cts`, and `--config xspec.config.tsx`, each run from the +// root of a fresh workspace holding that plain file — the canonical +// configuration's bytes — beside `specs/A.mdx` and no `xspec.config.ts`: +// `build` and then `check` exit 0, and `inventory`'s `configuration` is +// byte-identical to its twin's (compared as T7-2's comments arm +// compares, below), the twin the same bytes named `xspec.config.ts` in a +// workspace of its own, driven by the same three commands given +// `--config xspec.config.ts` — so each arm differs from the twin in the +// configuration file's name alone (`configurationViewOf`'s +// `configPath`). The `.mts` and `.cts` files stage `SPECS_ONLY_CONFIG` +// itself, plain TypeScript being the grammar their names select; the +// `.tsx` file stages its text as a TSX record (S-9 judges it under TSX), +// and a module-load self-check pins every arm's bytes to the twin's under +// the grammar its name selects. A product admitting a `.ts` name alone +// refuses an arm (exit 2 at `build`); one reading a name's file otherwise +// than its twin's fails the comparison. The arms run after the occupancy +// arms and before the name-casing probe, which stays last. // - T7-2 single-deviation staging: every invalid fixture is the valid // canonical configuration with exactly one deviation, so the refusal is // attributable to the arm's malformation and nothing else. @@ -110,25 +135,105 @@ // declarative form's (14.14), never a parse failure's; a product reading // the binding loosely loads each and builds (exit 0), failing the // exit-code assertion. -// - T7-2's further form arms (SPEC 7: the specifier `"xspec"`, a literal -// set of strings and the two booleans, non-computed identifier or -// string-literal keys, one call whose sole argument is statically -// literal): the import from `"XSPEC"`, a single-casing arm — no case -// folding anywhere (12.0); `markdown: { emit: true, outDir: null }` and a -// profile's `targetTags: null`, one arm each — `null` lies outside 7's -// literal set, though `inventory` reports unset members as `null` (12.7) -// — each fixture valid with the member omitted (the profile's target and -// boundary the unambiguous group `main`), so a product reading `null` as -// an omitted member loads it and builds (exit 0); `defineConfig()` and -// `defineConfig({…}, {})`, the second's first argument the canonical -// configuration, so a product reading the first argument alone loads it; -// and the numeric-literal key `specs: { 1: ["specs/*.mdx"] }`, spelled as -// TEST-SPEC spells it (its glob, like the canonical one, matches the -// staged `specs/A.mdx`), which TypeScript admits and a product reading -// keys loosely takes for a group named `1`. Every one is a text +// - T7-2's import arms never vary the import's module specifier: SPEC 7 +// accepts any static string literal there, so an import from a specifier +// other than `"xspec"` is valid — T7-9's subject (its single-casing +// `"XSPEC"` among T7-9(a)'s spellings), never a T7-2 refusal. +// - T7-2's further form arms (SPEC 7: a literal set of strings and the two +// booleans, non-computed identifier or string-literal keys, one call +// whose sole argument is statically literal): `markdown: { emit: true, +// outDir: null }` and a profile's `targetTags: null`, one arm each — +// `null` lies outside 7's literal set, though `inventory` reports unset +// members as `null` (12.7) — each fixture valid with the member omitted +// (the profile's target and boundary the unambiguous group `main`), so a +// product reading `null` as an omitted member loads it and builds (exit +// 0); `defineConfig()` and `defineConfig({…}, {})`, the second's first +// argument the canonical configuration, so a product reading the first +// argument alone loads it; and the numeric-literal key +// `specs: { 1: ["specs/*.mdx"] }`, spelled as TEST-SPEC spells it (its +// glob, like the canonical one, matches the staged `specs/A.mdx`), which +// TypeScript admits and a product reading keys loosely takes for a group +// named `1`. Every one is a text TypeScript 5.9.3 accepts both as module +// code and as script code, so each record is declared well-formed (S-9) +// and the refusal is the declarative form's (14.14), never a parse +// failure's. +// - T7-2's wrapped forms and call variants (SPEC 7: the file consists of +// exactly the import and a default export of one call to that binding +// whose sole argument is statically literal — no other statement or +// expression form, comments alone permitted beside them): nine arms, one +// each, every one the canonical configuration with one deviation — the +// call wrapped (`export default defineConfig({…}) satisfies object`, +// `export default (defineConfig({…}))`, and `export default +// defineConfig({…})!`), the argument wrapped (`defineConfig({…} as +// const)`, `defineConfig(({…}))`), a value inside it wrapped (`markdown: +// { emit: true as boolean }`, the fixture valid with `emit: true`, and +// `specs: ({…})`), and the call spelled with syntax outside 7's list +// (`defineConfig<object>({…})`, carrying type arguments, and +// `defineConfig?.({…})`, an optional call). Every one is a text // TypeScript 5.9.3 accepts both as module code and as script code, so // each record is declared well-formed (S-9) and the refusal is the -// declarative form's (14.14), never a parse failure's. +// declarative form's (14.14), never a parse failure's; a product +// skipping TypeScript's outer expressions (parentheses, type assertions, +// `satisfies`, and non-null assertions) before reading the form, or +// reading a call by its callee and arguments alone, loads each and +// builds (exit 0), failing the exit-code assertion. +// - T7-2's binding forms (SPEC 7: exactly an import of `defineConfig`, +// optionally aliased; 2.4: every configuration literal, an import name +// spelled as a string literal included, is read verbatim): the +// string-literal import name, `import { "defineConfig" as d } from +// "xspec"` with `export default d({…})` over the canonical argument, is +// that import, aliased — it loads, and `inventory`'s `configuration` is +// byte-identical to its identifier-named twin's, `import { defineConfig +// as d } from "xspec"`, the same file but for the name's quotes +// (compared as the comments arm compares, below; `bindingFormConfig` +// composes both). Refused, one arm each (14.14, exit 2): its +// escape-spelled twin, the same file with the name's `C` written as the +// hexadecimal escape of U+0043 (backslash, `x43`; the backslash built +// from `BACKSLASH`, and the spelling checked at module load), which, +// read verbatim, imports no `defineConfig`; and a default import +// (`import defineConfig from "xspec"`), a namespace import (`import * as +// X from "xspec"` with `export default X.defineConfig({…})`), an extra +// default binding (`import d, { defineConfig } from "xspec"`), and an +// extra named binding (`import { defineConfig, other } from "xspec"`), +// each the canonical configuration with only its import line — and, for +// the namespace import, the callee — changed. Every one of these texts +// is accepted by TypeScript 5.9.3 both as module code and as script code, +// so each record is declared well-formed (S-9) and a refusal is the +// declarative form's (14.14), never a parse failure's. A product reading +// identifier import names alone refuses the string-literal name and +// fails `build`'s exit code; one reading the binding loosely — decoding +// the name's escape, or taking any import that binds or reaches +// `defineConfig` for the import of it — loads a refused text and builds +// (exit 0), failing the exit-code assertion. +// - T7-2's statement forms (SPEC 7: exactly an import of `defineConfig` and +// a default export of one call to that binding, no other statement form): +// TypeScript's two CommonJS-interop statements, one arm each, every one +// the canonical configuration with one deviation — an export assignment, +// `export = defineConfig({…})` beside `import { defineConfig } from +// "xspec"`, which is no default export, and an import assignment, `import +// defineConfig = require("xspec")` beside `export default +// defineConfig({…})`, which binds the module itself and, like the default +// and namespace imports, imports no `defineConfig`. Each is a text +// TypeScript 5.9.3 accepts both as module code and as script code, so +// each record is declared well-formed (S-9) and the refusal is the +// declarative form's (14.14), never a parse failure's; a product taking +// an export assignment for a default export, or an import assignment for +// an import of `defineConfig`, loads it and builds (exit 0), failing the +// exit-code assertion. +// - T7-2's statement order (SPEC 7 fixes which statements the file holds, +// never their order; an import binds its name throughout its module, so +// a call spelled before it calls that binding): the canonical +// configuration's two statements exchanged, `export default +// defineConfig({…})` first and `import { defineConfig } from "xspec"` +// after it — a text TypeScript 5.9.3 accepts both as module code and as +// script code — loads: `build` and then `check` exit 0, and `inventory`'s +// `configuration` is byte-identical to its import-first twin's, the +// canonical file itself (compared as the comments arm compares, below). +// `twoStatementConfig` composes both orders from the same two statements, +// and a module-load self-check pins the import-first order to the +// canonical text, so the two files differ in the statements' order +// alone. A product requiring the import first refuses the file and fails +// `build`'s exit code. // - T7-2 string-literal keys arm: "both groups discover their globs' files" // is observed as the spec group's exact `ids` listing plus whole-graph // edge-set equality carrying the code file's marker edge (T7-3's @@ -170,6 +275,24 @@ // (dropping or stringifying the element) discovers no source and builds // anyway — a group matching no files is valid (7) — so exit 0 still // discriminates it. +// - T7-3 empty glob lists (SPEC 7: an empty list is barred only for +// `targetTags`, `edgeKinds`, a rule's `kinds`, and a selector's `tags`, +// 7.4, 7.5, 14.14; a group whose globs match no files is valid): two arms +// in TEST-SPEC's order (`EMPTY_GLOB_LIST_ARMS`), each a fresh workspace +// holding exactly what TEST-SPEC names — the spec group `product: []` as +// the configuration's one group, the configuration staged alone; and the +// code group `app: []` beside the spec group `main` globbing +// `specs/*.mdx`, staged over `specs/A.mdx`. Each is driven by `build`, +// then `check`, then `inventory --json` (`expectEmptyGlobListLoads`): +// `build` and `check` exit 0 — the configuration loads — and the +// inventory's list of the empty group's kind is exactly that group with +// `globs` `[]` (12.7: `globs` as configured), its `sources` exactly what +// discovery yields — none in the first arm, `specs/A.mdx` a member of +// `main` alone in the second — so no source is a member of the empty +// group (11.6). A product refusing an empty glob list as an invalid group +// shape (14.14) fails `build`'s exit code; one dropping the group or +// reporting other globs fails the inventory's view; one whose empty group +// matches a file fails `build` or the inventory's `sources`. // - every `expectConfigRefused` arm (T7-2, T7-3): the finding's concerned // path is exactly `xspec.config.ts` — the file the upward search found, // in 11.6's anchoring form relative to the invocation working directory, @@ -191,6 +314,39 @@ // boundary the same group, the target set is the group's one leaf, // uncovered (8.1, 8.2); the `target: "product"` twin differs in that one // value alone and is refused as an unknown group (7.4, 14.14). +// - T7-2 keys and enumerated values read as spelled (SPEC 7, 2.4; the +// spellings 7.6's covered-file bar cites), an identifier key's alike: +// `specs` with its `s` written as the hexadecimal escape of U+0073 as a +// string-literal top-level key, and as the Unicode escape of U+0073 as an +// identifier one; `direct` with its `d` written as the hexadecimal escape +// of U+0064 as a profile's `mode`; `ab` with its `b` written as the +// hexadecimal (string literal) or Unicode (identifier) escape of U+0062 +// as a group key beside `ab`; and the verbatim group name keyed as an +// identifier. Each spelling is built from `BACKSLASH` and pinned at +// module load (`checkedEscapeSpelling`: one backslash, then the escape's +// text, which designates the character it replaces, and the spelling +// with it decoded), and each composed file is checked to hold the +// backslashes its spellings bring and no other. The refused top-level-key +// and `mode` arms (`SPELLED_KEY_VIOLATIONS`, and the first row of +// `SPELLED_IDENTIFIER_KEY_VIOLATIONS`) are each the canonical +// configuration — for `mode`, the `targetTags: null` row's valid twin — +// with the one escape as its deviation, valid with it decoded +// (`canonicalWithSpecsKey`, pinned to the canonical text for the plain +// key), so a product decoding escapes loads each and builds (exit 0). +// The identifier-keyed group name is the group-name arm above with its +// key an identifier: refused under `target: "product"` (the table's +// second row; a product decoding every escape loads it, one decoding the +// identifier alone refuses its resolving twin) and resolving under the +// escape spelling, observed alike (`expectVerbatimGroupNameResolves`). +// "Two groups, no key repeated — it loads, `inventory` reporting both, +// each discovering its own glob's file" is observed after `build` exits +// 0 as `inventory`'s `configuration.specs`, exactly `ab` (`a/*.mdx`) and +// the escape-spelled key's group (`b/*.mdx`) named as spelled, in +// configuration order, and its `sources`, exactly `a/A.mdx` a member of +// `ab` alone and `b/B.mdx` of the other alone, in byte order of path +// (11.6), over the minimal sources a and b (`expectTwoSpelledGroups`); a +// product decoding the escape reads the key `ab` twice and refuses the +// file (14.14), failing `build`'s exit code. // - T7-2 encoding: the non-UTF-8 fixture carries its one invalid byte // (0xFF) inside a trailing line comment, so the decoded text is a valid // configuration and the encoding is the sole defect; the BOM fixture is @@ -201,10 +357,26 @@ // product reporting it through a compiler diagnostic and one detecting // it itself pass alike, while one taking the last member loads and // builds (exit 0). -// - T7-2 comments: "inventory's `configuration` byte-identical to its -// comment-free twin's" is compared as the `configuration` member of each -// `inventory --json` document (form-decoded first), as values and as -// serializations — member order included. +// - T7-2 comments (SPEC 7: comments are permitted anywhere and contribute +// nothing): one commented file holds line and block comments at every +// position TEST-SPEC lists — before the import, inside the import +// declaration between each two of its tokens (spelled as TEST-SPEC +// spells it, its line comment after `from` putting the module specifier +// on the next line), inside the argument between keys and inside the +// glob list, and after the export — and at others besides (after the +// import, after the glob list, after everything); its twin is the same +// file with every comment removed. The commented file is declared +// well-formed (S-9). A product reading the import declaration by its +// tokens' adjacency, or a line at a time, refuses the commented file and +// fails `build`'s exit code. +// - T7-2 comments, the string-literal import name, and statement order: +// "inventory's `configuration` byte-identical to its comment-free twin's" +// (to its identifier-named twin's, to its import-first twin's) is +// compared as the `configuration` member of each `inventory --json` +// document (form-decoded first), as values and as serializations — member +// order included (`configurationViewOf`, after `build` loads the file and, +// for the statement-order arm, `check` exits 0, and +// `assertConfigurationViewsIdentical`). // - T7-3 U+FFFD names: the character is staged as the validly encoded code // point EF BF BD between two letters — a spec group's and a code group's // string-literal key, a profile name, a rule name — so 14.14's name rule, @@ -279,13 +451,17 @@ // product invocation — `expectConfigRefused`'s one staging site (serving // every arm of every refused-configuration table, the first included: // `refusedConfigArms` makes one record per row at module load), T7-1's -// occupancy and name-casing workspaces, T7-2's and T7-3's later arms, -// T7-7's arm workspaces and arm (a)'s inside link target — is a ledger -// record carrying its S-9 declaration (T7-2's syntax-error and encoding -// arms and T7-1's `XSPEC.config.ts` holding `)` unparseable, 14.20; -// every other well-formed), judged by test/self/s9-staged-sources.test.ts -// before any product exists. The canonical `SPECS_ONLY_CONFIG` is one -// record wherever it is staged, `LOCATION_FILES` included; so is T7-7's +// occupancy, name-casing, and configuration-name workspaces (the last +// staging the canonical record at `xspec.config.mts`, `xspec.config.cts`, +// and the twin's `xspec.config.ts`, and its text at `xspec.config.tsx` as +// a TSX record, the grammar that name selects, 14.20), T7-2's and T7-3's +// later arms, T7-7's arm workspaces and arm (a)'s inside link target — is +// a ledger record carrying its S-9 declaration (T7-2's syntax-error and +// encoding arms and T7-1's `XSPEC.config.ts` holding `)` unparseable, +// 14.20; every other well-formed), judged by +// test/self/s9-staged-sources.test.ts before any product exists. The +// canonical `SPECS_ONLY_CONFIG` is one record wherever it is staged, +// `LOCATION_FILES` and T7-1's `.mts` and `.cts` names included; so is T7-7's // configuration (`T7_7_CONFIG`), at `xspec.config.ts` and at the inside // link target, its text the bytes the outside target is written with // beyond the root. @@ -293,7 +469,11 @@ import { Buffer } from "node:buffer"; import * as fsp from "node:fs/promises"; import * as path from "node:path"; -import type { GraphEdge } from "../../helpers/adapters/index.js"; +import type { + GraphEdge, + InventoryGroupDef, + InventorySourceEntry, +} from "../../helpers/adapters/index.js"; import { decodeCoverageReport, decodeEdgesReport, @@ -318,7 +498,11 @@ import { } from "../../helpers/snapshot.js"; import { assertSelfContainedRoot } from "../../helpers/self-contained-root.js"; import { stagedMdx } from "../../helpers/staged-mdx.js"; -import { type StagedTs, stagedTs } from "../../helpers/staged-ts.js"; +import { + type StagedTs, + stagedTs, + tsGrammarOf, +} from "../../helpers/staged-ts.js"; import type { ProductBinding } from "../../helpers/subprocess.js"; import { runProduct, summarizeResult } from "../../helpers/subprocess.js"; import { TestWorkspace } from "../../helpers/workspace.js"; @@ -351,32 +535,37 @@ function mdxSection(id: string): string { // The minimal sources the §7 modules stage in workspaces created after a // body's first product invocation (module header): byte-identical wherever -// they are staged — `mdxSection("a")` at `specs/A.mdx` here and in -// section-7-discovery.ts, section-7.1-7.3.ts, section-7.4-7.5.ts (T7.4-1, -// T7.5-1; T7.5-2 at `lo/BASE.mdx` alone; T7.5-5 also at `tgt/a.mdx`), and -// section-12.6.ts (T12.6-1, T12.6-2: the version workspaces' minimal -// source, the same bytes); `mdxSection("b")` at `specs/sub/B.mdx` (T7-3, -// T7-6, T7.3-1) and +// they are staged — `mdxSection("a")` at `specs/A.mdx` here (and at +// `a/A.mdx`, T7-2's keys read as spelled) and in section-7-discovery.ts, +// section-7.1-7.3.ts, section-7.4-7.5.ts (T7.4-1, T7.5-1; T7.5-2 at +// `lo/BASE.mdx` alone; T7.5-5 also at `tgt/a.mdx`), and section-12.6.ts +// (T12.6-1, T12.6-2: the version workspaces' minimal source, the same +// bytes); `mdxSection("b")` at `specs/sub/B.mdx` (T7-3, T7-6, T7.3-1), +// `b/B.mdx` (T7-2's keys read as spelled), and // `specs2/B.mdx` (T7-4) — so each is ONE staged-source record, named with // every staging test in ID order and every path; the other modules import // them (section-7.4-7.5.ts and section-12.6.ts the `a` alone). export const SECTION_A_SOURCE = stagedMdx( - "T7-1/T7-2/T7-3/T7-4/T7-6/T7-7/T7.1-1/T7.3-1/T7.4-1/T7.5-1/T7.5-2/T7.5-5/T12.6-1/T12.6-2 specs/A.mdx (the minimal section a; T7.5-2's lo/BASE.mdx; T7.5-5's tgt/a.mdx)", + "T7-1/T7-2/T7-3/T7-4/T7-6/T7-7/T7.1-1/T7.3-1/T7.4-1/T7.5-1/T7.5-2/T7.5-5/T12.6-1/T12.6-2 specs/A.mdx (the minimal section a; T7-2's a/A.mdx; T7.5-2's lo/BASE.mdx; T7.5-5's tgt/a.mdx)", mdxSection("a"), ); export const SECTION_B_SOURCE = stagedMdx( - "T7-3/T7-4/T7-6/T7.3-1 the minimal section b (specs/sub/B.mdx; T7-4's specs2/B.mdx)", + "T7-2/T7-3/T7-4/T7-6/T7.3-1 the minimal section b (specs/sub/B.mdx; T7-2's b/B.mdx; T7-4's specs2/B.mdx)", mdxSection("b"), ); // The canonical valid configuration (SPEC 7): exactly one spec group, no // optional keys. Every T7-2 violation below is this file with one deviation. // A staged-source record (module header): T7-1's occupancy and name-casing -// workspaces and T7-3's omission arms stage it in workspaces created after -// a product invocation; T7-1's first workspace passes the record too, and -// T7-2's encoding arms compose their bytes from its text. +// workspaces, T7-1's configuration-name workspaces (at `xspec.config.mts` +// and `xspec.config.cts`, and the twin's `xspec.config.ts`), T7-2's +// statement-order arm (the import-first twin), and T7-3's omission arms +// stage it in workspaces created after a product invocation; T7-1's first +// workspace passes the record too, T7-1's `xspec.config.tsx` stages its +// text as a TSX record of its own (14.20), and T7-2's encoding arms compose +// their bytes from its text. const SPECS_ONLY_CONFIG = stagedTs( - "T7-1/T7-3 xspec.config.ts (the canonical configuration: exactly one spec group, no optional keys)", + "T7-1/T7-2/T7-3 xspec.config.ts (the canonical configuration: exactly one spec group, no optional keys; T7-1's xspec.config.mts and xspec.config.cts)", `import { defineConfig } from "xspec" export default defineConfig({ @@ -895,6 +1084,112 @@ export async function runT71ConfigNameCasingProbe( }); } +// --- T7-1 configuration file names (SPEC 7, 14.20) -------------------------- + +// `--config` names any path, the file judged by the grammar its name selects +// (SPEC 7, 14.20: a name ending `.tsx` parses as TSX, any other as plain +// TypeScript; module header). The twin names the same bytes +// `xspec.config.ts`; each arm's file is a plain file at the root holding +// the canonical configuration's bytes, no `xspec.config.ts` beside it. +const CONFIG_NAME_TWIN = "xspec.config.ts"; +// The canonical configuration's text as a TSX record: the `.tsx` name +// selects TSX, so its record is judged under that grammar (S-9) — the +// builder refuses to stage a plain-TypeScript record there. Staged after a +// product invocation (S-9's timing clause). +const TSX_SPECS_ONLY_CONFIG = stagedTs( + "T7-1 xspec.config.tsx (the canonical configuration's bytes, judged under TSX, the grammar the .tsx name selects)", + configText(SPECS_ONLY_CONFIG), + "well-formed", + "tsx", +); +// The three names, in TEST-SPEC's order: `.mts` and `.cts` select plain +// TypeScript and stage the canonical record itself. +const CONFIG_NAME_ARMS: readonly { + readonly name: string; + readonly config: StagedTs; +}[] = [ + { name: "xspec.config.mts", config: SPECS_ONLY_CONFIG }, + { name: "xspec.config.cts", config: SPECS_ONLY_CONFIG }, + { name: "xspec.config.tsx", config: TSX_SPECS_ONLY_CONFIG }, +]; + +// The module-load self-check of the configuration-name arms: each file +// holds the twin's bytes exactly, under the grammar its name selects — so +// an arm differs from its twin in the file's name alone. A mismatch is a +// harness error thrown at load, never a product verdict. +for (const arm of CONFIG_NAME_ARMS) { + if ( + configText(arm.config) !== configText(SPECS_ONLY_CONFIG) || + arm.config.grammar !== tsGrammarOf(arm.name) + ) { + throw new Error( + `T7-1 fixture self-check: ${arm.name} must hold the bytes of its ` + + `twin ${CONFIG_NAME_TWIN} (the canonical configuration), judged ` + + `under the grammar its name selects (${tsGrammarOf(arm.name)}; ` + + `SPEC 14.20); its record ${JSON.stringify(arm.config.name)} is ` + + `judged under ${arm.config.grammar} and holds ` + + JSON.stringify(configText(arm.config)), + ); + } +} + +/** + * T7-1's configuration file names (SPEC 7: `--config` names any path, the + * file judged by the grammar its name selects, 14.20): `--config + * xspec.config.mts`, `--config xspec.config.cts`, and `--config + * xspec.config.tsx`, each run from the root of a fresh workspace holding + * that plain file — the canonical configuration's bytes — beside the + * minimal source and no `xspec.config.ts`, each load: `build` and then + * `check` exit 0, and `inventory`'s `configuration` is byte-identical to + * its twin's, the same bytes named `xspec.config.ts` in a workspace of its + * own, driven by the same commands given `--config xspec.config.ts` + * (module header). A product admitting a `.ts` name alone refuses an arm + * and fails `build`'s exit code; one reading a name's file otherwise than + * its twin's fails the comparison. + */ +async function runConfigurationNameArms( + product: ProductBinding, +): Promise<void> { + const views: { readonly name: string; readonly view: unknown }[] = []; + for (const arm of CONFIG_NAME_ARMS) { + const grammar = + tsGrammarOf(arm.name) === "tsx" ? "TSX" : "plain TypeScript"; + views.push({ + name: arm.name, + view: await configurationViewOf( + product, + arm.config, + `T7-1 (configuration file names: --config ${arm.name}, a plain ` + + `file at the root holding a valid configuration's bytes, no ` + + `${CONFIG_NAME_TWIN} existing — --config names any path, the ` + + `file judged by the grammar its name selects, ${grammar} here ` + + `(SPEC 7, 14.20); a product admitting a .ts name alone refuses ` + + `it)`, + { check: true, configPath: arm.name }, + ), + }); + } + const twinView = await configurationViewOf( + product, + SPECS_ONLY_CONFIG, + `T7-1 (configuration file names: the twin, the same bytes named ` + + `${CONFIG_NAME_TWIN}, given by --config ${CONFIG_NAME_TWIN})`, + { check: true, configPath: CONFIG_NAME_TWIN }, + ); + for (const { name, view } of views) { + assertConfigurationViewsIdentical( + view, + twinView, + "T7-1 (configuration file names): `inventory`'s `configuration` " + + `member under --config ${name} is byte-identical to its twin's, ` + + `the same bytes named ${CONFIG_NAME_TWIN} and given by --config ` + + `${CONFIG_NAME_TWIN} — the file's name selects only the grammar it ` + + `is judged by, a choice no file in 7's declarative form observes ` + + `(SPEC 7, 14.20, 11.6)`, + ); + } +} + const T7_1 = defineProductTest({ id: "T7-1", title: @@ -911,7 +1206,13 @@ const T7_1 = defineProductTest({ "working directory beneath the valid root configuration is passed by " + "the search, which loads the root's configuration, `build` and then " + "`check` run from there exiting 0 (a single-casing probe, rerun on the " + - "Windows leg, E-6) (SPEC 7, 12.0, 12.6, 12.7, 14.14)", + "Windows leg, E-6); configuration file names — --config naming " + + "xspec.config.mts, xspec.config.cts, or xspec.config.tsx, a plain " + + "file at the root holding a valid configuration's bytes with no " + + "xspec.config.ts existing, loads, the file judged by the grammar its " + + "name selects: `build` and `check` exit 0, and inventory's " + + "configuration is byte-identical to its twin's, the same bytes named " + + "xspec.config.ts (SPEC 7, 11.6, 12.0, 12.6, 12.7, 14.14, 14.20)", run: async (product) => { await withWorkspace( { files: LOCATION_FILES, dirs: [SEARCH_CWD] }, @@ -1057,6 +1358,13 @@ const T7_1 = defineProductTest({ // symbolic link (SPEC 7, 14.14; helpers above). await runOccupancyArms(product); + // Configuration file names: --config naming xspec.config.mts, + // xspec.config.cts, or xspec.config.tsx loads, its resolved view + // byte-identical to its twin's, the same bytes named xspec.config.ts + // (SPEC 7, 14.20; helpers above). Run before the name-casing probe, + // which stays last. + await runConfigurationNameArms(product); + // Name casing: a plain file XSPEC.config.ts beneath the valid root // configuration is no entry named xspec.config.ts (SPEC 7, 12.0) — the // single-casing probe the Windows leg reruns (E-6; helpers above). @@ -1068,17 +1376,75 @@ const T7_1 = defineProductTest({ // T7-2 — declarative form // --------------------------------------------------------------------------- +// Verbatim spellings (SPEC 7, 2.4: configuration literals are static string +// literals read exactly as spelled). Every escape spelling this module +// stages is built from the backslash's code point, so that its characters +// reach the staged file exactly — a template literal would itself interpret +// a backslash escape — and this source spells no escape (the header's +// verbatim-literal note). +const BACKSLASH = String.fromCodePoint(0x5c); + +// Binding forms (SPEC 7: exactly an import of `defineConfig`, optionally +// aliased; 2.4; module header): the canonical configuration imported under +// the alias `d`, its import name spelled `importName` — the identifier +// `defineConfig` (the identifier-named twin), the string literal +// `"defineConfig"` (that import, aliased: it loads), or that string literal +// with the name's `C` written as the hexadecimal escape of U+0043 (read +// verbatim, it imports no `defineConfig`: refused, FORM_VIOLATIONS). The +// three files differ in the import name's spelling alone. +function bindingFormConfig(importName: string): string { + return `import { ${importName} as d } from "xspec" + +export default d({ + specs: { + main: ["specs/**/*.mdx"] + } +}) +`; +} +const STRING_IMPORT_NAME = '"defineConfig"'; +const ESCAPE_SPELLED_IMPORT_NAME = `"define${BACKSLASH}x43onfig"`; + +// The module-load self-check of the escape-spelled import name: it holds +// exactly one backslash, followed by `x43`, and with that one escape decoded +// (U+0043 is `C`) it is the string-literal import name — so the refused file +// differs from the loading one in that escape alone, and no escape was +// decoded or lost on its way to the staged text. A mismatch is a harness +// error thrown at load, never a product verdict. +if ( + ESCAPE_SPELLED_IMPORT_NAME.split(BACKSLASH).length !== 2 || + ESCAPE_SPELLED_IMPORT_NAME.indexOf(`${BACKSLASH}x43`) !== '"define'.length || + ESCAPE_SPELLED_IMPORT_NAME.replace( + `${BACKSLASH}x43`, + String.fromCodePoint(0x43), + ) !== STRING_IMPORT_NAME || + bindingFormConfig(ESCAPE_SPELLED_IMPORT_NAME).split(BACKSLASH).length !== 2 +) { + throw new Error( + "T7-2 fixture self-check: the escape-spelled import name must be the " + + 'string literal "defineConfig" with its C written as the hexadecimal ' + + "escape of U+0043 — one backslash, then x43, after define — and its " + + "configuration must hold that backslash alone (module header); got " + + JSON.stringify(ESCAPE_SPELLED_IMPORT_NAME), + ); +} + // Each fixture is SPECS_ONLY_CONFIG with exactly one deviation (module // header). SPEC 7: the file MUST consist of exactly an import of -// `defineConfig` from `"xspec"` (optionally aliased) and a default export of -// one call to that binding whose sole argument is statically literal — -// object literals with non-computed identifier or string-literal keys, array -// literals, static string literals, and the boolean literals; no other -// statement or expression form, no spread, no computed value. The rows -// follow TEST-SPEC's order: the import (its specifier `"XSPEC"` among the -// misdirected ones), extra statements, each non-literal argument form, the -// `null` literal, a non-call default export, a call without a sole -// argument, a numeric-literal key, and the import's modifiers. +// `defineConfig` (optionally aliased) whose module specifier is any static +// string literal, and a default export of one call to that binding whose +// sole argument is statically literal — object literals with non-computed +// identifier or string-literal keys, array literals, static string +// literals, and the boolean literals; no other statement or expression +// form, no spread, no computed value. The rows follow TEST-SPEC's order: a +// syntax error, the missing import, extra statements, each non-literal +// argument form, the `null` literal, a non-call default export, a call +// without a sole argument, a numeric-literal key, the wrapped forms and +// call variants, the refused binding forms, the import's modifiers, and the +// statement forms. The escape-spelled import name's valid twin is the +// string-literal import name's file (`bindingFormConfig`, loaded by the +// body), the escape its one deviation. No row varies the specifier: any +// static string literal is valid there (SPEC 7), T7-9's subject. const FORM_VIOLATIONS = refusedConfigArms("T7-2", [ { label: "not well-formed TypeScript — a syntax error (unclosed braces)", @@ -1097,30 +1463,6 @@ export default defineConfig({ main: ["specs/**/*.mdx"] } }) -`, - }, - { - label: 'import from a specifier other than "xspec"', - config: `import { defineConfig } from "not-xspec" - -export default defineConfig({ - specs: { - main: ["specs/**/*.mdx"] - } -}) -`, - }, - { - label: - 'import from the specifier "XSPEC": a single-casing arm, no case ' + - "folding anywhere (SPEC 12.0)", - config: `import { defineConfig } from "XSPEC" - -export default defineConfig({ - specs: { - main: ["specs/**/*.mdx"] - } -}) `, }, { @@ -1306,6 +1648,182 @@ export default defineConfig({ export default defineConfig({ specs: { 1: ["specs/*.mdx"] } }) +`, + }, + // Wrapped forms and call variants (SPEC 7: exactly the import and a + // default export of one call to that binding whose sole argument is + // statically literal — no other statement or expression form): the call + // wrapped, the argument wrapped, a value inside it wrapped, and the call + // spelled with syntax outside 7's list — nine well-formed texts, one arm + // each (module header). + { + label: + "the call wrapped: export default defineConfig({…}) satisfies object", + config: `import { defineConfig } from "xspec" + +export default defineConfig({ + specs: { + main: ["specs/**/*.mdx"] + } +}) satisfies object +`, + }, + { + label: "the call wrapped: export default (defineConfig({…}))", + config: `import { defineConfig } from "xspec" + +export default (defineConfig({ + specs: { + main: ["specs/**/*.mdx"] + } +})) +`, + }, + { + label: + "the call wrapped: export default defineConfig({…})!, a non-null " + + "assertion", + config: `import { defineConfig } from "xspec" + +export default defineConfig({ + specs: { + main: ["specs/**/*.mdx"] + } +})! +`, + }, + { + label: "the argument wrapped: defineConfig({…} as const)", + config: `import { defineConfig } from "xspec" + +export default defineConfig({ + specs: { + main: ["specs/**/*.mdx"] + } +} as const) +`, + }, + { + label: "the argument wrapped: defineConfig(({…}))", + config: `import { defineConfig } from "xspec" + +export default defineConfig(({ + specs: { + main: ["specs/**/*.mdx"] + } +})) +`, + }, + { + label: + "a value inside the argument wrapped: markdown: { emit: true as " + + "boolean }", + config: `import { defineConfig } from "xspec" + +export default defineConfig({ + specs: { + main: ["specs/**/*.mdx"] + }, + markdown: { emit: true as boolean } +}) +`, + }, + { + label: "a value inside the argument wrapped: specs: ({…})", + config: `import { defineConfig } from "xspec" + +export default defineConfig({ + specs: ({ + main: ["specs/**/*.mdx"] + }) +}) +`, + }, + { + label: + "the call spelled outside 7's list: export default " + + "defineConfig<object>({…}), carrying type arguments", + config: `import { defineConfig } from "xspec" + +export default defineConfig<object>({ + specs: { + main: ["specs/**/*.mdx"] + } +}) +`, + }, + { + label: + "the call spelled outside 7's list: export default " + + "defineConfig?.({…}), an optional call", + config: `import { defineConfig } from "xspec" + +export default defineConfig?.({ + specs: { + main: ["specs/**/*.mdx"] + } +}) +`, + }, + // Binding forms (SPEC 7: exactly an import of `defineConfig`, optionally + // aliased; 2.4): the escape-spelled string-literal import name, read + // verbatim, imports no `defineConfig`; a default import, a namespace + // import, an extra default binding, and an extra named binding are no + // import of exactly `defineConfig` — five well-formed texts, one arm each + // (module header). + { + label: + "an escape-spelled string-literal import name: import { " + + '"defineConfig" as d } from "xspec" with the name' + + "'s C written as the hexadecimal escape of U+0043 — read verbatim, " + + "it imports no defineConfig (2.4)", + config: bindingFormConfig(ESCAPE_SPELLED_IMPORT_NAME), + }, + { + label: 'a default import: import defineConfig from "xspec"', + config: `import defineConfig from "xspec" + +export default defineConfig({ + specs: { + main: ["specs/**/*.mdx"] + } +}) +`, + }, + { + label: + 'a namespace import: import * as X from "xspec" with export default ' + + "X.defineConfig({…})", + config: `import * as X from "xspec" + +export default X.defineConfig({ + specs: { + main: ["specs/**/*.mdx"] + } +}) +`, + }, + { + label: 'an extra default binding: import d, { defineConfig } from "xspec"', + config: `import d, { defineConfig } from "xspec" + +export default defineConfig({ + specs: { + main: ["specs/**/*.mdx"] + } +}) +`, + }, + { + label: + 'an extra named binding: import { defineConfig, other } from "xspec"', + config: `import { defineConfig, other } from "xspec" + +export default defineConfig({ + specs: { + main: ["specs/**/*.mdx"] + } +}) `, }, // The import carries no `type` or `defer` modifier and no import @@ -1351,6 +1869,40 @@ export default defineConfig({ 'import { defineConfig } from "xspec" with { type: "json" }', config: `import { defineConfig } from "xspec" with { type: "json" } +export default defineConfig({ + specs: { + main: ["specs/**/*.mdx"] + } +}) +`, + }, + // Statement forms (SPEC 7: exactly an import of `defineConfig` and a + // default export of one call to that binding, no other statement form): + // TypeScript's two CommonJS-interop statements — an export assignment, + // which is no default export, and an import assignment, which binds the + // module itself and imports no `defineConfig` — two well-formed texts, + // one arm each (module header). + { + label: + "a statement form: an export assignment, export = " + + 'defineConfig({…}) beside import { defineConfig } from "xspec" — no ' + + "default export", + config: `import { defineConfig } from "xspec" + +export = defineConfig({ + specs: { + main: ["specs/**/*.mdx"] + } +}) +`, + }, + { + label: + "a statement form: an import assignment, import defineConfig = " + + 'require("xspec") beside export default defineConfig({…}) — it ' + + "binds the module itself, importing no defineConfig", + config: `import defineConfig = require("xspec") + export default defineConfig({ specs: { main: ["specs/**/*.mdx"] @@ -1373,6 +1925,68 @@ export default makeConfig({ `, ); +// The valid binding form (SPEC 7, 2.4; module header): the string-literal +// import name spelling `defineConfig` is that import, aliased, and loads +// alike with its identifier-named twin, the same file but for the name's +// quotes (`bindingFormConfig`). Records made at module load: T7-2 stages +// both after a product invocation (S-9's timing clause). +const STRING_IMPORT_NAME_CONFIG = stagedTs( + 'T7-2 xspec.config.ts (binding forms: a string-literal import name, import { "defineConfig" as d } from "xspec")', + bindingFormConfig(STRING_IMPORT_NAME), +); +const IDENTIFIER_IMPORT_NAME_CONFIG = stagedTs( + 'T7-2 xspec.config.ts (binding forms: the identifier-named twin, import { defineConfig as d } from "xspec")', + bindingFormConfig("defineConfig"), +); + +// Statement order (SPEC 7 fixes which statements the file holds, never +// their order; an import binds its name throughout its module, so a call +// spelled before it calls that binding; module header): the canonical +// configuration's two statements, the default export first and the import +// after it. `twoStatementConfig` composes a file from the two statements in +// the order given, one blank line between them; the import-first order is +// the canonical text itself (`SPECS_ONLY_CONFIG`, the twin the body +// compares against), so the two files differ in the statements' order +// alone. A record made at module load: T7-2 stages it after a product +// invocation (S-9's timing clause). +const CANONICAL_IMPORT_STATEMENT = 'import { defineConfig } from "xspec"'; +const CANONICAL_EXPORT_STATEMENT = `export default defineConfig({ + specs: { + main: ["specs/**/*.mdx"] + } +})`; +function twoStatementConfig(first: string, second: string): string { + return `${first} + +${second} +`; +} +const STATEMENT_ORDER_CONFIG = stagedTs( + 'T7-2 xspec.config.ts (statement order: export default defineConfig({…}) followed by import { defineConfig } from "xspec")', + twoStatementConfig(CANONICAL_EXPORT_STATEMENT, CANONICAL_IMPORT_STATEMENT), +); + +// The module-load self-check of the statement-order pair: the import-first +// composition is the canonical configuration byte for byte, and the +// export-first file holds the same two statements in the other order — so +// the arm's one deviation from its twin is the order. A mismatch is a +// harness error thrown at load, never a product verdict. +if ( + twoStatementConfig(CANONICAL_IMPORT_STATEMENT, CANONICAL_EXPORT_STATEMENT) !== + configText(SPECS_ONLY_CONFIG) || + configText(STATEMENT_ORDER_CONFIG).indexOf(CANONICAL_IMPORT_STATEMENT) <= + configText(STATEMENT_ORDER_CONFIG).indexOf(CANONICAL_EXPORT_STATEMENT) +) { + throw new Error( + "T7-2 fixture self-check: the statement-order arm must be the canonical " + + "configuration's import and default export exchanged — the " + + "import-first composition equal to the canonical text, the " + + "export-first file holding the default export before the import " + + "(module header); got " + + JSON.stringify(configText(STATEMENT_ORDER_CONFIG)), + ); +} + // The string-literal keys arm (SPEC 7: the statically literal argument's // object literals carry "non-computed identifier or string-literal keys"): // a spec group and a code group whose names are not TypeScript identifiers @@ -1456,10 +2070,10 @@ const QUOTED_KEYS_EDGES: readonly GraphEdge[] = [ // Verbatim literals (SPEC 7, 2.4: configuration literals are static string // literals read exactly as spelled). The escape spellings below are built -// from the backslash's code point so the six characters reach the staged -// file exactly — a template literal would itself interpret a backslash-u -// escape (the header's verbatim-literal note). -const BACKSLASH = String.fromCodePoint(0x5c); +// from the backslash's code point (`BACKSLASH`, defined with T7-2's binding +// forms above) so the six characters reach the staged file exactly — a +// template literal would itself interpret a backslash-u escape (the +// header's verbatim-literal note). // A glob spelled with the six-character escape of `*` (backslash, `u002A`) // is read as those characters: it names only a file literally so called, @@ -1485,13 +2099,17 @@ export default defineConfig({ // `target: "product"` is then an unknown group (14.14, SPEC 7.4) while the // same escape spelling resolves. `boundary` carries the verbatim spelling // in both fixtures, so the profile's target is their only difference. +// `groupKey` spells the group's key: the string literal here, and the +// identifier `prod`, backslash, `u0075`, `ct` in the identifier-key arms +// below (SPEC 7, 2.4: an identifier key is read as spelled too). const VERBATIM_GROUP_NAME = `prod${BACKSLASH}u0075ct`; -function verbatimNameConfig(target: string): string { +const VERBATIM_GROUP_STRING_KEY = `"${VERBATIM_GROUP_NAME}"`; +function verbatimNameConfig(groupKey: string, target: string): string { return `import { defineConfig } from "xspec" export default defineConfig({ specs: { - "${VERBATIM_GROUP_NAME}": ["specs/**/*.mdx"] + ${groupKey}: ["specs/**/*.mdx"] }, coverage: [ { @@ -1509,42 +2127,404 @@ export default defineConfig({ // both after a product invocation (S-9's timing clause). const VERBATIM_NAME_UNKNOWN_TARGET_CONFIG = stagedTs( 'T7-2 xspec.config.ts (verbatim group name: a profile\'s target "product")', - verbatimNameConfig("product"), + verbatimNameConfig(VERBATIM_GROUP_STRING_KEY, "product"), ); const VERBATIM_NAME_CONFIG = stagedTs( "T7-2 xspec.config.ts (verbatim group name: the target spelled as the group's key)", - verbatimNameConfig(VERBATIM_GROUP_NAME), + verbatimNameConfig(VERBATIM_GROUP_STRING_KEY, VERBATIM_GROUP_NAME), ); -// Encoding (SPEC 7: the file's bytes MUST be valid UTF-8 and MUST NOT begin -// with a byte-order mark; either violation is 14.14). The non-UTF-8 fixture -// is the canonical configuration plus one trailing line comment holding the -// byte 0xFF, valid in no UTF-8 sequence: a product decoding leniently (0xFF -// → U+FFFD) sees the valid configuration and a comment contributing nothing, -// loads, and builds (exit 0). The BOM fixture is the canonical text prefixed -// by EF BB BF, which TypeScript tooling strips silently, so a product -// reading through the compiler alone loads it too. -const NON_UTF8_CONFIG = stagedTs( - "T7-2 xspec.config.ts (encoding: the byte 0xFF inside a trailing line comment)", - Buffer.concat([ - Buffer.from(configText(SPECS_ONLY_CONFIG), "utf8"), - Buffer.from("// ", "utf8"), - Buffer.from([0xff]), - Buffer.from("\n", "utf8"), - ]), - "unparseable", +// Keys and enumerated values read as spelled (SPEC 7, 2.4; the spellings +// 7.6's covered-file bar cites; module header): a key or an enumerated +// value spelled with an escape is read as its characters, as every +// configuration literal is, and an identifier key alike — its characters +// as spelled, where TypeScript decodes an identifier's Unicode escapes. +// Each spelling below holds one escape, built from `BACKSLASH` so that this +// source spells none, and is pinned at module load. + +/** + * An escape spelling pinned at module load (T7-2; module header): `spelled` + * holds exactly one backslash, followed by `escapeText` — `x` and two + * hexadecimal digits, or `u` and four — which designates `character`, and + * with that one escape decoded the spelling is `decoded`. So a staged file + * differs from its decoded twin in that escape alone, and no escape was + * decoded or lost on its way to the staged text. A mismatch is a harness + * error thrown at load, never a product verdict. + */ +function checkedEscapeSpelling( + spelled: string, + escapeText: string, + character: string, + decoded: string, +): string { + const sequence = `${BACKSLASH}${escapeText}`; + if ( + !/^(?:x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4})$/.test(escapeText) || + String.fromCodePoint(Number.parseInt(escapeText.slice(1), 16)) !== + character || + spelled.split(BACKSLASH).length !== 2 || + !spelled.includes(sequence) || + spelled.replace(sequence, character) !== decoded + ) { + throw new Error( + `T7-2 fixture self-check: ${JSON.stringify(spelled)} must hold ` + + `exactly one backslash, followed by ${escapeText} (an escape of ` + + `${JSON.stringify(character)}), and decode to ` + + `${JSON.stringify(decoded)} (module header)`, + ); + } + return spelled; +} + +// The string-literal spellings: the top-level key `"specs"` with its `s` +// written as the hexadecimal escape of U+0073 (backslash, `x73`); the +// `mode` value `"direct"` with its `d` written as that of U+0064 +// (backslash, `x64`); and the group key `"ab"` with its `b` written as that +// of U+0062 (backslash, `x62`), distinct as spelled from `"ab"`. +const ESCAPED_SPECS_STRING_KEY = checkedEscapeSpelling( + `"${BACKSLASH}x73pecs"`, + "x73", + "s", + '"specs"', ); -const BOM_CONFIG = stagedTs( - "T7-2 xspec.config.ts (encoding: a leading byte-order mark)", - Buffer.concat([ - Buffer.from([0xef, 0xbb, 0xbf]), - Buffer.from(configText(SPECS_ONLY_CONFIG), "utf8"), - ]), - "unparseable", +const ESCAPED_DIRECT_MODE = checkedEscapeSpelling( + `"${BACKSLASH}x64irect"`, + "x64", + "d", + '"direct"', ); - -// Object-literal keys and names (SPEC 7, 14.14): a key repeated within one -// object literal — an identifier key and a string-literal key spelling the +const ESCAPED_AB_STRING_KEY = checkedEscapeSpelling( + `"a${BACKSLASH}x62"`, + "x62", + "b", + '"ab"', +); +// The identifier twins: the keys `specs` and `ab` with their `s` and `b` +// written as the Unicode escapes of U+0073 and U+0062 (backslash, `u0073`; +// backslash, `u0062`), and the verbatim group name keyed as an identifier +// (`prod`, backslash, `u0075`, `ct`). +const ESCAPED_SPECS_IDENTIFIER = checkedEscapeSpelling( + `${BACKSLASH}u0073pecs`, + "u0073", + "s", + "specs", +); +const ESCAPED_AB_IDENTIFIER = checkedEscapeSpelling( + `a${BACKSLASH}u0062`, + "u0062", + "b", + "ab", +); +const VERBATIM_GROUP_IDENTIFIER_KEY = checkedEscapeSpelling( + VERBATIM_GROUP_NAME, + "u0075", + "u", + "product", +); + +/** The canonical configuration with its top-level key spelled `key`. */ +function canonicalWithSpecsKey(key: string): string { + return `import { defineConfig } from "xspec" + +export default defineConfig({ + ${key}: { + main: ["specs/**/*.mdx"] + } +}) +`; +} + +// The refused string-literal arms (14.14, exit 2), one each, every file the +// canonical configuration — for `mode`, the `targetTags: null` row's valid +// twin, a profile over `main` — with one escape as its deviation, valid +// with that escape decoded, so a product decoding escapes loads it and +// builds (exit 0). Read as spelled, the top-level key is no `specs` (an +// unknown key, `specs` then missing) and the `mode` value is no mode. +const SPELLED_KEY_VIOLATIONS = refusedConfigArms("T7-2", [ + { + label: + 'keys read as spelled: a top-level string-literal key "specs" with ' + + "its s written as the hexadecimal escape of U+0073 — an unknown key, " + + "specs then missing", + config: canonicalWithSpecsKey(ESCAPED_SPECS_STRING_KEY), + }, + { + label: + "enumerated values read as spelled: a coverage profile with mode " + + '"direct", its d written as the hexadecimal escape of U+0064 — no ' + + "mode", + config: `import { defineConfig } from "xspec" + +export default defineConfig({ + specs: { + main: ["specs/**/*.mdx"] + }, + coverage: [ + { + name: "p", + target: "main", + boundary: "main", + mode: ${ESCAPED_DIRECT_MODE} + } + ] +}) +`, + }, +]); + +// The refused identifier twins (14.14, exit 2), one each: the canonical +// configuration with its top-level identifier key `specs` written with the +// escape of its `s` — read as spelled, an unknown key, `specs` then missing +// — and the verbatim group name keyed as an identifier under a profile +// whose `target: "product"` names no configured group, its resolving twin +// (`IDENTIFIER_NAME_CONFIG`) differing in that target alone. +const SPELLED_IDENTIFIER_KEY_VIOLATIONS = refusedConfigArms("T7-2", [ + { + label: + "identifier keys read as spelled: a top-level identifier key specs " + + "with its s written as the Unicode escape of U+0073 — an unknown " + + "key, specs then missing", + config: canonicalWithSpecsKey(ESCAPED_SPECS_IDENTIFIER), + }, + { + label: + "identifier keys read as spelled: a spec group keyed by the " + + "identifier product with its u written as the Unicode escape of " + + 'U+0075 — a profile target "product" names no configured group', + config: verbatimNameConfig(VERBATIM_GROUP_IDENTIFIER_KEY, "product"), + }, +]); + +// The identifier-keyed group named by a target spelled as its key — a +// record made at module load: T7-2 stages it after a product invocation +// (S-9's timing clause). +const IDENTIFIER_NAME_CONFIG = stagedTs( + "T7-2 xspec.config.ts (identifier keys read as spelled: a spec group keyed by the identifier product with its u written as the Unicode escape of U+0075, the target spelled as its key)", + verbatimNameConfig(VERBATIM_GROUP_IDENTIFIER_KEY, VERBATIM_GROUP_NAME), +); + +// Keys distinct as spelled (SPEC 7, 2.4): the spec groups keyed `ab` and its +// escape-spelled twin — string literals, or identifiers — are two groups, +// no key repeated, each globbing its own directory over one minimal source +// there (`expectTwoSpelledGroups`); a product decoding the escape reads the +// key `ab` twice and refuses the file (14.14). Records made at module load: +// T7-2 stages both after a product invocation (S-9's timing clause). +function twoSpelledGroupsConfig(firstKey: string, secondKey: string): string { + return `import { defineConfig } from "xspec" + +export default defineConfig({ + specs: { + ${firstKey}: ["a/*.mdx"], + ${secondKey}: ["b/*.mdx"] + } +}) +`; +} +const STRING_KEYS_TWO_GROUPS_CONFIG = stagedTs( + 'T7-2 xspec.config.ts (keys read as spelled: the string-literal group keys "ab" and "ab" with its b written as the hexadecimal escape of U+0062)', + twoSpelledGroupsConfig('"ab"', ESCAPED_AB_STRING_KEY), +); +const IDENTIFIER_KEYS_TWO_GROUPS_CONFIG = stagedTs( + "T7-2 xspec.config.ts (identifier keys read as spelled: the group keys ab and ab with its b written as the Unicode escape of U+0062)", + twoSpelledGroupsConfig("ab", ESCAPED_AB_IDENTIFIER), +); + +// The module-load self-check of the composed files: the canonical +// composition with the plain key is the canonical text byte for byte, so +// each top-level-key arm differs from it in the key's spelling alone; and +// each file holds the backslashes its spellings bring and no other — one in +// each refused arm but the identifier-keyed group's, two there (its key +// and its boundary), three in its resolving twin, and one in each +// two-group file. A mismatch is a harness error thrown at load, never a +// product verdict. +const SPELLED_KEY_BACKSLASHES = [ + ...SPELLED_KEY_VIOLATIONS.map((arm) => arm.config), + ...SPELLED_IDENTIFIER_KEY_VIOLATIONS.map((arm) => arm.config), + IDENTIFIER_NAME_CONFIG, + STRING_KEYS_TWO_GROUPS_CONFIG, + IDENTIFIER_KEYS_TWO_GROUPS_CONFIG, +].map((config) => configText(config).split(BACKSLASH).length - 1); +if ( + canonicalWithSpecsKey("specs") !== configText(SPECS_ONLY_CONFIG) || + JSON.stringify(SPELLED_KEY_BACKSLASHES) !== + JSON.stringify([1, 1, 1, 2, 3, 1, 1]) +) { + throw new Error( + "T7-2 fixture self-check: the canonical composition with the plain " + + "top-level key must be the canonical text, and the files of the keys " + + "read as spelled must hold 1, 1, 1, 2, 3, 1, and 1 backslashes " + + "(module header); got " + + JSON.stringify(SPELLED_KEY_BACKSLASHES), + ); +} + +/** + * A verbatim group name resolving (T7-2's group-name arms; module header): + * `config` — the spec group keyed `prod`, backslash, `u0075`, `ct`, as a + * string literal or as an identifier, its profile's target and boundary + * spelled as that key is — staged beside the minimal source; `build` loads + * it (exit 0), `inventory` names the group as spelled, and the profile's + * rows show its target resolved: with the boundary the same group, the + * target set is the group's one leaf, uncovered (8.1, 8.2). + */ +async function expectVerbatimGroupNameResolves( + product: ProductBinding, + config: StagedTs, + label: string, +): Promise<void> { + await withWorkspace( + { + files: { + "xspec.config.ts": config, + "specs/A.mdx": SECTION_A_SOURCE, + }, + }, + async (workspace) => { + await buildOk( + product, + workspace, + `${label}: ` + + "`build` — the profile's target and boundary, spelled as the " + + "group's key is, resolve (SPEC 7, 2.4, 7.4)", + ); + const inventoryLabel = `${label} ` + "`inventory --json`"; + const inventory = decodeInventoryDocument( + await runJson( + product, + workspace, + ["inventory", "--json"], + inventoryLabel, + ), + inventoryLabel, + ); + assertSameJson( + inventory.configuration.specs.map((group) => group.name), + [VERBATIM_GROUP_NAME], + `${inventoryLabel}: the group is named as spelled — eleven ` + + `characters, the six of the escape included — never the ` + + `interpreted "product" (SPEC 7, 2.4, 11.6)`, + ); + const coverageLabel = `${label} ` + "`coverage --json`"; + const coverage = decodeCoverageReport( + await runJson( + product, + workspace, + ["coverage", "--json"], + coverageLabel, + ), + coverageLabel, + ); + assertSameJson( + coverage.profiles.map((row) => ({ + name: row.name, + covered: row.covered.map((entry) => entry.identity), + uncovered: [...row.uncovered].sort(), + })), + [{ name: "verbatim", covered: [], uncovered: ["specs/A.mdx#a"] }], + `${coverageLabel}: the profile resolved its target — the ` + + `group's one leaf is its target set, uncovered under a ` + + `boundary sourcing no edge into it (SPEC 7, 2.4, 7.4, 8.1, 8.2)`, + ); + }, + ); +} + +/** + * Keys distinct as spelled (T7-2; module header): `config` — the spec + * groups keyed `ab` (`a/*.mdx`) and its escape-spelled twin (`b/*.mdx`), + * whose name as spelled is `secondName` — staged beside the minimal sources + * `a/A.mdx` and `b/B.mdx`; `build` loads it (exit 0), and `inventory --json` + * reports both groups in configuration order, the second named as spelled, + * and each source a member of its own glob's group alone, in byte order of + * path (11.6). + */ +async function expectTwoSpelledGroups( + product: ProductBinding, + config: StagedTs, + secondName: string, + label: string, +): Promise<void> { + await withWorkspace( + { + files: { + "xspec.config.ts": config, + "a/A.mdx": SECTION_A_SOURCE, + "b/B.mdx": SECTION_B_SOURCE, + }, + }, + async (workspace) => { + await buildOk( + product, + workspace, + `${label}: ` + + "`build` — two groups, no key repeated: the configuration loads " + + "(SPEC 7, 2.4)", + ); + const inventoryLabel = `${label} ` + "`inventory --json`"; + const inventory = decodeInventoryDocument( + await runJson( + product, + workspace, + ["inventory", "--json"], + inventoryLabel, + ), + inventoryLabel, + ); + assertSameJson( + inventory.configuration.specs, + [ + { name: "ab", globs: ["a/*.mdx"] }, + { name: secondName, globs: ["b/*.mdx"] }, + ], + `${inventoryLabel}: both groups are reported in configuration ` + + `order, the escape-spelled key's group named as spelled — ` + + `${JSON.stringify(secondName)} as a JSON string, the escape's ` + + `characters included — never the decoded "ab" (SPEC 7, 2.4, 11.6)`, + ); + assertSameJson( + inventory.sources, + [ + { path: "a/A.mdx", groups: [{ name: "ab", kind: "spec" }] }, + { path: "b/B.mdx", groups: [{ name: secondName, kind: "spec" }] }, + ], + `${inventoryLabel}: each group discovers its own glob's file — ` + + `a/A.mdx a member of "ab" alone and b/B.mdx of the ` + + `escape-spelled key's group alone, in byte order of path ` + + `(SPEC 7, 7.1, 11.6)`, + ); + }, + ); +} + +// Encoding (SPEC 7: the file's bytes MUST be valid UTF-8 and MUST NOT begin +// with a byte-order mark; either violation is 14.14). The non-UTF-8 fixture +// is the canonical configuration plus one trailing line comment holding the +// byte 0xFF, valid in no UTF-8 sequence: a product decoding leniently (0xFF +// → U+FFFD) sees the valid configuration and a comment contributing nothing, +// loads, and builds (exit 0). The BOM fixture is the canonical text prefixed +// by EF BB BF, which TypeScript tooling strips silently, so a product +// reading through the compiler alone loads it too. +const NON_UTF8_CONFIG = stagedTs( + "T7-2 xspec.config.ts (encoding: the byte 0xFF inside a trailing line comment)", + Buffer.concat([ + Buffer.from(configText(SPECS_ONLY_CONFIG), "utf8"), + Buffer.from("// ", "utf8"), + Buffer.from([0xff]), + Buffer.from("\n", "utf8"), + ]), + "unparseable", +); +const BOM_CONFIG = stagedTs( + "T7-2 xspec.config.ts (encoding: a leading byte-order mark)", + Buffer.concat([ + Buffer.from([0xef, 0xbb, 0xbf]), + Buffer.from(configText(SPECS_ONLY_CONFIG), "utf8"), + ]), + "unparseable", +); + +// Object-literal keys and names (SPEC 7, 14.14): a key repeated within one +// object literal — an identifier key and a string-literal key spelling the // same name included, whatever TypeScript's own diagnosis of the // repetition — and an empty spec group, code group, profile, or rule name // (`""`), one arm each. Every fixture is otherwise valid: each repeated @@ -1648,12 +2628,17 @@ export default defineConfig({ ]); // Comments (SPEC 7: permitted anywhere, contributing nothing). The commented -// fixture places line and block comments before the import, after it, -// before the first key, between keys, inside the glob list (after a glob -// and between two globs), after the list, after the export, and after -// everything; its twin is the same configuration with every comment -// removed. Two globs and a `markdown` key give the "between" positions -// something to stand between (`docs/` matches nothing: valid, 7). +// fixture places line and block comments before the import, inside the +// import declaration between each two of its tokens, after it, before the +// first key, between keys, inside the glob list (after a glob and between +// two globs), after the list, after the export, and after everything; its +// twin is the same configuration with every comment removed. The import +// declaration is spelled as TEST-SPEC T7-2 spells it: `/* c */` between +// `import` and `{`, `{` and `defineConfig`, `defineConfig` and `}`, and `}` +// and `from`; `// c` after `from`, its line feed putting the module +// specifier `"xspec"` on the next line; and `/* c */` after the specifier. +// Two globs and a `markdown` key give the "between" positions something to +// stand between (`docs/` matches nothing: valid, 7). const COMMENT_FREE_CONFIG = stagedTs( "T7-2 xspec.config.ts (comment-free twin)", `import { defineConfig } from "xspec" @@ -1674,7 +2659,8 @@ const COMMENTED_CONFIG = stagedTs( `// a line comment before the import /* a block comment before the import */ -import { defineConfig } from "xspec" // after the import +import /* c */ { /* c */ defineConfig /* c */ } /* c */ from // c +"xspec" /* c */ // after the import export default defineConfig({ // before the first key @@ -1691,25 +2677,125 @@ export default defineConfig({ `, ); +/** + * The resolved configuration view under `config` (T7-1's configuration + * file names; T7-2's comments, string-literal import name, and + * statement-order arms; module header): `config` staged beside the minimal + * source in a fresh workspace — as `xspec.config.ts`, found by the upward + * search, or, where `configPath` is given (T7-1), at that path under the + * root and nowhere else, every command naming it through `--config` — + * `build` required to load it (exit 0) — then, where `check` is asked for + * (T7-1's arms and twin, T7-2's statement-order arm), `check` required to + * exit 0 too — and the `configuration` member of `inventory --json` + * returned as reported, the document form-decoded first. + */ +async function configurationViewOf( + product: ProductBinding, + config: StagedTs, + label: string, + options: { readonly check?: true; readonly configPath?: string } = {}, +): Promise<unknown> { + const configArgv: readonly string[] = + options.configPath === undefined ? [] : ["--config", options.configPath]; + const spelled = (...argv: readonly string[]): string => + "`" + [...argv, ...configArgv].join(" ") + "`"; + return await withWorkspace( + { + files: { + [options.configPath ?? "xspec.config.ts"]: config, + "specs/A.mdx": SECTION_A_SOURCE, + }, + }, + async (workspace) => { + await expectExit( + product, + workspace, + ["build", ...configArgv], + 0, + `${label}: ${spelled("build")} — the configuration loads (SPEC 7)`, + ); + if (options.check === true) { + await expectExit( + product, + workspace, + ["check", ...configArgv], + 0, + `${label}: ${spelled("check")} after the build — the ` + + "configuration loads, and the freshly built workspace yields " + + "no finding (SPEC 7, 12.0)", + ); + } + const inventoryLabel = `${label} ${spelled("inventory", "--json")}`; + const raw = await runJson( + product, + workspace, + ["inventory", "--json", ...configArgv], + inventoryLabel, + ); + decodeInventoryDocument(raw, inventoryLabel); + return (raw as { readonly configuration: unknown }).configuration; + }, + ); +} + +/** + * Two resolved configuration views byte-identical (module header): equal + * as values and as serializations, member order included. + */ +function assertConfigurationViewsIdentical( + actual: unknown, + twin: unknown, + context: string, +): void { + assertSameJson(actual, twin, context); + if (JSON.stringify(actual) !== JSON.stringify(twin)) { + fail( + `${context}; the members are equal as values but serialize ` + + `differently (member order): ${JSON.stringify(actual)} vs ` + + JSON.stringify(twin), + ); + } +} + const T7_2 = defineProductTest({ id: "T7-2", title: - "declarative form: a syntax error, a missing or misdirected " + - 'defineConfig import (the specifier "XSPEC" among them: no case ' + - "folding, 12.0), a type or defer modifier or import attributes on " + - "that import, extra statements, each non-literal argument form, a " + + "declarative form: a syntax error, a missing defineConfig import, a " + + "type or defer modifier or import attributes on that import, extra " + + "statements, each non-literal argument form, a " + "null literal (markdown's outDir, a profile's targetTags), a non-call " + "default export, a call without a sole argument (defineConfig(), " + - "defineConfig({…}, {})), and a numeric-literal key are configuration " + - "errors (14.14, exit 2); an aliased defineConfig import is valid; " + + "defineConfig({…}, {})), a numeric-literal key, the call, its " + + "argument, or a value inside it wrapped (satisfies object, " + + "parentheses, a non-null assertion, as const, as boolean), the call " + + "spelled with type arguments or as an optional call, an escape-spelled " + + "string-literal import name, a default or namespace import, an extra " + + "default or named binding, an export assignment (export = " + + "defineConfig({…})), and an import assignment (import defineConfig = " + + 'require("xspec")) are configuration errors (14.14, exit 2); an ' + + "aliased defineConfig import is valid, and so is a string-literal " + + "import name spelling defineConfig, read verbatim (2.4) — it loads, " + + "inventory's configuration byte-identical to its identifier-named " + + "twin's; the default export may precede the import — it loads, build " + + "and check exit 0, inventory's configuration byte-identical to its " + + "import-first twin's; " + "string-literal group-name keys are part of the accepted form — they " + "load, discover, and resolve in a coverage profile and a policy " + "selector (SPEC 7, 7.4, 7.5, 8); literals are read verbatim — an " + "escape-spelled glob matches nothing and an escape-spelled group name " + - "is named only by the same spelling (2.4); a non-UTF-8 file, a " + + "is named only by the same spelling (2.4); keys and enumerated values " + + "are read as spelled, an identifier key alike — an escape-spelled " + + "top-level key, a string literal or an identifier, is an unknown key " + + "(specs then missing) and an escape-spelled mode no mode, each a " + + "configuration error, while keys distinct only as spelled (ab and its " + + "escape-spelled twin, string literals or identifiers) load as two " + + "groups, each discovering its own glob's file, and an escape-spelled " + + "identifier group key is named only by the same spelling (2.4); a " + + "non-UTF-8 file, a " + "byte-order mark, a repeated key, and an empty spec group, code " + "group, profile, or rule name are configuration errors; comments " + - "anywhere contribute nothing (inventory's configuration " + + "anywhere, inside the import declaration between each two of its " + + "tokens included, contribute nothing (inventory's configuration " + "byte-identical to the comment-free twin's)", run: async (product) => { for (const arm of FORM_VIOLATIONS) { @@ -1745,6 +2831,60 @@ const T7_2 = defineProductTest({ }, ); + // Binding forms (SPEC 7, 2.4): the string-literal import name spelling + // `defineConfig` is that import, aliased — it loads, and the inventory's + // resolved `configuration` view is byte-identical to its + // identifier-named twin's (compared as the comments arm compares). Its + // escape-spelled twin and the other binding forms are FORM_VIOLATIONS + // rows, refused above. + const stringImportNameView = await configurationViewOf( + product, + STRING_IMPORT_NAME_CONFIG, + 'T7-2 (binding forms: the string-literal import name, import { "defineConfig" as d } from "xspec" — that import, aliased, read verbatim)', + ); + const identifierImportNameView = await configurationViewOf( + product, + IDENTIFIER_IMPORT_NAME_CONFIG, + 'T7-2 (binding forms: the identifier-named twin, import { defineConfig as d } from "xspec")', + ); + assertConfigurationViewsIdentical( + stringImportNameView, + identifierImportNameView, + "T7-2 (binding forms): `inventory`'s `configuration` member under the " + + 'string-literal import name, import { "defineConfig" as d } from ' + + '"xspec", is byte-identical to its identifier-named twin' + + "'s — the name, read verbatim, spells defineConfig, so the import " + + "is that import, aliased (SPEC 7, 2.4, 11.6)", + ); + + // Statement order (SPEC 7 fixes which statements the file holds, never + // their order): the default export spelled before the import loads — + // `build` and `check` exit 0 — and the inventory's resolved + // `configuration` view is byte-identical to its import-first twin's, + // the canonical file's (compared as the comments arm compares). The + // statement forms are FORM_VIOLATIONS rows, refused above. + const exportFirstView = await configurationViewOf( + product, + STATEMENT_ORDER_CONFIG, + 'T7-2 (statement order: export default defineConfig({…}) followed by import { defineConfig } from "xspec")', + { check: true }, + ); + const importFirstView = await configurationViewOf( + product, + SPECS_ONLY_CONFIG, + "T7-2 (statement order: the import-first twin, the canonical " + + "configuration)", + ); + assertConfigurationViewsIdentical( + exportFirstView, + importFirstView, + "T7-2 (statement order): `inventory`'s `configuration` member under " + + "the configuration whose default export precedes its import is " + + "byte-identical to its import-first twin's — an import binds its " + + "name throughout its module, and SPEC 7 fixes which statements the " + + "file holds, never their order (SPEC 7, 11.6)", + ); + // String-literal group-name keys are part of the accepted form (SPEC 7): // the quoted-key groups load, discover, and resolve in a coverage // profile and in a policy selector. @@ -1937,60 +3077,50 @@ const T7_2 = defineProductTest({ 'T7-2 (verbatim group name: a profile\'s target "product" names no ' + "configured group — the group's spelling contains a backslash)", ); - await withWorkspace( - { - files: { - "xspec.config.ts": VERBATIM_NAME_CONFIG, - "specs/A.mdx": SECTION_A_SOURCE, - }, - }, - async (workspace) => { - await buildOk( - product, - workspace, - "T7-2 (verbatim group name): `build` — the profile's target and " + - "boundary, spelled as the group's key is, resolve (SPEC 7, " + - "2.4, 7.4)", - ); - const inventoryLabel = "T7-2 (verbatim group name) `inventory --json`"; - const inventory = decodeInventoryDocument( - await runJson( - product, - workspace, - ["inventory", "--json"], - inventoryLabel, - ), - inventoryLabel, - ); - assertSameJson( - inventory.configuration.specs.map((group) => group.name), - [VERBATIM_GROUP_NAME], - `${inventoryLabel}: the group is named as spelled — eleven ` + - `characters, the six of the escape included — never the ` + - `interpreted "product" (SPEC 7, 2.4, 11.6)`, - ); - const coverageLabel = "T7-2 (verbatim group name) `coverage --json`"; - const coverage = decodeCoverageReport( - await runJson( - product, - workspace, - ["coverage", "--json"], - coverageLabel, - ), - coverageLabel, - ); - assertSameJson( - coverage.profiles.map((row) => ({ - name: row.name, - covered: row.covered.map((entry) => entry.identity), - uncovered: [...row.uncovered].sort(), - })), - [{ name: "verbatim", covered: [], uncovered: ["specs/A.mdx#a"] }], - `${coverageLabel}: the profile resolved its target — the ` + - `group's one leaf is its target set, uncovered under a ` + - `boundary sourcing no edge into it (SPEC 7, 2.4, 7.4, 8.1, 8.2)`, - ); - }, + await expectVerbatimGroupNameResolves( + product, + VERBATIM_NAME_CONFIG, + "T7-2 (verbatim group name)", + ); + + // Keys and enumerated values are read as spelled too (SPEC 7, 2.4): a + // string-literal top-level key and a profile's `mode` spelled with an + // escape are refused (14.14) — no `specs`, and no mode — while the + // keys "ab" and its escape-spelled twin declare two groups that load, + // each discovering its own glob's file. + for (const arm of SPELLED_KEY_VIOLATIONS) { + await expectConfigRefused(product, arm.config, `T7-2 (${arm.label})`); + } + await expectTwoSpelledGroups( + product, + STRING_KEYS_TWO_GROUPS_CONFIG, + // The name as spelled: the characters between its delimiters (2.4). + ESCAPED_AB_STRING_KEY.slice(1, -1), + 'T7-2 (keys read as spelled: the string-literal group keys "ab" and ' + + "its escape-spelled twin)", + ); + + // Identifier keys are read as spelled alike (SPEC 7, 2.4): the top-level + // identifier key `specs` with its `s` so escaped, and the verbatim group + // name keyed as an identifier under a profile targeting `product`, are + // refused (14.14); the identifier keys `ab` and its escape-spelled twin + // declare two groups that load; and the identifier-keyed group is named + // by a target spelled as its key. + for (const arm of SPELLED_IDENTIFIER_KEY_VIOLATIONS) { + await expectConfigRefused(product, arm.config, `T7-2 (${arm.label})`); + } + await expectTwoSpelledGroups( + product, + IDENTIFIER_KEYS_TWO_GROUPS_CONFIG, + ESCAPED_AB_IDENTIFIER, + "T7-2 (identifier keys read as spelled: the group keys ab and its " + + "escape-spelled twin)", + ); + await expectVerbatimGroupNameResolves( + product, + IDENTIFIER_NAME_CONFIG, + "T7-2 (identifier keys read as spelled: the group keyed by the " + + "identifier spelling, the target spelled as its key)", ); // Encoding (SPEC 7, 14.14): bytes that are not valid UTF-8; a @@ -2013,60 +3143,32 @@ const T7_2 = defineProductTest({ await expectConfigRefused(product, arm.config, `T7-2 (${arm.label})`); } - // Comments (SPEC 7): the commented configuration loads, and the - // inventory's resolved `configuration` view is byte-identical to its - // comment-free twin's — compared as the member's serialization, member - // order and spellings included. - const configurationViewOf = async ( - config: StagedTs, - label: string, - ): Promise<unknown> => - await withWorkspace( - { - files: { - "xspec.config.ts": config, - "specs/A.mdx": SECTION_A_SOURCE, - }, - }, - async (workspace) => { - await buildOk( - product, - workspace, - `${label}: \`build\` — the configuration loads (SPEC 7)`, - ); - const inventoryLabel = `${label} \`inventory --json\``; - const raw = await runJson( - product, - workspace, - ["inventory", "--json"], - inventoryLabel, - ); - decodeInventoryDocument(raw, inventoryLabel); - return (raw as { readonly configuration: unknown }).configuration; - }, - ); + // Comments (SPEC 7): the commented configuration — comments inside the + // import declaration between each two of its tokens included — loads, + // and the inventory's resolved `configuration` view is byte-identical to + // its comment-free twin's — compared as the member's serialization, + // member order and spellings included. const commented = await configurationViewOf( + product, COMMENTED_CONFIG, "T7-2 (comments)", ); const commentFree = await configurationViewOf( + product, COMMENT_FREE_CONFIG, "T7-2 (comment-free twin)", ); - const commentsContext = + assertConfigurationViewsIdentical( + commented, + commentFree, "T7-2 (comments): `inventory`'s `configuration` member under the " + - "commented configuration is byte-identical to the comment-free " + - "twin's — line and block comments before the import, after it, " + - "between keys, inside the glob list, and after the export " + - "contribute nothing (SPEC 7, 11.6)"; - assertSameJson(commented, commentFree, commentsContext); - if (JSON.stringify(commented) !== JSON.stringify(commentFree)) { - fail( - `${commentsContext}; the members are equal as values but ` + - `serialize differently (member order): ` + - `${JSON.stringify(commented)} vs ${JSON.stringify(commentFree)}`, - ); - } + "commented configuration is byte-identical to the comment-free " + + "twin's — line and block comments before the import, inside the " + + "import declaration between each two of its tokens (import /* c */ " + + "{ /* c */ defineConfig /* c */ } /* c */ from // c, a line feed, " + + '"xspec" /* c */), after it, between keys, inside the glob list, ' + + "and after the export contribute nothing (SPEC 7, 11.6)", + ); }, }); @@ -2408,6 +3510,141 @@ async function assertViolatingEdgePresent( ); } +// Empty glob lists (SPEC 7: an empty list is barred only for `targetTags`, +// `edgeKinds`, a rule's `kinds`, and a selector's `tags`, 7.4, 7.5, 14.14; +// a group whose globs match no files is valid) — TEST-SPEC T7-3's two arms, +// each workspace holding exactly what TEST-SPEC names (module header): the +// spec group `product: []` as the configuration's one group, staged alone, +// and the code group `app: []` beside the spec group `main` globbing +// `specs/*.mdx`, staged over the minimal `specs/A.mdx`. Each configuration +// is a staged-source record (module header: staged after the body's first +// product invocation). +const EMPTY_SPEC_GLOBS_CONFIG = stagedTs( + "T7-3 xspec.config.ts (an empty spec glob list: the spec group product: [] alone)", + `import { defineConfig } from "xspec" + +export default defineConfig({ + specs: { + product: [] + } +}) +`, +); + +const EMPTY_CODE_GLOBS_CONFIG = stagedTs( + "T7-3 xspec.config.ts (an empty code glob list: the code group app: [] beside the spec group main over specs/*.mdx)", + `import { defineConfig } from "xspec" + +export default defineConfig({ + specs: { + main: ["specs/*.mdx"] + }, + code: { + app: [] + } +}) +`, +); + +/** + * An empty-glob-list arm (T7-3): its label, its workspace's files, the + * kind of its empty group, the inventory's expected list of groups of that + * kind, and the inventory's expected `sources`. + */ +interface EmptyGlobListArm { + readonly label: string; + readonly files: Readonly<Record<string, InitialFileContents>>; + readonly kind: "spec" | "code"; + readonly groups: readonly InventoryGroupDef[]; + readonly sources: readonly InventorySourceEntry[]; +} + +const EMPTY_GLOB_LIST_ARMS: readonly EmptyGlobListArm[] = [ + { + label: "an empty spec glob list: the spec group product: [] alone", + files: { "xspec.config.ts": EMPTY_SPEC_GLOBS_CONFIG }, + kind: "spec", + groups: [{ name: "product", globs: [] }], + sources: [], + }, + { + label: + "an empty code glob list: the code group app: [] beside the spec " + + "group main over specs/*.mdx", + files: { + "xspec.config.ts": EMPTY_CODE_GLOBS_CONFIG, + "specs/A.mdx": SECTION_A_SOURCE, + }, + kind: "code", + groups: [{ name: "app", globs: [] }], + sources: [ + { path: "specs/A.mdx", groups: [{ name: "main", kind: "spec" }] }, + ], + }, +]; + +/** + * An empty glob list loading (T7-3; module header): the arm's files staged + * in a fresh workspace; `build` and then `check` exit 0 — the configuration + * loads — and `inventory --json` reports the list of the empty group's kind + * exactly as the arm expects, the group with `globs` `[]` as configured + * (12.7), and `sources` exactly as discovery yields them, no source a + * member of the empty group (11.6). + */ +async function expectEmptyGlobListLoads( + product: ProductBinding, + arm: EmptyGlobListArm, +): Promise<void> { + const label = `T7-3 (${arm.label})`; + await withWorkspace({ files: arm.files }, async (workspace) => { + await buildOk( + product, + workspace, + `${label}: ` + + "`build` — an empty glob list is valid, 7 barring an empty list " + + "only for targetTags, edgeKinds, a rule's kinds, and a selector's " + + "tags, and a group whose globs match no files is valid; a product " + + "refusing it as an invalid group shape (14.14) fails here (SPEC 7, " + + "7.4, 7.5)", + ); + await expectExit( + product, + workspace, + ["check"], + 0, + `${label}: ` + + "`check` after the build — the configuration loads, and the " + + "freshly built workspace yields no finding (SPEC 7, 12.0)", + ); + const inventoryLabel = `${label} ` + "`inventory --json`"; + const inventory = decodeInventoryDocument( + await runJson( + product, + workspace, + ["inventory", "--json"], + inventoryLabel, + ), + inventoryLabel, + ); + assertSameJson( + arm.kind === "spec" + ? inventory.configuration.specs + : inventory.configuration.code, + arm.groups, + `${inventoryLabel}: the configuration's ${arm.kind} groups are ` + + `reported in configuration order, the empty group with globs ` + + `exactly [] — globs as configured (SPEC 7, 11.6, 12.7)`, + ); + assertSameJson( + inventory.sources, + arm.sources, + `${inventoryLabel}: the discovered sources with their group ` + + `memberships — the empty group discovers zero sources, so no ` + + `source is a member of it (SPEC 7, 11.6)`, + ); + }); +} + // Names containing U+FFFD (SPEC 7, 14.14; 12.0: no argument value carries // the character, and configured names are named in arguments): a spec // group, a code group, a profile, and a rule, one arm each. The character @@ -2490,12 +3727,15 @@ const T7_3 = defineProductTest({ title: "keys: specs is required; omitted code/markdown/coverage/policy mean " + "no code groups, no emission, zero profiles, and no policy findings; " + - "empty coverage/policy lists equal omission; unknown keys at every " + - "position, values of the wrong shape (a group valued by a single " + - "string, a glob list holding true, coverage/policy given as objects, " + - "specs/code given as lists), and a spec group, a code group, a " + - "profile, or a rule named with U+FFFD are configuration errors (SPEC " + - "7, 7.1, 7.2, 14.14)", + "empty coverage/policy lists equal omission; an empty glob list is " + + "valid — the spec group product: [] alone, and the code group app: [] " + + "beside a spec group over specs/A.mdx, each load (`build` and `check` " + + "exit 0), inventory reporting the group with globs exactly [] and no " + + "source in it; unknown keys at every position, values of the wrong " + + "shape (a group valued by a single string, a glob list holding true, " + + "coverage/policy given as objects, specs/code given as lists), and a " + + "spec group, a code group, a profile, or a rule named with U+FFFD are " + + "configuration errors (SPEC 7, 7.1, 7.2, 11.6, 12.7, 14.14)", run: async (product) => { // (a) `specs` missing and the unknown-key matrix — each 14.14, exit 2. for (const arm of KEY_VIOLATIONS) { @@ -2700,6 +3940,15 @@ const T7_3 = defineProductTest({ ); }, ); + + // (g) empty glob lists — valid (SPEC 7): the spec group `product: []` + // alone, then the code group `app: []` beside the spec group `main` + // over `specs/A.mdx`; each loads — `build` and `check` exit 0 — and + // `inventory` reports the group with `globs` exactly [] and no source + // in it (SPEC 7, 11.6, 12.7). + for (const arm of EMPTY_GLOB_LIST_ARMS) { + await expectEmptyGlobListLoads(product, arm); + } }, }); diff --git a/test/suite/registry/section-7-import.ts b/test/suite/registry/section-7-import.ts new file mode 100644 index 00000000..e48d3b69 --- /dev/null +++ b/test/suite/registry/section-7-import.ts @@ -0,0 +1,4709 @@ +// TEST-SPEC §7 configuration import — T7-9's arms (a), the specifier's +// spellings, (b), the scanner-rejected escapes, (c), the specifier's +// designations, and (d), installs; and T7-10's arms (a) and (b), the +// configuration file as a source, undiscovered and discovered, (c), its +// consequences, with the converse, (d), baselines, and (e), discovered by +// a spec group (below the T7-9 header). Configuration basics (T7-1…T7-3) +// and T7-7 live in +// section-7-basics.ts, discovery (T7-4…T7-6, T7-8) in +// section-7-discovery.ts, and P-19, the property searching the spellings +// (a) never stages, in section-16-p19.ts. +// +// Registered product-facing body (C-2 "one code path"): each arm builds its +// own fresh workspace (H-1), drives the product strictly as a subprocess +// (H-2), asserts exact exit codes (H-5), decodes reports through the H-3 +// adapters, and rejects a product only via diagnosed assertion failures +// (H-8). +// +// SPEC 7: the configuration's import takes any static string literal (2.4) +// as its module specifier, and wherever xspec reads a configuration it never +// executes the file and never interprets, resolves, or loads the specifier, +// making no read and no network access on its account — so validity, and +// everything xspec derives from the configuration, are independent of what +// the specifier designates and of its spelling wherever the file stays +// well-formed TypeScript (14.20), while an escape TypeScript 5.9.3's scanner +// rejects leaves the file not well-formed, a configuration error (14.14). +// +// The workspace (T7-9's opening; helpers/config-import.ts, shared with +// P-19): `xspec.config.ts` with one spec group `main` globbing `specs/*.mdx` +// and `markdown: { emit: true }`, emitting next to sources — no code group, +// so no configured group discovers the configuration file — over +// `specs/A.mdx` (`<S id="a">A</S>`) and `specs/B.mdx` (`<S id="b">B</S>`); +// no git repository, and no `node_modules` but (d)'s. Every workspace is +// fresh (H-1), and every configuration and source is a staged-source record +// made at module load (S-9's timing clause: each arm's workspace is created +// after the body's first product invocation, the twin's) but (d)'s one +// configuration composed at run time (below). +// +// The twin imports from `"xspec"` (`CONFIG_IMPORT_TWIN_CONFIG`). It runs +// first, in a workspace of its own, and holds the outcome such a workspace +// gives (H-5): `build` and `check` exit 0 finding-free, `ids` and +// `inventory` exit 0 with one JSON document each. A twin failing there fails +// the body at once, (a)'s premise unmet. +// +// (a) Spellings (`T7_9_A_ARMS`): eleven configurations, each differing from +// the twin's in the specifier alone — the bare names `"XSPEC"` (a +// single-casing arm, 12.0: no case folding) and `"left-pad"`, the scoped +// name `"@acme/config"`, the relative path `"./lib/define.js"`, the absolute +// path `"/opt/define.mjs"`, the URL `"https://example.com/define.js"`, the +// empty string, the single-quoted `xspec`, `xspec` with its `x` written as a +// hexadecimal escape, a line continuation between `xs` and `pec` (a +// backslash, then U+000A), and a raw U+FFFD between `x` and `spec`. Each arm +// runs `build`, `check`, `ids`, and `inventory`, each under `--json`, in +// that order, and answers as the twin did — the same exit outcome and +// byte-equal standard output (`inventory`'s `configuration` byte-identical +// among it, and `build` and `check` therefore exiting 0 finding-free) — and, +// once the four have run, every file outside `.xspec/` but the +// configuration file is byte-identical to the twin's: the generated modules +// and the emitted Markdown, graph data, whose opaque content a differing +// configuration file may change, not compared (as in T7-8), and the lock +// path with it (H-6). Standard error is not compared: its wording is free +// (12.0). P-19 holds each of its draws to these same assertions (TEST-SPEC +// P-19: "under T7-9's assertions") and compares alike. The URL arm's network +// is the one every product invocation has: CI's Linux jobs run +// network-denied (E-1; .github/scripts/run-without-network.sh), so a product +// fetching the specifier fails there; the harness adds no denial of its own. +// +// Staging (CERTIFICATIONS.md, Exclusions, "T7-9 and T7-10"; §CONF-IMPORT's +// two staging hazards): a literal reaches its file exactly as spelled. Every +// arm's configuration is the shared builder's `configImportText` over the +// literal — three strings joined, nothing printed, decoded, or re-quoted — +// the one path P-19's draws are staged through, so that (a)'s +// escape-spelled, line-continuation, single-quoted, and raw-U+FFFD arms ride +// CONF-IMPORT's certification of P-19 representatively. Every backslash is +// the builder's `BACKSLASH`, built from code point U+005C, and every line +// feed is built from its code point, so this module's source spells no +// escape at all. A module-load self-check (`assertStagedAsSpelled`) pins +// each record's bytes: the builder's head, the literal, and the builder's +// tail, nothing else; the literal delimited by its arm's quote; and the +// literal holding exactly the backslashes, line feeds, and U+FFFD its arm +// spells, each escape at its place — so a staging that decoded, re-quoted, +// or re-spelled a literal fails at load, a harness error, never an arm that +// equals its twin for every product. +// +// (b) Scanner-rejected escapes (`T7_9_B_ARMS`): the specifier a hexadecimal +// escape with one hex digit, a braced Unicode escape of the code point +// 110000 hexadecimal (past U+10FFFF), an octal escape (a backslash, `0`, +// `1`), and a backslash before `8` — each a scanning error of TypeScript +// 5.9.3 under both readings, so each record is declared unparseable and S-9 +// verifies it so before any product exists +// (test/self/s9-staged-sources.test.ts; each escape's one scanning error is +// pinned in test/self/s9-typescript-well-formedness.test.ts). Each leaves +// the file not well-formed (14.20): `build`, `check`, `ids`, and +// `inventory`, each under `--json`, are held to the shared 14.14 contract +// (support.ts `expectConfigurationError`: exit 2, the 12.7 error document as +// the whole of standard output, a standard-error diagnostic naming the +// configuration), the document's one finding exactly `code` +// `"configuration-error"`, `path` `"xspec.config.ts"` — the file the upward +// search found, anchored at the workspace root (T12.7-3) — and `locations` +// `[]`, a configuration condition carrying no in-source location (SPEC 14). +// +// (c) Designations (`T7_9_C_ARMS`): seven configurations, each differing +// from the twin's in the specifier alone, a double-quoted relative path +// designating, from the configuration file's directory (the workspace +// root): nothing (`"./nowhere.js"`); a plain file the environment refuses +// to read (`"./locked.js"`, an ES module defining `defineConfig`, staged +// mode 0o200 by `stageReadRefusalOfFile` — T14-10's discipline, Linux leg: +// its content refused, its write kept — and its kind verified still +// examinable); a path below a directory stripped of its read and search +// permission both (`"./sealed/define.js"`, `sealed/` holding that module, +// staged mode 000 by `stageDirectoryMode` — T14-10(l)'s discipline, Linux +// leg: the directory's listing, the entry's kind, and its content each +// refused); a FIFO (`"./fifo"`, made by `stageFifo` and never opened by the +// harness); a directory (`"./specs"`, the sources' own); and the +// configuration file itself, spelled `"./xspec.config"` and +// `"./xspec.config.ts"`. Each staging is made once the arm's workspace +// stands, before its first command, and verifies itself on the harness +// (E-1: a privileged runner, whose own read reaches the refused object, is +// the harness error `HarnessStagingError`, never a verdict); a permission +// staging stands around the arm's four commands and is restored before the +// compare. Each arm runs (a)'s four commands and compares as (a) does, its +// designated entry — the staged file, directory, or FIFO, which the twin's +// workspace does not hold — pruned from the file compare beside graph data +// and the configuration file: discovery under the one glob `specs/*.mdx` +// never examines a root-level entry but `specs` (SPEC 7), so the answers +// are the twin's. After each command of the FIFO arm, the FIFO is still a +// FIFO in place (`assertFifosIntact`), and the command ended within its own +// guard: with termination, that is all "unopened" asserts (S-3; a product +// opening a FIFO with no writer blocks until its guard kills it). A read +// on the specifier's account that the product survives reaches nothing +// H-2's channel observes and admits no discriminating staging (TEST-SPEC +// T7-9(c)), so nothing is recorded for it. Every (c) record — the seven +// configurations and the two modules — is a staged-source record made at +// module load and declared well-formed (S-9); each configuration's bytes +// are pinned as (a)'s are (`assertStagedAsSpelled`), and its literal +// against the path its arm stages at (`assertDesignates`). +// +// (d) Installs (SPEC 7: no command's outcome depends, through a +// configuration's import, on the `defineConfig` module or on whether a +// project installed it; 7.6: no name is privileged). The configuration +// imports from `"N"`, double-quoted, beside one of two stagings +// (`T7_9_D_KINDS`) at `node_modules/N`, where resolving `N` from the +// configuration file's directory, the workspace root, looks: a trap +// package — its manifest (`trapManifest`) giving `N` as its `name` and +// naming `index.js` as its entry (`main`, and `exports`), the entry +// (`TRAP_ENTRY`, a CommonJS module, so that it parses as script code too, +// S-9), if loaded, writing the marker `t7-9-trap-marker` at the workspace +// root (the parent of its own nearest `node_modules` ancestor, and nowhere +// where it has none), printing a line holding `TRAP_TELL` on each stream, +// and exiting 113 — and, separately, a `node_modules/N` holding only its +// `package.json`, a FIFO (`stageFifo`, never opened by the harness). Each +// is staged under three names: `trap` and `xspec`, the executable's name +// (`T7_9_D_FIXED_NAMES`); and the `name` the module channel's package +// manifest gives (`thirdInstallName`), read as T7.6-4(a) reads it +// (helpers/module-channel.ts `modulePackageDirectory`: +// the binding's package directory checked as every test of 7.6 checks it, +// its `package.json` read strictly by `readManifestName`), wherever that is +// a name of 7.6's grammar (`moduleNameGrammarProblem`; 7.6's exclusions +// concern TypeScript's and Node.js's resolution, which no command +// performs, so none applies) — staged once where it is `trap` or `xspec` +// (TEST-SPEC: the last two coinciding where it is `xspec`), and not at all +// where the manifest gives no such name, as TEST-SPEC stages it only where +// it is one. That name's configuration, known only once the package +// directory is read, is composed through `configImportText` and judged by +// S-9's TypeScript check, as module and as script code, before anything is +// staged (`composedInstallConfig`, as T7.6-4(a)'s composed files are), then +// staged under the per-draw declaration (`ts.perDraw`: judged again at +// staging, no module-level record being able to hold it); the fixed +// names' configurations are records. With no package directory given — +// or, on the built product's binding, one that does not exist — that +// name's two arms each fail as a diagnosed assertion failure naming the +// missing package directory: the module channel counts as part of the +// product (H-8), and an arm is never skipped (H-9) — a conservative +// choice, TEST-SPEC naming no outcome for a name it cannot read. +// +// Each name's twin — the same configuration and sources, holding no +// `node_modules` — runs first, in a workspace of its own, T7-8's +// representative commands (`T7_9_D_COMMANDS`): `build`, `check`, `ids`, +// `view specs/A.mdx`, `inventory`, `review list`, and `rename specs/A.mdx a +// b`, each under `--json`, in that order, the files each writes taken as +// T7-8 takes them (the workspace's snapshots around the run, the lock path +// pruned, H-6). Then each kind's arm runs them in its own fresh workspace, +// and after each command asserts: no marker at the workspace root, and +// neither standard output nor standard error holding `TRAP_TELL`; the +// FIFO, where staged, still a FIFO in place (`assertFifosIntact`), the +// command having ended within its own guard — all that "unopened" asserts +// (S-3); the exit outcome and standard output equal to the twin's same +// command's; the files it wrote byte-equal to those the twin's wrote +// (`assertWriteDeltasEqual`, graph data included, the two configurations +// being byte-identical; the lock path aside, H-6); and the outcome such a +// workspace gives it (H-5) — `build` and `check` exit 0 finding-free, `ids` +// 0 with its listing (`a` in `specs/A.mdx`, `b` in `specs/B.mdx`), `view` +// and `inventory` 0 finding-free, `review list` 0 listing no session and +// no finding, and the `rename` 0 with its applied mapping `specs/A.mdx#a` +// to `specs/A.mdx#b` — so that the arm stays red against S-7's stub, whose +// runs equal its twin's. +// +// Every arm runs: each arm's diagnosed failure (a `HarnessAssertionError`, +// its message naming the arm) is collected, and the body fails once at the +// end naming every failed arm, so one run diagnoses every spelling, +// designation, and install; a harness error or a hang propagates at once — +// a (c) or (d) arm's hang renamed for its arm and command, the driver's +// kill kept as its cause, so the certification runner still records the +// hang it is (helpers/hang-guards.ts `isHangGuardKill`; S-3: a tripped +// guard ends its test). Certification: T7-9 is in no +// conformer's scope (CERTIFICATIONS.md, Exclusions, "T7-9 and T7-10": its +// operative assertions are positive, each failing loud against the product +// it targets; every FIFO, (d)'s manifest among them, is asserted afterwards +// still a FIFO in place, so a staging whose effect misses fails loud). +// +// T7-10, the configuration file as a source (SPEC 7: the rules of 4 and +// 14.15 reach the configuration file only where a configured group +// discovers it, and xspec then analyzes it as it does every source it +// discovers, its import declaration included, while the configuration +// itself stays valid). The workspace (T7-10's opening): T7-9's but for +// `specs/B.mdx` — the one spec group `main` globbing `specs/*.mdx` over +// `specs/A.mdx` (`<S id="a">A</S>`, T7-9's record of those bytes), Markdown +// emitted next to sources — its configuration importing, one arm each +// (`T7_10_SPECIFIERS`), from `"./specs/A.xspec"` (a spec module import +// binding `defineConfig`, neither the default nor the `text` export), +// `"./missing.xspec"` (designating no discovered spec source), +// `"./specs/A.xspec.ts"` and `"./.xspec/x"` (relative specifiers +// designating derived-file paths, 13.4), and `"./specs/A.md"` (the Markdown +// emit destination of `specs/A.mdx` while emission is enabled, 7.3). Every +// configuration is a staged-source record made at module load and +// declared well-formed (S-9) — but (d)'s not-well-formed baseline's, +// declared unparseable — composed through the shared builder's head +// (`CONFIG_IMPORT_HEAD`); none of these literals spells an escape but that +// baseline's, built from `BACKSLASH` (checked at load). +// +// (a) Undiscovered (`T7_10_A_ARMS`): T7-9's configuration over each +// specifier (`configImportText`), no code group at all, so no configured +// group matches the configuration file: `build` and `check`, each under +// `--json`, exit 0 finding-free — a product applying a source's import +// rules to every configuration reports 14.15 there. +// +// (b) Discovered (`T7_10_B_STAGINGS`): the same configuration with one code +// group, `app`, globbing `*.ts` and, separately, `xspec.config.ts` (a code +// group's glob between `specs` and `markdown`, `discoveredTail`), so that +// the configuration is a code source. Each group's control runs first: +// importing from `"xspec"`, the discovered configuration is clean — `build` +// and `check` exit 0 finding-free — and its whole-file location exists +// (`query edges --from xspec.config.ts` exits 0 with one JSON document, +// T7-3's idiom). Then each specifier's arm: `build` and `check`, each under +// `--json`, exit 1 — never 2, the configuration staying valid — reporting +// 14.15 and, in the two `.xspec` arms (`specModule`: the declaration a spec +// module import, so `defineConfig` a spec-module binding and its call a +// value-level use 4.5 does not sanction), 14.18, and no other finding. +// TEST-SPEC pins no count ("each such finding": the `"./missing.xspec"` +// declaration is invalid on two counts, its target and its binding), so +// each condition is asserted reported at least once, every finding of it +// located exactly: a 14.15 finding carries the stable code +// `"invalid-import"` and the one location of the configuration's import +// declaration by its own characters, the import range of 11.4 — the file's +// first bytes, `import` through the specifier's closing quote, no +// terminator spelled (SPEC 14, 1.7) — and a 14.18 finding the stable code +// `"unsupported-node-usage"` and the one location of `defineConfig`'s +// spelling at its call, the default export's callee (SPEC 14: the +// binding's identifier at the offending use; no property chain follows +// it); each `path` `null` (12.7). Both ranges are composed from the +// record's parts and self-checked at module load (`sourceConfig`). +// `inventory --json` then exits 0 with no finding, listing +// `xspec.config.ts` once among its `sources`, in the code group `app` +// alone (11.6). +// +// (c) Consequences (`T7_10_C_ARMS`), each on the discovered configuration — +// under each of (b)'s two code groups (`T7_10_C_STAGINGS`) — beside its +// undiscovered twin, which differs from it by the code group alone in every +// configuration it stages (`T7_10_C_TWINS`): +// - The gate. After a successful `build --json` under the control's +// `"xspec"`, the configuration is restaged importing from +// `"./missing.xspec"` ((b)'s record for that group, through `file()`): +// `build --json` exits 1 reporting (b)'s findings for that arm, 14.15 and +// 14.18, and modifies nothing — a whole-root compare around it, so every +// derived file and all graph data byte-identical to the state before it +// (12.1) — and the gated reads, `ids --json` and `query nodes` (a +// JSON-only surface, 11), each exit 1 reporting exactly `build`'s +// findings — every member but the message, in 12.7's order +// (`gateComparable`, T12.0-10's projection) — and modify nothing (13.3). +// The twin, built under T7-9's twin configuration and restaged importing +// from `"./missing.xspec"` ((a)'s record): `build --json` exits 0 +// finding-free, and `ids --json` and `query nodes` answer, exit 0 with +// one JSON document each. +// - The designation. Importing from `"./specs/B.md"` — no `specs/B.mdx` +// existing, so the specifier designates no derived-file path and the +// workspace is valid — before any build, `move specs/A.mdx specs/B.mdx +// --json` is refused inside a whole-root compare: exit 1 and exactly one +// `refused-invalid-destination` finding, `path` the destination as +// spelled and `locations` `[]` (T6.5-20's contract), the destination's +// would-be emit path `specs/B.md` designated by the configuration's +// specifier, a code source's module-linking form (6.5, as T6.5-20(d) +// stages one). The twin moves: exit 0, its applied mapping `specs/A.mdx` +// to `specs/B.mdx` and `specs/A.mdx#a` to `specs/B.mdx#a` (6.5, 12.7), +// `specs/B.mdx` then holding the moved bytes and `specs/A.mdx` gone. +// - The baseline. A repository at the workspace root (the builder's +// scripted commits, H-1) whose commit `c1` holds the discovered +// configuration importing from `"./missing.xspec"` beside `specs/A.mdx`, +// the working tree then taking the control's configuration back, valid +// (`build --json` exits 0 finding-free, the premise): `impact --base c1 +// --json` and `review create --base c1 --name n --json` each fail as +// T6.3-4's baseline failing validation does — exit 2, the 12.7 error +// document the whole of standard output, its `code` and `path` `null`, +// standard error naming the offending file `xspec.config.ts` (6.3) — and +// `review create` modifies nothing, no session written (a whole-root +// compare, `.git/` included; 10.7). The twin's commit — no code group in +// `c1`'s configuration or the working tree's, T7-9's twin configuration +// — resolves: `impact --base c1 --json` exits 0 with one impact report +// (decoded through H-3's adapter), and `review create --base c1 --name n +// --json` exits 0. +// - The converse (6.5 reaching no undiscovered configuration): importing +// from `"./specs/A.xspec"` undiscovered ((a)'s record), `move specs/A.mdx +// specs/B.mdx --preview --json` exits 0, its preview document (decoded +// form-exact, 6.6) listing no edit in `xspec.config.ts`; the `move --json` +// exits 0 with the applied mapping above, `xspec.config.ts` byte-identical +// to its staged bytes afterwards — its import never rewritten to +// `"./specs/B.xspec"`; and `build --json` and `check --json` then exit 0 +// finding-free. Its discovered twin ((b)'s record), invalid per (b): the +// `move --json` is refused as 6.4's invalid workspace inside a whole-root +// compare — exit 1, (b)'s findings for that arm alone +// (`assertSourceFindings`). +// Every modifies-nothing compare is the shared compare-around-command +// protocol (helpers/snapshot.ts `assertLeavesUnchanged`), H-6's lock-path +// exclusion applied around the mutating `move` and `review create`. +// +// (d) Baselines (`T7_10_D_ARMS`; SPEC 7: a baseline's configuration, 6.3, +// is read alike). Each arm's workspace is a repository at the workspace +// root (the builder's scripted commits, H-1) whose commit `c1` holds an +// undiscovered configuration — T7-9's, no code group — importing from +// `""`, `"./nowhere"`, `"XSPEC"`, `"./fifo"`, or `"trap"`, one arm each, +// beside `specs/A.mdx` holding `<S id="a">Old A</S>` +// (`T7_10_D_C1_SOURCE`); the working tree then takes T7-9's twin +// configuration, importing from `"xspec"`, and T7-10's source, `<S +// id="a">A</S>` — its sources differing from `c1`'s by one section's edited +// text, its workspace valid (a premise `build --json`, exit 0 +// finding-free) — and, what the specifier designates varied as T7-9(c) and +// (d) vary it for the current configuration, the FIFO arm a FIFO at `fifo` +// (`stageFifo`, never opened by the harness) and the trap arm T7-9(d)'s +// trap package at `node_modules/trap` (`trapManifest` and `TRAP_ENTRY`), +// each staged in the working tree alone, once `c1` is committed and the +// premise has run. `impact --base c1 --json` exits 0, its impact +// information — the report decoded through H-3's adapter but for the +// baseline a product may echo: categories with their attributions, +// collapsed chains, deleted and added identities, and each impacted +// location with its witness edge and path (9.3) — reporting the edited +// section `specs/A.mdx#a` `changed` (5.6) and equal to that against the +// twin commit; the reports are never compared byte for byte, the two +// commits' identities differing (E-6). In the FIFO and trap arms, `review +// create --base c1 --name n --json` and then `review status n --json` +// (which resolves and reconstructs the recorded baseline, reading its +// configuration again, 10.7) each exit 0, the items `status` reports — +// their kinds, scopes, statuses, and blocked states, in item order (10.5) +// — equal to the twin's. After each of those commands, the FIFO is still a +// FIFO in place (`assertFifosIntact`), the command having ended within its +// own guard (S-3; a hang renamed for its arm, as (c)'s are), and no trap +// marker stands at the workspace root and neither stream carries the +// trap's tell (`assertTrapNeverRan`). The twin (`runBaselineReadTwin`) runs +// first, in a workspace of its own: `c1` importing from `"xspec"` beside +// the same source, the working tree the arms' but for the FIFO and the +// trap (as T7-9(d)'s twin holds no `node_modules`: discovery under +// `specs/*.mdx` examines no root-level entry but `specs`, SPEC 7, so +// neither reaches a conforming product's answer). It runs the three +// commands, its answers each arm's comparison basis; its diagnosed failure +// is collected as an arm of its own, each comparison then failing +// diagnosed. And a commit whose configuration spells T7-9(b)'s hexadecimal +// escape with one hex digit as its specifier (`T7_10_D_ESCAPE`, its +// backslash `BACKSLASH`, declared unparseable, S-9, and pinned as T7-9's +// records are), the working tree's configuration and sources valid as +// above: `impact --base c1 --json` fails as T6.3-4's baseline whose +// configuration fails validation does — exit 2, the error document's +// `code` and `path` `null`, standard error naming `xspec.config.ts` (6.3, +// 14.20). +// +// (e) Discovered by a spec group (`T7_10_E_FAMILIES`; SPEC 2.1, 7.1): the +// configuration imports from `"xspec"`, its default export spelled with no +// blank line inside it, so that, read as MDX, its import and its export +// each derive as an ESM block (14.20) — MDX 3 reads a flow line beginning +// `import` or `export` as an ESM block running to the next blank line, and +// one blank line follows the import's. (i) `xspec.config.ts`, the spec +// group `main` globbing `specs/*.mdx` and `xspec.config.ts` and, +// separately, `specs/*.mdx` and `*.ts`, is a spec-group file without the +// `.mdx` extension: `build` and `check`, each under `--json`, exit 1, never +// 2, reporting 14.19 concerning it (`"invalid-source-path"`, its `path` +// the file's, `locations` `[]`) and — its content analyzed as a spec +// source's, an invalid path masking nothing (SPEC 14) — 14.15 +// (`"invalid-import"`) at its import declaration by the import range of +// 11.4, the file's first bytes, `import` through the specifier's closing +// quote, and 14.16 (`"invalid-construct"`) at its export statement whole, +// `export` through the call's closing parenthesis, the line feed ending +// the file excluded (SPEC 14), each `path` `null`; `inventory --json` exits +// 0 listing `xspec.config.ts` once among its `sources`, in `main` alone, +// its `derived` entry's `module` and `markdown` `null` (13.1, 11.6; +// T7.1-1). (ii) `xspec.config.mdx`, given by `--config xspec.config.mdx` +// on every invocation, no `xspec.config.ts` existing — judged as plain +// TypeScript, the grammar its name selects (14.20) — and matched by the +// spec glob `*.mdx` beside `specs/*.mdx`, is a spec source: `build` and +// `check` exit 1, never 2, reporting 14.15 at its import declaration (2.1: +// a named binding, its specifier designating no spec source) and 14.16 at +// its export statement (2.7), located as in (i); `inventory` exits 0 +// listing it once among its `sources`, in `main` alone, its `derived` +// entry's `module` its generated-module path, `xspec.config.xspec.ts` +// (13.1). TEST-SPEC pins no count and names no other finding, so each +// named condition is asserted reported at least once, every finding of it +// located exactly, and no other finding is examined. Each family's +// undiscovered twin runs first, in a workspace of its own — the spec group +// globbing `specs/*.mdx` alone: (i)'s T7-9's twin configuration at +// `xspec.config.ts`, (ii)'s the same bytes at `xspec.config.mdx`, given by +// `--config` — its `build` and `check`, each under `--json`, exiting 0 +// finding-free. A configuration a spec group discovers is read both as a +// configuration (plain TypeScript) and as a spec source (MDX), and (ii)'s +// twin, an `.mdx` path, is judged as MDX by the builder's default: each is +// an MDX staged-source record carrying its TypeScript declaration, declared +// well-formed under each grammar (S-9; helpers/staged-mdx.ts). Both ranges +// are composed from the record's parts and self-checked at module load +// (`specDiscoveredArm`); the MDX parse S-9 judges by and TypeScript 5.9.3's +// parser give the same spans (`[0, 36)` and `[38, 158)` for (i)'s first +// configuration). +// +// Every T7-10 arm builds its own fresh workspace (H-1); its diagnosed +// failure is collected and the body fails once at the end naming every +// failed arm, a harness error or a hang propagating at once, as in T7-9. +// Certification: T7-10 is in no conformer's scope (CERTIFICATIONS.md, +// Exclusions, "T7-9 and T7-10": its findings for the discovered +// configuration — (b)'s 14.15 and 14.18, and (e)'s 14.19, 14.15, and 14.16 +// — its gated reads, its refused `move`, and its failing baselines, each +// beside its undiscovered twin's clean outcome, and each +// baseline configuration of (d) answering exactly as its `"xspec"` twin, +// fail loud against the product each targets, (d)'s FIFO asserted +// afterwards still a FIFO in place; the converse's unrewritten import is +// braced by its discovered twin's refusal over the same import; and the +// modifies-nothing compares share the compare-around machinery +// VIOL-CORE-CHATTYREADS certifies). + +import { Buffer } from "node:buffer"; +import type { + AppliedMappingPair, + Finding, + SourceRange, +} from "../../helpers/adapters/index.js"; +import { + decodeAppliedMappingReport, + decodeFindingsReport, + decodeIdsReport, + decodeImpactReport, + decodeInventoryDocument, + decodePreviewReport, + decodeSessionListReport, + decodeSessionStatusReport, + decodeViewReport, + pathValueBytes, + renderPathValue, +} from "../../helpers/adapters/index.js"; +import { + assertBytesEqual, + assertExitCode, + assertFileBytes, + fail, + HarnessAssertionError, + parseJsonStdout, +} from "../../helpers/assertions.js"; +import { + BACKSLASH, + CONFIG_IMPORT_CONFIG_PATH, + CONFIG_IMPORT_HEAD, + CONFIG_IMPORT_SOURCES, + CONFIG_IMPORT_TAIL, + CONFIG_IMPORT_TWIN_CONFIG, + CONFIG_IMPORT_TWIN_LITERAL, + configImportText, +} from "../../helpers/config-import.js"; +import type { WriteDeltaLabels } from "../../helpers/determinism.js"; +import { assertWriteDeltasEqual } from "../../helpers/determinism.js"; +import { isHangGuardKill } from "../../helpers/hang-guards.js"; +import { EXCLUDE_LOCK_PATH } from "../../helpers/lock-path.js"; +import type { StagedLeftover } from "../../helpers/lock-staging.js"; +import { assertFifosIntact, stageFifo } from "../../helpers/lock-staging.js"; +import { + moduleNameGrammarProblem, + modulePackageDirectory, +} from "../../helpers/module-channel.js"; +import { + HarnessStagingError, + stageDirectoryMode, + stageReadRefusalOfFile, +} from "../../helpers/permissions.js"; +import type { DirectoryModeProbe } from "../../helpers/permissions.js"; +import { defineProductTest } from "../../helpers/registry.js"; +import type { ProductTestEntry } from "../../helpers/registry.js"; +import type { + DirectorySnapshot, + SnapshotChange, + SnapshotOptions, +} from "../../helpers/snapshot.js"; +import { + assertLeavesUnchanged, + assertSnapshotsEqual, + diffSnapshots, + snapshotDirectory, +} from "../../helpers/snapshot.js"; +import { stagedMdx } from "../../helpers/staged-mdx.js"; +import type { StagedMdx } from "../../helpers/staged-mdx.js"; +import { stagedTs } from "../../helpers/staged-ts.js"; +import type { StagedTs } from "../../helpers/staged-ts.js"; +import { guardSyncStep } from "../../helpers/step-guards.js"; +import type { ProductBinding, RunResult } from "../../helpers/subprocess.js"; +import { runProduct, summarizeResult } from "../../helpers/subprocess.js"; +import { + judgeTypeScript, + tsDeclarationProblem, +} from "../../helpers/ts-derivability.js"; +import { TestWorkspace } from "../../helpers/workspace.js"; +import type { EntryKind, WorkspaceDecl } from "../../helpers/workspace.js"; +import { + assertAppliedMapping, + assertSameJson, + expectConfigurationError, + expectErrorDocument, + REPLACEMENT_CHARACTER, +} from "./support.js"; + +// --------------------------------------------------------------------------- +// Code points and spellings + +/** U+000A, built from its code point (the module spells no escape). */ +const LINE_FEED = String.fromCodePoint(0x0a); +/** U+0022 and U+0027, the two quote styles of a static string literal. */ +const DOUBLE_QUOTE = '"'; +const SINGLE_QUOTE = "'"; + +/** How many times `piece` occurs in `text` (non-overlapping). */ +function occurrences(text: string, piece: string): number { + return text.split(piece).length - 1; +} + +// --------------------------------------------------------------------------- +// The arms' configurations + +/** + * What an arm's literal spells, pinned at module load + * (`assertStagedAsSpelled`): its quote, and how many backslashes, line + * feeds, and U+FFFD it holds; and, for an escape, the escape's spelling and + * the code-unit index at which it stands in the literal. + */ +interface Spelled { + readonly quote: string; + readonly backslashes: number; + readonly lineFeeds: number; + readonly replacements: number; + readonly escape?: { readonly spelling: string; readonly at: number }; +} + +/** A literal with no escape, no line feed, and no U+FFFD. */ +const PLAIN_DOUBLE: Spelled = { + quote: DOUBLE_QUOTE, + backslashes: 0, + lineFeeds: 0, + replacements: 0, +}; + +/** One arm of T7-9's (a) or (b). */ +interface ImportArm { + /** The arm as diagnoses name it — every escape named in words. */ + readonly label: string; + /** The specifier exactly as it stands in the file, its quotes included. */ + readonly literal: string; + /** What `literal` spells (module header). */ + readonly spelled: Spelled; + /** The configuration over `literal`, a staged-source record (S-9). */ + readonly config: StagedTs; +} + +/** An (a) arm: its configuration declared well-formed (14.20, S-9). */ +function spellingArm( + label: string, + literal: string, + spelled: Spelled, +): ImportArm { + return { + label, + literal, + spelled, + config: stagedTs( + `T7-9 xspec.config.ts ((a) importing from ${label})`, + configImportText(literal), + ), + }; +} + +/** + * A (b) arm: `escape` the whole of a double-quoted specifier, the + * configuration declared unparseable (14.20, S-9). + */ +function rejectedEscapeArm(label: string, escape: string): ImportArm { + const literal = DOUBLE_QUOTE + escape + DOUBLE_QUOTE; + return { + label, + literal, + spelled: { + ...PLAIN_DOUBLE, + backslashes: 1, + escape: { spelling: escape, at: 1 }, + }, + config: stagedTs( + `T7-9 xspec.config.ts ((b) importing from a specifier holding ${label}, a scanning error)`, + configImportText(literal), + "unparseable", + ), + }; +} + +/** + * T7-9(a)'s eleven spellings (TEST-SPEC T7-9(a)), each a configuration + * differing from the twin's in the specifier alone. + */ +export const T7_9_A_ARMS: readonly ImportArm[] = [ + spellingArm( + 'the bare name "XSPEC", a single-casing arm (12.0: no case folding)', + '"XSPEC"', + PLAIN_DOUBLE, + ), + spellingArm('the bare name "left-pad"', '"left-pad"', PLAIN_DOUBLE), + spellingArm('the scoped name "@acme/config"', '"@acme/config"', PLAIN_DOUBLE), + spellingArm( + 'the relative path "./lib/define.js"', + '"./lib/define.js"', + PLAIN_DOUBLE, + ), + spellingArm( + 'the absolute path "/opt/define.mjs"', + '"/opt/define.mjs"', + PLAIN_DOUBLE, + ), + spellingArm( + 'the URL "https://example.com/define.js", under the denied network every product invocation has (E-1)', + '"https://example.com/define.js"', + PLAIN_DOUBLE, + ), + spellingArm('the empty string ""', '""', PLAIN_DOUBLE), + spellingArm("the single-quoted 'xspec'", "'xspec'", { + ...PLAIN_DOUBLE, + quote: SINGLE_QUOTE, + }), + spellingArm( + "an escape sequence: xspec with its x written as the hexadecimal escape of U+0078 (a backslash, x, 7, 8)", + `"${BACKSLASH}x78spec"`, + { + ...PLAIN_DOUBLE, + backslashes: 1, + escape: { spelling: `${BACKSLASH}x78`, at: 1 }, + }, + ), + spellingArm( + "a line continuation: xs, a backslash, U+000A, then pec", + `"xs${BACKSLASH}${LINE_FEED}pec"`, + { + ...PLAIN_DOUBLE, + backslashes: 1, + lineFeeds: 1, + escape: { spelling: BACKSLASH + LINE_FEED, at: 3 }, + }, + ), + spellingArm( + "a raw U+FFFD: x, U+FFFD, then spec", + `"x${REPLACEMENT_CHARACTER}spec"`, + { ...PLAIN_DOUBLE, replacements: 1 }, + ), +]; + +/** + * T7-9(b)'s four scanner-rejected escapes (TEST-SPEC T7-9(b); SPEC 7, 14.20), + * each the whole of a double-quoted specifier. + */ +export const T7_9_B_ARMS: readonly ImportArm[] = [ + rejectedEscapeArm( + "a hexadecimal escape with one hex digit (a backslash, x, then 4)", + `${BACKSLASH}x4`, + ), + rejectedEscapeArm( + "a braced Unicode escape of the code point 110000 hexadecimal, past U+10FFFF (a backslash, u, then 110000 in braces)", + `${BACKSLASH}u{110000}`, + ), + rejectedEscapeArm( + "an octal escape (a backslash, 0, then 1)", + `${BACKSLASH}01`, + ), + rejectedEscapeArm("a backslash before 8", `${BACKSLASH}8`), +]; + +/** + * What a (c) arm stages once its workspace stands, verified on the harness + * itself before the arm's first command (module header). + */ +interface DesignationStaging { + /** Reinstate what the staging changed (a permission staging's mode). */ + readonly restore: () => Promise<void>; + /** + * After each command: the staging still in place where TEST-SPEC asserts + * it — the FIFO still a FIFO in place. + */ + readonly afterCommand: (context: string) => Promise<void>; +} + +/** One arm of T7-9's (c): what its specifier designates, and its staging. */ +interface DesignationArm extends ImportArm { + /** + * The workspace-relative path the specifier designates from the + * configuration file's directory, the workspace root: the literal is + * exactly `"./<target>"` (pinned at module load, `assertDesignates`). + */ + readonly target: string; + /** The arm's own files, beside the configuration and the two sources. */ + readonly files: Readonly<Record<string, StagedTs>>; + /** + * The top-level entry the arm stages beyond the twin's workspace — the + * file, directory, or FIFO at or above `target` — pruned from the file + * compare; none where the arm stages nothing. + */ + readonly staged?: string; + /** The staging made at `staged` once the workspace stands. */ + readonly stage?: (workspace: TestWorkspace) => Promise<DesignationStaging>; +} + +/** + * The module `"./locked.js"` and `"./sealed/define.js"` designate: a plain + * ES module defining `defineConfig` as the identity, which no conforming + * product reads (module header). + */ +const DESIGNATED_MODULE_TEXT = + "export function defineConfig(config) {" + + LINE_FEED + + " return config;" + + LINE_FEED + + "}" + + LINE_FEED; + +/** The plain file whose content `"./locked.js"`'s arm refuses. */ +const LOCKED_PATH = "locked.js"; +/** The directory `"./sealed/define.js"`'s arm strips (mode 000). */ +const SEALED_DIR = "sealed"; +/** The plain file under `sealed/` that `"./sealed/define.js"` designates. */ +const SEALED_ENTRY = "define.js"; +/** The FIFO `"./fifo"` designates. */ +const FIFO_PATH = "fifo"; + +const LOCKED_MODULE: StagedTs = stagedTs( + 'T7-9 locked.js ((c) the plain file "./locked.js" designates, its content refused: an ES module defining defineConfig)', + DESIGNATED_MODULE_TEXT, +); + +const SEALED_MODULE: StagedTs = stagedTs( + 'T7-9 sealed/define.js ((c) the plain file "./sealed/define.js" designates, below sealed/ of mode 000: an ES module defining defineConfig)', + DESIGNATED_MODULE_TEXT, +); + +/** A staging with nothing to undo or recheck. */ +const NOTHING_TO_UNDO = async (): Promise<void> => undefined; + +/** + * `"./locked.js"`'s staging (module header; TEST-SPEC T7-9(c), T14-10's + * discipline, Linux leg): its content read refused and its write kept + * (`stageReadRefusalOfFile`, mode 0o200, verified on the harness itself), + * and its kind still examinable — the harness's own examination, never + * following a link, finds the plain file still there. + */ +async function stageLockedFile( + workspace: TestWorkspace, +): Promise<DesignationStaging> { + const staging = await stageReadRefusalOfFile(workspace.path(LOCKED_PATH)); + let kind: EntryKind | undefined; + let examination = ""; + try { + kind = await workspace.kind(LOCKED_PATH); + } catch (thrown) { + examination = thrown instanceof Error ? thrown.message : String(thrown); + } + if (kind !== "file") { + await staging.restore(); + throw new HarnessStagingError( + "read-refusal-of-file", + workspace.path(LOCKED_PATH), + "T7-9(c) refuses its content alone, its kind still examinable, but " + + "the harness's own examination of it " + + (kind === undefined + ? `failed — ${examination}` + : `found ${kind}, not a plain file`) + + " (E-1)", + ); + } + return { + restore: () => staging.restore(), + afterCommand: NOTHING_TO_UNDO, + }; +} + +/** + * T14-10(l)'s verification of `sealed/` stripped of its read and search + * permission both: the harness's own listing of it, examination of + * `define.js`'s kind, and read of `define.js`, each refused. + */ +const SEALED_PROBES: readonly DirectoryModeProbe[] = [ + { attempt: "list", refused: true }, + { attempt: "examine", name: SEALED_ENTRY, refused: true }, + { attempt: "read", name: SEALED_ENTRY, refused: true }, +]; + +/** + * `"./sealed/define.js"`'s staging (module header; TEST-SPEC T7-9(c), + * T14-10(l)'s discipline, Linux leg): `sealed/` given mode 000 by + * `stageDirectoryMode`, every route to the designated path refused and + * verified so on the harness itself. + */ +async function stageSealedDirectory( + workspace: TestWorkspace, +): Promise<DesignationStaging> { + const staging = await stageDirectoryMode( + workspace.path(SEALED_DIR), + 0o000, + SEALED_PROBES, + ); + return { + restore: () => staging.restore(), + afterCommand: NOTHING_TO_UNDO, + }; +} + +/** + * `"./fifo"`'s staging (module header; TEST-SPEC T7-9(c), S-3): a FIFO made + * by `stageFifo`, verified a FIFO in place on the harness itself and never + * opened by it; after each command it is still a FIFO in place. + */ +async function stageDesignatedFifo( + workspace: TestWorkspace, +): Promise<DesignationStaging> { + const staged = await stageFifo(workspace, FIFO_PATH); + return { + restore: NOTHING_TO_UNDO, + afterCommand: async (context) => { + await assertFifosIntact( + staged, + `${context}: the FIFO "./fifo" designates is still a FIFO in ` + + "place, the command having ended within its own guard — " + + "unopened, as xspec never resolves, reads, or loads the " + + "specifier (SPEC 7; TEST-SPEC T7-9(c), S-3)", + ); + }, + }; +} + +/** A (c) arm: its configuration declared well-formed (14.20, S-9). */ +function designationArm( + label: string, + literal: string, + target: string, + staging: Pick<DesignationArm, "files" | "staged" | "stage"> = { + files: {}, + }, +): DesignationArm { + return { + label, + literal, + spelled: PLAIN_DOUBLE, + config: stagedTs( + `T7-9 xspec.config.ts ((c) importing from ${label})`, + configImportText(literal), + ), + target, + ...staging, + }; +} + +/** + * T7-9(c)'s seven designations (TEST-SPEC T7-9(c)), each a configuration + * differing from the twin's in the specifier alone, a double-quoted + * relative path. + */ +export const T7_9_C_ARMS: readonly DesignationArm[] = [ + designationArm( + 'the relative specifier "./nowhere.js", designating nothing', + '"./nowhere.js"', + "nowhere.js", + ), + designationArm( + 'the relative specifier "./locked.js", designating a plain file whose ' + + "content the environment refuses, its kind still examinable " + + "(T14-10's discipline, Linux leg)", + '"./locked.js"', + LOCKED_PATH, + { + files: { [LOCKED_PATH]: LOCKED_MODULE }, + staged: LOCKED_PATH, + stage: stageLockedFile, + }, + ), + designationArm( + 'the relative specifier "./sealed/define.js", designating a path below ' + + "sealed/, a directory of mode 000 holding define.js, every route to " + + "it refused (T14-10(l)'s discipline, Linux leg)", + '"./sealed/define.js"', + `${SEALED_DIR}/${SEALED_ENTRY}`, + { + files: { [`${SEALED_DIR}/${SEALED_ENTRY}`]: SEALED_MODULE }, + staged: SEALED_DIR, + stage: stageSealedDirectory, + }, + ), + designationArm( + 'the relative specifier "./fifo", designating a FIFO', + '"./fifo"', + FIFO_PATH, + { files: {}, staged: FIFO_PATH, stage: stageDesignatedFifo }, + ), + designationArm( + 'the relative specifier "./specs", designating a directory (the ' + + "sources' own)", + '"./specs"', + "specs", + ), + designationArm( + 'the relative specifier "./xspec.config", designating the ' + + "configuration file itself, its extension left off", + '"./xspec.config"', + "xspec.config", + ), + designationArm( + 'the relative specifier "./xspec.config.ts", designating the ' + + "configuration file itself", + '"./xspec.config.ts"', + CONFIG_IMPORT_CONFIG_PATH, + ), +]; + +/** + * The module-load self-check (module header): `arm`'s record holds the + * builder's head, the literal, and the builder's tail, nothing else, and the + * literal spells exactly what the arm states. A mismatch is a harness error + * thrown at load — the registry fails to load — never a product verdict. + * `test` names the arm's test in the diagnosis (T7-10(d) reuses the check). + */ +function assertStagedAsSpelled(arm: ImportArm, test = "T7-9"): void { + const { literal, spelled } = arm; + const problems: string[] = []; + if (arm.config.source !== CONFIG_IMPORT_HEAD + literal + CONFIG_IMPORT_TAIL) { + problems.push( + "its configuration is not the builder's head, the literal, and the " + + "builder's tail, joined", + ); + } + if ( + literal.length < 2 || + !literal.startsWith(spelled.quote) || + !literal.endsWith(spelled.quote) || + occurrences(literal, spelled.quote) !== 2 + ) { + problems.push( + `the literal is not delimited by ${JSON.stringify(spelled.quote)} ` + + "alone", + ); + } + const counts: ReadonlyArray<readonly [string, string, number]> = [ + ["backslashes (U+005C)", BACKSLASH, spelled.backslashes], + ["line feeds (U+000A)", LINE_FEED, spelled.lineFeeds], + ["U+FFFD", REPLACEMENT_CHARACTER, spelled.replacements], + ]; + for (const [what, piece, expected] of counts) { + const found = occurrences(literal, piece); + if (found !== expected) { + problems.push( + `the literal holds ${String(found)} ${what} where its arm spells ` + + String(expected), + ); + } + } + if ( + spelled.escape !== undefined && + literal.indexOf(spelled.escape.spelling) !== spelled.escape.at + ) { + problems.push( + "the literal's escape does not stand at code unit " + + String(spelled.escape.at), + ); + } + if (problems.length > 0) { + throw new Error( + `${test} ${arm.label}: the staged record ${JSON.stringify(arm.config.name)} ` + + `is not spelled as its arm states — ${problems.join("; ")} (module ` + + "header: a literal reaches its file exactly as spelled; the " + + `literal's code points: ${codePointsOf(literal)})`, + ); + } +} + +/** `text`'s code points, as `U+XXXX` each, for a diagnosis. */ +function codePointsOf(text: string): string { + return [...text] + .map( + (character) => + "U+" + + character.codePointAt(0)!.toString(16).toUpperCase().padStart(4, "0"), + ) + .join(" "); +} + +for (const piece of [CONFIG_IMPORT_HEAD, CONFIG_IMPORT_TAIL]) { + if ( + occurrences(piece, BACKSLASH) !== 0 || + occurrences(piece, REPLACEMENT_CHARACTER) !== 0 + ) { + throw new Error( + "T7-9: the configuration builder's head or tail holds a backslash or " + + "U+FFFD, so a literal's count of them no longer pins the file's " + + "(helpers/config-import.ts)", + ); + } +} +// The twin: the double-quoted `xspec` between the same head and tail, so +// that each arm's configuration differs from the twin's in the specifier +// alone (TEST-SPEC T7-9). +if ( + CONFIG_IMPORT_TWIN_LITERAL !== DOUBLE_QUOTE + "xspec" + DOUBLE_QUOTE || + CONFIG_IMPORT_TWIN_CONFIG.source !== + CONFIG_IMPORT_HEAD + CONFIG_IMPORT_TWIN_LITERAL + CONFIG_IMPORT_TAIL +) { + throw new Error( + "T7-9: the twin's record is not the builder's head, the double-quoted " + + "xspec, and the builder's tail, joined (helpers/config-import.ts)", + ); +} +for (const arm of [...T7_9_A_ARMS, ...T7_9_B_ARMS, ...T7_9_C_ARMS]) { + assertStagedAsSpelled(arm); +} + +/** Whether the workspace-relative `rel` is `entry` or lies below it. */ +function atOrBelow(rel: string, entry: string): boolean { + return rel === entry || rel.startsWith(entry + "/"); +} + +/** The twin's top-level entries (module header), which no arm stages. */ +const TWIN_ENTRIES: readonly string[] = [ + CONFIG_IMPORT_CONFIG_PATH, + ".xspec", + ...Object.keys(CONFIG_IMPORT_SOURCES).map((rel) => rel.split("/")[0]!), +]; + +/** + * The module-load self-check of a (c) arm (module header): its literal is + * exactly `"./<target>"`; and what it stages lies where its specifier + * designates — its one staged entry a top-level entry the twin's workspace + * does not hold, at or above `target`, made by a staging of its own, its + * files all at or below it. A mismatch is a harness error thrown at load. + */ +function assertDesignates(arm: DesignationArm): void { + const problems: string[] = []; + if (arm.literal !== DOUBLE_QUOTE + "./" + arm.target + DOUBLE_QUOTE) { + problems.push(`its literal is not "./${arm.target}", double-quoted`); + } + const { staged } = arm; + if ((staged === undefined) !== (arm.stage === undefined)) { + problems.push( + "it names a staged entry without a staging, or a staging without one", + ); + } + if (staged !== undefined) { + if (staged.includes("/") || TWIN_ENTRIES.includes(staged)) { + problems.push( + `its staged entry ${staged} is no top-level entry of its own beside the twin's`, + ); + } + if (!atOrBelow(arm.target, staged)) { + problems.push( + `the path it designates lies neither at nor below ${staged}`, + ); + } + } + for (const rel of Object.keys(arm.files)) { + if (staged === undefined || !atOrBelow(rel, staged)) { + problems.push(`its file ${rel} lies outside its staged entry`); + } + } + if (problems.length > 0) { + throw new Error( + `T7-9 ${arm.label}: the arm does not stage where its specifier ` + + `designates — ${problems.join("; ")} (module header)`, + ); + } +} + +for (const arm of T7_9_C_ARMS) { + assertDesignates(arm); +} + +// --------------------------------------------------------------------------- +// The commands, the twin, and the compared files + +/** One of T7-9's four commands, run from the workspace root under `--json`. */ +interface ImportCommand { + readonly word: "build" | "check" | "ids" | "inventory"; + /** The outcome the twin's valid workspace gives it (H-5). */ + readonly expectOnTwin: (result: RunResult, context: string) => void; +} + +/** A findings-only surface: exit 0 with exactly `{"findings": []}`. */ +function expectFindingFree( + result: RunResult, + context: string, + rule: string, +): void { + assertExitCode( + result, + 0, + `${context} — on a valid workspace it exits 0 finding-free (${rule}; H-5)`, + ); + assertSameJson( + decodeFindingsReport(parseJsonStdout(result, context), context).findings, + [], + `${context} — the report is exactly {"findings": []}, the ` + + `findings-only form's one member holding the empty array (SPEC 12.7)`, + ); +} + +/** A reading surface: exit 0 with exactly one JSON document (H-5, 12.0). */ +function expectAnswered( + result: RunResult, + context: string, + rule: string, +): void { + assertExitCode( + result, + 0, + `${context} — a valid workspace's answer, exit 0 (${rule}; H-5)`, + ); + parseJsonStdout(result, context); +} + +/** T7-9's commands, in the order every arm runs them. */ +const T7_9_COMMANDS: readonly ImportCommand[] = [ + { + word: "build", + expectOnTwin: (result, context) => { + expectFindingFree(result, context, "SPEC 12.1"); + }, + }, + { + word: "check", + expectOnTwin: (result, context) => { + expectFindingFree(result, context, "SPEC 12.2: graph data current"); + }, + }, + { + word: "ids", + expectOnTwin: (result, context) => { + expectAnswered(result, context, "SPEC 12.3"); + }, + }, + { + word: "inventory", + expectOnTwin: (result, context) => { + expectAnswered(result, context, "SPEC 11.6"); + }, + }, +]; + +/** A command as diagnoses name it. */ +function commandLabel(command: ImportCommand): string { + return "`" + command.word + " --json`"; +} + +/** + * An arm's workspace: its configuration record beside the two sources, and + * a (c) arm's own files. + */ +function armDecl( + config: StagedTs, + files: Readonly<Record<string, StagedTs>> = {}, +): WorkspaceDecl { + return { + files: { + [CONFIG_IMPORT_CONFIG_PATH]: config, + ...CONFIG_IMPORT_SOURCES, + ...files, + }, + }; +} + +/** + * What an arm compares with the twin's files (module header): every entry + * outside `.xspec/` but the configuration file — the sources, the generated + * modules (13.1), and the emitted Markdown (13.2) — and, for a (c) arm, but + * its `staged` entry with everything below it. Graph data, the lock path, + * and everything else under `.xspec/` are pruned. + */ +function comparedFiles(staged?: string): SnapshotOptions { + return { + exclude: (relPathBytes) => { + const rel = Buffer.from(relPathBytes).toString("latin1"); + return ( + atOrBelow(rel, ".xspec") || + rel === CONFIG_IMPORT_CONFIG_PATH || + (staged !== undefined && atOrBelow(rel, staged)) + ); + }, + }; +} + +/** What the twin and each (a) arm compare (module header). */ +const T7_9_COMPARED_FILES: SnapshotOptions = comparedFiles(); + +/** The twin's four runs and its compared files, once they have run. */ +interface ImportTwin { + readonly results: readonly RunResult[]; + readonly compared: DirectorySnapshot; +} + +/** + * The twin (module header): the four commands in order on its fresh + * workspace, each holding the outcome that workspace gives it (H-5), then + * its compared files; the workspace is disposed once they are taken. + */ +async function runImportTwin(product: ProductBinding): Promise<ImportTwin> { + const workspace = await TestWorkspace.create( + armDecl(CONFIG_IMPORT_TWIN_CONFIG), + ); + try { + const results: RunResult[] = []; + for (const command of T7_9_COMMANDS) { + const context = + `T7-9's twin (importing from ${CONFIG_IMPORT_TWIN_LITERAL}): ` + + commandLabel(command); + const result = await runProduct(product, { + cwd: workspace.root, + argv: [command.word, "--json"], + }); + command.expectOnTwin(result, context); + results.push(result); + } + return { + results, + compared: await snapshotDirectory(workspace.root, T7_9_COMPARED_FILES), + }; + } finally { + await workspace.dispose(); + } +} + +/** Why each (a) answer must be the twin's (TEST-SPEC T7-9; SPEC 7, 2.4). */ +const TWIN_RULE = + "the configuration differs from the twin's in its import's specifier " + + "alone, a static string literal xspec reads as spelled and never " + + "interprets, resolves, or loads, so that validity and everything xspec " + + "derives from the configuration are independent of its spelling and of " + + "what it designates (SPEC 7, 2.4; TEST-SPEC T7-9)"; + +/** + * An arm's run answers exactly as the twin's: the same exit outcome — exit + * code, or death by signal — and byte-equal standard output (for + * `inventory`, its `configuration` byte-identical among it). Standard error + * is not compared: its wording is free (12.0). `twinLabel` and `rule` name + * the twin and why (defaulting to (a)'s, (c)'s, and their `"xspec"` twin's). + */ +function assertAnswersAsTwin( + result: RunResult, + twin: RunResult, + context: string, + twinLabel = `its twin importing from ${CONFIG_IMPORT_TWIN_LITERAL}`, + rule = TWIN_RULE, +): void { + if (result.exitCode !== twin.exitCode || result.signal !== twin.signal) { + fail( + `${context}: it exits exactly as on ${twinLabel} — ${rule}; the arm: ` + + `${summarizeResult(result)}; the twin: ${summarizeResult(twin)}`, + ); + } + assertBytesEqual( + result.stdoutBytes, + twin.stdoutBytes, + `${context}: its standard output is byte-equal to the twin's — ${rule}`, + ); +} + +// --------------------------------------------------------------------------- +// The arms + +/** + * One (a) arm (module header): a fresh workspace staging the arm's + * configuration, the four commands in order, each answering as the twin's + * did, then the compared files byte-identical to the twin's. + */ +async function runSpellingArm( + product: ProductBinding, + twin: ImportTwin, + arm: ImportArm, +): Promise<void> { + const workspace = await TestWorkspace.create(armDecl(arm.config)); + try { + for (const [index, command] of T7_9_COMMANDS.entries()) { + const twinResult = twin.results[index]; + if (twinResult === undefined) { + throw new Error(`T7-9: no twin run for ${commandLabel(command)}`); + } + const result = await runProduct(product, { + cwd: workspace.root, + argv: [command.word, "--json"], + }); + assertAnswersAsTwin( + result, + twinResult, + `T7-9(a), importing from ${arm.label}: ${commandLabel(command)}`, + ); + } + assertSnapshotsEqual( + twin.compared, + await snapshotDirectory(workspace.root, T7_9_COMPARED_FILES), + `T7-9(a), importing from ${arm.label}, once its four commands have ` + + `run: the generated modules and emitted Markdown — every file ` + + `outside .xspec/ but the configuration file, the twin's first, the ` + + `arm's second — are byte-identical to the twin's, graph data not ` + + `compared (${TWIN_RULE})`, + ); + } finally { + await workspace.dispose(); + } +} + +/** + * One (b) arm (module header): a fresh workspace staging the arm's + * unparseable configuration; each of the four commands under `--json` held + * to the 14.14 contract, its error document's one finding exactly the + * configuration error concerning `xspec.config.ts`, with no location. + */ +async function runRejectedEscapeArm( + product: ProductBinding, + arm: ImportArm, +): Promise<void> { + const workspace = await TestWorkspace.create(armDecl(arm.config)); + try { + for (const command of T7_9_COMMANDS) { + const context = + `T7-9(b), importing from a specifier holding ${arm.label}: ` + + commandLabel(command); + const result = await expectConfigurationError( + product, + workspace, + [command.word], + `${context} — the escape is a scanning error of TypeScript 5.9.3, ` + + `so the file is not well-formed TypeScript (SPEC 7, 14.20)`, + ); + const finding = expectErrorDocument(result, context); + assertSameJson( + { + code: finding.code, + path: finding.path, + locations: finding.locations.map((location) => location.file), + }, + { + code: "configuration-error", + path: CONFIG_IMPORT_CONFIG_PATH, + locations: [], + }, + `${context}: the error document's one finding carries the stable ` + + `code "configuration-error" (SPEC 14 condition 14), as its ` + + `concerned path the configuration file the upward search found, ` + + `in the anchoring form of 11.6 relative to the invocation working ` + + `directory — the workspace root, so exactly "xspec.config.ts" ` + + `(SPEC 14, 12.7; T12.7-3) — and locations [], a configuration ` + + `condition carrying no in-source location (SPEC 14)`, + ); + } + } finally { + await workspace.dispose(); + } +} + +/** + * A (c) or (d) arm's command, `argv` run from the workspace root within + * the driver's own guard (S-3). Its hang propagates at once, ending the test + * (S-3: a tripped guard ends its test), renamed for the arm and the command + * — `blocked` saying what a product blocking there opened — with the + * driver's kill as its cause, so the certification runner still records it + * as the hang it is (`isHangGuardKill`); anything else the run rejects with + * propagates unchanged. + */ +async function runGuardedCommand( + product: ProductBinding, + workspace: TestWorkspace, + argv: readonly string[], + context: string, + blocked: string, +): Promise<RunResult> { + try { + return await runProduct(product, { cwd: workspace.root, argv }); + } catch (error) { + if (!isHangGuardKill(error)) throw error; + throw new Error( + `${context}: the command did not end within its own guard, which ` + + `killed it — ${blocked} (S-3: a tripped guard ends its test) — ` + + (error instanceof Error ? error.message : String(error)), + { cause: error }, + ); + } +} + +/** Why a (c) command's hang is the product's (module header). */ +const DESIGNATION_BLOCKED = + "a product opening what the specifier designates, a FIFO with no " + + "writer among them, blocks there, where xspec never resolves, reads, or " + + "loads the specifier (SPEC 7; TEST-SPEC T7-9(c))"; + +/** + * One (c) arm (module header): a fresh workspace staging the arm's + * configuration and files; its staging made and verified on the harness + * itself; the four commands in order, each answering as the twin's did and + * leaving the staging in place where asserted (the FIFO); then, the staging + * restored, the compared files — the arm's staged entry pruned — + * byte-identical to the twin's. + */ +async function runDesignationArm( + product: ProductBinding, + twin: ImportTwin, + arm: DesignationArm, +): Promise<void> { + const workspace = await TestWorkspace.create(armDecl(arm.config, arm.files)); + try { + const staging = + arm.stage === undefined ? undefined : await arm.stage(workspace); + try { + for (const [index, command] of T7_9_COMMANDS.entries()) { + const twinResult = twin.results[index]; + if (twinResult === undefined) { + throw new Error(`T7-9: no twin run for ${commandLabel(command)}`); + } + const context = + `T7-9(c), importing from ${arm.label}: ` + commandLabel(command); + const result = await runGuardedCommand( + product, + workspace, + [command.word, "--json"], + context, + DESIGNATION_BLOCKED, + ); + assertAnswersAsTwin(result, twinResult, context); + await staging?.afterCommand(context); + } + } finally { + await staging?.restore(); + } + assertSnapshotsEqual( + twin.compared, + await snapshotDirectory(workspace.root, comparedFiles(arm.staged)), + `T7-9(c), importing from ${arm.label}, once its four commands have ` + + `run and its staging is undone: the generated modules and emitted ` + + `Markdown — every file outside .xspec/ but the configuration file` + + (arm.staged === undefined + ? "" + : ` and the arm's own staged ${arm.staged}`) + + `, the twin's first, the arm's second — are byte-identical to the ` + + `twin's, graph data not compared (${TWIN_RULE})`, + ); + } finally { + await workspace.dispose(); + } +} + +/** + * Run one arm, collecting its diagnosed failure (module header): a + * `HarnessAssertionError` is recorded and the next arm runs; anything else — + * a harness error, a hang — propagates at once. + */ +async function collectArmFailure( + failures: string[], + arm: () => Promise<void>, +): Promise<void> { + try { + await arm(); + } catch (error) { + if (!(error instanceof HarnessAssertionError)) throw error; + failures.push(error.message); + } +} + +// --------------------------------------------------------------------------- +// (d) Installs: the names, the trap package, and the FIFO manifest + +/** T7-9(d)'s first name (module header). */ +const TRAP_NAME = "trap"; +/** T7-9(d)'s second name, the executable's (module header). */ +const EXECUTABLE_NAME = "xspec"; + +/** The marker the trap's entry writes at the workspace root, if loaded. */ +const TRAP_MARKER = "t7-9-trap-marker"; +/** What every line the trap's entry prints holds, on either stream. */ +const TRAP_TELL = "T7-9(d) trap entry ran"; +/** + * The trap's exit code: non-zero, outside 12.0's partition (0, 1, 2), and + * apart from S-7's stub's 87, so that a diagnosis quoting it names the trap. + */ +const TRAP_EXIT_CODE = 113; + +/** A package's manifest within its directory (SPEC 7.6). */ +const PACKAGE_MANIFEST = "package.json"; +/** The trap package's entry within its directory, its manifest naming it. */ +const TRAP_ENTRY_FILE = "index.js"; + +/** + * The trap package's entry (module header): a CommonJS module that, if + * loaded, finds its own nearest `node_modules` ancestor and writes the + * marker in that directory's parent, the workspace root (nowhere where it + * finds none), prints a line holding `TRAP_TELL` on each stream, and exits + * `TRAP_EXIT_CODE`. Its strings are plain ASCII, with no backslash (checked + * at load): its line feed is built from its code point when it runs. + */ +const TRAP_ENTRY_TEXT = [ + '"use strict";', + 'const fs = require("node:fs");', + 'const path = require("node:path");', + "const lineFeed = String.fromCharCode(10);", + "let holder = __dirname;", + 'while (path.basename(holder) !== "node_modules") {', + " const parent = path.dirname(holder);", + " if (parent === holder) break;", + " holder = parent;", + "}", + 'if (path.basename(holder) === "node_modules") {', + " fs.writeFileSync(", + ` path.join(path.dirname(holder), ${JSON.stringify(TRAP_MARKER)}),`, + ` ${JSON.stringify(TRAP_TELL)} + lineFeed`, + " );", + "}", + `process.stdout.write(${JSON.stringify(`${TRAP_TELL}: standard output`)} + lineFeed);`, + `process.stderr.write(${JSON.stringify(`${TRAP_TELL}: standard error`)} + lineFeed);`, + `process.exit(${String(TRAP_EXIT_CODE)});`, + "", +].join(LINE_FEED); + +const TRAP_ENTRY: StagedTs = stagedTs( + `T7-9 node_modules/N/${TRAP_ENTRY_FILE} ((d) the trap package's entry under each name N: if loaded, it writes the marker ${TRAP_MARKER} at the workspace root, prints a line on each stream, and exits ${String(TRAP_EXIT_CODE)})`, + TRAP_ENTRY_TEXT, +); + +/** + * The trap package's manifest under `name` (module header): `name` itself, + * a version, and the entry for every resolution — `main`, and `exports` — + * so that a product resolving `N` from the configuration file's directory + * and loading it runs the trap. Plain JSON, which nothing judges (S-9). + */ +function trapManifest(name: string): string { + const manifest = { + name, + version: "1.0.0", + main: TRAP_ENTRY_FILE, + exports: `./${TRAP_ENTRY_FILE}`, + }; + return JSON.stringify(manifest, null, 2) + LINE_FEED; +} + +/** One of T7-9(d)'s names N (module header), with its configuration. */ +interface InstallName { + readonly name: string; + /** How diagnoses describe the name beside its spelling. */ + readonly what: string; + /** + * The configuration importing from `"N"`, double-quoted: a record for a + * fixed name, else the text composed once the package directory was + * read, declared per draw (module header). + */ + readonly config: StagedTs | string; +} + +/** The configuration importing from `"N"`, double-quoted (module header). */ +function installConfigText(name: string): string { + return configImportText(DOUBLE_QUOTE + name + DOUBLE_QUOTE); +} + +/** T7-9(d)'s two fixed names (module header), each configuration a record. */ +const T7_9_D_FIXED_NAMES: readonly InstallName[] = [ + { + name: TRAP_NAME, + what: "the name trap", + config: stagedTs( + 'T7-9 xspec.config.ts ((d) importing from "trap": beside the trap package or the FIFO manifest at node_modules/trap, and in its twin)', + installConfigText(TRAP_NAME), + ), + }, + { + name: EXECUTABLE_NAME, + what: "xspec, the executable's name", + config: CONFIG_IMPORT_TWIN_CONFIG, + }, +]; + +// The module-load self-checks of (d)'s staging (module header): the trap's +// entry holds no backslash and its tell no character JSON or a line could +// re-spell; each fixed name is a name of 7.6's grammar — so that a +// manifest's name equal to it is recognized as it — and its configuration's +// bytes are the builder's over the double-quoted name. +if ( + occurrences(TRAP_ENTRY_TEXT, BACKSLASH) !== 0 || + !/^[A-Za-z0-9 ():-]+$/.test(TRAP_TELL) || + !/^[a-z0-9.-]+$/.test(TRAP_MARKER) +) { + throw new Error( + "T7-9(d): the trap's entry holds a backslash, or its tell or marker a " + + "character outside plain ASCII words (module header)", + ); +} +for (const fixed of T7_9_D_FIXED_NAMES) { + const problem = moduleNameGrammarProblem(fixed.name); + if ( + problem !== null || + typeof fixed.config === "string" || + fixed.config.source !== installConfigText(fixed.name) + ) { + throw new Error( + `T7-9(d): the fixed name ${JSON.stringify(fixed.name)} ` + + (problem === null + ? "has no configuration record whose bytes are the builder's over " + + "the double-quoted name" + : `is no name of 7.6's grammar: it ${problem}`) + + " (module header)", + ); + } +} + +/** T7-9(d)'s two stagings at `node_modules/N` (module header). */ +type InstallKind = "trap" | "fifo"; + +/** The stagings, in the order each name's arms run. */ +const T7_9_D_KINDS: readonly InstallKind[] = ["trap", "fifo"]; + +/** `node_modules/N`, workspace-relative. */ +function installedDirectory(name: string): string { + return `node_modules/${name}`; +} + +/** An arm as diagnoses name it. */ +function installArmLabel(installName: InstallName, kind: InstallKind): string { + const { name } = installName; + const at = installedDirectory(name); + return ( + `importing from ${JSON.stringify(name)} (${installName.what}) ` + + (kind === "trap" + ? `beside a trap package at ${at}` + : `beside ${at} whose ${PACKAGE_MANIFEST} is a FIFO`) + ); +} + +/** + * A (d) workspace (module header): the configuration and the two sources, + * and, for an arm, its staging's files and directories — the trap package's + * manifest and entry, or the directory the FIFO manifest is made in once + * the workspace stands. A composed configuration is declared per draw. + */ +function installDecl( + installName: InstallName, + kind?: InstallKind, +): WorkspaceDecl { + const at = installedDirectory(installName.name); + return { + files: { + [CONFIG_IMPORT_CONFIG_PATH]: installName.config, + ...CONFIG_IMPORT_SOURCES, + ...(kind === "trap" + ? { + [`${at}/${PACKAGE_MANIFEST}`]: trapManifest(installName.name), + [`${at}/${TRAP_ENTRY_FILE}`]: TRAP_ENTRY, + } + : {}), + }, + ...(kind === "fifo" ? { dirs: [at] } : {}), + ...(typeof installName.config === "string" + ? { ts: { perDraw: [CONFIG_IMPORT_CONFIG_PATH] } } + : {}), + }; +} + +/** + * The configuration importing from `name`, composed once the package + * directory is read (module header): `installConfigText` over it, judged by + * S-9's TypeScript check — accepted as module code and as script code — + * before anything is staged, a failure a harness error (H-11), as + * T7.6-4(a)'s composed files' is. + */ +function composedInstallConfig(name: string, context: string): string { + const text = installConfigText(name); + const problem = guardSyncStep( + `judging the configuration importing from ${JSON.stringify(name)} ` + + "(T7-9(d), S-9)", + () => + tsDeclarationProblem( + judgeTypeScript(text, CONFIG_IMPORT_CONFIG_PATH), + "well-formed", + ), + ); + if (problem !== undefined) { + throw new HarnessStagingError( + "ts-derivability", + CONFIG_IMPORT_CONFIG_PATH, + `${context}: the configuration importing from ${JSON.stringify(name)}, ` + + `composed once the package directory was read, is ${problem} ` + + "(TEST-SPEC S-9: a composed configuration file is judged " + + "well-formed before the product is driven on it)", + ); + } + return text; +} + +/** + * T7-9(d)'s third name (module header): the name the module channel's + * package manifest gives, staged as `name`; none to stage where the + * manifest gives no name of 7.6's grammar, or one of the fixed names; or + * the diagnosis its missing package directory is (H-8, H-9). + */ +type ThirdInstallName = + | { readonly kind: "name"; readonly installName: InstallName } + | { readonly kind: "none" } + | { readonly kind: "missing"; readonly diagnosis: string }; + +/** How diagnoses name the third name where it cannot be read. */ +const THIRD_NAME_CONTEXT = + "T7-9(d), under its third name, the name the module channel's package " + + "manifest gives"; + +/** + * Read T7-9(d)'s third name off `product`'s package directory, as + * T7.6-4(a) reads it (module header): the directory checked by + * `modulePackageDirectory`, its manifest read strictly. None given, or the + * built product's missing one, is a diagnosis to record for each of the + * name's arms; every other refusal of the directory is a harness error. + */ +async function thirdInstallName( + product: ProductBinding, +): Promise<ThirdInstallName> { + if (product.packageDir === undefined) { + const executable = [product.command, ...(product.prefixArgs ?? [])]; + return { + kind: "missing", + diagnosis: + `${product.label}: no package directory is given beside the ` + + `executable (${executable.join(" ")}), so that name cannot be ` + + "read — the module channel counts as part of the product " + + "(TEST-SPEC H-8) and an arm is never skipped (H-9), so each of its " + + "arms fails here, diagnosed. Give the directory " + + ".github/scripts/pack-package.sh prints as XSPEC_PACKAGE_DIR " + + "(AGENTS.md). Nothing was staged.", + }; + } + let manifestName: string | undefined; + try { + const pkg = await modulePackageDirectory( + product, + "T7-9(d), reading its third name", + ); + manifestName = pkg.manifestName.name; + } catch (error) { + if (!(error instanceof HarnessAssertionError)) throw error; + return { kind: "missing", diagnosis: error.message }; + } + if ( + manifestName === undefined || + moduleNameGrammarProblem(manifestName) !== null || + T7_9_D_FIXED_NAMES.some((fixed) => fixed.name === manifestName) + ) { + return { kind: "none" }; + } + return { + kind: "name", + installName: { + name: manifestName, + what: "the name the module channel's package manifest gives", + config: composedInstallConfig(manifestName, THIRD_NAME_CONTEXT), + }, + }; +} + +// --------------------------------------------------------------------------- +// (d) Installs: the representative commands + +/** One of T7-9(d)'s representative commands (T7-8's), under `--json`. */ +interface InstallCommand { + readonly argv: readonly string[]; + /** The outcome such a workspace gives it (H-5; module header). */ + readonly expect: (result: RunResult, context: string) => void; +} + +/** One `{file, ids}` entry of `ids`'s flat listing (SPEC 12.3). */ +interface IdsListingEntry { + readonly file: string; + readonly ids: readonly string[]; +} + +/** A listing sorted bytewise by file path (membership is the subject). */ +function sortedIdsListing( + entries: readonly IdsListingEntry[], +): IdsListingEntry[] { + return entries + .map((entry) => ({ file: entry.file, ids: entry.ids })) + .sort((a, b) => + Buffer.compare(Buffer.from(a.file, "utf8"), Buffer.from(b.file, "utf8")), + ); +} + +/** Every (d) workspace's discovered set: `a` and `b`, by file (SPEC 12.3). */ +const T7_9_D_LISTING: readonly IdsListingEntry[] = [ + { file: "specs/A.mdx", ids: ["a"] }, + { file: "specs/B.mdx", ids: ["b"] }, +]; + +/** The representative `rename`'s applied mapping (SPEC 6.4, 12.7). */ +const T7_9_D_MAPPING: readonly AppliedMappingPair[] = [ + { from: "specs/A.mdx#a", to: "specs/A.mdx#b" }, +]; + +/** + * T7-9(d)'s commands (module header): T7-8's representative commands, each + * under `--json`, in TEST-SPEC's order — the `rename`, the one writing + * sources, last — each with the outcome such a workspace gives it (H-5). + */ +const T7_9_D_COMMANDS: readonly InstallCommand[] = [ + { + argv: ["build", "--json"], + expect: (result, context) => { + expectFindingFree(result, context, "SPEC 12.1"); + }, + }, + { + argv: ["check", "--json"], + expect: (result, context) => { + expectFindingFree(result, context, "SPEC 12.2: graph data current"); + }, + }, + { + argv: ["ids", "--json"], + expect: (result, context) => { + assertExitCode( + result, + 0, + `${context} — a valid workspace's ` + + "`ids` answers, exit 0 (SPEC 12.3, 13.3; H-5)", + ); + const report = decodeIdsReport(parseJsonStdout(result, context), context); + assertSameJson( + sortedIdsListing(report.files), + sortedIdsListing(T7_9_D_LISTING), + `${context}: its listing — requirement IDs grouped by file, compared ` + + "bytewise-sorted by path — is the workspace's discovered set, a " + + "in specs/A.mdx and b in specs/B.mdx (SPEC 12.3, 7)", + ); + }, + }, + { + argv: ["view", "specs/A.mdx", "--json"], + expect: (result, context) => { + assertExitCode( + result, + 0, + `${context} — ` + + "`view` answers for a discovered source, exit 0 (SPEC 11.4, 12.0; H-5)", + ); + assertSameJson( + decodeViewReport( + parseJsonStdout(result, context), + { text: false }, + context, + ).findings, + [], + `${context}: the answer is finding-free — the workspace is valid ` + + "(SPEC 11.4, 11.2)", + ); + }, + }, + { + argv: ["inventory", "--json"], + expect: (result, context) => { + assertExitCode( + result, + 0, + `${context} — ` + "`inventory` answers, exit 0 (SPEC 11.6, 12.0; H-5)", + ); + assertSameJson( + decodeInventoryDocument(parseJsonStdout(result, context), context) + .findings, + [], + `${context}: the inventory is finding-free — no journal, session, ` + + "or record condition stands on the workspace (SPEC 11.6)", + ); + }, + }, + { + argv: ["review", "list", "--json"], + expect: (result, context) => { + assertExitCode( + result, + 0, + `${context} — ` + + "`review list` answers, exit 0 (SPEC 10.7, 10.1; H-5)", + ); + const listing = decodeSessionListReport( + parseJsonStdout(result, context), + context, + ); + assertSameJson( + { sessions: listing.sessions, findings: listing.findings ?? [] }, + { sessions: [], findings: [] }, + `${context}: no session is listed and no finding reported — the ` + + "workspace holds no session directory (SPEC 10.1: an absent " + + "session directory holds no sessions; 10.7)", + ); + }, + }, + { + argv: ["rename", "specs/A.mdx", "a", "b", "--json"], + expect: (result, context) => { + assertExitCode( + result, + 0, + `${context} — the rename applies, exit 0 (SPEC 6.4, 12.0; H-5)`, + ); + assertAppliedMapping( + decodeAppliedMappingReport(parseJsonStdout(result, context), context), + T7_9_D_MAPPING, + `${context}: its applied mapping is exactly specs/A.mdx#a → ` + + "specs/A.mdx#b — IDs are unique within a file, so b in " + + "specs/B.mdx collides with nothing (SPEC 6.4, 12.7)", + ); + }, + }, +]; + +/** A (d) command as diagnoses name it. */ +function installCommandLabel(command: InstallCommand): string { + return "`" + command.argv.join(" ") + "`"; +} + +// --------------------------------------------------------------------------- +// (d) Installs: the twins and the arms + +/** Why each (d) answer must be the twin's (TEST-SPEC T7-9(d); SPEC 7, 7.6). */ +const INSTALL_RULE = + "no command's outcome depends, through a configuration's import, on the " + + "defineConfig module or on whether a project installed it, and no name " + + "is privileged: xspec never executes the configuration and never " + + "resolves or loads its import, so nothing node_modules holds reaches an " + + "answer (SPEC 7, 7.6; TEST-SPEC T7-9(d))"; + +/** Why a (d) command's hang is the product's (module header). */ +const INSTALL_BLOCKED = + "a product resolving or loading the configuration's import opens the " + + "installed package's manifest, here a FIFO with no writer, and blocks " + + "there, where xspec never resolves or loads the import (SPEC 7, 7.6; " + + "TEST-SPEC T7-9(d))"; + +/** A (d) arm's twin, as diagnoses name it. */ +const INSTALL_TWIN_LABEL = + "its twin, the same workspace and configuration holding no node_modules"; + +/** How the written-file compare names a (d) arm's two runs. */ +const T7_9_D_TWIN_LABELS: WriteDeltaLabels = { + first: "the arm's workspace", + second: "its twin", + pair: "the arm's workspace and its twin", +}; + +/** One of a (d) twin's runs: its result, and the files it wrote. */ +interface InstallTwinRun { + readonly result: RunResult; + /** Its workspace's changes across the run (the lock path pruned, H-6). */ + readonly delta: readonly SnapshotChange[]; + /** Its workspace after the run (the lock path pruned). */ + readonly after: DirectorySnapshot; +} + +/** + * A name's twin (module header): its configuration and the two sources in + * a fresh workspace holding no `node_modules`, the commands run in order, + * each with the files it writes — the workspace's snapshots around the + * run, the lock path pruned (H-6). The workspace is disposed once they are + * taken; a run the twin's guard kills propagates as the hang it is. + */ +async function runInstallTwin( + product: ProductBinding, + installName: InstallName, +): Promise<readonly InstallTwinRun[]> { + const workspace = await TestWorkspace.create(installDecl(installName)); + try { + const runs: InstallTwinRun[] = []; + for (const command of T7_9_D_COMMANDS) { + const before = await snapshotDirectory(workspace.root, EXCLUDE_LOCK_PATH); + const result = await runProduct(product, { + cwd: workspace.root, + argv: command.argv, + }); + const after = await snapshotDirectory(workspace.root, EXCLUDE_LOCK_PATH); + runs.push({ result, delta: diffSnapshots(before, after), after }); + } + return runs; + } finally { + await workspace.dispose(); + } +} + +/** + * After each (d) command (module header): no marker at the workspace root, + * and neither standard output nor standard error holding the trap's tell — + * the trap package's entry never ran. `rule` says why (T7-10(d) reuses the + * check for a baseline configuration's import). + */ +async function assertTrapNeverRan( + workspace: TestWorkspace, + result: RunResult, + context: string, + rule = INSTALL_RULE, +): Promise<void> { + const marker = await workspace.kind(TRAP_MARKER); + if (marker !== "absent") { + fail( + `${context}: the trap's marker ${TRAP_MARKER} stands at the ` + + `workspace root (${marker}) — the trap package's entry ran, ` + + `loaded through the configuration's import — where ${rule}; ` + + summarizeResult(result), + ); + } + const streams: ReadonlyArray<readonly [string, Uint8Array]> = [ + ["standard output", result.stdoutBytes], + ["standard error", result.stderrBytes], + ]; + for (const [stream, bytes] of streams) { + if (Buffer.from(bytes).includes(TRAP_TELL)) { + fail( + `${context}: its ${stream} carries what the trap package's entry ` + + `prints (${JSON.stringify(TRAP_TELL)}) — the entry ran, loaded ` + + `through the configuration's import — where ${rule}; ` + + summarizeResult(result), + ); + } + } +} + +/** + * One (d) arm (module header): a fresh workspace staging `installName`'s + * configuration, the two sources, and `kind`'s staging at `node_modules/N` + * — the FIFO made and verified once the workspace stands, never opened by + * the harness — then each command in order: the trap never ran, the FIFO + * still in place, the twin's answer and written files, and the outcome + * such a workspace gives it (H-5). + */ +async function runInstallArm( + product: ProductBinding, + installName: InstallName, + kind: InstallKind, + twin: readonly InstallTwinRun[], +): Promise<void> { + const label = installArmLabel(installName, kind); + const manifest = `${installedDirectory(installName.name)}/${PACKAGE_MANIFEST}`; + const workspace = await TestWorkspace.create(installDecl(installName, kind)); + try { + const fifo: StagedLeftover | undefined = + kind === "fifo" ? await stageFifo(workspace, manifest) : undefined; + for (const [index, command] of T7_9_D_COMMANDS.entries()) { + const twinRun = twin[index]; + if (twinRun === undefined) { + throw new Error( + `T7-9(d): no twin run for ${installCommandLabel(command)}`, + ); + } + const context = `T7-9(d), ${label}: ${installCommandLabel(command)}`; + const before = await snapshotDirectory(workspace.root, EXCLUDE_LOCK_PATH); + const result = await runGuardedCommand( + product, + workspace, + command.argv, + context, + INSTALL_BLOCKED, + ); + const after = await snapshotDirectory(workspace.root, EXCLUDE_LOCK_PATH); + await assertTrapNeverRan(workspace, result, context); + if (fifo !== undefined) { + await assertFifosIntact( + fifo, + `${context}: ${manifest} is still a FIFO in place, the command ` + + "having ended within its own guard — unopened, as xspec never " + + "resolves or loads the configuration's import (SPEC 7, 7.6; " + + "TEST-SPEC T7-9(d), S-3)", + ); + } + assertAnswersAsTwin( + result, + twinRun.result, + context, + INSTALL_TWIN_LABEL, + INSTALL_RULE, + ); + assertWriteDeltasEqual( + diffSnapshots(before, after), + after, + twinRun.delta, + twinRun.after, + `${context}: the files it writes are byte-equal to those the same ` + + `command writes on ${INSTALL_TWIN_LABEL}, the two configurations ` + + "byte-identical (TEST-SPEC T7-9(d); H-6: the lock path left out " + + "of every written-file compare across workspaces)", + T7_9_D_TWIN_LABELS, + ); + command.expect(result, context); + } + } finally { + await workspace.dispose(); + } +} + +/** + * T7-9(d) (module header): the third name read first, so that a refused + * package directory ends the body before anything runs; then each name in + * turn — `trap`, `xspec`, and the manifest's where staged — its twin, then + * its two arms, each arm's diagnosed failure collected into `failures`; + * with the third name's package directory missing, a diagnosis for each of + * its arms. Returns how many arms it counted. + */ +async function runInstalls( + product: ProductBinding, + failures: string[], +): Promise<number> { + const third = await thirdInstallName(product); + const names: readonly InstallName[] = + third.kind === "name" + ? [...T7_9_D_FIXED_NAMES, third.installName] + : T7_9_D_FIXED_NAMES; + let arms = 0; + for (const installName of names) { + const twin = await runInstallTwin(product, installName); + for (const kind of T7_9_D_KINDS) { + arms += 1; + await collectArmFailure(failures, () => + runInstallArm(product, installName, kind, twin), + ); + } + } + if (third.kind === "missing") { + for (const kind of T7_9_D_KINDS) { + arms += 1; + failures.push( + `${THIRD_NAME_CONTEXT}, its arm beside ` + + (kind === "trap" + ? "a trap package" + : `a ${PACKAGE_MANIFEST} that is a FIFO`) + + `: ${third.diagnosis}`, + ); + } + } + return arms; +} + +// --------------------------------------------------------------------------- +// T7-10 (a) and (b): the configuration file as a source + +/** T7-10's one source's path (TEST-SPEC T7-10's opening). */ +const T7_10_SOURCE_PATH = "specs/A.mdx"; + +/** + * T7-10's one source, `specs/A.mdx` holding `<S id="a">A</S>`: T7-9's record + * of those very bytes (helpers/config-import.ts), `specs/B.mdx` left out. + */ +const T7_10_SOURCE: StagedMdx = (() => { + const record = CONFIG_IMPORT_SOURCES[T7_10_SOURCE_PATH]; + if (record === undefined) { + throw new Error( + `T7-10: the shared sources hold no ${T7_10_SOURCE_PATH} record ` + + "(helpers/config-import.ts; harness bug)", + ); + } + return record; +})(); + +/** The code group discovering the configuration file in (b) (module header). */ +const T7_10_CODE_GROUP = "app"; + +/** One of T7-10(b)'s code groups, each discovering the configuration file. */ +interface DiscoveringGroup { + /** The group as diagnoses name it. */ + readonly label: string; + /** Its one glob, matching the configuration file at the workspace root. */ + readonly glob: string; +} + +/** T7-10(b)'s two code groups (TEST-SPEC T7-10(b)). */ +const T7_10_DISCOVERING_GROUPS: readonly DiscoveringGroup[] = [ + { label: "a code group globbing *.ts", glob: "*.ts" }, + { + label: "a code group whose glob is xspec.config.ts", + glob: CONFIG_IMPORT_CONFIG_PATH, + }, +]; + +/** + * The discovered configuration's text after its specifier: T7-9's tail + * (`CONFIG_IMPORT_TAIL`) with the code group `app` globbing `glob` between + * `specs` and `markdown` (module header). + */ +function discoveredTail(glob: string): string { + return ` + +export default defineConfig({ + specs: { + main: ["specs/*.mdx"] + }, + code: { + ${T7_10_CODE_GROUP}: ["${glob}"] + }, + markdown: { emit: true } +}) +`; +} + +/** One of T7-10's specifiers (TEST-SPEC T7-10's opening). */ +interface SourceSpecifier { + /** The specifier as diagnoses name it, with what it designates. */ + readonly label: string; + /** The double-quoted specifier exactly as it stands in the file. */ + readonly literal: string; + /** + * A `.xspec` specifier: the declaration is a spec module import (SPEC 4), + * so `defineConfig` is a spec-module binding (14.15) and its call a + * value-level use 4.5 does not sanction (14.18). + */ + readonly specModule: boolean; +} + +/** T7-10's five specifiers, one arm each in (a) and in each (b) group. */ +const T7_10_SPECIFIERS: readonly SourceSpecifier[] = [ + { + label: + '"./specs/A.xspec" (a spec module import binding defineConfig, ' + + "neither the default nor the text export)", + literal: '"./specs/A.xspec"', + specModule: true, + }, + { + label: + '"./missing.xspec" (a .xspec specifier designating no discovered ' + + "spec source)", + literal: '"./missing.xspec"', + specModule: true, + }, + { + label: + '"./specs/A.xspec.ts" (a relative specifier designating a ' + + "derived-file path, its file name containing .xspec., 13.4)", + literal: '"./specs/A.xspec.ts"', + specModule: false, + }, + { + label: + '"./.xspec/x" (a relative specifier designating a derived-file path, ' + + "a path under .xspec/, 13.4)", + literal: '"./.xspec/x"', + specModule: false, + }, + { + label: + '"./specs/A.md" (the Markdown emit destination of specs/A.mdx while ' + + "emission is enabled, 7.3)", + literal: '"./specs/A.md"', + specModule: false, + }, +]; + +// Each specifier is one double-quoted literal spelling no escape, and a +// `.xspec` specifier — its value ending in `.xspec`, SPEC 4's spec module +// import — exactly where `specModule` says so. +for (const specifier of T7_10_SPECIFIERS) { + const value = specifier.literal.slice(1, -1); + if ( + specifier.literal.length < 2 || + !specifier.literal.startsWith(DOUBLE_QUOTE) || + !specifier.literal.endsWith(DOUBLE_QUOTE) || + value.includes(DOUBLE_QUOTE) || + value.includes(BACKSLASH) || + value.endsWith(".xspec") !== specifier.specModule + ) { + throw new Error( + `T7-10 fixture self-check: the specifier ${specifier.literal} must be ` + + "one double-quoted literal spelling no escape, a .xspec specifier " + + "exactly where specModule says so (harness bug)", + ); + } +} + +/** The import's one binding, the default export's callee. */ +const DEFINE_CONFIG = "defineConfig"; + +/** The default export's keywords, before its call's callee. */ +const EXPORT_DEFAULT_PREFIX = "export default "; + +/** + * A T7-10 configuration over a specifier: its record, and the ranges (b)'s + * findings locate (module header), composed from the record's parts. + */ +interface SourceConfig { + readonly config: StagedTs; + /** + * The import declaration by its own characters, the import range of + * 11.4: the file's first bytes, `import` through the specifier's closing + * quote, no terminator spelled (SPEC 14, 1.7). + */ + readonly importRange: SourceRange; + /** + * `defineConfig`'s spelling at its call, the default export's callee + * (SPEC 14: the binding's identifier at the offending use). + */ + readonly callRange: SourceRange; +} + +/** + * Compose a configuration — the shared builder's head, `literal`, and + * `tail` — as the record `name`, and pin its two ranges, checking at module + * load that the text is ASCII (its code units its bytes), that the import + * declaration ends at the specifier's closing quote with the line, and that + * `defineConfig` is spelled exactly twice: its binding in the declaration, + * and its call, the default export's callee, spelled once. + */ +function sourceConfig( + name: string, + literal: string, + tail: string, +): SourceConfig { + const declaration = CONFIG_IMPORT_HEAD + literal; + const text = declaration + tail; + const call = EXPORT_DEFAULT_PREFIX + DEFINE_CONFIG + "("; + const callAt = text.indexOf(call); + if ( + Buffer.byteLength(text, "utf8") !== text.length || + !declaration.startsWith("import ") || + !tail.startsWith(LINE_FEED) || + callAt === -1 || + text.lastIndexOf(call) !== callAt || + occurrences(text, DEFINE_CONFIG) !== 2 || + text.indexOf(DEFINE_CONFIG) >= declaration.length + ) { + throw new Error( + `T7-10 fixture self-check: ${name} must be ASCII, its import ` + + "declaration ending at the specifier's closing quote with its " + + "line, and defineConfig spelled exactly twice — its binding in the " + + "declaration and its call, the default export's callee (harness bug)", + ); + } + const callStart = callAt + EXPORT_DEFAULT_PREFIX.length; + return { + config: stagedTs(name, text), + importRange: { start: 0, end: declaration.length }, + callRange: { start: callStart, end: callStart + DEFINE_CONFIG.length }, + }; +} + +/** A T7-10(a) arm: the specifier over T7-9's configuration, no code group. */ +interface UndiscoveredArm { + readonly specifier: SourceSpecifier; + readonly config: StagedTs; +} + +/** T7-10(a)'s five arms (TEST-SPEC T7-10(a)). */ +const T7_10_A_ARMS: readonly UndiscoveredArm[] = T7_10_SPECIFIERS.map( + (specifier) => ({ + specifier, + config: stagedTs( + `T7-10 xspec.config.ts ((a) undiscovered, no code group: importing from ${specifier.literal})`, + configImportText(specifier.literal), + ), + }), +); + +/** A T7-10(b) arm: the specifier over the configuration a code group discovers. */ +interface DiscoveredArm { + readonly specifier: SourceSpecifier; + readonly source: SourceConfig; +} + +/** One code group's (b) stagings: its control and its five arms. */ +interface DiscoveringStaging { + readonly group: DiscoveringGroup; + /** The control's configuration, importing from `"xspec"`. */ + readonly control: StagedTs; + readonly arms: readonly DiscoveredArm[]; +} + +/** T7-10(b)'s stagings, per discovering code group (TEST-SPEC T7-10(b)). */ +const T7_10_B_STAGINGS: readonly DiscoveringStaging[] = + T7_10_DISCOVERING_GROUPS.map((group) => ({ + group, + control: sourceConfig( + `T7-10 xspec.config.ts (the control, discovered by ${group.label}: importing from ${CONFIG_IMPORT_TWIN_LITERAL})`, + CONFIG_IMPORT_TWIN_LITERAL, + discoveredTail(group.glob), + ).config, + arms: T7_10_SPECIFIERS.map((specifier) => ({ + specifier, + source: sourceConfig( + `T7-10 xspec.config.ts ((b) discovered by ${group.label}: importing from ${specifier.literal})`, + specifier.literal, + discoveredTail(group.glob), + ), + })), + })); + +/** + * How many (a) and (b) arms T7-10 runs: (a)'s, and each (b) group's control + * and arms ((c)'s are `T7_10_C_ARMS`). + */ +const T7_10_AB_ARM_COUNT = T7_10_B_STAGINGS.reduce( + (count, staging) => count + 1 + staging.arms.length, + T7_10_A_ARMS.length, +); + +/** A T7-10 workspace: the arm's configuration beside `specs/A.mdx`. */ +function sourceDecl(config: StagedTs): WorkspaceDecl { + return { + files: { + [CONFIG_IMPORT_CONFIG_PATH]: config, + [T7_10_SOURCE_PATH]: T7_10_SOURCE, + }, + }; +} + +/** The two validating commands every T7-10 arm runs, each under `--json`. */ +const T7_10_VALIDATING_WORDS: readonly ("build" | "check")[] = [ + "build", + "check", +]; + +/** The control's query of the configuration's whole-file location. */ +const CONTROL_QUERY_ARGV: readonly string[] = [ + "query", + "edges", + "--from", + CONFIG_IMPORT_CONFIG_PATH, +]; + +/** A T7-10 command as diagnoses name it, its argv in backticks. */ +function sourceCommandLabel(argv: readonly string[]): string { + return "`" + argv.join(" ") + "`"; +} + +/** Why each (a) arm is valid (TEST-SPEC T7-10(a); SPEC 7). */ +const UNDISCOVERED_RULE = + "no configured group discovers the configuration file, so reading it " + + "applies none of the rules 4 and 14.15 set for a TypeScript file's " + + "imports, whatever its specifier designates (SPEC 7; TEST-SPEC T7-10(a))"; + +/** Why each (b) arm reports its findings, the configuration staying valid. */ +const DISCOVERED_RULE = + "a code group discovers the configuration file, so xspec analyzes it as " + + "it does every source it discovers, its import declaration included, " + + "while the configuration itself stays valid (SPEC 7, 4, 14.15; " + + "TEST-SPEC T7-10(b))"; + +/** Why each (b) group's control is clean (TEST-SPEC T7-10(b)). */ +const CONTROL_RULE = + 'importing from "xspec" — a bare name, no .xspec specifier and no ' + + "relative path — the discovered configuration's import breaks none of " + + "4's rules, so the workspace is clean (SPEC 7, 4; TEST-SPEC T7-10(b)'s " + + "control)"; + +/** + * One (a) arm (module header): a fresh workspace staging the arm's + * configuration; `build` and `check`, each under `--json`, exit 0 + * finding-free. + */ +async function runUndiscoveredArm( + product: ProductBinding, + arm: UndiscoveredArm, +): Promise<void> { + const workspace = await TestWorkspace.create(sourceDecl(arm.config)); + try { + for (const word of T7_10_VALIDATING_WORDS) { + const result = await runProduct(product, { + cwd: workspace.root, + argv: [word, "--json"], + }); + expectFindingFree( + result, + "T7-10(a), undiscovered (no code group), importing from " + + `${arm.specifier.label}: ${sourceCommandLabel([word, "--json"])}`, + UNDISCOVERED_RULE, + ); + } + } finally { + await workspace.dispose(); + } +} + +/** + * One (b) group's control (module header): a fresh workspace whose + * discovered configuration imports from `"xspec"`; `build` and `check`, each + * under `--json`, exit 0 finding-free, and `query edges --from + * xspec.config.ts` exits 0 with one JSON document. + */ +async function runDiscoveredControl( + product: ProductBinding, + staging: DiscoveringStaging, +): Promise<void> { + const workspace = await TestWorkspace.create(sourceDecl(staging.control)); + const label = + `T7-10(b)'s control, discovered by ${staging.group.label}, importing ` + + `from ${CONFIG_IMPORT_TWIN_LITERAL}`; + try { + for (const word of T7_10_VALIDATING_WORDS) { + const result = await runProduct(product, { + cwd: workspace.root, + argv: [word, "--json"], + }); + expectFindingFree( + result, + `${label}: ${sourceCommandLabel([word, "--json"])}`, + CONTROL_RULE, + ); + } + const context = `${label}: ${sourceCommandLabel(CONTROL_QUERY_ARGV)}`; + const result = await runProduct(product, { + cwd: workspace.root, + argv: CONTROL_QUERY_ARGV, + }); + assertExitCode( + result, + 0, + `${context} — the discovered configuration's whole-file location ` + + "exists, a code source's known graph node, so the query answers, " + + "exit 0 (SPEC 11.1, 4.6, 7; TEST-SPEC T7-10(b), T7-3's idiom; H-5)", + ); + parseJsonStdout(result, context); + } finally { + await workspace.dispose(); + } +} + +/** A finding as (b) pins it: its stable code, locations, and concerned path. */ +function pinnedFinding(finding: Finding): unknown { + return { + code: finding.code, + locations: finding.locations.map((location) => ({ + file: location.file, + range: { start: location.range.start, end: location.range.end }, + })), + path: finding.path, + }; +} + +/** What (b) and (e) pin for a finding locating `range` in `file`. */ +function locatedAt(file: string, code: string, range: SourceRange): unknown { + return { + code, + locations: [{ file, range: { start: range.start, end: range.end } }], + path: null, + }; +} + +/** What (b) pins for a finding locating `range` in the configuration file. */ +function locatedInConfig(code: string, range: SourceRange): unknown { + return locatedAt(CONFIG_IMPORT_CONFIG_PATH, code, range); +} + +/** + * A (b) arm's `build` or `check` findings (module header): 14.15 reported, + * and 14.18 in a `.xspec` arm, nothing else; every 14.15 finding locating + * the import declaration by the import range of 11.4 and every 14.18 + * finding `defineConfig` at its call, each `path` `null`. + */ +function assertSourceFindings( + findings: readonly Finding[], + arm: DiscoveredArm, + context: string, +): void { + const reported = + "the report's findings (code, locations, path): " + + JSON.stringify(findings.map(pinnedFinding)); + const { specModule } = arm.specifier; + const imports = findings.filter((finding) => finding.condition === "14.15"); + const calls = findings.filter((finding) => finding.condition === "14.18"); + const others = + findings.length - imports.length - (specModule ? calls.length : 0); + if (others > 0) { + fail( + `${context}: no other finding is reported — ` + + (specModule ? "14.15 and 14.18" : "14.15") + + " alone, never 14.14 (the configuration stays valid) nor a " + + "condition of the workspace's other files, which are valid " + + `(${DISCOVERED_RULE}); ${reported}`, + ); + } + if (imports.length === 0) { + fail( + `${context}: the report carries 14.15 (invalid-import), the ` + + "configuration's import declaration analyzed as a code source's " + + `(${DISCOVERED_RULE}); ${reported}`, + ); + } + if (specModule && calls.length === 0) { + fail( + `${context}: the report carries 14.18 (unsupported-node-usage) — ` + + "the declaration is a spec module import (SPEC 4), so defineConfig " + + "is a spec-module binding and its call a value-level use 4.5 does " + + `not sanction (SPEC 4.5, 14; TEST-SPEC T7-10(b)); ${reported}`, + ); + } + const { importRange, callRange } = arm.source; + for (const finding of imports) { + assertSameJson( + pinnedFinding(finding), + locatedInConfig("invalid-import", importRange), + `${context}: each 14.15 finding carries the stable code ` + + `"invalid-import" and locates the configuration's import ` + + "declaration by its own characters, the import range of 11.4 — " + + `[${String(importRange.start)}, ${String(importRange.end)}) of ` + + `${CONFIG_IMPORT_CONFIG_PATH}, ` + + "`import` through the specifier's " + + "closing quote, no terminator spelled — its path null, a located " + + "condition (SPEC 14, 1.7, 11.4, 12.7; TEST-SPEC T7-10(b))", + ); + } + if (!specModule) return; + for (const finding of calls) { + assertSameJson( + pinnedFinding(finding), + locatedInConfig("unsupported-node-usage", callRange), + `${context}: each 14.18 finding carries the stable code ` + + `"unsupported-node-usage" and locates defineConfig's spelling at ` + + "its call, the default export's callee — " + + `[${String(callRange.start)}, ${String(callRange.end)}) of ` + + `${CONFIG_IMPORT_CONFIG_PATH} — its path null, a located condition ` + + "(SPEC 14, 1.7, 12.7; TEST-SPEC T7-10(b))", + ); + } +} + +/** + * One (b) arm (module header): a fresh workspace staging the arm's + * discovered configuration; `build` and `check`, each under `--json`, exit 1 + * with the arm's findings; then `inventory --json` exits 0 with no finding, + * listing `xspec.config.ts` among its sources in the discovering group. + */ +async function runDiscoveredArm( + product: ProductBinding, + staging: DiscoveringStaging, + arm: DiscoveredArm, +): Promise<void> { + const workspace = await TestWorkspace.create(sourceDecl(arm.source.config)); + const label = + `T7-10(b), discovered by ${staging.group.label}, importing from ` + + arm.specifier.label; + const conditions = arm.specifier.specModule ? "14.15 and 14.18" : "14.15"; + try { + for (const word of T7_10_VALIDATING_WORDS) { + const context = `${label}: ${sourceCommandLabel([word, "--json"])}`; + const result = await runProduct(product, { + cwd: workspace.root, + argv: [word, "--json"], + }); + assertExitCode( + result, + 1, + `${context} — the discovered configuration carries ${conditions}, ` + + `findings: exit 1, never 14.14 or exit 2 (${DISCOVERED_RULE}; ` + + "SPEC 12.0; H-5)", + ); + assertSourceFindings( + decodeFindingsReport(parseJsonStdout(result, context), context) + .findings, + arm, + context, + ); + } + const context = `${label}: ${sourceCommandLabel(["inventory", "--json"])}`; + const result = await runProduct(product, { + cwd: workspace.root, + argv: ["inventory", "--json"], + }); + assertExitCode( + result, + 0, + `${context} — the configuration stays valid, so the inventory ` + + `answers, exit 0 (${DISCOVERED_RULE}; SPEC 11.6; H-5)`, + ); + const inventory = decodeInventoryDocument( + parseJsonStdout(result, context), + context, + ); + assertSameJson( + inventory.findings, + [], + `${context}: the answer carries no finding (SPEC 11.6, 12.7; ` + + "TEST-SPEC T7-10(b))", + ); + assertSameJson( + inventory.sources + .filter((entry) => entry.path === CONFIG_IMPORT_CONFIG_PATH) + .map((entry) => ({ + path: entry.path, + groups: entry.groups.map((group) => ({ + name: group.name, + kind: group.kind, + })), + })), + [ + { + path: CONFIG_IMPORT_CONFIG_PATH, + groups: [{ name: T7_10_CODE_GROUP, kind: "code" }], + }, + ], + `${context}: ${CONFIG_IMPORT_CONFIG_PATH} is listed once among the ` + + `sources, in the code group ${T7_10_CODE_GROUP} alone — the one ` + + `group whose glob, ${JSON.stringify(staging.group.glob)}, matches ` + + "it (SPEC 11.6, 7.2, 7; TEST-SPEC T7-10(b))", + ); + } finally { + await workspace.dispose(); + } +} + +// --------------------------------------------------------------------------- +// T7-10 (c): consequences, and the converse + +/** T7-10's specifier whose literal is `literal` (a harness bug if none). */ +function t710Specifier(literal: string): SourceSpecifier { + const specifier = T7_10_SPECIFIERS.find( + (candidate) => candidate.literal === literal, + ); + if (specifier === undefined) { + throw new Error( + `T7-10: no specifier ${literal} among T7_10_SPECIFIERS (harness bug)`, + ); + } + return specifier; +} + +/** (c)'s gate and baseline specifier, `"./missing.xspec"` (module header). */ +const MISSING_SPECIFIER = t710Specifier('"./missing.xspec"'); + +/** The converse's specifier, `"./specs/A.xspec"` (module header). */ +const SPEC_MODULE_SPECIFIER = t710Specifier('"./specs/A.xspec"'); + +/** + * (c)'s designating specifier: the emit destination `specs/B.mdx` would + * have while emission is enabled (7.3) — no `specs/B.mdx` existing, so it + * designates no derived-file path and the workspace is valid. One + * double-quoted literal spelling no escape, as T7-10's five are. + */ +const DESIGNATING_LITERAL = '"./specs/B.md"'; + +/** (a)'s record over `specifier`: undiscovered, no code group. */ +function undiscoveredRecord(specifier: SourceSpecifier): StagedTs { + const arm = T7_10_A_ARMS.find( + (candidate) => candidate.specifier === specifier, + ); + if (arm === undefined) { + throw new Error( + `T7-10: (a) holds no arm over ${specifier.literal} (harness bug)`, + ); + } + return arm.config; +} + +/** (b)'s arm over `specifier` among one code group's stagings. */ +function discoveredArmOf( + staging: DiscoveringStaging, + specifier: SourceSpecifier, +): DiscoveredArm { + const arm = staging.arms.find( + (candidate) => candidate.specifier === specifier, + ); + if (arm === undefined) { + throw new Error( + `T7-10: (b) by ${staging.group.label} holds no arm over ` + + `${specifier.literal} (harness bug)`, + ); + } + return arm; +} + +/** One code group's (c) stagings: (b)'s records, and the designating one. */ +interface ConsequenceStaging { + readonly group: DiscoveringGroup; + /** (b)'s control: the discovered configuration importing from "xspec". */ + readonly control: StagedTs; + /** (b)'s arm importing from `"./missing.xspec"`: the gate's, the baseline's. */ + readonly missing: DiscoveredArm; + /** (b)'s arm importing from `"./specs/A.xspec"`: the converse's twin. */ + readonly specModule: DiscoveredArm; + /** The discovered configuration importing from `"./specs/B.md"`. */ + readonly designating: StagedTs; +} + +/** (c)'s stagings, per discovering code group (TEST-SPEC T7-10(c)). */ +const T7_10_C_STAGINGS: readonly ConsequenceStaging[] = T7_10_B_STAGINGS.map( + (staging) => ({ + group: staging.group, + control: staging.control, + missing: discoveredArmOf(staging, MISSING_SPECIFIER), + specModule: discoveredArmOf(staging, SPEC_MODULE_SPECIFIER), + designating: sourceConfig( + `T7-10 xspec.config.ts ((c) discovered by ${staging.group.label}: importing from ${DESIGNATING_LITERAL})`, + DESIGNATING_LITERAL, + discoveredTail(staging.group.glob), + ).config, + }), +); + +/** + * (c)'s undiscovered twins (module header): each the configuration its + * discovered side stages, the code group left out. + */ +interface ConsequenceTwins { + /** T7-9's twin configuration, importing from `"xspec"`. */ + readonly control: StagedTs; + /** (a)'s record importing from `"./missing.xspec"`. */ + readonly missing: StagedTs; + /** (a)'s record importing from `"./specs/A.xspec"`: the converse's arm. */ + readonly specModule: StagedTs; + /** The undiscovered configuration importing from `"./specs/B.md"`. */ + readonly designating: StagedTs; +} + +/** (c)'s undiscovered twins (TEST-SPEC T7-10(c)). */ +const T7_10_C_TWINS: ConsequenceTwins = { + control: CONFIG_IMPORT_TWIN_CONFIG, + missing: undiscoveredRecord(MISSING_SPECIFIER), + specModule: undiscoveredRecord(SPEC_MODULE_SPECIFIER), + designating: stagedTs( + `T7-10 xspec.config.ts ((c) undiscovered, no code group: importing from ${DESIGNATING_LITERAL})`, + configImportText(DESIGNATING_LITERAL), + ), +}; + +// The designating literal spells no escape and no quote but its own, as +// T7-10's five do, and is no `.xspec` specifier (its declaration no spec +// module import, so no 14.18 to bring). +if ( + !DESIGNATING_LITERAL.startsWith(DOUBLE_QUOTE) || + !DESIGNATING_LITERAL.endsWith(DOUBLE_QUOTE) || + DESIGNATING_LITERAL.slice(1, -1).includes(DOUBLE_QUOTE) || + DESIGNATING_LITERAL.includes(BACKSLASH) || + DESIGNATING_LITERAL.slice(1, -1).endsWith(".xspec") +) { + throw new Error( + `T7-10 fixture self-check: ${DESIGNATING_LITERAL} must be one ` + + "double-quoted literal spelling no escape, no .xspec specifier " + + "(harness bug)", + ); +} + +/** The (c) and converse move's destination (6.5's file form). */ +const MOVE_DESTINATION = "specs/B.mdx"; + +/** `move specs/A.mdx specs/B.mdx`, its options appended per run. */ +const MOVE_ARGV: readonly string[] = [ + "move", + T7_10_SOURCE_PATH, + MOVE_DESTINATION, +]; + +/** + * The file move's applied mapping: the moved file's root, its bare-path + * identity, and its one section `a`, each ID kept and its file part + * changed, ordered by `from` bytes (SPEC 6.5, 6.6, 12.7). + */ +const MOVE_MAPPING: readonly AppliedMappingPair[] = [ + { from: T7_10_SOURCE_PATH, to: MOVE_DESTINATION }, + { from: `${T7_10_SOURCE_PATH}#a`, to: `${MOVE_DESTINATION}#a` }, +]; + +/** The session name (c)'s `review create --base` runs ask for (T6.3-4's). */ +const BASELINE_SESSION = "n"; + +/** The gated reads (c) runs, representative (TEST-SPEC T7-10(c)). */ +const GATED_READS: readonly (readonly string[])[] = [ + ["ids", "--json"], + ["query", "nodes"], +]; + +/** The validating command (c)'s premises and restaged builds run. */ +const BUILD_JSON_ARGV: readonly string[] = ["build", "--json"]; + +/** Run `argv` from the workspace root. */ +async function runAt( + product: ProductBinding, + workspace: TestWorkspace, + argv: readonly string[], +): Promise<RunResult> { + return await runProduct(product, { cwd: workspace.root, argv }); +} + +/** + * A finding as the gate compares it: every member but the message — code, + * locations, concerned path, identities (T12.0-10's projection; wording + * unpinned, H-3). + */ +function gateComparable(finding: Finding): unknown { + return { + code: finding.code, + locations: finding.locations, + path: finding.path, + identities: finding.identities, + }; +} + +/** + * A refused or gated `--json` run: exit 1 exactly, its standard output the + * 12.7 findings-only report, decoded form-exact (H-3, H-5). + */ +function refusedFindings( + result: RunResult, + context: string, + why: string, +): readonly Finding[] { + assertExitCode(result, 1, `${context} — ${why}`); + return decodeFindingsReport(parseJsonStdout(result, context), context) + .findings; +} + +/** A premise `build --json` on a valid workspace: exit 0 finding-free. */ +async function expectPremiseBuild( + product: ProductBinding, + workspace: TestWorkspace, + label: string, + rule: string, +): Promise<void> { + expectFindingFree( + await runAt(product, workspace, BUILD_JSON_ARGV), + `${label}: the premise ${sourceCommandLabel(BUILD_JSON_ARGV)}`, + rule, + ); +} + +/** + * The gate's undiscovered twin (module header): built under T7-9's twin + * configuration and restaged importing from `"./missing.xspec"`, no code + * group in either; `build --json` exits 0 finding-free, and the gated reads + * answer, exit 0. + */ +async function runGateTwin(product: ProductBinding): Promise<void> { + const label = "T7-10(c), the gate's undiscovered twin (no code group)"; + const workspace = await TestWorkspace.create( + sourceDecl(T7_10_C_TWINS.control), + ); + try { + await expectPremiseBuild( + product, + workspace, + `${label}, importing from ${CONFIG_IMPORT_TWIN_LITERAL}`, + UNDISCOVERED_RULE, + ); + await workspace.file(CONFIG_IMPORT_CONFIG_PATH, T7_10_C_TWINS.missing); + const restaged = `${label}, then importing from ${MISSING_SPECIFIER.label}`; + expectFindingFree( + await runAt(product, workspace, BUILD_JSON_ARGV), + `${restaged}: ${sourceCommandLabel(BUILD_JSON_ARGV)}`, + UNDISCOVERED_RULE, + ); + for (const argv of GATED_READS) { + expectAnswered( + await runAt(product, workspace, argv), + `${restaged}: ${sourceCommandLabel(argv)}`, + `${UNDISCOVERED_RULE}, so the workspace passes build's validations ` + + "and the read is no gated non-answer (SPEC 13.3)", + ); + } + } finally { + await workspace.dispose(); + } +} + +/** + * The gate, discovered by one code group (module header): built under the + * control's `"xspec"`, restaged importing from `"./missing.xspec"`; the + * failing `build --json` reports (b)'s findings for that arm and modifies + * nothing, and each gated read reports exactly `build`'s findings, exit 1, + * modifying nothing. + */ +async function runGateArm( + product: ProductBinding, + staging: ConsequenceStaging, +): Promise<void> { + const label = `T7-10(c), the gate, discovered by ${staging.group.label}`; + const workspace = await TestWorkspace.create(sourceDecl(staging.control)); + try { + await expectPremiseBuild( + product, + workspace, + `${label}, importing from ${CONFIG_IMPORT_TWIN_LITERAL}`, + CONTROL_RULE, + ); + await workspace.file( + CONFIG_IMPORT_CONFIG_PATH, + staging.missing.source.config, + ); + const restaged = + `${label}, then importing from ` + staging.missing.specifier.label; + const buildContext = `${restaged}: ${sourceCommandLabel(BUILD_JSON_ARGV)}`; + const built = await assertLeavesUnchanged( + workspace.root, + async () => { + const findings = refusedFindings( + await runAt(product, workspace, BUILD_JSON_ARGV), + buildContext, + "the discovered configuration carries 14.15 and 14.18, so the " + + "build fails with findings: exit 1, never 14.14 or exit 2 " + + `(${DISCOVERED_RULE}; SPEC 12.1, 12.0; TEST-SPEC T7-10(c); H-5)`, + ); + assertSourceFindings(findings, staging.missing, buildContext); + return findings; + }, + `${buildContext}: the failing build modifies nothing — every derived ` + + "file and all graph data byte-identical to the state before it " + + "(SPEC 12.1; TEST-SPEC T7-10(c))", + ); + for (const argv of GATED_READS) { + const context = `${restaged}: ${sourceCommandLabel(argv)}`; + await assertLeavesUnchanged( + workspace.root, + async () => { + const findings = refusedFindings( + await runAt(product, workspace, argv), + context, + "on a workspace failing build's validations a gated read " + + "reports the findings a build would now report and exits 1, " + + "answering nothing (SPEC 13.3, 12.0; TEST-SPEC T7-10(c); H-5)", + ); + assertSameJson( + findings.map(gateComparable), + built.map(gateComparable), + `${context}: the gate reports exactly the findings the build ` + + "reported — that arm's 14.15 and 14.18 — every member but " + + "the message, in 12.7's order (SPEC 13.3, 12.7, 14; " + + "TEST-SPEC T7-10(c))", + ); + }, + `${context}: the gated read modifies nothing — derived files and ` + + "graph data byte-identical (SPEC 13.3; TEST-SPEC T7-10(c))", + ); + } + } finally { + await workspace.dispose(); + } +} + +/** + * `move specs/A.mdx specs/B.mdx --json` performed (module header): exit 0 + * with the applied mapping, `specs/B.mdx` then holding the moved bytes and + * `specs/A.mdx` gone. + */ +async function expectMoved( + product: ProductBinding, + workspace: TestWorkspace, + label: string, + rule: string, +): Promise<void> { + const argv = [...MOVE_ARGV, "--json"]; + const context = `${label}: ${sourceCommandLabel(argv)}`; + const result = await runAt(product, workspace, argv); + assertExitCode( + result, + 0, + `${context} — the move proceeds, exit 0 (${rule}; SPEC 6.5; H-5)`, + ); + assertAppliedMapping( + decodeAppliedMappingReport(parseJsonStdout(result, context), context), + MOVE_MAPPING, + `${context}: its applied mapping is the moved file's root and its ` + + "section a, each ID kept and its file part changed (SPEC 6.5, 6.6, " + + "12.7)", + ); + await assertFileBytes( + workspace.path(MOVE_DESTINATION), + T7_10_SOURCE.source, + `${context}: ${MOVE_DESTINATION} holds the moved bytes — the moved ` + + "file holds no import and no reference, so the move rewrites none " + + "of them (SPEC 6.5)", + ); + const origin = await workspace.kind(T7_10_SOURCE_PATH); + if (origin !== "absent") { + fail( + `${context}: the relocated origin ${T7_10_SOURCE_PATH} is gone ` + + `after the file move (SPEC 6.5); found a ${origin} there`, + ); + } +} + +/** + * The designation's undiscovered twin (module header): importing from + * `"./specs/B.md"` with no code group, the move proceeds. + */ +async function runMoveTwin(product: ProductBinding): Promise<void> { + const workspace = await TestWorkspace.create( + sourceDecl(T7_10_C_TWINS.designating), + ); + try { + await expectMoved( + product, + workspace, + "T7-10(c), the designation's undiscovered twin (no code group), " + + `importing from ${DESIGNATING_LITERAL}`, + `${UNDISCOVERED_RULE}, so its specifier designates nothing 6.5 reads`, + ); + } finally { + await workspace.dispose(); + } +} + +/** + * The designation, discovered by one code group (module header): the move + * is refused with exactly one `refused-invalid-destination` finding, + * modifying nothing. + */ +async function runRefusedMoveArm( + product: ProductBinding, + staging: ConsequenceStaging, +): Promise<void> { + const argv = [...MOVE_ARGV, "--json"]; + const context = + `T7-10(c), the designation, discovered by ${staging.group.label}, ` + + `importing from ${DESIGNATING_LITERAL}: ${sourceCommandLabel(argv)}`; + const workspace = await TestWorkspace.create(sourceDecl(staging.designating)); + try { + await assertLeavesUnchanged( + workspace.root, + async () => { + const findings = refusedFindings( + await runAt(product, workspace, argv), + context, + "the destination's would-be emit path specs/B.md is designated " + + "by the relative specifier of a code source's module-linking " + + "form — the discovered configuration's import — which the " + + "move would make a derived-file path, so the move is refused, " + + "exit 1 (SPEC 6.5, 4, 14.15, 12.0; TEST-SPEC T7-10(c), " + + "T6.5-20(d); H-5)", + ); + assertSameJson( + findings.map(pinnedFinding), + [ + { + code: "refused-invalid-destination", + locations: [], + path: MOVE_DESTINATION, + }, + ], + `${context}: exactly one refused-invalid-destination finding, ` + + "concerning the destination as spelled, its locations [] — one " + + "finding per reason and nothing beside it, the workspace being " + + "valid while no specs/B.mdx exists (SPEC 6.5, 14, 12.7; " + + "T6.5-20's contract)", + ); + }, + `${context}: the refused move modifies nothing — sources, derived ` + + "files, and the journal alike (SPEC 6.5; TEST-SPEC T7-10(c))", + ); + } finally { + await workspace.dispose(); + } +} + +/** `impact --base <c1> --json`, as diagnoses name it. */ +const IMPACT_LABEL = "`impact --base c1 --json`"; + +/** `review create --base <c1> --name n --json`, as diagnoses name it. */ +const CREATE_LABEL = + "`review create --base c1 --name " + BASELINE_SESSION + " --json`"; + +/** `impact --base <c1> --json`. */ +function impactArgv(c1: string): readonly string[] { + return ["impact", "--base", c1, "--json"]; +} + +/** `review create --base <c1> --name n --json`. */ +function createArgv(c1: string): readonly string[] { + return [ + "review", + "create", + "--base", + c1, + "--name", + BASELINE_SESSION, + "--json", + ]; +} + +/** Why (c)'s discovered baseline fails (module header). */ +const DISCOVERED_BASELINE_WHY = + "c1's configuration, discovered by its own code group, is a code source " + + "failing validation (14.15 and 14.18), so the baseline content cannot " + + "be parsed and validated as a workspace: a usage error, exit 2 (SPEC " + + "6.3, 12.0; TEST-SPEC T7-10(c), T6.3-4; H-5)"; + +/** + * A baseline-taking command failing as T6.3-4's baseline failing validation + * does (module header): exit 2, the 12.7 error document the whole of + * standard output, its `code` and `path` `null`, and standard error naming + * the offending file, `xspec.config.ts`. `why` says why the baseline fails. + */ +function expectFailingBaseline( + result: RunResult, + context: string, + why: string, +): void { + assertExitCode(result, 2, `${context} — ${why}`); + const error = expectErrorDocument(result, context); + assertSameJson( + { code: error.code, path: error.path }, + { code: null, path: null }, + `${context}: a baseline that cannot be reconstructed is a plain usage ` + + "error — the error document's code and path null, never a numbered " + + "condition's stable code and concerned path (SPEC 6.3, 12.7; " + + `T6.3-4) (message: ${JSON.stringify(error.message)})`, + ); + if (!result.stderr.includes(CONFIG_IMPORT_CONFIG_PATH)) { + fail( + `${context}: the actionable error on standard error names the ` + + `offending file, the configuration in c1's tree ` + + `(${CONFIG_IMPORT_CONFIG_PATH}) (SPEC 6.3: a baseline whose ` + + "content cannot be parsed and validated fails with an error " + + "naming the offending entries or files; 12.0: usage-error " + + `messages are standard-error content); got ${summarizeResult(result)}`, + ); + } +} + +/** + * A baseline staging (module header): `c1` committed over the workspace as + * created — its configuration `c1Config` beside `specs/A.mdx` — and the + * working tree then taking `currentConfig`, its premise `build --json` + * exiting 0 finding-free. Returns `c1`'s commit identity. + */ +async function stageBaseline( + product: ProductBinding, + workspace: TestWorkspace, + currentConfig: StagedTs, + label: string, + rule: string, +): Promise<string> { + await workspace.gitInit(); + const c1 = await workspace.gitCommitAll(`c1: ${label}`); + await workspace.file(CONFIG_IMPORT_CONFIG_PATH, currentConfig); + await expectPremiseBuild(product, workspace, label, rule); + return c1; +} + +/** + * The baseline's undiscovered twin (module header): `c1`'s configuration + * imports from `"./missing.xspec"`, the working tree's from `"xspec"`, no + * code group in either; both baseline-taking commands resolve, exit 0. + */ +async function runBaselineTwin(product: ProductBinding): Promise<void> { + const label = + "T7-10(c), the baseline's undiscovered twin (no code group): c1 " + + `importing from ${MISSING_SPECIFIER.literal}, the working tree from ` + + CONFIG_IMPORT_TWIN_LITERAL; + const resolves = + "no configured group discovers c1's configuration, so the baseline " + + "content parses and validates as a workspace and the baseline " + + "resolves, exit 0 (SPEC 6.3, 7; TEST-SPEC T7-10(c); H-5)"; + const workspace = await TestWorkspace.create( + sourceDecl(T7_10_C_TWINS.missing), + ); + try { + const c1 = await stageBaseline( + product, + workspace, + T7_10_C_TWINS.control, + label, + UNDISCOVERED_RULE, + ); + const impactContext = `${label}: ${IMPACT_LABEL}`; + const impact = await runAt(product, workspace, impactArgv(c1)); + assertExitCode(impact, 0, `${impactContext} — ${resolves}`); + decodeImpactReport(parseJsonStdout(impact, impactContext), impactContext); + assertExitCode( + await runAt(product, workspace, createArgv(c1)), + 0, + `${label}: ${CREATE_LABEL} — ${resolves}`, + ); + } finally { + await workspace.dispose(); + } +} + +/** + * The baseline, discovered by one code group (module header): `c1`'s + * discovered configuration imports from `"./missing.xspec"`, the working + * tree's is the control; both baseline-taking commands fail as T6.3-4's + * baseline failing validation does, `review create` modifying nothing. + */ +async function runBaselineArm( + product: ProductBinding, + staging: ConsequenceStaging, +): Promise<void> { + const label = + `T7-10(c), the baseline, discovered by ${staging.group.label}: c1 ` + + `importing from ${staging.missing.specifier.literal}, the working ` + + `tree from ${CONFIG_IMPORT_TWIN_LITERAL}`; + const workspace = await TestWorkspace.create( + sourceDecl(staging.missing.source.config), + ); + try { + const c1 = await stageBaseline( + product, + workspace, + staging.control, + label, + CONTROL_RULE, + ); + expectFailingBaseline( + await runAt(product, workspace, impactArgv(c1)), + `${label}: ${IMPACT_LABEL}`, + DISCOVERED_BASELINE_WHY, + ); + const createContext = `${label}: ${CREATE_LABEL}`; + await assertLeavesUnchanged( + workspace.root, + async () => { + expectFailingBaseline( + await runAt(product, workspace, createArgv(c1)), + createContext, + DISCOVERED_BASELINE_WHY, + ); + }, + `${createContext}: refused at baseline resolution, review create ` + + "modifies nothing — no session written; sources, derived files, " + + "graph data, and .git/ byte-identical (SPEC 10.7, 6.3; TEST-SPEC " + + "T7-10(c))", + ); + } finally { + await workspace.dispose(); + } +} + +/** + * The converse (module header): importing from `"./specs/A.xspec"`, + * undiscovered, the preview lists no edit in `xspec.config.ts`, the move + * leaves it byte-identical, and `build` and `check` then exit 0 + * finding-free. + */ +async function runConverseArm(product: ProductBinding): Promise<void> { + const label = + "T7-10(c), the converse, undiscovered (no code group), importing from " + + SPEC_MODULE_SPECIFIER.label; + const workspace = await TestWorkspace.create( + sourceDecl(T7_10_C_TWINS.specModule), + ); + try { + const previewArgv = [...MOVE_ARGV, "--preview", "--json"]; + const previewContext = `${label}: ${sourceCommandLabel(previewArgv)}`; + const preview = await runAt(product, workspace, previewArgv); + assertExitCode( + preview, + 0, + `${previewContext} — valid undiscovered ((a)), the move would ` + + "proceed, so its preview completes, exit 0 (SPEC 6.6, 7; H-5)", + ); + const plan = decodePreviewReport( + parseJsonStdout(preview, previewContext), + previewContext, + ); + if (plan.files === null) { + fail( + `${previewContext}: the completed preview reports its plan — its ` + + "files non-null (SPEC 6.6, 12.7)", + ); + } + const configPath = Buffer.from(CONFIG_IMPORT_CONFIG_PATH, "utf8"); + assertSameJson( + plan.files + .filter((entry) => pathValueBytes(entry.file).equals(configPath)) + .flatMap((entry) => + entry.edits.map((edit) => ({ + file: renderPathValue(entry.file), + class: edit.class, + range: { start: edit.range.start, end: edit.range.end }, + })), + ), + [], + `${previewContext}: the preview lists no edit in ` + + `${CONFIG_IMPORT_CONFIG_PATH} — no configured group discovers it, ` + + "so its import is none of the paths by which other files import " + + "the moved file's generated module, and 6.5 rewrites no specifier " + + "there (SPEC 6.5, 6.6, 7; TEST-SPEC T7-10(c))", + ); + await expectMoved(product, workspace, label, UNDISCOVERED_RULE); + await assertFileBytes( + workspace.path(CONFIG_IMPORT_CONFIG_PATH), + T7_10_C_TWINS.specModule.source, + `${label}: after the move, ${CONFIG_IMPORT_CONFIG_PATH} is ` + + "byte-identical to its staged bytes — its import never rewritten " + + 'to "./specs/B.xspec" (SPEC 6.5, 7; TEST-SPEC T7-10(c))', + ); + for (const word of T7_10_VALIDATING_WORDS) { + const argv = [word, "--json"]; + expectFindingFree( + await runAt(product, workspace, argv), + `${label}, after the move: ${sourceCommandLabel(argv)}`, + UNDISCOVERED_RULE, + ); + } + } finally { + await workspace.dispose(); + } +} + +/** + * The converse's discovered twin, by one code group (module header): + * invalid per (b), the move is refused as 6.4's invalid workspace — exit 1, + * (b)'s findings for that arm alone — modifying nothing. + */ +async function runConverseTwin( + product: ProductBinding, + staging: ConsequenceStaging, +): Promise<void> { + const arm = staging.specModule; + const argv = [...MOVE_ARGV, "--json"]; + const context = + `T7-10(c), the converse's discovered twin, by ${staging.group.label}, ` + + `importing from ${arm.specifier.label}: ${sourceCommandLabel(argv)}`; + const workspace = await TestWorkspace.create(sourceDecl(arm.source.config)); + try { + await assertLeavesUnchanged( + workspace.root, + async () => { + const findings = refusedFindings( + await runAt(product, workspace, argv), + context, + "invalid per (b), the workspace fails build's validations, so " + + "the move is refused before modifying anything, exit 1 (SPEC " + + "6.5, 6.4, 12.0; TEST-SPEC T7-10(c); H-5)", + ); + assertSourceFindings( + findings, + arm, + `${context} — an invalid-workspace refusal reports the ` + + "workspace's findings alone, no refusal reason beside them " + + "(SPEC 6.4, 6.5, 14)", + ); + }, + `${context}: the refused move modifies nothing (SPEC 6.5, 6.4; ` + + "TEST-SPEC T7-10(c))", + ); + } finally { + await workspace.dispose(); + } +} + +/** One (c) arm's run; each names itself in its diagnoses. */ +type ConsequenceArm = (product: ProductBinding) => Promise<void>; + +/** (c)'s arms, in the order the body runs them (module header). */ +const T7_10_C_ARMS: readonly ConsequenceArm[] = [ + runGateTwin, + ...T7_10_C_STAGINGS.map( + (staging): ConsequenceArm => + (product) => + runGateArm(product, staging), + ), + runMoveTwin, + ...T7_10_C_STAGINGS.map( + (staging): ConsequenceArm => + (product) => + runRefusedMoveArm(product, staging), + ), + runBaselineTwin, + ...T7_10_C_STAGINGS.map( + (staging): ConsequenceArm => + (product) => + runBaselineArm(product, staging), + ), + runConverseArm, + ...T7_10_C_STAGINGS.map( + (staging): ConsequenceArm => + (product) => + runConverseTwin(product, staging), + ), +]; + +// --------------------------------------------------------------------------- +// T7-10 (d): baselines + +/** + * (d)'s `c1` source (module header): `specs/A.mdx` with its one section's + * text before the edit the working tree holds — T7-10's own source, + * `<S id="a">A</S>` — so that `c1`'s sources differ from the working + * tree's by that section's edited text alone. + */ +const T7_10_D_C1_SOURCE: StagedMdx = stagedMdx( + `T7-10 specs/A.mdx ((d) c1's source, its one section's text before the working tree's edit: <S id="a">Old A</S>)`, + `<S id="a">Old A</S> +`, +); + +/** The section whose text `c1` and the working tree differ by (5.6). */ +const EDITED_SECTION = `${T7_10_SOURCE_PATH}#a`; + +/** The opening tag both texts of `specs/A.mdx` spell, its id `a`. */ +const EDITED_SECTION_OPENING = '<S id="a">'; + +// c1's source and the working tree's each spell the one section `a` once, +// their texts differing (module header). +for (const record of [T7_10_D_C1_SOURCE, T7_10_SOURCE]) { + if ( + typeof record.source !== "string" || + !record.source.startsWith(EDITED_SECTION_OPENING) || + occurrences(record.source, EDITED_SECTION_OPENING) !== 1 + ) { + throw new Error( + `T7-10(d) fixture self-check: ${record.name} must spell the one ` + + `section a, opening with ${EDITED_SECTION_OPENING}, once (harness bug)`, + ); + } +} +if (T7_10_D_C1_SOURCE.source === T7_10_SOURCE.source) { + throw new Error( + "T7-10(d) fixture self-check: c1's source must differ from the " + + "working tree's by its section's edited text (harness bug)", + ); +} + +/** + * What a resolving (d) arm stages in the working tree once `c1` is + * committed (module header): nothing; a FIFO at the path `"./fifo"` + * designates; or T7-9(d)'s trap package at `node_modules/trap`, where + * resolving `"trap"` from the configuration file's directory looks. + */ +type BaselineReadStaging = "none" | "fifo" | "trap"; + +/** One (d) arm whose `c1` resolves (module header). */ +interface BaselineReadArm { + /** `c1`'s specifier as diagnoses name it, with what it designates. */ + readonly label: string; + /** `c1`'s specifier exactly as it stands in the file, its quotes included. */ + readonly literal: string; + /** `c1`'s configuration: T7-9's over `literal`, no code group. */ + readonly c1Config: StagedTs; + readonly staging: BaselineReadStaging; +} + +/** A resolving (d) arm: `c1`'s configuration declared well-formed (S-9). */ +function baselineReadArm( + label: string, + literal: string, + staging: BaselineReadStaging, +): BaselineReadArm { + return { + label, + literal, + staging, + c1Config: stagedTs( + `T7-10 xspec.config.ts ((d) c1's undiscovered configuration, importing from ${literal})`, + configImportText(literal), + ), + }; +} + +/** T7-10(d)'s five resolving baselines (TEST-SPEC T7-10(d)). */ +const T7_10_D_ARMS: readonly BaselineReadArm[] = [ + baselineReadArm('the empty string ""', '""', "none"), + baselineReadArm( + 'the relative specifier "./nowhere", designating nothing', + '"./nowhere"', + "none", + ), + baselineReadArm( + 'the bare name "XSPEC", a single-casing arm (12.0: no case folding)', + '"XSPEC"', + "none", + ), + baselineReadArm( + `the relative specifier "./${FIFO_PATH}", designating a FIFO at that ` + + "path in the working tree", + DOUBLE_QUOTE + "./" + FIFO_PATH + DOUBLE_QUOTE, + "fifo", + ), + baselineReadArm( + `the bare name "${TRAP_NAME}", beside T7-9(d)'s trap package at ` + + `${installedDirectory(TRAP_NAME)} in the working tree`, + DOUBLE_QUOTE + TRAP_NAME + DOUBLE_QUOTE, + "trap", + ), +]; + +/** + * (d)'s not-well-formed baseline (module header): `c1`'s configuration + * spells T7-9(b)'s hexadecimal escape with one hex digit as its specifier — + * a scanning error of TypeScript 5.9.3, the record declared unparseable + * (S-9) — its backslash `BACKSLASH`, so that this module spells no escape. + */ +const T7_10_D_ESCAPE: ImportArm = (() => { + const escape = `${BACKSLASH}x4`; + const literal = DOUBLE_QUOTE + escape + DOUBLE_QUOTE; + return { + label: + "a hexadecimal escape with one hex digit (a backslash, x, then 4), " + + "T7-9(b)'s first", + literal, + spelled: { + ...PLAIN_DOUBLE, + backslashes: 1, + escape: { spelling: escape, at: 1 }, + }, + config: stagedTs( + "T7-10 xspec.config.ts ((d) c1's configuration spelling a hexadecimal escape with one hex digit as its specifier, a scanning error)", + configImportText(literal), + "unparseable", + ), + }; +})(); + +// (d)'s module-load self-checks (module header): each resolving baseline's +// literal is one double-quoted literal spelling no escape, its record the +// builder's over it, the FIFO arm's designating the FIFO's path and the +// trap arm's the trap package's name; and the not-well-formed baseline's +// literal is T7-9(b)'s first, staged exactly as spelled. +for (const arm of T7_10_D_ARMS) { + const value = arm.literal.slice(1, -1); + if ( + arm.literal.length < 2 || + !arm.literal.startsWith(DOUBLE_QUOTE) || + !arm.literal.endsWith(DOUBLE_QUOTE) || + value.includes(DOUBLE_QUOTE) || + value.includes(BACKSLASH) || + arm.c1Config.source !== configImportText(arm.literal) || + (arm.staging === "fifo" && value !== "./" + FIFO_PATH) || + (arm.staging === "trap" && value !== TRAP_NAME) + ) { + throw new Error( + `T7-10(d) fixture self-check: the baseline importing from ` + + `${arm.literal} must be one double-quoted literal spelling no ` + + "escape, its record the builder's over it, designating where its " + + "staging stands (harness bug)", + ); + } +} +if (T7_9_B_ARMS[0]?.literal !== T7_10_D_ESCAPE.literal) { + throw new Error( + "T7-10(d) fixture self-check: the not-well-formed baseline's specifier " + + "must be T7-9(b)'s first, a hexadecimal escape with one hex digit " + + "(harness bug)", + ); +} +assertStagedAsSpelled(T7_10_D_ESCAPE, "T7-10(d)"); + +/** Why each resolving (d) baseline answers as the twin's (module header). */ +const BASELINE_READ_RULE = + "a baseline's configuration is read as the current one's (SPEC 7, 6.3): " + + "xspec never interprets, resolves, or loads its import's specifier, " + + "making no read on its account, so c1 resolves and everything xspec " + + "derives from it is independent of the specifier's spelling and of what " + + "it designates — nothing, a FIFO, or an installed package alike " + + "(TEST-SPEC T7-10(d))"; + +/** Why a (d) command's hang is the product's (module header). */ +const BASELINE_READ_BLOCKED = + "a product resolving, reading through, or loading c1's configuration's " + + 'specifier — in the FIFO arm opening the FIFO "./fifo" designates in ' + + "the working tree, which has no writer — blocks there, where xspec " + + "never resolves, reads, or loads a baseline configuration's specifier " + + "(SPEC 7, 6.3; TEST-SPEC T7-10(d))"; + +/** Why each (d) working tree's premise `build` passes (module header). */ +const BASELINE_READ_PREMISE = + "the working tree's configuration imports from " + + CONFIG_IMPORT_TWIN_LITERAL + + ", no group discovering it, beside a valid source, so the workspace is " + + "valid (TEST-SPEC T7-10(d))"; + +/** Why (d)'s not-well-formed baseline fails (module header). */ +const ESCAPE_BASELINE_WHY = + "c1's configuration spells a scanner-rejected escape as its specifier, " + + "so it is not well-formed TypeScript (14.20) and the baseline content " + + "cannot be parsed and validated as a workspace — a baseline's " + + "configuration read as the current one's is (SPEC 7) — the code-less " + + "usage error, exit 2 (SPEC 6.3, 7, 12.0; TEST-SPEC T7-10(d), T6.3-4; H-5)"; + +/** (d)'s twin as diagnoses name it (module header). */ +const BASELINE_TWIN_LABEL = + "the twin commit importing from " + + CONFIG_IMPORT_TWIN_LITERAL + + ", beside the same sources and working tree"; + +/** `review status n --json`, which reconstructs the recorded baseline. */ +const STATUS_ARGV: readonly string[] = [ + "review", + "status", + BASELINE_SESSION, + "--json", +]; + +/** `review status n --json`, as diagnoses name it. */ +const STATUS_LABEL = "`review status " + BASELINE_SESSION + " --json`"; + +/** A (d) workspace as `c1` commits it: `c1Config` beside `c1`'s source. */ +function baselineReadDecl(c1Config: StagedTs): WorkspaceDecl { + return { + files: { + [CONFIG_IMPORT_CONFIG_PATH]: c1Config, + [T7_10_SOURCE_PATH]: T7_10_D_C1_SOURCE, + }, + }; +} + +/** + * A (d) staging (module header): `c1` committed over the workspace as + * created, the working tree then taking T7-9's twin configuration and + * T7-10's source, its premise `build --json` exiting 0 finding-free. + * Returns `c1`'s commit identity. + */ +async function stageBaselineRead( + product: ProductBinding, + workspace: TestWorkspace, + label: string, +): Promise<string> { + await workspace.gitInit(); + const c1 = await workspace.gitCommitAll(`c1: ${label}`); + await workspace.file(CONFIG_IMPORT_CONFIG_PATH, CONFIG_IMPORT_TWIN_CONFIG); + await workspace.file(T7_10_SOURCE_PATH, T7_10_SOURCE); + await expectPremiseBuild(product, workspace, label, BASELINE_READ_PREMISE); + return c1; +} + +/** After each (d) command: what the arm's staging asserts (module header). */ +type BaselineReadCheck = (result: RunResult, context: string) => Promise<void>; + +/** + * Stage what `staging` names in the working tree (module header) — the FIFO + * made by `stageFifo`, verified a FIFO in place and never opened by the + * harness; the trap package's manifest and entry — and return the check + * that follows each command. + */ +async function stageBaselineDesignation( + workspace: TestWorkspace, + staging: BaselineReadStaging, +): Promise<BaselineReadCheck> { + if (staging === "fifo") { + const fifo = await stageFifo(workspace, FIFO_PATH); + return async (_result, context) => { + await assertFifosIntact( + fifo, + `${context}: the FIFO "./${FIFO_PATH}" designates in the working ` + + "tree is still a FIFO in place, the command having ended within " + + "its own guard — unopened, as xspec never resolves, reads, or " + + "loads a baseline configuration's specifier (SPEC 7, 6.3; " + + "TEST-SPEC T7-10(d), S-3)", + ); + }; + } + if (staging === "trap") { + const at = installedDirectory(TRAP_NAME); + await workspace.file(`${at}/${PACKAGE_MANIFEST}`, trapManifest(TRAP_NAME)); + await workspace.file(`${at}/${TRAP_ENTRY_FILE}`, TRAP_ENTRY); + return async (result, context) => { + await assertTrapNeverRan(workspace, result, context, BASELINE_READ_RULE); + }; + } + return async () => undefined; +} + +/** + * A resolving (d) baseline's `impact --base c1 --json` (module header): + * exit 0 — impact is informational (9.3) — with one impact report decoded + * through H-3's adapter, reporting the edited section `changed` (5.6). + * Returns its impact information: the report but the baseline a product + * may echo, which the two commits' identities make differ (E-6). + */ +function expectBaselineImpact( + result: RunResult, + context: string, + why: string, +): unknown { + assertExitCode( + result, + 0, + `${context} — ${why}; impact is informational, exit 0 (SPEC 9.3, 6.3; ` + + "H-5)", + ); + const report = decodeImpactReport(parseJsonStdout(result, context), context); + const edited = report.requirements.some( + (entry) => + !entry.deleted && + entry.nodes.includes(EDITED_SECTION) && + entry.categories.some((category) => category.category === "changed"), + ); + if (!edited) { + fail( + `${context}: the impact information reports the edited section ` + + `${EDITED_SECTION} changed — c1's sources differ from the working ` + + "tree's by that section's edited text (SPEC 5.6, 9.3; TEST-SPEC " + + "T7-10(d)); its requirements: " + + JSON.stringify(report.requirements), + ); + } + return { requirements: report.requirements, code: report.code }; +} + +/** + * A resolving (d) baseline's `review status n --json` (module header): exit + * 0 with one status report decoded through H-3's adapter. Returns its + * items' kinds, scopes, statuses, and blocked states, in item order. + */ +function expectBaselineItems( + result: RunResult, + context: string, + why: string, +): unknown { + assertExitCode(result, 0, `${context} — ${why} (SPEC 10.7; H-5)`); + return decodeSessionStatusReport( + parseJsonStdout(result, context), + context, + ).items.map((row) => ({ + kind: row.kind, + scope: row.scope, + status: row.status, + blocked: row.blocked, + })); +} + +/** What (d)'s twin reports, each arm's comparison basis (module header). */ +interface BaselineReadTwin { + /** Its impact information (`expectBaselineImpact`). */ + readonly impact: unknown; + /** Its status items (`expectBaselineItems`). */ + readonly items: unknown; +} + +/** + * (d)'s twin (module header): `c1` importing from `"xspec"` beside `c1`'s + * source, the working tree the arms' but for their FIFO and trap; `impact + * --base c1 --json`, `review create --base c1 --name n --json`, and + * `review status n --json` each exit 0. + */ +async function runBaselineReadTwin( + product: ProductBinding, +): Promise<BaselineReadTwin> { + const label = `T7-10(d), ${BASELINE_TWIN_LABEL}`; + const resolves = + "c1's configuration, undiscovered, is the working tree's own, so the " + + "baseline resolves (SPEC 6.3, 7)"; + const workspace = await TestWorkspace.create( + baselineReadDecl(CONFIG_IMPORT_TWIN_CONFIG), + ); + try { + const c1 = await stageBaselineRead(product, workspace, label); + const impact = expectBaselineImpact( + await runAt(product, workspace, impactArgv(c1)), + `${label}: ${IMPACT_LABEL}`, + resolves, + ); + assertExitCode( + await runAt(product, workspace, createArgv(c1)), + 0, + `${label}: ${CREATE_LABEL} — ${resolves}, so the session is created ` + + "(SPEC 10.7; H-5)", + ); + const items = expectBaselineItems( + await runAt(product, workspace, STATUS_ARGV), + `${label}: ${STATUS_LABEL}`, + "the session exists and its recorded baseline resolves and " + + "reconstructs", + ); + return { impact, items }; + } finally { + await workspace.dispose(); + } +} + +/** + * The twin's answers, for an arm comparing with them; where the twin's run + * failed — its diagnosis collected among the body's failures — the + * comparison fails diagnosed, the arm never skipped (H-9). + */ +function twinOf( + twin: BaselineReadTwin | undefined, + context: string, +): BaselineReadTwin { + if (twin === undefined) { + fail( + `${context}: its answer is compared with that against ` + + `${BASELINE_TWIN_LABEL}, whose run failed (diagnosed among this ` + + "test's failed arms), so the comparison cannot hold (H-9: an arm " + + "is never skipped)", + ); + } + return twin; +} + +/** + * One resolving (d) baseline (module header): its staging, then `impact + * --base c1 --json` answering as the twin's; in the FIFO and trap arms, + * `review create --base c1 --name n --json` and `review status n --json` + * too, each exiting 0, status's items the twin's; after each command, the + * FIFO still a FIFO in place, or the trap never run. + */ +async function runBaselineReadArm( + product: ProductBinding, + twin: BaselineReadTwin | undefined, + arm: BaselineReadArm, +): Promise<void> { + const label = + "T7-10(d), c1's undiscovered configuration importing from " + arm.label; + const workspace = await TestWorkspace.create(baselineReadDecl(arm.c1Config)); + try { + const c1 = await stageBaselineRead(product, workspace, label); + const check = await stageBaselineDesignation(workspace, arm.staging); + const run = async ( + argv: readonly string[], + context: string, + ): Promise<RunResult> => { + const result = await runGuardedCommand( + product, + workspace, + argv, + context, + BASELINE_READ_BLOCKED, + ); + await check(result, context); + return result; + }; + const impactContext = `${label}: ${IMPACT_LABEL}`; + assertSameJson( + expectBaselineImpact( + await run(impactArgv(c1), impactContext), + impactContext, + BASELINE_READ_RULE, + ), + twinOf(twin, impactContext).impact, + `${impactContext}: its impact information — categories with their ` + + "attributions, collapsed chains, deleted and added identities, and " + + "each impacted location with its witness edge and path, decoded " + + "through H-3's adapter, never compared byte for byte (E-6) — " + + `equals that against ${BASELINE_TWIN_LABEL} (SPEC 9.3; ` + + `${BASELINE_READ_RULE})`, + ); + if (arm.staging === "none") return; + const createContext = `${label}: ${CREATE_LABEL}`; + assertExitCode( + await run(createArgv(c1), createContext), + 0, + `${createContext} — ${BASELINE_READ_RULE}, so the session is created ` + + "(SPEC 10.7; H-5)", + ); + const statusContext = `${label}: ${STATUS_LABEL}`; + assertSameJson( + expectBaselineItems( + await run(STATUS_ARGV, statusContext), + statusContext, + "reconstructing the recorded baseline reads c1's configuration " + + "again, as the current one's is read (SPEC 10.7, 7)", + ), + twinOf(twin, statusContext).items, + `${statusContext}: the items it reports — their kinds, scopes, ` + + "statuses, and blocked states, in item order, decoded through " + + "H-3's adapter — equal those the same two commands report against " + + `${BASELINE_TWIN_LABEL} (SPEC 10.7, 10.5; ${BASELINE_READ_RULE})`, + ); + } finally { + await workspace.dispose(); + } +} + +/** + * (d)'s not-well-formed baseline (module header): `c1`'s configuration + * spells T7-9(b)'s hexadecimal escape with one hex digit as its specifier, + * the working tree's configuration and sources valid; `impact --base c1 + * --json` fails as T6.3-4's baseline whose configuration fails validation + * does. + */ +async function runBaselineEscapeArm(product: ProductBinding): Promise<void> { + const label = + `T7-10(d), c1's configuration spelling ${T7_10_D_ESCAPE.label} as its ` + + "specifier, not well-formed TypeScript (14.20)"; + const workspace = await TestWorkspace.create( + baselineReadDecl(T7_10_D_ESCAPE.config), + ); + try { + const c1 = await stageBaselineRead(product, workspace, label); + expectFailingBaseline( + await runAt(product, workspace, impactArgv(c1)), + `${label}: ${IMPACT_LABEL}`, + ESCAPE_BASELINE_WHY, + ); + } finally { + await workspace.dispose(); + } +} + +/** + * Run (d)'s twin, collecting its diagnosed failure as `collectArmFailure` + * does (module header): its answers, or `undefined` once its failure is + * recorded; anything else propagates at once. + */ +async function collectTwinFailure( + failures: string[], + twin: () => Promise<BaselineReadTwin>, +): Promise<BaselineReadTwin | undefined> { + try { + return await twin(); + } catch (error) { + if (!(error instanceof HarnessAssertionError)) throw error; + failures.push(error.message); + return undefined; + } +} + +/** How many (d) arms T7-10 runs: the twin, the resolving ones, the escape. */ +const T7_10_D_ARM_COUNT = 1 + T7_10_D_ARMS.length + 1; + +// --------------------------------------------------------------------------- +// T7-10 (e): discovered by a spec group + +/** The one spec group of every T7-10 configuration (T7-9's tail names it). */ +const T7_10_SPEC_GROUP = "main"; + +/** (e)(ii)'s configuration file, named by `--config` on every invocation. */ +const MDX_CONFIG_PATH = "xspec.config.mdx"; + +/** `xspec.config.mdx`'s generated-module path, `NAME.xspec.ts` (SPEC 13.1). */ +const MDX_CONFIG_MODULE = "xspec.config.xspec.ts"; + +/** (e)(ii)'s `--config` option and value, carried by every invocation. */ +const MDX_CONFIG_ARGV: readonly string[] = ["--config", MDX_CONFIG_PATH]; + +/** + * (e)'s configuration text after its specifier: T7-9's tail + * (`CONFIG_IMPORT_TAIL`) with the spec group `main` globbing `specs/*.mdx` + * and `glob` — the import's line end, a blank line, and the default export + * spelled with no blank line inside it, so that, read as MDX, the import and + * the export each derive as an ESM block (module header; SPEC 14.20). + */ +function specDiscoveredTail(glob: string): string { + return ` + +export default defineConfig({ + specs: { + ${T7_10_SPEC_GROUP}: ["specs/*.mdx", "${glob}"] + }, + markdown: { emit: true } +}) +`; +} + +/** + * One of T7-10(e)'s configurations a spec group discovers (module header): + * its record, and the ranges its findings locate. + */ +interface SpecDiscoveredArm { + /** The arm as diagnoses name it. */ + readonly label: string; + /** The configuration file's workspace-relative path. */ + readonly configPath: string; + /** The spec group's glob matching the configuration file. */ + readonly glob: string; + /** `--config` and its value where the arm names the file, else none. */ + readonly configArgv: readonly string[]; + /** + * The configuration, read both as a configuration (plain TypeScript, the + * grammar its name selects, 14.20) and as a spec source (MDX): an MDX + * record carrying its TypeScript declaration, well-formed under each + * (S-9; helpers/staged-mdx.ts). + */ + readonly config: StagedMdx; + /** + * The import declaration by its own characters, the import range of + * 11.4: the file's first bytes, `import` through the specifier's closing + * quote, no terminator spelled (SPEC 14, 1.7). + */ + readonly importRange: SourceRange; + /** + * The export statement whole: `export` through the call's closing + * parenthesis, the line feed ending the file excluded (SPEC 14). + */ + readonly exportRange: SourceRange; + /** + * The file lacks the `.mdx` extension ((i); SPEC 7.1): 14.19 concerning + * it, and its `derived` entry's `module` and `markdown` `null` (13.1, + * 11.6). Otherwise ((ii)) its `derived` entry's `module` is its + * generated-module path, `xspec.config.xspec.ts` (13.1). + */ + readonly withoutMdxExtension: boolean; +} + +/** + * Compose (e)'s configuration at `configPath` — the shared builder's head, + * `"xspec"`, and `specDiscoveredTail(glob)` — as an MDX record carrying its + * TypeScript declaration, declared well-formed as MDX and as TypeScript + * (S-9), and pin its two ranges, checking at module + * load that the text is ASCII (its code units its bytes), its first line + * the import declaration ending at the specifier's closing quote, then one + * blank line, then the export statement — `import` and `export` each + * spelled once — running through the call's closing parenthesis with no + * blank line inside it, and one line feed ending the file. + */ +function specDiscoveredArm( + part: "(i)" | "(ii)", + configPath: string, + glob: string, +): SpecDiscoveredArm { + const declaration = CONFIG_IMPORT_HEAD + CONFIG_IMPORT_TWIN_LITERAL; + const tail = specDiscoveredTail(glob); + const text = declaration + tail; + const exportStart = declaration.length + 2 * LINE_FEED.length; + const exportEnd = text.length - LINE_FEED.length; + const statement = text.slice(exportStart, exportEnd); + if ( + Buffer.byteLength(text, "utf8") !== text.length || + !tail.startsWith(LINE_FEED + LINE_FEED) || + !statement.startsWith(EXPORT_DEFAULT_PREFIX + DEFINE_CONFIG + "(") || + !statement.endsWith(")") || + statement.includes(LINE_FEED + LINE_FEED) || + !text.endsWith(")" + LINE_FEED) || + occurrences(text, "import") !== 1 || + occurrences(text, "export") !== 1 || + !text.startsWith("import ") + ) { + throw new Error( + `T7-10(e) fixture self-check: the configuration ${part} over the ` + + `glob ${glob} must be ASCII, its first line the import declaration ` + + "ending at the specifier's closing quote, then one blank line, " + + "then the export statement through the call's closing parenthesis " + + "with no blank line inside it, and one line feed ending the file " + + "(harness bug)", + ); + } + const where = + configPath === MDX_CONFIG_PATH + ? `given by --config, no ${CONFIG_IMPORT_CONFIG_PATH} existing` + : "found by the upward search"; + const label = + `${configPath} (${where}) discovered by the spec group ` + + `${T7_10_SPEC_GROUP} globbing specs/*.mdx and ${glob}`; + return { + label, + configPath, + glob, + configArgv: configPath === MDX_CONFIG_PATH ? MDX_CONFIG_ARGV : [], + config: stagedMdx( + `T7-10 ${configPath} ((e)${part} discovered by the spec group ` + + `${T7_10_SPEC_GROUP} globbing specs/*.mdx and ${glob}: importing ` + + `from ${CONFIG_IMPORT_TWIN_LITERAL}, read as a configuration and ` + + "as a spec source)", + text, + "well-formed", + "well-formed", + ), + importRange: { start: 0, end: declaration.length }, + exportRange: { start: exportStart, end: exportEnd }, + withoutMdxExtension: !configPath.endsWith(".mdx"), + }; +} + +/** + * One of (e)'s undiscovered twins (module header): the spec group globbing + * `specs/*.mdx` alone, so no configured group discovers the configuration. + */ +interface SpecUndiscoveredTwin { + readonly label: string; + readonly configPath: string; + readonly configArgv: readonly string[]; + readonly config: StagedTs | StagedMdx; +} + +/** One (e) family: its undiscovered twin, then its discovered arms. */ +interface SpecDiscoveryFamily { + /** `"(i)"` or `"(ii)"`, as diagnoses name the family. */ + readonly part: string; + readonly twin: SpecUndiscoveredTwin; + readonly arms: readonly SpecDiscoveredArm[]; +} + +/** T7-10(e)'s two families (TEST-SPEC T7-10(e)). */ +const T7_10_E_FAMILIES: readonly SpecDiscoveryFamily[] = [ + { + part: "(i)", + twin: { + label: + `${CONFIG_IMPORT_CONFIG_PATH}, the spec group ${T7_10_SPEC_GROUP} ` + + "globbing specs/*.mdx alone", + configPath: CONFIG_IMPORT_CONFIG_PATH, + configArgv: [], + config: CONFIG_IMPORT_TWIN_CONFIG, + }, + arms: [ + specDiscoveredArm("(i)", CONFIG_IMPORT_CONFIG_PATH, "xspec.config.ts"), + specDiscoveredArm("(i)", CONFIG_IMPORT_CONFIG_PATH, "*.ts"), + ], + }, + { + part: "(ii)", + twin: { + label: + `${MDX_CONFIG_PATH} given by --config, no ` + + `${CONFIG_IMPORT_CONFIG_PATH} existing, the spec group ` + + `${T7_10_SPEC_GROUP} globbing specs/*.mdx alone`, + configPath: MDX_CONFIG_PATH, + configArgv: MDX_CONFIG_ARGV, + config: stagedMdx( + `T7-10 ${MDX_CONFIG_PATH} ((e)(ii)'s undiscovered twin, given by ` + + `--config: T7-9's twin configuration, the spec group ` + + `${T7_10_SPEC_GROUP} globbing specs/*.mdx alone)`, + configImportText(CONFIG_IMPORT_TWIN_LITERAL), + "well-formed", + "well-formed", + ), + }, + arms: [specDiscoveredArm("(ii)", MDX_CONFIG_PATH, "*.mdx")], + }, +]; + +/** How many (e) arms T7-10 runs: each family's twin and its arms. */ +const T7_10_E_ARM_COUNT = T7_10_E_FAMILIES.reduce( + (count, family) => count + 1 + family.arms.length, + 0, +); + +/** Why each (e) twin is clean (TEST-SPEC T7-10(e)'s undiscovered twin). */ +const SPEC_UNDISCOVERED_RULE = + "the spec group globs specs/*.mdx alone, so no configured group " + + "discovers the configuration file and reading it applies no source's " + + "rules (SPEC 7; TEST-SPEC T7-10(e)'s undiscovered twin)"; + +/** Why each (e) arm reports its findings, the configuration staying valid. */ +const SPEC_DISCOVERED_RULE = + "a spec group discovers the configuration file, so xspec analyzes it as " + + "it does every spec source it discovers — read as MDX, its import a " + + "named binding whose specifier designates no spec source (2.1) and its " + + "default export an export statement (2.7) — while the configuration " + + "itself stays valid (SPEC 7, 7.1, 2.1, 2.7, 14; TEST-SPEC T7-10(e))"; + +/** One condition (e) asserts reported, and how each finding of it is pinned. */ +interface SpecSourceExpectation { + readonly condition: string; + readonly code: string; + readonly expected: unknown; + /** What each finding of the condition carries, and why. */ + readonly what: string; +} + +/** + * An (e) arm's `build` or `check` findings (module header): 14.19 where the + * file lacks the `.mdx` extension, 14.15, and 14.16 each reported, every + * finding of each pinned — 14.19 concerning the configuration file, its + * `locations` `[]`; 14.15 at the import declaration by the import range of + * 11.4; 14.16 at the export statement whole, each `path` `null`. TEST-SPEC + * pins no count and names no other finding, so no other is examined. + */ +function assertSpecSourceFindings( + findings: readonly Finding[], + arm: SpecDiscoveredArm, + context: string, +): void { + const reported = + "the report's findings (code, locations, path): " + + JSON.stringify(findings.map(pinnedFinding)); + const range = (pinned: SourceRange): string => + `[${String(pinned.start)}, ${String(pinned.end)}) of ${arm.configPath}`; + const expectations: SpecSourceExpectation[] = []; + if (arm.withoutMdxExtension) { + expectations.push({ + condition: "14.19", + code: "invalid-source-path", + expected: { + code: "invalid-source-path", + locations: [], + path: arm.configPath, + }, + what: + `concerning ${arm.configPath}, its path, ` + + "`locations` [] — a " + + "spec-group file without the .mdx extension (SPEC 7.1, 14.19, 14, " + + "12.7)", + }); + } + expectations.push( + { + condition: "14.15", + code: "invalid-import", + expected: locatedAt(arm.configPath, "invalid-import", arm.importRange), + what: + "locating the configuration's import declaration by its own " + + `characters, the import range of 11.4 — ${range(arm.importRange)}, ` + + "`import` through the specifier's closing quote — its path null: a " + + "spec source's import that is a named binding, its specifier " + + "designating no spec source (SPEC 2.1, 14, 1.7, 11.4, 12.7)", + }, + { + condition: "14.16", + code: "invalid-construct", + expected: locatedAt(arm.configPath, "invalid-construct", arm.exportRange), + what: + "locating the export statement whole — " + + `${range(arm.exportRange)}, ` + + "`export` through the call's closing " + + "parenthesis — its path null: an export statement in a spec source " + + "(SPEC 2.7, 14, 1.7, 12.7)", + }, + ); + for (const expectation of expectations) { + const matching = findings.filter( + (finding) => finding.condition === expectation.condition, + ); + if (matching.length === 0) { + fail( + `${context}: the report carries ${expectation.condition} ` + + `(${expectation.code}) ${expectation.what} ` + + `(${SPEC_DISCOVERED_RULE}; an invalid path masks nothing, SPEC ` + + `14); ${reported}`, + ); + } + for (const finding of matching) { + assertSameJson( + pinnedFinding(finding), + expectation.expected, + `${context}: each ${expectation.condition} finding carries the ` + + `stable code "${expectation.code}", ${expectation.what} ` + + "(TEST-SPEC T7-10(e))", + ); + } + } +} + +/** + * One (e) family's undiscovered twin (module header): a fresh workspace + * staging its configuration beside `specs/A.mdx`; `build` and `check`, each + * under `--json` and the family's `--config`, exit 0 finding-free. + */ +async function runSpecUndiscoveredTwin( + product: ProductBinding, + family: SpecDiscoveryFamily, +): Promise<void> { + const { twin } = family; + const workspace = await TestWorkspace.create({ + files: { + [twin.configPath]: twin.config, + [T7_10_SOURCE_PATH]: T7_10_SOURCE, + }, + }); + const label = `T7-10(e)${family.part}'s undiscovered twin, ${twin.label}`; + try { + for (const word of T7_10_VALIDATING_WORDS) { + const argv = [word, "--json", ...twin.configArgv]; + const result = await runProduct(product, { + cwd: workspace.root, + argv, + }); + expectFindingFree( + result, + `${label}: ${sourceCommandLabel(argv)}`, + SPEC_UNDISCOVERED_RULE, + ); + } + } finally { + await workspace.dispose(); + } +} + +/** + * One (e) arm (module header): a fresh workspace staging the arm's + * configuration beside `specs/A.mdx`; `build` and `check`, each under + * `--json` and the arm's `--config`, exit 1 with the arm's findings; then + * `inventory --json` exits 0, listing the configuration file among the spec + * group's sources with its `derived` entry. + */ +async function runSpecDiscoveredArm( + product: ProductBinding, + family: SpecDiscoveryFamily, + arm: SpecDiscoveredArm, +): Promise<void> { + const workspace = await TestWorkspace.create({ + files: { + [arm.configPath]: arm.config, + [T7_10_SOURCE_PATH]: T7_10_SOURCE, + }, + }); + const label = `T7-10(e)${family.part}, ${arm.label}`; + const conditions = arm.withoutMdxExtension + ? "14.19, 14.15, and 14.16" + : "14.15 and 14.16"; + try { + for (const word of T7_10_VALIDATING_WORDS) { + const argv = [word, "--json", ...arm.configArgv]; + const context = `${label}: ${sourceCommandLabel(argv)}`; + const result = await runProduct(product, { + cwd: workspace.root, + argv, + }); + assertExitCode( + result, + 1, + `${context} — the configuration file, a spec source, carries ` + + `${conditions}, findings: exit 1, never 14.14 or exit 2 ` + + `(${SPEC_DISCOVERED_RULE}; SPEC 12.0; H-5)`, + ); + assertSpecSourceFindings( + decodeFindingsReport(parseJsonStdout(result, context), context) + .findings, + arm, + context, + ); + } + const argv = ["inventory", "--json", ...arm.configArgv]; + const context = `${label}: ${sourceCommandLabel(argv)}`; + const result = await runProduct(product, { + cwd: workspace.root, + argv, + }); + assertExitCode( + result, + 0, + `${context} — the configuration stays valid and the inventory parses ` + + `no sources, so it answers, exit 0 (${SPEC_DISCOVERED_RULE}; SPEC ` + + "11.6; H-5)", + ); + const inventory = decodeInventoryDocument( + parseJsonStdout(result, context), + context, + ); + assertSameJson( + inventory.sources + .filter((entry) => entry.path === arm.configPath) + .map((entry) => ({ + path: entry.path, + groups: entry.groups.map((group) => ({ + name: group.name, + kind: group.kind, + })), + })), + [ + { + path: arm.configPath, + groups: [{ name: T7_10_SPEC_GROUP, kind: "spec" }], + }, + ], + `${context}: ${arm.configPath} is listed once among the sources, in ` + + `the spec group ${T7_10_SPEC_GROUP} alone — the one group, its ` + + `glob ${JSON.stringify(arm.glob)} matching it (SPEC 11.6, 7.1, 7; ` + + "TEST-SPEC T7-10(e))", + ); + const derived = inventory.derived.filter( + (entry) => entry.source === arm.configPath, + ); + if (arm.withoutMdxExtension) { + assertSameJson( + derived.map((entry) => ({ + source: entry.source, + module: entry.module, + markdown: entry.markdown, + })), + [{ source: arm.configPath, module: null, markdown: null }], + `${context}: ${arm.configPath}'s ` + + "`derived` entry carries " + + "`module` and `markdown` null — a spec-group file without the " + + ".mdx extension generates and emits nothing, though emission is " + + "enabled — the stated null, never omission (SPEC 13.1, 11.6, " + + "7.3, 12.7; TEST-SPEC T7-10(e), T7.1-1)", + ); + } else { + assertSameJson( + derived.map((entry) => ({ + source: entry.source, + module: entry.module, + })), + [{ source: arm.configPath, module: MDX_CONFIG_MODULE }], + `${context}: ${arm.configPath}'s ` + + "`derived` entry carries its " + + `generated-module path, ${MDX_CONFIG_MODULE} — NAME.mdx ` + + "generates NAME.xspec.ts in its directory (SPEC 13.1, 11.6; " + + "TEST-SPEC T7-10(e))", + ); + } + } finally { + await workspace.dispose(); + } +} + +// --------------------------------------------------------------------------- +// Registration + +const T7_9 = defineProductTest({ + id: "T7-9", + title: + "configuration import (TEST-SPEC T7-9 (a), (b), (c), (d)): on a valid " + + "workspace — one spec group globbing specs/*.mdx over specs/A.mdx and " + + "specs/B.mdx, Markdown emitted next to sources, no group discovering " + + "the configuration file — (a) the import's module specifier spelled as " + + 'the bare names "XSPEC" (a single-casing arm, 12.0: no case folding) ' + + 'and "left-pad", the scoped name "@acme/config", the relative path ' + + '"./lib/define.js", the absolute path "/opt/define.mjs", the URL ' + + '"https://example.com/define.js" under the denied network (E-1), the ' + + "empty string, the single-quoted xspec, xspec with its x written as a " + + "hexadecimal escape, a line continuation between xs and pec, and a raw " + + "U+FFFD between x and spec — each staged exactly as spelled and " + + 'differing from its twin importing from "xspec" in the specifier alone ' + + "— answers as the twin: `build`, `check`, `ids`, and `inventory`, each " + + "under `--json`, exit code and standard output equal to the twin's " + + "(`inventory`'s `configuration` byte-identical among them), `build` " + + "and `check` exiting 0 finding-free, and the generated modules and " + + "emitted Markdown byte-identical, graph data not compared; (b) a " + + "scanner-rejected escape as the specifier — a hexadecimal escape with " + + "one hex digit, a braced Unicode escape of the code point 110000 " + + "hexadecimal, an octal escape, and a backslash before 8, each a " + + "scanning error of TypeScript 5.9.3 declared unparseable (S-9) — " + + "leaves the file not well-formed (14.20): the four commands, each " + + "under `--json`, report 14.14, exit 2, the error document's one " + + 'finding `code` "configuration-error", `path` "xspec.config.ts", and ' + + "`locations` []; (c) the specifier designating, from the workspace " + + 'root, nothing ("./nowhere.js"), a plain file whose content the ' + + 'environment refuses, its kind still examinable ("./locked.js", mode ' + + "0o200: T14-10's discipline, Linux leg), a path below a directory of " + + 'mode 000 holding it ("./sealed/define.js": ' + + "T14-10(l)'s discipline, Linux leg, every route refused), a FIFO " + + '("./fifo"), a directory ("./specs"), and the configuration file ' + + 'itself ("./xspec.config", "./xspec.config.ts") — each staging ' + + "verified on the harness itself — answers as the twin, as (a) " + + "compares, the arm's staged entry left out of the file compare, and " + + "the FIFO after each command still a FIFO in place, each command " + + "ending within its guard; (d) the configuration importing from " + + '"N" beside a trap package at node_modules/N — its manifest naming an ' + + "entry that, if loaded, writes a marker into the workspace, prints to " + + "both streams, and exits non-zero — and, separately, beside a " + + "node_modules/N whose package.json is a FIFO, under each of the names " + + "trap, xspec, and the name the module channel's package manifest " + + "gives, wherever that is a name of 7.6's grammar (no package " + + "directory given, its arms fail diagnosed): `build`, `check`, `ids`, " + + "`view specs/A.mdx`, `inventory`, `review list`, and `rename " + + "specs/A.mdx a b`, each under `--json`, exit and answer exactly as on " + + "the twin holding no node_modules — exit code and standard output " + + "equal, the files each writes byte-equal, the lock path aside — and " + + "as such a workspace gives them (`build` and `check` 0 finding-free, " + + "`ids` 0 with its listing, `view` and `inventory` 0 finding-free, " + + "`review list` 0, the `rename` 0 with its applied mapping), no marker " + + "written, neither stream carrying what the entry prints, the FIFO " + + "after each command still a FIFO in place, each command ending within " + + "its guard (SPEC 7, 7.6, 2.4, 12.7, 14; S-3)", + run: async (product) => { + const twin = await runImportTwin(product); + const failures: string[] = []; + for (const arm of T7_9_A_ARMS) { + await collectArmFailure(failures, () => + runSpellingArm(product, twin, arm), + ); + } + for (const arm of T7_9_B_ARMS) { + await collectArmFailure(failures, () => + runRejectedEscapeArm(product, arm), + ); + } + for (const arm of T7_9_C_ARMS) { + await collectArmFailure(failures, () => + runDesignationArm(product, twin, arm), + ); + } + const installArms = await runInstalls(product, failures); + if (failures.length > 0) { + const arms = + T7_9_A_ARMS.length + + T7_9_B_ARMS.length + + T7_9_C_ARMS.length + + installArms; + fail( + `T7-9: ${String(failures.length)} of ${String(arms)} arms failed, ` + + "each diagnosed below:" + + LINE_FEED + + failures.join(LINE_FEED), + ); + } + }, +}); + +const T7_10 = defineProductTest({ + id: "T7-10", + title: + "the configuration file as a source (TEST-SPEC T7-10 (a), (b), (c), " + + "(d), (e)): " + + "on a valid workspace — one spec group globbing specs/*.mdx over " + + "specs/A.mdx, Markdown emitted next to sources — the configuration " + + 'importing, one arm each, from "./specs/A.xspec" (a spec module ' + + 'import binding defineConfig), "./missing.xspec" (designating no ' + + 'discovered spec source), "./specs/A.xspec.ts" and "./.xspec/x" ' + + "(relative specifiers designating derived-file paths), and " + + '"./specs/A.md" (the emit destination of specs/A.mdx): (a) ' + + "undiscovered, no code group matching it, each arm is valid — " + + "`build` and `check`, each under `--json`, exit 0 finding-free; (b) " + + "discovered, by a code group globbing *.ts and, separately, by one " + + "whose glob is xspec.config.ts — each group's control, importing " + + 'from "xspec", clean (`build` and `check` exit 0 finding-free) with ' + + "its whole-file location existing (`query edges --from " + + "xspec.config.ts`, exit 0) — each arm's `build` and `check`, each " + + "under `--json`, exit 1, never 2, reporting 14.15 (invalid-import), " + + "each such finding locating the configuration's import declaration " + + "by the import range of 11.4, its path null, and, in the two .xspec " + + "arms, 14.18 (unsupported-node-usage) locating defineConfig at its " + + "call, no other finding, and `inventory --json` exits 0 with no " + + "finding, listing xspec.config.ts among its sources in that code " + + "group alone; (c) consequences, each on the configuration discovered " + + "by each of those code groups beside its undiscovered twin (no code " + + 'group): after a successful `build` under "xspec", the configuration ' + + 'restaged importing from "./missing.xspec", `build --json` exits 1 ' + + "reporting (b)'s 14.15 and 14.18 and modifies nothing (a whole-root " + + "compare), and the gated reads `ids --json` and `query nodes` each " + + "exit 1 reporting exactly `build`'s findings, modifying nothing, " + + "while the twin's `build` exits 0 finding-free and its reads answer, " + + 'exit 0; importing from "./specs/B.md", no specs/B.mdx existing, ' + + "`move specs/A.mdx specs/B.mdx --json` is refused — exit 1, exactly " + + "one refused-invalid-destination finding concerning specs/B.mdx, " + + "locations [], nothing modified — while the twin moves, exit 0 with " + + "its applied mapping, specs/B.mdx holding the moved bytes; a commit c1 " + + 'whose configuration imports from "./missing.xspec", the working ' + + "tree's configuration and sources valid: `impact --base c1 --json` " + + "and `review create --base c1 --name n --json` each exit 2, the error " + + "document's code and path null, standard error naming " + + "xspec.config.ts, `review create` modifying nothing, while the twin's " + + "commit resolves, both exit 0; and the converse — undiscovered, " + + 'importing from "./specs/A.xspec", `move specs/A.mdx specs/B.mdx ' + + "--preview --json` exits 0 listing no edit in xspec.config.ts, the " + + "`move` exits 0 leaving xspec.config.ts byte-identical, and `build` " + + "and `check` then exit 0 finding-free, while the discovered twin's " + + "`move` is refused as an invalid workspace: exit 1, (b)'s findings " + + "alone, nothing modified; (d) baselines, the working tree's " + + `configuration importing from "xspec" and its source one section's ` + + "text edited since a commit c1 whose undiscovered configuration " + + 'imports from "", "./nowhere", or "XSPEC", or from "./fifo" (a FIFO at ' + + `that path in the working tree) or "trap" (T7-9(d)'s trap package at ` + + "node_modules/trap in the working tree): `impact --base c1 --json` " + + "exits 0, its impact information decoded through H-3's adapter — " + + "categories with their attributions, collapsed chains, deleted and " + + "added identities, impacted locations with witness edges and paths, " + + "never byte for byte — equal to that against the twin commit " + + 'importing from "xspec", the edited section changed; in the FIFO and ' + + "trap arms `review create --base c1 --name n --json` and `review " + + "status n --json` each exit 0, status's items (kinds, scopes, " + + "statuses, blocked states) the twin's, the FIFO after each command " + + "still a FIFO in place, each command ending within its guard, no trap " + + "marker written and neither stream carrying the trap's tell; and a " + + "commit whose configuration spells a hexadecimal escape with one hex " + + "digit as its specifier, not well-formed: `impact --base c1 --json` " + + "exits 2, the error document's code and path null, standard error " + + "naming xspec.config.ts; (e) discovered by a spec group, the " + + 'configuration importing from "xspec", spelled with no blank line ' + + "inside its default export so that, read as MDX, its import and its " + + "export derive as ESM blocks — (i) xspec.config.ts, the spec group " + + "globbing specs/*.mdx and xspec.config.ts and, separately, " + + "specs/*.mdx and *.ts: `build` and `check`, each under `--json`, exit " + + "1, never 2, reporting 14.19 (invalid-source-path) concerning " + + "xspec.config.ts, locations [], 14.15 (invalid-import) locating its " + + "import declaration by the import range of 11.4, and 14.16 " + + "(invalid-construct) locating its export statement whole, each such " + + "finding so located, its path null, and `inventory --json` exits 0, " + + "listing xspec.config.ts once among its sources in that spec group " + + "alone, its derived entry's module and markdown null; (ii) " + + "xspec.config.mdx, given by `--config xspec.config.mdx` on every " + + "invocation, no xspec.config.ts existing, the spec group globbing " + + "specs/*.mdx and *.mdx: `build` and `check` exit 1, never 2, " + + "reporting 14.15 at its import declaration and 14.16 at its export " + + "statement, so located, and `inventory` exits 0, listing it once " + + "among its sources in that spec group alone, its derived entry's " + + "module xspec.config.xspec.ts; each beside its undiscovered twin, the " + + "spec group globbing specs/*.mdx alone, whose `build` and `check` " + + "exit 0 finding-free (SPEC 7, 1.7, 2.1, 2.7, 4, 4.5, 5.6, 6.3, 6.4, " + + "6.5, 6.6, 7.1, 7.2, 7.3, 9.3, 10.7, 11.1, 11.4, 11.6, 12.0, 12.1, " + + "12.7, 13.1, 13.3, 13.4, 14)", + run: async (product) => { + const failures: string[] = []; + for (const arm of T7_10_A_ARMS) { + await collectArmFailure(failures, () => runUndiscoveredArm(product, arm)); + } + for (const staging of T7_10_B_STAGINGS) { + await collectArmFailure(failures, () => + runDiscoveredControl(product, staging), + ); + for (const arm of staging.arms) { + await collectArmFailure(failures, () => + runDiscoveredArm(product, staging, arm), + ); + } + } + for (const arm of T7_10_C_ARMS) { + await collectArmFailure(failures, () => arm(product)); + } + const baselineTwin = await collectTwinFailure(failures, () => + runBaselineReadTwin(product), + ); + for (const arm of T7_10_D_ARMS) { + await collectArmFailure(failures, () => + runBaselineReadArm(product, baselineTwin, arm), + ); + } + await collectArmFailure(failures, () => runBaselineEscapeArm(product)); + for (const family of T7_10_E_FAMILIES) { + await collectArmFailure(failures, () => + runSpecUndiscoveredTwin(product, family), + ); + for (const arm of family.arms) { + await collectArmFailure(failures, () => + runSpecDiscoveredArm(product, family, arm), + ); + } + } + if (failures.length > 0) { + const arms = + T7_10_AB_ARM_COUNT + + T7_10_C_ARMS.length + + T7_10_D_ARM_COUNT + + T7_10_E_ARM_COUNT; + fail( + `T7-10: ${String(failures.length)} of ${String(arms)} ` + + "arms failed, each diagnosed below:" + + LINE_FEED + + failures.join(LINE_FEED), + ); + } + }, +}); + +/** TEST-SPEC §7 configuration import: T7-9 and T7-10. */ +export const section7ImportTests: readonly ProductTestEntry[] = [T7_9, T7_10]; diff --git a/test/suite/registry/section-7-names.ts b/test/suite/registry/section-7-names.ts new file mode 100644 index 00000000..218ed8cd --- /dev/null +++ b/test/suite/registry/section-7-names.ts @@ -0,0 +1,939 @@ +// TEST-SPEC §7 configured names — T7-11 (SPEC 7, 7.4, 7.5, 8.2, 11.6, 12.0, +// 12.7, 14). Configuration basics (T7-1…T7-3, T7-7) live in +// section-7-basics.ts, discovery (T7-4…T7-6, T7-8) in +// section-7-discovery.ts, the configuration's import (T7-9, T7-10) in +// section-7-import.ts, and profile and rule validation (T7.4-1, T7.5-1) in +// section-7.4-7.5.ts. +// +// Registered product-facing body (C-2 "one code path"): each arm builds its +// own fresh workspace (H-1), drives the product strictly as a subprocess +// (H-2), asserts exact exit codes (H-5), decodes reports through the H-3 +// adapters, and rejects a product only via diagnosed assertion failures +// (H-8). +// +// SPEC 7 bars a group, profile, or rule name only when it is empty or +// contains U+FFFD, so the members of TypeScript's global `Object` interface +// and `__proto__`, which 7.6 spells out, are names like any other. Each arm +// fails a product that looks configured names up in a plain object, where +// `constructor` and `__proto__` name inherited members — a lookup finds a +// group or profile nobody configured, and an assignment keyed `__proto__` +// replaces the object's prototype instead of adding a member — and a group +// named `hasOwnProperty` shadows the method such a product calls on that +// object; (a)'s and (c)'s identifier-key spellings of `__proto__` also fail +// a product reading an identifier key through TypeScript's escaped +// identifier text, which prefixes a third underscore to a name beginning +// with two. +// +// The arms, each on an otherwise valid workspace (TEST-SPEC T7-11): +// +// (a) Groups (`T7_11_A_ARMS`, eight arms): a spec group named `__proto__` — +// spelled once as an identifier key and once as a string-literal key — +// one named `constructor`, and one named `hasOwnProperty`, each +// globbing `specs/*.mdx` over `specs/A.mdx`; and code groups so named, +// in the same four spellings, each globbing `src/*.ts` over `src/a.ts` +// beside no spec group (`specs: {}`, valid with zero sources, SPEC 7, the +// shape T7-4's literal-backslash arm stages), so that each workspace +// holds exactly what its arm names. `build --json` and `check --json` +// exit 0 finding-free (12.7's `{"findings": []}`), and `inventory +// --json` exits 0 reporting the group under its name with its glob, the +// other group list empty, and its one source in it: `sources` exactly +// one `{"path", "groups"}` entry whose one membership is the group's +// `{"name", "kind"}` (11.6, 12.7). +// (b) A profile and a rule (`T7_11_B_CONFIG`): a profile named `toString` +// (target `product`, boundary `tests`, mode `direct`) and a `forbidden` +// rule named `toString` from `{ group: "tests" }` to `{ group: +// "product" }`, over the one depends edge `tests/T.mdx#t` → +// `specs/A.mdx#a`, which the rule forbids. `build --json` exits 0 +// finding-free (build evaluates no policy, 12.1); `inventory --json` +// reports both with their complete definitions in 12.7's resolved view, +// every default and inferred kind explicit (`targetTags` null, `targets` +// "leaves", `boundaryKind` "spec", both selectors' kinds "spec", both +// kind sets all three kinds in 5.2's order); `coverage toString --json` +// exits 0 reporting exactly that profile, `specs/A.mdx#a` covered over +// the path [`tests/T.mdx#t`, `specs/A.mdx#a`] and nothing uncovered +// (8.2: `coverage <name>` runs one profile); and `check --json` exits 1 +// with exactly one finding, 14.12's, its identities the rule's name +// `toString` and the edge's source, kind token, and target, `locations` +// [] and `path` null (14.12, 12.7). +// (c) References (`T7_11_C_ARMS`, six arms of two workspaces each): a +// profile's `target`, its `boundary`, and a rule's selector `group` (its +// `from`), each naming `__proto__` and, separately, `constructor` — +// TEST-SPEC's "each naming `__proto__` or `constructor`, one arm each" +// read as one arm per reference and name. With a spec group of that name +// configured — keyed by its identifier spelling, in place of the neutral +// group (`product` or `tests`) the reference names in the other arms — +// the reference resolves: `build --json` exits 0 finding-free, and the +// profile's coverage is reported (`coverage --json`: profile `p`, +// `specs/A.mdx#a` covered over [`tests/T.mdx#t`, `specs/A.mdx#a`], +// nothing uncovered) or the rule evaluated (`check --json`: the one +// 14.12 finding of rule `r` on that edge). With none — the same +// configuration with that group keyed by its neutral name, so the +// reference is the workspace's only defect — the reference names an +// unknown group, 14.14: `build` exits 2 with the 12.7 error document +// whose one finding carries `configuration-error`, `path` +// `xspec.config.ts`, and `locations` [], and writes nothing (the +// contract section-7.4-7.5.ts's `expectConfigRefused` holds T7.4-1's +// and T7.5-1's unknown references to). +// (d) Unknown profiles (`runUnknownProfileArms`): on a workspace configuring +// one profile, `p`, whose `coverage p --json` answers first (exit 0, the +// profile reported as in (c) — the premise that the surface answers a +// configured name), `coverage constructor --json` and `coverage +// __proto__ --json`, one arm each, name an unknown profile: the plain +// usage error of 12.0 — exit 2, the 12.7 error document with `code` and +// `path` null and no locations, a standard-error message (support.ts +// `expectPlainUsageError`). +// +// Every arm runs: each arm's diagnosed failure (a `HarnessAssertionError`, +// its message naming the arm) is collected, and the body fails once at the +// end naming every failed arm; a harness error or a hang propagates at once +// (section-7-import.ts's pattern). Against S-7's empty stub every arm fails +// at its first command. +// +// Staging (S-9's timing clause; helpers/staged-ts.ts, helpers/staged-mdx.ts): +// every configuration and source is a staged-source record made at module +// load — every arm past the first stages its workspace after the body's +// first product invocation — judged by test/self/s9-staged-sources.test.ts +// before any product exists. The three sources (`specs/A.mdx`, +// `tests/T.mdx`, `src/a.ts`) are one record each, named with every arm +// staging them. No staged text needs a backslash, and this source spells +// none. +// +// Certification: T7-11 is in no conformer's scope (CERTIFICATIONS.md); its +// operative assertions are positive — each name reported, resolving, or +// refused as such — so a staging that misses fails loud. + +import type { CoverageReport } from "../../helpers/adapters/index.js"; +import { + decodeCoverageReport, + decodeFindingsReport, + decodeInventoryDocument, +} from "../../helpers/adapters/index.js"; +import { + HarnessAssertionError, + fail, + parseJsonStdout, +} from "../../helpers/assertions.js"; +import { defineProductTest } from "../../helpers/registry.js"; +import type { ProductTestEntry } from "../../helpers/registry.js"; +import { + assertSnapshotsEqual, + snapshotDirectory, +} from "../../helpers/snapshot.js"; +import { type StagedMdx, stagedMdx } from "../../helpers/staged-mdx.js"; +import { type StagedTs, stagedTs } from "../../helpers/staged-ts.js"; +import type { ProductBinding } from "../../helpers/subprocess.js"; +import { TestWorkspace } from "../../helpers/workspace.js"; +import type { InitialFileContents } from "../../helpers/workspace.js"; +import { + assertConditionCounts, + assertSameJson, + expectConfigurationError, + expectErrorDocument, + expectExit, + expectFindingFreeReport, + expectPlainUsageError, + runJson, +} from "./support.js"; + +// --------------------------------------------------------------------------- +// Shared fixture material +// --------------------------------------------------------------------------- + +/** U+000A, built from its code point (module header: no escape spelled). */ +const LINE_FEED = String.fromCodePoint(0x0a); + +/** The configuration file every arm stages at the workspace root. */ +const CONFIG_PATH = "xspec.config.ts"; + +/** The spec glob of (a)'s spec groups and of (b)–(d)'s group `product`. */ +const SPEC_GLOB = "specs/*.mdx"; +/** The spec glob of (b)–(d)'s group `tests`. */ +const TESTS_GLOB = "tests/*.mdx"; +/** The code glob of (a)'s code groups. */ +const CODE_GLOB = "src/*.ts"; + +/** Every arm's spec source but (a)'s code-group arms': one section, `a`. */ +const SPEC_A_PATH = "specs/A.mdx"; +const SPEC_A_SOURCE: StagedMdx = stagedMdx( + "T7-11 specs/A.mdx (one section a; (a)'s spec-group arms, (b), (c), and (d))", + `<S id="a"> +Requirement a. +</S> +`, +); + +/** (b)–(d)'s second spec source: section `t`, depending on `a`. */ +const TESTS_T_PATH = "tests/T.mdx"; +const TESTS_T_SOURCE: StagedMdx = stagedMdx( + "T7-11 tests/T.mdx (section t, its d prop depending on specs/A.mdx#a; " + + "(b), (c), and (d))", + `import A from "../specs/A.xspec" + +<S id="t" d={A.a}> +Depends on requirement a. +</S> +`, +); + +/** (a)'s code-group arms' one code source. */ +const SRC_A_PATH = "src/a.ts"; +const SRC_A_SOURCE: StagedTs = stagedTs( + "T7-11 src/a.ts (the code source of (a)'s code-group arms)", + `export const a = 1; +`, +); + +/** The requirement node every profile's target set holds: `a`. */ +const NODE_A = "specs/A.mdx#a"; +/** The boundary node whose depends edge covers `a`, and offends a rule. */ +const NODE_T = "tests/T.mdx#t"; + +/** + * The one dependency edge (b)–(d)'s workspace holds, as 14.12's identities + * name it after the rule's name: the source, the kind token, the target. + */ +const EDGE_IDENTITIES: readonly string[] = [NODE_T, "depends", NODE_A]; + +/** A configuration file: the import, then the default export over `body`. */ +function configText(body: string): string { + return `import { defineConfig } from "xspec" + +export default defineConfig({ +${body} +}) +`; +} + +/** (b)–(d)'s workspace: the configuration beside `specs/A.mdx` and `tests/T.mdx`. */ +function graphFiles( + config: StagedTs, +): Readonly<Record<string, InitialFileContents>> { + return { + [CONFIG_PATH]: config, + [SPEC_A_PATH]: SPEC_A_SOURCE, + [TESTS_T_PATH]: TESTS_T_SOURCE, + }; +} + +// --------------------------------------------------------------------------- +// (a) Groups named by `Object` members and `__proto__` +// --------------------------------------------------------------------------- + +type GroupKind = "spec" | "code"; + +/** One spelling of a configured group's key (TEST-SPEC T7-11(a)). */ +interface GroupKeySpelling { + /** The group's name. */ + readonly name: string; + /** The key exactly as the configuration spells it. */ + readonly key: string; + /** The spelling, in words, for labels. */ + readonly spelled: string; +} + +const GROUP_KEY_SPELLINGS: readonly GroupKeySpelling[] = [ + { name: "__proto__", key: "__proto__", spelled: "an identifier key" }, + { name: "__proto__", key: '"__proto__"', spelled: "a string-literal key" }, + { name: "constructor", key: "constructor", spelled: "an identifier key" }, + { + name: "hasOwnProperty", + key: "hasOwnProperty", + spelled: "an identifier key", + }, +]; + +/** One (a) arm: a group of `kind` named by an `Object` member or `__proto__`. */ +interface GroupArm { + readonly label: string; + readonly kind: GroupKind; + readonly name: string; + readonly glob: string; + readonly sourcePath: string; + readonly files: Readonly<Record<string, InitialFileContents>>; +} + +/** The `defineConfig` argument of one (a) arm: the one group, keyed `key`. */ +function groupArmBody(kind: GroupKind, key: string): string { + if (kind === "spec") { + return ` specs: { + ${key}: ["${SPEC_GLOB}"] + }`; + } + return ` specs: {}, + code: { + ${key}: ["${CODE_GLOB}"] + }`; +} + +const T7_11_A_ARMS: readonly GroupArm[] = (["spec", "code"] as const).flatMap( + (kind) => + GROUP_KEY_SPELLINGS.map((spelling): GroupArm => { + const label = + "the " + + kind + + " group " + + JSON.stringify(spelling.name) + + ", " + + spelling.spelled; + const sourcePath = kind === "spec" ? SPEC_A_PATH : SRC_A_PATH; + return { + label, + kind, + name: spelling.name, + glob: kind === "spec" ? SPEC_GLOB : CODE_GLOB, + sourcePath, + files: { + [CONFIG_PATH]: stagedTs( + "T7-11 xspec.config.ts ((a): " + label + ")", + configText(groupArmBody(kind, spelling.key)), + ), + [sourcePath]: kind === "spec" ? SPEC_A_SOURCE : SRC_A_SOURCE, + }, + }; + }), +); + +// --------------------------------------------------------------------------- +// (b) A profile and a rule both named `toString` +// --------------------------------------------------------------------------- + +/** (b)'s profile and rule name. */ +const TO_STRING = "toString"; + +const T7_11_B_CONFIG: StagedTs = stagedTs( + "T7-11 xspec.config.ts ((b): a profile and a forbidden rule both named " + + "toString)", + configText(` specs: { + product: ["${SPEC_GLOB}"], + tests: ["${TESTS_GLOB}"] + }, + coverage: [ + { + name: "${TO_STRING}", + target: "product", + boundary: "tests", + mode: "direct" + } + ], + policy: [ + { + name: "${TO_STRING}", + type: "forbidden", + from: { group: "tests" }, + to: { group: "product" } + } + ]`), +); + +/** Every dependency kind, the kind set's 12.7 form (5.2's order). */ +const ALL_DEPENDENCY_KINDS: readonly string[] = [ + "depends", + "embeds", + "references", +]; + +/** + * (b)'s profile in 12.7's resolved view, every default and inferred kind + * explicit (11.6), its members in the order the form-exact decoder builds + * them (forms.ts `decodeCoverageProfileView`). + */ +const T7_11_B_PROFILE_VIEW = { + name: TO_STRING, + target: "product", + targetTags: null, + targets: "leaves", + boundary: "tests", + boundaryKind: "spec", + mode: "direct", + edgeKinds: ALL_DEPENDENCY_KINDS, +}; + +/** (b)'s rule in 12.7's resolved view (forms.ts `decodePolicyRuleView`). */ +const T7_11_B_RULE_VIEW = { + name: TO_STRING, + type: "forbidden", + from: { group: "tests", kind: "spec" }, + to: { group: "product", kind: "spec" }, + kinds: ALL_DEPENDENCY_KINDS, +}; + +// --------------------------------------------------------------------------- +// (c) References naming `__proto__` and `constructor` +// --------------------------------------------------------------------------- + +type ReferenceSite = "target" | "boundary" | "selector"; + +/** The reference, in words, for labels. */ +function referenceSiteWords(site: ReferenceSite): string { + switch (site) { + case "target": + return "a profile's target"; + case "boundary": + return "a profile's boundary"; + case "selector": + return "a rule's selector group (its from)"; + } +} + +/** One (c) arm: the reference and the name, configured and not. */ +interface ReferenceArm { + readonly label: string; + readonly site: ReferenceSite; + readonly name: string; + /** A spec group of that name configured: the reference resolves. */ + readonly resolving: Readonly<Record<string, InitialFileContents>>; + /** No group of that name: the reference names an unknown group (14.14). */ + readonly unknown: Readonly<Record<string, InitialFileContents>>; +} + +/** + * The `defineConfig` argument of one (c) workspace: the spec groups + * `product` (`specs/*.mdx`) and `tests` (`tests/*.mdx`) — the group the + * reference names keyed `name` instead where `configured` — and the profile + * `p` (target `product`, boundary `tests`) or the forbidden rule `r` (from + * `tests` to `product`), its referencing field naming `name`. + */ +function referenceArmBody( + site: ReferenceSite, + name: string, + configured: boolean, +): string { + const productKey = site === "target" && configured ? name : "product"; + const testsKey = site !== "target" && configured ? name : "tests"; + const groups = ` specs: { + ${productKey}: ["${SPEC_GLOB}"], + ${testsKey}: ["${TESTS_GLOB}"] + },`; + if (site === "selector") { + return `${groups} + policy: [ + { + name: "r", + type: "forbidden", + from: { group: "${name}" }, + to: { group: "product" } + } + ]`; + } + const target = site === "target" ? name : "product"; + const boundary = site === "boundary" ? name : "tests"; + return `${groups} + coverage: [ + { + name: "p", + target: "${target}", + boundary: "${boundary}", + mode: "direct" + } + ]`; +} + +/** (c)'s names, each naming an inherited member of a plain object. */ +const REFERENCE_NAMES: readonly string[] = ["__proto__", "constructor"]; + +const T7_11_C_ARMS: readonly ReferenceArm[] = ( + ["target", "boundary", "selector"] as const +).flatMap((site) => + REFERENCE_NAMES.map((name): ReferenceArm => { + const label = referenceSiteWords(site) + " naming " + JSON.stringify(name); + return { + label, + site, + name, + resolving: graphFiles( + stagedTs( + "T7-11 xspec.config.ts ((c): " + + label + + ", a spec group of that name configured)", + configText(referenceArmBody(site, name, true)), + ), + ), + unknown: graphFiles( + stagedTs( + "T7-11 xspec.config.ts ((c): " + label + ", no group of that name)", + configText(referenceArmBody(site, name, false)), + ), + ), + }; + }), +); + +// --------------------------------------------------------------------------- +// (d) Unknown profiles named `constructor` and `__proto__` +// --------------------------------------------------------------------------- + +/** (d)'s configuration: the one profile `p`, no other. */ +const T7_11_D_CONFIG: StagedTs = stagedTs( + "T7-11 xspec.config.ts ((d): the one profile p, none named constructor or " + + "__proto__)", + configText(` specs: { + product: ["${SPEC_GLOB}"], + tests: ["${TESTS_GLOB}"] + }, + coverage: [ + { + name: "p", + target: "product", + boundary: "tests", + mode: "direct" + } + ]`), +); + +/** (d)'s profile names, neither configured. */ +const UNKNOWN_PROFILE_NAMES: readonly string[] = ["constructor", "__proto__"]; + +/** T7-11's arm count, for the collected failures' summary. */ +const T7_11_ARM_COUNT = + T7_11_A_ARMS.length + + 1 + + 2 * T7_11_C_ARMS.length + + UNKNOWN_PROFILE_NAMES.length; + +// --------------------------------------------------------------------------- +// Arm runners +// --------------------------------------------------------------------------- + +/** Stage a fresh workspace (H-1), run `body`, dispose. */ +async function withWorkspace( + files: Readonly<Record<string, InitialFileContents>>, + body: (workspace: TestWorkspace) => Promise<void>, +): Promise<void> { + const workspace = await TestWorkspace.create({ files }); + try { + await body(workspace); + } finally { + await workspace.dispose(); + } +} + +/** + * Run one arm, collecting its diagnosed failure (module header): a + * `HarnessAssertionError` is recorded and the next arm runs; anything else — + * a harness error, a hang — propagates at once. + */ +async function collectArmFailure( + failures: string[], + arm: () => Promise<void>, +): Promise<void> { + try { + await arm(); + } catch (error) { + if (!(error instanceof HarnessAssertionError)) throw error; + failures.push(error.message); + } +} + +/** + * A coverage report holding exactly the profile `name` — the one the + * workspace configures — whose target group's one leaf `a` is covered over + * the one depends edge from the boundary group's `t`, nothing uncovered + * (SPEC 8, 8.1, 8.2). Counts and ignored nodes are T8.2-1's subject. + */ +function assertProfileCoversA( + report: CoverageReport, + name: string, + context: string, +): void { + assertSameJson( + report.profiles.map((profile) => ({ + name: profile.name, + covered: profile.covered.map((row) => ({ + identity: row.identity, + path: row.path, + })), + uncovered: [...profile.uncovered].sort(), + })), + [ + { + name, + covered: [{ identity: NODE_A, path: [NODE_T, NODE_A] }], + uncovered: [], + }, + ], + context + + ": the report carries exactly the profile " + + JSON.stringify(name) + + ", its target group's one leaf " + + NODE_A + + " covered over the one depends edge from the boundary group's " + + NODE_T + + " (the covering path [" + + NODE_T + + ", " + + NODE_A + + "]), nothing uncovered — the profile found under its name and its " + + "group references resolved (SPEC 7.4, 8, 8.1, 8.2)", + ); +} + +/** + * `check --json` on a freshly built workspace whose one dependency edge the + * forbidden rule `rule` forbids: exit 1 with exactly one finding, 14.12's — + * its identities the rule's name and the edge's source, kind token, and + * target, no location, no concerned path (SPEC 7.5, 14.12, 12.7). + */ +async function expectOneViolation( + product: ProductBinding, + workspace: TestWorkspace, + rule: string, + context: string, +): Promise<void> { + const result = await expectExit( + product, + workspace, + ["check", "--json"], + 1, + context + + " — the forbidden rule " + + JSON.stringify(rule) + + " is evaluated, its one offending edge a finding of check, exit 1 " + + "(SPEC 7.5, 14.12, 12.0)", + ); + const findings = decodeFindingsReport( + parseJsonStdout(result, context), + context, + ).findings; + assertConditionCounts(findings, { "14.12": 1 }, context); + assertSameJson( + findings.map((finding) => ({ + locations: finding.locations, + path: finding.path, + identities: finding.identities, + })), + [{ locations: [], path: null, identities: [rule, ...EDGE_IDENTITIES] }], + context + + ": the one policy finding names the rule " + + JSON.stringify(rule) + + " and the offending edge — identities in order the rule's name, the " + + "edge's source, kind token, and target; no in-source location, no " + + "concerned path (SPEC 7.5, 14.12, 12.7)", + ); +} + +/** (a): the group loads, and `inventory` reports it with its one source. */ +async function runGroupArm( + product: ProductBinding, + arm: GroupArm, +): Promise<void> { + await withWorkspace(arm.files, async (workspace) => { + const label = "T7-11(a) (" + arm.label + ")"; + await expectFindingFreeReport( + product, + workspace, + ["build", "--json"], + label + + " `build --json` — the configuration loads: 7 bars a group name " + + "only when it is empty or contains U+FFFD (SPEC 7)", + ); + await expectFindingFreeReport( + product, + workspace, + ["check", "--json"], + label + " `check --json` on the freshly built workspace (SPEC 7, 12.2)", + ); + const inventoryLabel = label + " `inventory --json`"; + const inventory = decodeInventoryDocument( + await runJson( + product, + workspace, + ["inventory", "--json"], + inventoryLabel, + ), + inventoryLabel, + ); + const group = { name: arm.name, globs: [arm.glob] }; + assertSameJson( + { + specs: inventory.configuration.specs, + code: inventory.configuration.code, + sources: inventory.sources, + }, + { + specs: arm.kind === "spec" ? [group] : [], + code: arm.kind === "code" ? [group] : [], + sources: [ + { + path: arm.sourcePath, + groups: [{ name: arm.name, kind: arm.kind }], + }, + ], + }, + inventoryLabel + + ": the " + + arm.kind + + " group is reported under its name " + + JSON.stringify(arm.name) + + " with its glob " + + arm.glob + + ", the other group list empty, and its one discovered source " + + arm.sourcePath + + " a member of it — a name like any other (SPEC 7, 11.6, 12.7)", + ); + }); +} + +/** (b): a profile and a forbidden rule both named `toString`. */ +async function runProfileAndRuleArm(product: ProductBinding): Promise<void> { + await withWorkspace(graphFiles(T7_11_B_CONFIG), async (workspace) => { + const label = + "T7-11(b) (a profile and a forbidden rule both named toString)"; + await expectFindingFreeReport( + product, + workspace, + ["build", "--json"], + label + + " `build --json` — the configuration loads, and build evaluates no " + + "policy (SPEC 7, 7.4, 7.5, 12.1)", + ); + const inventoryLabel = label + " `inventory --json`"; + const inventory = decodeInventoryDocument( + await runJson( + product, + workspace, + ["inventory", "--json"], + inventoryLabel, + ), + inventoryLabel, + ); + assertSameJson( + { + coverage: inventory.configuration.coverage, + policy: inventory.configuration.policy, + }, + { coverage: [T7_11_B_PROFILE_VIEW], policy: [T7_11_B_RULE_VIEW] }, + inventoryLabel + + ": the profile and the rule are each reported under the name " + + "toString with its complete definition, every default and inferred " + + "kind explicit (SPEC 7, 7.4, 7.5, 11.6, 12.7)", + ); + const coverageLabel = label + " `coverage toString --json`"; + assertProfileCoversA( + decodeCoverageReport( + await runJson( + product, + workspace, + ["coverage", TO_STRING, "--json"], + coverageLabel, + ), + coverageLabel, + ), + TO_STRING, + coverageLabel, + ); + await expectOneViolation( + product, + workspace, + TO_STRING, + label + " `check --json`", + ); + }); +} + +/** (c), the group configured: the reference resolves. */ +async function runReferenceResolvingArm( + product: ProductBinding, + arm: ReferenceArm, +): Promise<void> { + await withWorkspace(arm.resolving, async (workspace) => { + const label = + "T7-11(c) (" + arm.label + ", a spec group of that name configured)"; + await expectFindingFreeReport( + product, + workspace, + ["build", "--json"], + label + + " `build --json` — the reference resolves, so the configuration " + + "loads (SPEC 7, " + + (arm.site === "selector" ? "7.5" : "7.4") + + ")", + ); + if (arm.site === "selector") { + await expectOneViolation( + product, + workspace, + "r", + label + " `check --json`", + ); + return; + } + const coverageLabel = label + " `coverage --json`"; + assertProfileCoversA( + decodeCoverageReport( + await runJson( + product, + workspace, + ["coverage", "--json"], + coverageLabel, + ), + coverageLabel, + ), + "p", + coverageLabel, + ); + }); +} + +/** (c), no group of that name: the reference names an unknown group. */ +async function runReferenceUnknownArm( + product: ProductBinding, + arm: ReferenceArm, +): Promise<void> { + await withWorkspace(arm.unknown, async (workspace) => { + const label = "T7-11(c) (" + arm.label + ", no group of that name)"; + const before = await snapshotDirectory(workspace.root); + const result = await expectConfigurationError( + product, + workspace, + ["build"], + label + + " `build --json` — the reference names no configured group, an " + + "unknown group (SPEC " + + (arm.site === "selector" ? "7.5" : "7.4") + + ", 14.14)", + ); + const finding = expectErrorDocument(result, label); + assertSameJson( + { + code: finding.code, + path: finding.path, + locations: finding.locations, + }, + { code: "configuration-error", path: CONFIG_PATH, locations: [] }, + label + + ": the error document's one finding carries the stable code " + + "configuration-error, locations [] (a configuration condition " + + "carries the file it concerns, never a source range), and as its " + + "concerned path the configuration file the upward search found, in " + + "the anchoring form of 11.6 relative to the invocation working " + + "directory, the workspace root — exactly xspec.config.ts (SPEC 14, " + + "12.7, 11.6)", + ); + assertSnapshotsEqual( + before, + await snapshotDirectory(workspace.root), + label + + ": a build failing at configuration load modifies nothing (SPEC " + + "12.1, 12.0) — no derived file or graph data appears anywhere under " + + "the root", + ); + }); +} + +/** + * (d): the premise — `coverage p` answers the one configured profile — then + * each unknown name, one arm each, its diagnosed failure collected. + */ +async function runUnknownProfileArms( + product: ProductBinding, + failures: string[], +): Promise<void> { + await withWorkspace(graphFiles(T7_11_D_CONFIG), async (workspace) => { + const label = "T7-11(d) (the one profile p configured)"; + await expectFindingFreeReport( + product, + workspace, + ["build", "--json"], + label + " `build --json` — the configuration loads (SPEC 7, 7.4)", + ); + const coverageLabel = + label + + " `coverage p --json` — the premise: the surface answers a configured " + + "profile's name"; + assertProfileCoversA( + decodeCoverageReport( + await runJson( + product, + workspace, + ["coverage", "p", "--json"], + coverageLabel, + ), + coverageLabel, + ), + "p", + coverageLabel, + ); + for (const name of UNKNOWN_PROFILE_NAMES) { + await collectArmFailure(failures, async () => { + await expectPlainUsageError( + product, + workspace, + ["coverage", name, "--json"], + label + + " `coverage " + + name + + " --json` — no profile named " + + name + + " is configured: an unknown profile named in arguments is the " + + "usage error of 12.0, exit 2 (SPEC 8.2, 12.0, 12.7)", + ); + }); + } + }); +} + +// --------------------------------------------------------------------------- +// T7-11 — configured names +// --------------------------------------------------------------------------- + +const T7_11 = defineProductTest({ + id: "T7-11", + title: + "configured names: 7 bars a group, profile, or rule name only when it " + + "is empty or contains U+FFFD, so the `Object` members and `__proto__` " + + "are names like any other — (a) a spec group named `__proto__` (an " + + "identifier key, and separately a string-literal key), one named " + + "`constructor`, and one named `hasOwnProperty`, each globbing " + + "specs/*.mdx over specs/A.mdx, and code groups so named globbing " + + "src/*.ts over src/a.ts beside no spec group, one arm each: `build` and " + + "`check` exit 0 finding-free and `inventory` reports the group under " + + "its name with its glob and its one source; (b) a profile and a " + + "`forbidden` rule both named `toString`, over the one edge the rule " + + "forbids: `build` exits 0, `inventory` reports both with their " + + "complete definitions, every default and inferred kind explicit, " + + "`coverage toString` reports exactly that profile, its target leaf " + + "covered over the edge, and `check` reports the violation under the " + + "rule's name, its one 14.12 finding, exit 1; (c) a profile's `target`, " + + "its `boundary`, and a rule's selector `group`, each naming " + + "`__proto__` and `constructor`, one arm each: with a spec group of " + + "that name configured the reference resolves — `build` exits 0 and " + + "the profile's coverage is reported, or the rule evaluated, its one " + + "violation reported by `check` — and with none it is an unknown group, " + + "14.14, exit 2, the finding naming xspec.config.ts, nothing written; " + + "(d) with the one profile p configured, which `coverage p` reports, " + + "`coverage constructor` and `coverage __proto__` each name an unknown " + + "profile, the plain usage error of 12.0 (exit 2, the error document's " + + "code and path null) (SPEC 7, 7.4, 7.5, 8.2, 11.6, 12.0, 12.7, 14)", + run: async (product) => { + const failures: string[] = []; + for (const arm of T7_11_A_ARMS) { + await collectArmFailure(failures, () => runGroupArm(product, arm)); + } + await collectArmFailure(failures, () => runProfileAndRuleArm(product)); + for (const arm of T7_11_C_ARMS) { + await collectArmFailure(failures, () => + runReferenceResolvingArm(product, arm), + ); + await collectArmFailure(failures, () => + runReferenceUnknownArm(product, arm), + ); + } + await collectArmFailure(failures, () => + runUnknownProfileArms(product, failures), + ); + if (failures.length > 0) { + fail( + "T7-11: " + + String(failures.length) + + " of " + + String(T7_11_ARM_COUNT) + + " arms failed, each diagnosed below:" + + LINE_FEED + + failures.join(LINE_FEED), + ); + } + }, +}); + +/** TEST-SPEC §7 configured names: T7-11. */ +export const section7NamesTests: readonly ProductTestEntry[] = [T7_11]; diff --git a/test/suite/registry/section-7.4-7.5.ts b/test/suite/registry/section-7.4-7.5.ts index 0714f91e..e14e4d49 100644 --- a/test/suite/registry/section-7.4-7.5.ts +++ b/test/suite/registry/section-7.4-7.5.ts @@ -17,8 +17,9 @@ // optional `edgeKinds` (non-empty subset of the three dependency kinds, // defaulting to all three). SPEC 7.5: policy rules carry `name` (unique), // `type` ("forbidden" | "allowedOnly"), `from`/`to` selectors (exactly one of -// group/files/tags; group optionally kind-qualified like boundaryKind), and -// optional `kinds`; `files` selectors support capture wildcards `$1`…`$9` +// group/files/tags; group optionally kind-qualified like boundaryKind, `kind` +// belonging to the group form alone), and optional `kinds`; `files` +// selectors support capture wildcards `$1`…`$9` // (each at most once in `from`; a `to` capture must exist in `from`; a // capture takes one or more bytes within a single segment, shortest-match // left to right) and follow 7's glob rules — a `files` glob, capture-bearing @@ -93,6 +94,15 @@ // edges` so its clean `check --json` (exit 0, findings []) is not vacuous, // and the twin reports the edge (exit 1) — a product normalizing a // selector glob's spelling before matching flags it under both. +// - A selector carrying `kind` without `group` (T7.5-1; SPEC 7.5: `kind` +// belongs to the group form alone): `{ files: "src/*.ts", kind: "code" }`, +// `{ tags: ["a"], kind: "spec" }`, and `{ kind: "spec" }`, one matrix row +// each, in `from`. The first two selectors are valid without their `kind` +// and each rule otherwise valid, so a product vetting `kind` only beside +// `group` accepts the configuration and builds (exit 0) where 14.14 +// requires exit 2; the third, holding none of the three forms besides, +// discriminates a product that reads a bare `kind` as a selector of every +// node of that kind. // - Every `check` run is preceded by a successful `build` in the same // workspace, so generated output is fresh and the policy findings are the // run's only findings (no 14.10 staleness contamination) — the exact @@ -1736,6 +1746,55 @@ const RULE_MATRIX: readonly { ], ], }, + // A selector carrying `kind` without `group` (7.5: `kind` belongs to the + // group form alone; 7.6 names the violation), one arm per selector TEST-SPEC + // spells, each in `from` beside the valid `to: { group: "aux" }`. The first + // two selectors are valid without their `kind` — `src/*.ts` reaches the code + // group app's src/impl.ts, `tags: ["a"]` is non-empty — so a product that + // vets `kind` only beside `group` accepts the configuration and builds (exit + // 0 — `build` never evaluates policy, 12.1) where 14.14 requires exit 2. + { + label: + 'selector `{ files: "src/*.ts", kind: "code" }` — `kind` beside ' + + "`files`, the selector valid without it, discriminating a product " + + "that vets `kind` only beside `group`", + rules: [ + [ + 'name: "r"', + 'type: "forbidden"', + 'from: { files: "src/*.ts", kind: "code" }', + 'to: { group: "aux" }', + ], + ], + }, + { + label: + 'selector `{ tags: ["a"], kind: "spec" }` — `kind` beside `tags`, ' + + "the selector valid without it, discriminating a product that vets " + + "`kind` only beside `group`", + rules: [ + [ + 'name: "r"', + 'type: "forbidden"', + 'from: { tags: ["a"], kind: "spec" }', + 'to: { group: "aux" }', + ], + ], + }, + { + label: + 'selector `{ kind: "spec" }` — `kind` alone, with none of ' + + "group/files/tags, discriminating a product that reads a bare `kind` " + + "as a selector of every node of that kind", + rules: [ + [ + 'name: "r"', + 'type: "forbidden"', + 'from: { kind: "spec" }', + 'to: { group: "aux" }', + ], + ], + }, { label: "unknown group name in a selector", rules: [ @@ -1888,7 +1947,10 @@ const T7_5_1 = defineProductTest({ "invalid type, empty kinds/tags lists, `kinds` not a subset of the " + "dependency edge kinds (a `contains` member, an unknown token, a " + "non-string element), a non-string selector `tags` element, selectors " + - "with zero or two of group/files/tags, unknown, wrong-kind, and " + + "with zero or two of group/files/tags, a selector carrying `kind` " + + 'without `group` — `{ files: "src/*.ts", kind: "code" }`, `{ tags: ' + + '["a"], kind: "spec" }`, and `{ kind: "spec" }`, one arm each (`kind` ' + + "belonging to the group form alone), unknown, wrong-kind, and " + "ambiguous group references, a capture used twice in `from`, a `to` " + "referencing an absent capture, and a selector `files` glob outside " + "the workspace root by its spelling alone — `../x/*.ts` and the " + diff --git a/test/suite/registry/section-7.6-ii.ts b/test/suite/registry/section-7.6-ii.ts new file mode 100644 index 00000000..0de9d38e --- /dev/null +++ b/test/suite/registry/section-7.6-ii.ts @@ -0,0 +1,2206 @@ +// TEST-SPEC §7.6 (the `defineConfig` module), second part — the placements, +// Reach's open cases, and the runtime: T7.6-4, placements; T7.6-5, Reach's +// open cases; T7.6-6, runtime exports and identity; and T7.6-7, runtime: no +// effect. T7.6-1, T7.6-2, and T7.6-3, the type contract, are +// section-7.6.ts's business; P-17, installation names, which draws its +// placements over T7.6-4's halves and T7.6-6's routes, is +// section-16-p17.ts's; P-18 is not registered yet. +// +// 7.6 is tested through H-2's module channel alone (TEST-SPEC §7.6's four +// rules: Placement, Covered setups, Verdict, Pairing). A body here never +// invokes the `xspec` executable: it places the product's package +// directory, the binding's `packageDir`, in fresh stagings — under the +// canonical placement, under each of T7.6-4's placements, or beside each +// of T7.6-5's manifests (helpers/module-channel.ts) — and loads the +// `defineConfig` module there on the Node.js releases E-1 provisions +// (helpers/node-releases.ts) through the module channel's release driver +// (helpers/module-channel-node.ts and its bootstrap), T7.6-4 and T7.6-5 +// also type-checking covered files there through the TypeScript driver +// (helpers/module-channel-ts.ts), as T7.6-1–3's bodies do (T7.6-4 and +// T7.6-5 at the end of this header). The driver runs each +// release under T7.6-6's run conditions — no option, and an environment of +// exactly a fresh `HOME` and `TMPDIR` and the harness's `PATH`, so no +// `NODE_OPTIONS` and no `NODE_PATH`, and with them no user condition and no +// loader or customization hook — checks them on every report, and makes +// T7.6-6's and T7.6-7's observations inside the run and around it; S-10 +// pins it on committed stand-ins (test/self/s10-node-release-driver.test.ts). +// With no package directory given, the body fails diagnosed before +// anything is staged (H-8: the module channel counts as part of the +// product); a listed release the environment has not provisioned is a +// harness error (E-1, H-11), never a skip or a product failure. +// +// T7.6-6 (SPEC 7.6 Runtime, Reach): on each release E-1 provisions — a +// release of 22.0–22.11, on which `require` cannot load an ES module +// without a flag, among them — the module is loaded along each of Node.js's +// routes from a harness-written importing module in the importing file's +// place: a static `import` from an ES module (`.mjs`), a dynamic `import()` +// from an ES module and from a CommonJS module (`.cjs`), and `require` from +// a CommonJS module. In each run: +// - (a) exports: an `import` namespace's own string-keyed properties are +// exactly `defineConfig` — a CommonJS-only entry, whose namespace carries +// `default`, fails — and a `require` result's own enumerable properties, +// string- and symbol-keyed alike, are exactly `defineConfig` — an +// enumerable `__esModule` fails (the driver's `exportsProblems`); +// - (b) identity: `defineConfig(v)` returns `v` itself, compared by +// SameValue, for an object, an array, a function, a symbol, `null`, +// `undefined` passed explicitly, a string, a boolean, a bigint, and the +// numbers `0`, `-0`, and `NaN`; a call with no argument returns +// `undefined`; and a call with a further argument returns its first +// (`identityProblems`); +// - (c) no examination, copy, or modification: called with a Proxy over a +// function whose every trap records its invocation and a second such +// Proxy, `defineConfig` returns the first Proxy itself with no trap of +// either invoked through the run's end; called with a frozen object, it +// returns that object without throwing (`examinationProblems`). +// +// T7.6-7 (SPEC 7.6 Runtime: beyond the runtime's own resolution of the +// specifier and loading of the package's files, neither loading the module +// nor calling `defineConfig` has any effect): in T7.6-6's runs, loading the +// module and making T7.6-6's calls have no effect: +// - (a) output: standard output is empty, and standard error is exactly the +// release's printed forms of the process warnings the run emits, in +// order, as the runtime delivers them to the `warning` listener the +// bootstrap registers on `process` before the importing module's own +// loading begins — each in the form learned from the release itself — +// and no captured warning's stack begins in the package's files, its +// first frame naming one of them (the driver's output oracle, +// `runtimeOutputProblems`). The release's own warnings in resolving the +// specifier and loading the package's files — the experimental warning +// for loading an ES module through `require`, DEP0128, DEP0151 — begin +// their stacks outside the package's files, so 7.6's exception admits +// them; text the module writes to either stream, in the warning form or +// not, has no captured warning behind it, so it fails, as does a warning +// the module emits through the runtime's warning facility; +// - (b) writes: no entry is created, modified, or removed in the staging, +// the placement included, in the run's working directory, or in its +// fresh `HOME` and `TMPDIR`, each compared entry by entry just before and +// just after the run, a plain file by its bytes as well and a FIFO by its +// kind alone, never opened (`writeProblems`); +// - (c) process state: unchanged across the load and the calls, as the +// bootstrap compares the state read before the importing module's own +// loading begins — the `warning` listener already registered — with the +// state once T7.6-6's calls are made: the global object's own properties +// with their descriptors, the built-ins' own properties, each observed +// object's extensibility and prototype, `process`'s own properties, +// `process.env`, the process title, the working directory, +// `process.exitCode`, the `write` each standard stream resolves to, the +// listeners registered on `process`, and the pending timers and handles +// (`stateProblems`); +// - (d) network: the environment's — every run inherits the network-denied +// namespace CI's Linux jobs run in (E-1), so an attempted access fails +// rather than reaching a network; nothing here observes it; +// - (e) reads: FIFOs named `xspec.config.ts` in the run's working +// directory, in the importing module's directory, and in its `HOME`, each +// afterwards still a FIFO in place (`fifoProblems`) and unopened — a run +// that opens one blocks until its guard, whose kill propagates and ends +// the test (S-3), so every run ending within its guard is all +// "unopened" asserts. +// Each of T7.6-7's absences counts only under §7.6's pairing: each of its +// readings reports first, where unmet, that the run never saw +// `defineConfig` return its argument in every one of T7.6-6's calls (the +// driver's `pairingProblem`), so a stub package fails every arm. The rest +// of T7.6-7's read, write, network, state, and output clauses admits no +// discriminating staging (its closing sentences): nothing is asserted +// there. +// +// Conservative operationalizations of T7.6-6 and T7.6-7 (noted per H-4): +// - One staging per test: a CommonJS project whose `package.json` holds no +// `type` (`project/`), beside the canonical placement — a copy at +// `node_modules/N` in the project's directory, the importing file's own, +// N the canonical name, which differs from the name the package's +// manifest gives, so the install is an aliased one — nothing else +// installed. The project kind bears on no route: each importing module's +// kind is fixed by its extension, whatever any `package.json` says, and +// no manifest in the importing file's directory or its ancestors gives a +// `name`, so none is a self-reference. It is the staging S-10's checks +// pin the driver on. +// Before each run the driver verifies Reach — the project kind and +// nothing else installed among it — and H-1 under the run's exact +// environment; an unmet condition is a harness error. +// - The releases: every release E-1 lists, in list order, resolved once +// the package directory has been checked. The body confirms that one of +// them is a 22.0–22.11 release, as T7.6-6 names one among them (a list +// lacking one is a harness defect), and the placement confirms that none +// resolves N to a built-in module. The routes: the driver's four, in +// T7.6-6's order. One run per release and route, one after another — 24 +// for E-1's six releases — each route's importing module written once in +// the project's directory and found byte-equal there by every later +// release's run. +// - T7.6-6 and T7.6-7 share one body (`runRuntimeRuns`), each test making +// its own runs, as each registered test runs alone on a fresh staging +// (H-1): T7.6-7's runs are runs of T7.6-6's shape — the same staging, +// releases, routes, and run conditions, the bootstrap making T7.6-6's +// calls in every run — each also observing its effects (the driver's +// `effects`: the three FIFOs staged before it, the staging, the working +// directory, `HOME`, and `TMPDIR` snapshotted just before and just after +// it). Of T7.6-6's observations, T7.6-7 reads the calls' returns alone, +// for its pairing, and T7.6-6 reads none of T7.6-7's. A run observing its +// effects compares the whole staging, so each run is prepared, launched, +// and disposed of before the next, never beside another. +// - Each run must load the module and end on its own with exit code 0 (the +// driver's `assertModuleLoaded`, the conservative reading: the route's +// load is its whole run, so a process ending otherwise — a crash, a +// signal, an exit the package forces — loaded nothing cleanly, whatever +// its report holds). Otherwise the run is reported as what it came to — +// the load threw (a missing entry, a `require` refused), the process +// ended before the load completed or during T7.6-6's calls, or it left no +// report — with its streams, a diagnosed failure (H-8). The body stops at +// the first such run, its diagnosis naming the problems the runs before +// it found, so S-7's stub package ends it at its first run. +// - On each run that loaded, the test's observations are read as problems +// in words, never thrown, and collected across every run; once all have +// run, the body fails once, diagnosed, naming each distinct problem in +// full with the runs it was found in (New-test conventions: many +// stagings) — a run's own directory, which holds its working directory, +// `HOME`, and `TMPDIR` and differs from run to run, written +// `<run directory>`, so that a write into `TMPDIR` made in every run is +// one problem found in each. A harness error, and a run's hang-guard +// kill (S-3), propagate at once. +// +// T7.6-4 (SPEC 7.6 Package and installation: a copy, a symbolic-link +// install, and an aliased install are alike; Reach): each placement below +// stands in for the canonical one in a run of T7.6-1, of T7.6-2(a) with +// T7.6-3's unknown-top-level-key arm paired to it in every covered setup, +// and of T7.6-6's exports and identity assertions ((a) and (b)) along every +// route on every release E-1 provisions, and fares as the canonical +// placement does: +// - (a) a copy under the `name` the package's manifest gives (the +// non-aliased install), wherever that is a name of 7.6's grammar outside +// its exclusions; +// - (b) `node_modules/N` a symbolic link to a copy of the package directory +// placed elsewhere in the staging, under no `node_modules`; +// - (c) names across 7.6's grammar: a scoped name, a name beginning with a +// digit, a name holding `-` and `_`, the dotted names `a.js` and `a.b`, +// whose `S` differs from N (each beside an unrelated package at +// `node_modules/a`, which Reach does not bar, and no `a.ts` beside +// `a.js`), and an unscoped and a scoped name each exactly 214 characters +// long; +// - (d) the holding directory a strict ancestor of the importing file's +// directory, and, separately, an ancestor of the file's physical path +// alone — the file's directory also reachable through a symbolic link +// elsewhere in the staging, on whose path that ancestor does not lie — +// each tool given the physical path; +// - (e) other packages installed — TypeScript 5.9.3's package at +// `node_modules/typescript` and an unrelated package beside the +// placement, and, the holding directory a strict ancestor, an unrelated +// package in the importing file's own directory — none an `@types` +// package; +// - (f) in the type-checking runs alone, N `fs`, and separately `path`, +// names the provisioned releases resolve to built-in modules. +// +// Conservative operationalizations of T7.6-4 (noted per H-4): +// - "Fares as the canonical placement does" is read as each of those runs' +// assertions holding under the placement as T7.6-1, T7.6-2, T7.6-3, and +// T7.6-6 require them to hold under the canonical one — never as a +// comparison with the canonical placement's own outcome, under which a +// missing or stub package, failing everywhere alike, would pass (H-8, +// S-7). +// - One registered test, one body (`runPlacements`), here beside the +// runtime tests whose runs it shares: the package directory checked +// first (none given fails diagnosed, before anything is staged), every +// release E-1 lists resolved, then each placement in TEST-SPEC's order +// (`T764_PLACEMENTS`), its type-checking half, then its runtime half. +// Each half makes stagings of its own, made as the canonical placement's +// are but for what the placement varies; nothing is shared across +// placements but parsed libraries and their diagnostics (the TypeScript +// driver's header), since a placement's package files lie elsewhere. +// - The type-checking half: one staging per project kind, the importing +// files' directory staged as that project; in it T7.6-1's covered file +// (T7.6-2(d)'s, its export listing asked), T7.6-2(a)'s file, and T7.6-3's +// unknown-top-level-key arm, written under each covered extension, Reach +// verified for each, and judged in one program per covered setup of the +// project — a batch TEST-SPEC §7.6 allows, the three importing the same +// module, which the driver confirms on each program, falling back to a +// program per file — in all 173 setups: T7.6-1's listing read through +// section-7.6.ts's `assertDeclaredExports`, (a)'s file type-checking, and +// the arm failing to type-check paired with it (`assertShapeViolation`; +// where (a)'s file does not type-check, the arm counts nowhere there). +// The files are those tests' own, N aside (section-7.6.ts +// `placementFiles`, which confirms at module load that beside the +// canonical candidates its bytes are their records'). +// - The runtime half: one staging, the importing files' directory staged as +// a CommonJS project, as T7.6-6's is, and T7.6-6's 24 runs from it — the +// same driver, run conditions, routes, and releases (`runRoutes`) — each +// read for T7.6-6's exports and identity (`exportsProblems`, +// `identityProblems`), never its (c), which T7.6-4 does not name. +// - N: (b), (d), and (e) place the canonical N (helpers/module-channel.ts +// `canonicalModuleName`), varying only what they name. (c)'s names are +// fixed here: `@staged-scope/config-module`, `7config`, +// `staged-config_module`, `a.js`, `a.b`, a 214-character unscoped name, +// and a 214-character name in the scope `@long-scope`, none a canonical +// candidate; a module-load check (`checkT764Placements`) holds the list to +// T7.6-4's — its arms' counts, each name's feature and its place in 7.6's +// grammar outside the exclusions, the runtime halves, and `alone`. +// (a)'s N is the manifest's `name`, read strictly (helpers/module-channel.ts +// `readManifestName`); where the manifest gives none, or one outside 7.6's +// grammar or under an exclusion every arm has, (a) is not staged, as +// TEST-SPEC stages it only where it is such a name; its runtime half runs +// on each release that resolves that N to no built-in module, each +// release asked, and on none where every release does. On every other +// runtime half the placement itself confirms that no release resolves N +// to a built-in module. +// - Layouts (`PLACEMENT_LAYOUTS`), staging-relative: the canonical one, the +// importing files and the holding directory both `project/`; for (d)'s +// first placement and (e)'s second, the files in `ancestor/project/` and +// the placement in `ancestor/`; for (d)'s second, the files in +// `physical/project/` and the placement in `physical/`, with a symbolic +// link at `linked/project` reaching the files' directory — each tool +// given the files by their physical paths, as Reach's physical naming has +// it, which the staging verifies. +// - Other packages: an unrelated package is a directory of the harness's +// writing — a manifest naming it, a CommonJS `index.js`, and its +// `index.d.ts` — which nothing imports, so a resolution straying into it +// (`a` for `a.js`) fails loud, its exports differing; TypeScript's +// package is a copy, entry by entry, of the harness's own +// `typescript-5.9.3` directory, the release the TypeScript driver runs, +// its manifest confirmed to name `typescript` at 5.9.3 — never a link out +// of the staging. Neither is an `@types` package, and the TypeScript +// driver refuses any program something else enters (the program +// condition). +// - Reach is verified for each written file and before each run, the +// project kind confirmed, and, where nothing else is installed — (a), +// (b), (c)'s undotted names, (d), and (f) — that the placement is alone; +// an unmet condition is a harness error. +// - S-9: the files beside each fixed N — the canonical candidates and every +// fixed name — are staged-source records made at module load, as plain +// TypeScript and as TSX of the same bytes, those beside the canonical +// candidates named for T7.6-5 too, which stages them (`T7.6-4/T7.6-5 …`). +// (a)'s files, whose N only the package's manifest gives, are composed at +// run time by the same composition (a generated form, the records its +// vector set) and judged well-formed under both grammars before anything +// is staged, a failure a harness error. +// - The body stops at its first failure, diagnosed, naming the placement, +// N, and the placements that held before it: in a type-checking half, the +// first covered setup where any of the three runs fails, every failing +// run's diagnosis given; in a runtime half, the first run that does not +// load the module and end on its own with exit code 0, or, once its 24 +// runs are made, the problems they found (T7.6-6's reading). So S-7's +// stub package ends the body at (a)'s first setup, and a missing package +// directory before anything is staged. +// +// T7.6-5 (SPEC 7.6 Reach: its four conditions rule out only what those +// tools do before they reach the installed package; Covered setups: a +// project is an ES-module one where the package.json nearest the +// configuration file holds `"type": "module"`, and a CommonJS one +// otherwise): stagings meeting every condition of Reach while leaving open +// what none of them bars, each run as T7.6-4's placements are — standing in +// for the canonical one in a run of T7.6-1, of T7.6-2(a) with T7.6-3's +// unknown-top-level-key arm paired to it in every covered setup, and of +// T7.6-6's exports and identity assertions along every route on every +// release E-1 provisions, and faring as the canonical placement does: +// - (a) an ancestor package.json whose `name`, `"unrelated"`, TypeScript +// and Node.js read as neither N nor a leading part of it; +// - (b) an ES-module project beneath an ancestor package.json holding +// `"type": "commonjs"`, and a CommonJS project — its nearest package.json +// without `type` — beneath an ancestor holding `"type": "module"`; +// - (c) a nearest package.json holding `"type": "commonjs"`. +// +// Conservative operationalizations of T7.6-5 (noted per H-4): +// - One registered test, its body T7.6-4's (`runPlacements`) over a list of +// its own (`T765_STAGINGS`), each staging a record of T7.6-4's +// placements' shape run through the same halves, its diagnoses naming +// T7.6-5 and its rule. Every staging keeps the canonical placement — a +// copy at node_modules/N in the importing files' own directory, N the +// canonical name, nothing else installed (confirmed `alone`) — and varies +// the manifests alone, so that what must fare as the canonical placement +// does is exactly what the staging leaves open. +// - Each staging is one project, staged afresh for each half: the +// type-checking half judges its files in every covered setup of that +// project's kind (59 for an ES-module project, 57 for a CommonJS one); +// the runtime half makes T7.6-6's 24 runs from that project's directory. +// The importing modules' kinds are fixed by their extensions, so the +// project kind bears on no route, while each manifest lies where Node.js +// reads it in resolving the specifier: its self-reference lookup reads +// the manifest nearest the importing module. +// - (a) is three stagings, its ancestor manifest `ancestor/package.json`, +// `{"name": "unrelated"}`, above the files' directory `ancestor/project/`: +// an ES-module project and a CommonJS project, each with its own manifest +// nearer, and a CommonJS project whose own directory holds none, so that +// the manifest naming `unrelated` is the nearest — the one TypeScript's +// and Node.js's self-reference lookups read. A project with no +// package.json at all cannot lie beneath an ancestor manifest; its +// covered setups are a CommonJS project's, and (a)'s third staging, a +// CommonJS project whose nearest manifest holds no `type`, is judged in +// those, so that (a), like each of T7.6-4's placements, judges 173 +// programs. +// - (b) is two stagings, the files in `ancestor/project/` beneath +// `ancestor/package.json`: the ES-module project's `{"type": "module"}` +// beneath `{"type": "commonjs"}`, and the CommonJS project's `{}` beneath +// `{"type": "module"}`. +// - (c) is one staging, the files in `project/` as the canonical placement +// has them, their manifest `{"type": "commonjs"}`, none above it in the +// staging: a CommonJS project as SPEC 7.6 reads it, judged in the +// CommonJS project's covered setups — whose labels name the CommonJS +// project whose package.json holds no type, as its diagnoses say — Reach +// confirming the nearest manifest's `type` as `"commonjs"` +// (helpers/module-channel.ts `ReachStaging.nearestType`). +// - Every manifest lies inside the staging, below its root, whose own +// ancestors H-1 verifies hold none. Each staging writes its manifests +// itself and reads them back before any tool runs: from the files' +// directory up to the staging root, each directory holds exactly the +// manifest the staging declares there, read strictly, or none where it +// declares none (`confirmManifests`), a deviation a harness error. Reach +// is verified for each written file and before each run, the project +// kind, its nearest manifest's `type` among it, and nothing else +// installed confirmed; a module-load check (`checkT765Stagings`) holds +// the list to T7.6-5's. +// - The files are T7.6-4's beside the canonical N, their records named for +// both tests. The body stops at its first failure, as T7.6-4's does, +// naming the staging and those that held before it, so S-7's stub +// package ends it at (a)'s first staging's first setup, and a missing +// package directory before anything is staged. + +import * as fsp from "node:fs/promises"; +import * as path from "node:path"; +import ts from "typescript-5.9.3"; +import { fail, HarnessAssertionError } from "../../helpers/assertions.js"; +import { + builtInNamesOn, + CANONICAL_MODULE_NAMES, + canonicalModuleName, + MODULE_NAME_MAX_LENGTH, + moduleNameExclusion, + moduleNameGrammarProblem, + modulePackageDirectory, + ModuleStaging, + PROJECT_KINDS, + readManifestStrictly, + runtimeArm, + TYPE_CHECKING_ARM, +} from "../../helpers/module-channel.js"; +import type { + CommonJsTypeMember, + ModuleArm, + PackageDirectory, + Placement, + PlacementForm, + ProjectKind, +} from "../../helpers/module-channel.js"; +import { + assertShapeViolation, + assertTypeChecks, + COVERED_SETUP_COUNT, + coveredSetupsOf, + stageCoveredFiles, +} from "../../helpers/module-channel-ts.js"; +import { + assertModuleLoaded, + examinationProblems, + exportsProblems, + fifoProblems, + identityProblems, + MODULE_ROUTES, + RUN_FIFO_NAME, + runModuleRoute, + runtimeOutputProblems, + stateProblems, + writeProblems, +} from "../../helpers/module-channel-node.js"; +import type { + LoadedModuleRun, + ModuleRoute, + ModuleRun, +} from "../../helpers/module-channel-node.js"; +import { resolveNodeReleases } from "../../helpers/node-releases.js"; +import type { NodeRelease } from "../../helpers/node-releases.js"; +import { HarnessStagingError } from "../../helpers/permissions.js"; +import { defineProductTest } from "../../helpers/registry.js"; +import type { ProductTestEntry } from "../../helpers/registry.js"; +import { stagedTs } from "../../helpers/staged-ts.js"; +import type { StagedTs } from "../../helpers/staged-ts.js"; +import { guardStep } from "../../helpers/step-guards.js"; +import type { ProductBinding } from "../../helpers/subprocess.js"; +import { + judgeTypeScript, + tsDeclarationProblem, +} from "../../helpers/ts-derivability.js"; +import { assertDeclaredExports, placementFiles } from "./section-7.6.js"; +import type { PlacementFile, PlacementFiles } from "./section-7.6.js"; + +const LF = String.fromCodePoint(0x0a); + +/** The project's directory, staging-relative: the importing file's own. */ +const PROJECT_DIR = "project"; + +/** The project kind the staging declares (module header). */ +const PROJECT_KIND: ProjectKind = "commonjs"; + +/** `n` and `word`, pluralized. */ +function count(n: number, word: string): string { + return `${String(n)} ${word}${n === 1 ? "" : "s"}`; +} + +// --------------------------------------------------------------------------- +// The runtime tests' runs (module header) +// --------------------------------------------------------------------------- + +/** + * One of 7.6's runtime tests (module header): whether its runs observe + * their effects, what it reads off each run, and the words its diagnoses + * use. + */ +interface RuntimeTest { + /** Its TEST-SPEC ID. */ + readonly id: string; + /** Leads every diagnosis of its runs. */ + readonly context: string; + /** TEST-SPEC's rule, closing its failures. */ + readonly rule: string; + /** The clauses a run's reading holds, in words: "(a), (b), and (c)". */ + readonly clauses: string; + /** + * Whether each run also observes T7.6-7(b) and (e) — its FIFOs staged + * before it, its places snapshotted around it (the driver's `effects`). + */ + readonly effects: boolean; + /** + * Its reading of a loaded run: problems in words, each led by the run's + * description. + */ + readonly read: (run: LoadedModuleRun) => Promise<readonly string[]>; +} + +/** + * Stands for a run's own directory — the one holding its working directory, + * `HOME`, and `TMPDIR`, removed once the run ends — in a recorded problem, + * so that the same problem found in many runs is named once. + */ +const RUN_DIRECTORY = "<run directory>"; + +/** How a run observing its effects is made, in words, for a diagnosis. */ +const OBSERVING_EFFECTS = + `, each run observing its effects — a FIFO named ${RUN_FIFO_NAME} ` + + "staged in its working directory, in the importing module's directory, " + + "and in its fresh HOME, and the staging, its working directory, HOME, " + + "and TMPDIR compared entry by entry just before and just after it, its " + + "working directory, HOME, and TMPDIR lying in a directory of its own, " + + `written ${RUN_DIRECTORY} below`; + +/** + * Whether `release` is of 22.0–22.11, on which `require` cannot load an ES + * module without a flag (TEST-SPEC T7.6-6). Its version is an exact + * `major.minor.patch` (helpers/node-releases.ts reads the list strictly). + */ +function refusesRequireOfModules(release: NodeRelease): boolean { + const [major, minor] = release.version.split(".").map(Number); + return major === 22 && minor !== undefined && minor <= 11; +} + +/** A run, in short, for a diagnosis listing many: its release and route. */ +function runLabel(release: NodeRelease, route: ModuleRoute): string { + return `${release.version} (${route})`; +} + +/** + * The problems a test's runs found (module header): each distinct problem, + * the run's description it is led by left out, with the runs it was found + * in, in the order found; and each run that found any. + */ +interface FoundProblems { + readonly problems: Map<string, string[]>; + readonly runs: string[]; +} + +/** + * Record `problems`, each led by `run`'s description, under `label`: the + * description left out, and the run's own directory written + * {@link RUN_DIRECTORY}. + */ +function recordProblems( + found: FoundProblems, + run: LoadedModuleRun, + label: string, + problems: readonly string[], +): void { + if (problems.length === 0) return; + found.runs.push(label); + const lead = `${run.description}: `; + const own = path.dirname(run.cwd); + for (const problem of problems) { + const body = ( + problem.startsWith(lead) ? problem.slice(lead.length) : problem + ) + .split(own) + .join(RUN_DIRECTORY); + const runs = found.problems.get(body); + if (runs === undefined) found.problems.set(body, [label]); + else if (!runs.includes(label)) runs.push(label); + } +} + +/** + * Each distinct problem found, in full, with the runs it was found in, of + * the `observed` runs whose problems were read: "every one" of them where + * it was found in each. + */ +function describeFound(found: FoundProblems, observed: number): string { + return [...found.problems] + .map(([body, labels]) => + labels.length === observed && observed > 1 + ? `${body} — in every one of the ${String(observed)} runs` + : `${body} — in ${count(labels.length, "run")}: ${labels.join("; ")}`, + ) + .join(" | "); +} + +/** + * `run` as a run that loaded the module and ended on its own with exit + * code 0 (`assertModuleLoaded`), or a diagnosed failure stopping `test`'s + * body there (module header), naming what the runs before it found. + */ +function loadedOrStop( + test: RuntimeTest, + run: ModuleRun, + label: string, + ordinal: number, + total: number, + found: FoundProblems, +): LoadedModuleRun { + try { + return assertModuleLoaded(run, "product"); + } catch (error) { + if (!(error instanceof HarnessAssertionError)) throw error; + const before = + found.problems.size === 0 + ? ordinal === 1 + ? "no run came before it" + : `each of the ${count(ordinal - 1, "run")} before it loaded the ` + + `module and held ${test.clauses}` + : `the ${count(ordinal - 1, "run")} before it, each of which loaded ` + + "the module and ended on its own with exit code 0, found " + + `${count(found.problems.size, "distinct problem")}: ` + + describeFound(found, ordinal - 1); + fail( + `${error.message}. The body stops at this run, ${label}, run ` + + `${String(ordinal)} of ${String(total)}, the first that did not ` + + `load the module and end on its own with exit code 0; ${before} ` + + test.rule, + ); + } +} + +/** Where a test's runs load the module from: a placement in its staging. */ +interface RunsPlace { + readonly staging: ModuleStaging; + readonly placement: Placement; + /** The importing file's directory, staging-relative, along its physical path. */ + readonly importingDir: string; + /** The project kind staged there, confirmed by Reach before each run. */ + readonly project: ProjectKind; + /** + * A CommonJS project's nearest manifest's `type`, where it holds one + * (T7.6-5(c)), confirmed likewise. + */ + readonly nearestType?: CommonJsTypeMember; + /** Whether nothing but the placement is installed, confirmed likewise. */ + readonly alone: boolean; +} + +/** + * Make `test`'s runs (module header): one per release of `releases` and + * route, one after another, each loading the module from `place`; the + * first run that does not load the module and end on its own with exit + * code 0 stops the body, diagnosed ({@link loadedOrStop}), and each loaded + * run's problems are recorded into `found`. Resolves with the number of + * runs made. + */ +async function runRoutes( + test: RuntimeTest, + place: RunsPlace, + releases: readonly NodeRelease[], + found: FoundProblems, +): Promise<number> { + const total = releases.length * MODULE_ROUTES.length; + let made = 0; + for (const release of releases) { + for (const route of MODULE_ROUTES) { + const label = runLabel(release, route); + const run = await runModuleRoute({ + staging: place.staging, + placement: place.placement, + route, + release, + importingDir: place.importingDir, + project: place.project, + ...(place.nearestType === undefined + ? {} + : { nearestType: place.nearestType }), + alone: place.alone, + effects: test.effects, + context: test.context, + }); + made += 1; + const loaded = loadedOrStop(test, run, label, made, total, found); + recordProblems(found, loaded, label, await test.read(loaded)); + } + } + return made; +} + +/** + * Fail `test` once, diagnosed, where its `made` runs — `summary` saying + * what they were — found any problem (module header); nothing otherwise. + */ +function failOnProblems( + test: RuntimeTest, + found: FoundProblems, + made: number, + summary: string, +): void { + if (found.problems.size === 0) return; + fail( + `${test.context}: ${count(found.problems.size, "distinct problem")} ` + + `in ${count(found.runs.length, "run")} of the ${String(made)} — ` + + `${summary} — each of which loaded the module and ended on its own ` + + `with exit code 0: ${describeFound(found, made)} ${test.rule}`, + ); +} + +/** The body `test` runs against `product` (module header). */ +async function runRuntimeRuns( + product: ProductBinding, + test: RuntimeTest, +): Promise<void> { + const staging = await ModuleStaging.create(product, test.context); + const found: FoundProblems = { problems: new Map(), runs: [] }; + let made = 0; + let summary = ""; + try { + const releases = await resolveNodeReleases(); + const versions = releases.map((release) => release.version); + if (!releases.some(refusesRequireOfModules)) { + throw new Error( + `${test.id}: none of the releases E-1 lists (${versions.join(", ")}) ` + + "is of 22.0–22.11, on which require cannot load an ES module " + + "without a flag, though TEST-SPEC T7.6-6 names one among them: a " + + "harness defect (E-1)", + ); + } + const directory = await staging.stageProject(PROJECT_DIR, PROJECT_KIND); + const placement = await staging.placeCanonical( + PROJECT_DIR, + runtimeArm(releases), + ); + summary = + `every release E-1 lists (${versions.join(", ")}) along each of ` + + `Node.js's ${String(MODULE_ROUTES.length)} routes, each run loading ` + + `${placement.name}, the canonical placement at ${placement.path}, ` + + `from its route's importing module in ${directory}` + + (test.effects ? OBSERVING_EFFECTS : ""); + made = await runRoutes( + test, + { + staging, + placement, + importingDir: PROJECT_DIR, + project: PROJECT_KIND, + alone: true, + }, + releases, + found, + ); + } finally { + await staging.dispose(); + } + failOnProblems(test, found, made, summary); +} + +// --------------------------------------------------------------------------- +// T7.6-6: runtime exports and identity +// --------------------------------------------------------------------------- + +/** T7.6-6's runs and reading (module header). */ +const T766: RuntimeTest = { + id: "T7.6-6", + context: "T7.6-6 (runtime exports and identity)", + rule: + "(TEST-SPEC T7.6-6: on each release E-1 provisions, run with no option, " + + "no environment variable, no user condition, and no loader or " + + "customization hook, the module loads along each of Node.js's routes, " + + "and in each run (a) an import namespace's own string-keyed properties " + + "and a require result's own enumerable properties, string- and " + + "symbol-keyed alike, are exactly defineConfig, (b) defineConfig returns " + + "its first argument, compared by SameValue, and undefined when called " + + "with none, and (c) it neither examines, copies, nor modifies its " + + "argument; SPEC 7.6 Runtime, Reach)", + clauses: "(a), (b), and (c)", + effects: false, + read: (run) => + Promise.resolve([ + ...exportsProblems(run), + ...identityProblems(run), + ...examinationProblems(run), + ]), +}; + +const T7_6_6 = defineProductTest({ + id: "T7.6-6", + title: + "on every Node.js release E-1 provisions (one of 22.0–22.11, on which " + + "require cannot load an ES module without a flag, among them), each run " + + "with no option and no environment variable but a fresh HOME and " + + "TMPDIR and the harness's PATH (so no NODE_OPTIONS or NODE_PATH, no user " + + "condition, and no loader or customization hook), the module placed at " + + "the canonical placement loads along each of Node.js's four routes — a " + + "static import and a dynamic import() from an ES module (.mjs), a " + + "dynamic import() and require from a CommonJS module (.cjs) — from a " + + "harness-written importing module in the importing file's place, the " + + "process ending on its own with exit code 0; and in each run (a) an " + + "import namespace's own string-keyed properties, and a require result's " + + "own enumerable properties, string- and symbol-keyed alike, are exactly " + + "defineConfig; (b) defineConfig(v) returns v itself, compared by " + + "SameValue, for an object, an array, a function, a symbol, null, " + + "undefined passed explicitly, a string, a boolean, a bigint, 0, -0, and " + + "NaN, returns undefined when called with no argument, and returns its " + + "first argument when called with a further one; (c) called with two " + + "Proxies over functions whose every trap records its invocation, it " + + "returns the first with no trap of either invoked through the run's " + + "end, and called with a frozen object it returns that object without " + + "throwing (SPEC 7.6 Runtime, Reach)", + run: (product) => runRuntimeRuns(product, T766), +}); + +// --------------------------------------------------------------------------- +// T7.6-7: runtime, no effect +// --------------------------------------------------------------------------- + +/** T7.6-7's runs and reading (module header). */ +const T767: RuntimeTest = { + id: "T7.6-7", + context: "T7.6-7 (runtime: no effect)", + rule: + "(TEST-SPEC T7.6-7: in T7.6-6's runs, beyond the runtime's own " + + "resolution of the specifier and loading of the package's files, " + + "loading the module and making T7.6-6's calls have no effect — (a) " + + "standard output empty, and standard error exactly the release's " + + "printed forms of the process warnings the run emits, in order, none " + + "beginning its stack in the package's files; (b) no entry created, " + + "modified, or removed in the staging, the working directory, HOME, or " + + "TMPDIR; (c) the process state unchanged across the load and the " + + "calls; (d) every run network-denied (E-1); and (e) the FIFOs named " + + "xspec.config.ts in the working directory, the importing module's " + + "directory, and HOME afterwards still FIFOs, unopened, every run ending " + + "within its guard — each absence counting only where the run saw " + + "defineConfig return its argument (§7.6 Pairing); SPEC 7.6 Runtime)", + clauses: "(a), (b), (c), and (e)", + effects: true, + read: async (run) => [ + ...(await runtimeOutputProblems(run)), + ...writeProblems(run), + ...stateProblems(run), + ...fifoProblems(run), + ], +}; + +const T7_6_7 = defineProductTest({ + id: "T7.6-7", + title: + "in runs of T7.6-6's shape — on every Node.js release E-1 provisions, " + + "along each of Node.js's four routes, the module placed at the " + + "canonical placement loaded from a harness-written importing module in " + + "the importing file's place, under T7.6-6's run conditions with a fresh " + + "HOME, TMPDIR, and working directory, T7.6-6's calls made, and the " + + "process ending on its own with exit code 0 — loading the module and " + + "making the calls have no effect, each absence counting only where the " + + "run saw defineConfig return its argument in every call: (a) standard " + + "output is empty, and standard error is exactly the release's printed " + + "forms, learned from the release, of the process warnings the run " + + "emits, in order, as delivered to a warning listener registered before " + + "the importing module's own loading begins, no captured warning's stack " + + "beginning in the package's files; (b) no entry is created, modified, " + + "or removed in the staging (the placement included), the working " + + "directory, HOME, or TMPDIR, each compared entry by entry just before " + + "and just after the run; (c) the process state — the global object's " + + "own properties with their descriptors, the built-ins' own properties, " + + "extensibility and prototypes, process's own properties, process.env, " + + "the title, the working directory, process.exitCode, each standard " + + "stream's write, process's listeners, and the pending timers and " + + "handles — is unchanged across the load and the calls; and (e) FIFOs " + + "named xspec.config.ts in the working directory, the importing module's " + + "directory, and HOME are afterwards still FIFOs, unopened, every run " + + "ending within its guard; (d), network denial, is the environment's " + + "(E-1) (SPEC 7.6 Runtime)", + run: (product) => runRuntimeRuns(product, T767), +}); + +// --------------------------------------------------------------------------- +// T7.6-4 and T7.6-5: what a placement or staging stages (module header) +// --------------------------------------------------------------------------- + +/** + * A test whose stagings each stand in for the canonical placement in the + * runs T7.6-4 names (module header) — T7.6-4, its placements, and T7.6-5, + * Reach's open cases, run as those placements are — and how its diagnoses + * word them. + */ +interface StandInTest { + /** Its TEST-SPEC ID. */ + readonly id: string; + /** Leads every diagnosis. */ + readonly context: string; + /** TEST-SPEC's rule, closing its failures. */ + readonly rule: string; + /** What one of its stagings is called in a diagnosis. */ + readonly unit: "placement" | "staging"; +} + +/** T7.6-4's words (module header). */ +const T764: StandInTest = { + id: "T7.6-4", + context: "T7.6-4 (placements)", + rule: + "(TEST-SPEC T7.6-4: each placement stands in for the canonical one in a " + + "run of T7.6-1, of T7.6-2(a) with T7.6-3's unknown-top-level-key arm " + + "paired to it in every covered setup, and of T7.6-6's exports and " + + "identity assertions along every route on every release E-1 provisions, " + + "and fares as the canonical placement does; SPEC 7.6 Package and " + + "installation — a copy, a symbolic-link install, and an aliased install " + + "are alike — and Reach)", + unit: "placement", +}; + +/** + * Where a placement's importing files lie and where it is placed, each + * staging-relative (module header): the importing file's own directory as + * the holding directory, as the canonical placement has it, in `project/` + * or, beneath a directory of the staging holding T7.6-5's ancestor + * manifests, in `ancestor/project/`; a strict ancestor of it; or a strict + * ancestor of its physical path alone, the directory also reachable + * through a symbolic link elsewhere in the staging, on whose path that + * ancestor does not lie. + */ +type PlacementLayout = "own" | "beneath" | "ancestor" | "physical ancestor"; + +interface LayoutShape { + /** The importing files' directory: the project's, along its physical path. */ + readonly importingDir: string; + readonly holdingDir: string; + /** A symbolic link at `at` reaching the importing files' directory. */ + readonly link?: { readonly at: string; readonly to: string }; +} + +/** The directory T7.6-5's ancestor manifests lie in, staging-relative. */ +const ANCESTOR_DIR = "ancestor"; + +/** The importing files' directory beneath it. */ +const NESTED_PROJECT_DIR = `${ANCESTOR_DIR}/${PROJECT_DIR}`; + +const PLACEMENT_LAYOUTS: Readonly<Record<PlacementLayout, LayoutShape>> = { + own: { importingDir: PROJECT_DIR, holdingDir: PROJECT_DIR }, + beneath: { importingDir: NESTED_PROJECT_DIR, holdingDir: NESTED_PROJECT_DIR }, + ancestor: { importingDir: NESTED_PROJECT_DIR, holdingDir: ANCESTOR_DIR }, + "physical ancestor": { + importingDir: `physical/${PROJECT_DIR}`, + holdingDir: "physical", + link: { at: `linked/${PROJECT_DIR}`, to: `physical/${PROJECT_DIR}` }, + }, +}; + +/** + * Another package a placement's staging installs (module header): an + * unrelated package of the harness's writing, or TypeScript 5.9.3's. + */ +type OtherPackage = + | { readonly kind: "unrelated"; readonly name: string } + | { readonly kind: "typescript" }; + +/** + * A placement's N: the name the package's manifest gives ((a)), the + * canonical N, or a name fixed here. + */ +type PlacementName = + | { readonly kind: "manifest" } + | { readonly kind: "canonical" } + | { readonly kind: "fixed"; readonly name: string }; + +/** + * One manifest a T7.6-5 staging writes (module header): its directory, + * staging-relative — the importing files' own or one of its ancestors + * below the staging root — and the members its package.json holds. + */ +interface StagedManifest { + readonly dir: string; + readonly members: Readonly<Record<string, string>>; +} + +/** + * The project a half stages its importing files' directory as (module + * header): a project kind as `ModuleStaging.stageProject` stages it + * (T7.6-4's), or, where `manifests` is given (T7.6-5's), exactly those + * manifests from that directory up to the staging root; and what Reach + * confirms — the project kind, in whose covered setups the files are + * judged, and a CommonJS project's nearest `type` where it holds one. + */ +interface ProjectStaging { + readonly project: ProjectKind; + readonly nearestType?: CommonJsTypeMember; + readonly manifests?: readonly StagedManifest[]; +} + +/** A project kind as `stageProject` stages it (T7.6-4's projects). */ +function projectOfKind(kind: ProjectKind): ProjectStaging { + return { project: kind }; +} + +/** + * How a diagnosis names a staged project (module header): for a + * type-checking half (`setups`), with the covered setups a project whose + * nearest manifest holds a type is judged in. + */ +function describeProject(staged: ProjectStaging, setups: boolean): string { + if (staged.manifests === undefined) return `the ${staged.project} project`; + const kind = + staged.project === "es-module" + ? "an ES-module project" + : "a CommonJS project"; + const manifests = staged.manifests + .map( + (manifest) => + `${manifest.dir}/package.json holding ${JSON.stringify(manifest.members)}`, + ) + .join(" and "); + const judged = + !setups || staged.nearestType === undefined + ? "" + : ", judged in the CommonJS project's covered setups, each named " + + "below as that project's, whose package.json holds no type: SPEC " + + `7.6 reads the type ${JSON.stringify(staged.nearestType)} as it ` + + "reads none"; + return `${kind}, its manifests ${manifests}${judged}`; +} + +/** One of T7.6-4's placements or T7.6-5's stagings (module header). */ +interface PlacementSpec { + /** The arm as TEST-SPEC letters it, with an ordinal where it holds several. */ + readonly arm: string; + /** What the placement stages, in words. */ + readonly what: string; + readonly name: PlacementName; + readonly form: PlacementForm; + readonly layout: PlacementLayout; + /** Other packages installed beside the placement, in its holding directory. */ + readonly beside: readonly OtherPackage[]; + /** Other packages installed in the importing files' own directory. */ + readonly inImportingDir: readonly OtherPackage[]; + /** Whether nothing but the placement is installed (Reach's `alone`). */ + readonly alone: boolean; + /** Whether it has a runtime half: every placement but T7.6-4(f)'s. */ + readonly runtime: boolean; + /** The projects its type-checking half stages, a staging each. */ + readonly projects: readonly ProjectStaging[]; + /** The project its runtime half stages. */ + readonly runtimeProject: ProjectStaging; +} + +/** The covered setups a placement's type-checking half judges, all told. */ +function setupCount(spec: PlacementSpec): number { + return spec.projects.reduce( + (sum, staged) => sum + coveredSetupsOf(staged.project).length, + 0, + ); +} + +/** (c)'s names across 7.6's grammar (module header). */ +const SCOPED_NAME = "@staged-scope/config-module"; +const DIGIT_FIRST_NAME = "7config"; +const DASH_UNDERSCORE_NAME = "staged-config_module"; +const DOTTED_NAMES: readonly string[] = ["a.js", "a.b"]; +const LONG_SCOPE = "@long-scope/"; +const LONG_UNSCOPED_NAME = "long-config-module-".padEnd( + MODULE_NAME_MAX_LENGTH, + "x", +); +const LONG_SCOPED_NAME = + LONG_SCOPE + + "long-config-module-".padEnd(MODULE_NAME_MAX_LENGTH - LONG_SCOPE.length, "x"); + +/** The unrelated package beside (c)'s dotted names: at node_modules/a. */ +const DOTTED_NEIGHBOUR = "a"; + +/** (e)'s unrelated package, unscoped, so never an `@types` package. */ +const UNRELATED_PACKAGE = "unrelated-package"; + +/** (f)'s names: the releases resolve each to a built-in module. */ +const BUILT_IN_NAMES: readonly string[] = ["fs", "path"]; + +/** + * A placement of the canonical layout, form, and N but for `overrides`, its + * type-checking half staging each project kind and its runtime half a + * CommonJS project, each as `stageProject` stages it, unless overridden. + */ +function placementOf( + arm: string, + what: string, + overrides: Partial<Omit<PlacementSpec, "arm" | "what">>, +): PlacementSpec { + return { + arm, + what, + name: { kind: "canonical" }, + form: "copy", + layout: "own", + beside: [], + inImportingDir: [], + alone: true, + runtime: true, + projects: PROJECT_KINDS.map(projectOfKind), + runtimeProject: projectOfKind(PROJECT_KIND), + ...overrides, + }; +} + +/** T7.6-4's placements, in TEST-SPEC's order (module header). */ +const T764_PLACEMENTS: readonly PlacementSpec[] = [ + placementOf( + "(a)", + "a copy under the name the package's manifest gives, the non-aliased " + + "install", + { name: { kind: "manifest" } }, + ), + placementOf( + "(b)", + "node_modules/N a symbolic link to a copy of the package directory " + + "elsewhere in the staging, under no node_modules", + { form: "symlink" }, + ), + placementOf("(c) 1", "a scoped name", { + name: { kind: "fixed", name: SCOPED_NAME }, + }), + placementOf("(c) 2", "a name beginning with a digit", { + name: { kind: "fixed", name: DIGIT_FIRST_NAME }, + }), + placementOf("(c) 3", "a name holding - and _", { + name: { kind: "fixed", name: DASH_UNDERSCORE_NAME }, + }), + ...DOTTED_NAMES.map((name, index) => + placementOf( + `(c) ${String(4 + index)}`, + `the dotted name ${name}, whose S, ${DOTTED_NEIGHBOUR}, differs from ` + + `N, beside an unrelated package at node_modules/` + + `${DOTTED_NEIGHBOUR}${name === "a.js" ? " and no a.ts" : ""}`, + { + name: { kind: "fixed", name }, + beside: [{ kind: "unrelated", name: DOTTED_NEIGHBOUR }], + alone: false, + }, + ), + ), + placementOf("(c) 6", "an unscoped name exactly 214 characters long", { + name: { kind: "fixed", name: LONG_UNSCOPED_NAME }, + }), + placementOf("(c) 7", "a scoped name exactly 214 characters long", { + name: { kind: "fixed", name: LONG_SCOPED_NAME }, + }), + placementOf( + "(d) 1", + "the holding directory a strict ancestor of the importing file's " + + "directory", + { layout: "ancestor" }, + ), + placementOf( + "(d) 2", + "the holding directory an ancestor of the importing file's physical " + + "path alone, the file's directory also reachable through a symbolic " + + "link elsewhere in the staging, on whose path that ancestor does not " + + "lie, each tool given the physical path", + { layout: "physical ancestor" }, + ), + placementOf( + "(e) 1", + "TypeScript 5.9.3's package at node_modules/typescript and an unrelated " + + "package beside the placement", + { + beside: [ + { kind: "typescript" }, + { kind: "unrelated", name: UNRELATED_PACKAGE }, + ], + alone: false, + }, + ), + placementOf( + "(e) 2", + "the holding directory a strict ancestor, an unrelated package in the " + + "importing file's own directory", + { + layout: "ancestor", + inImportingDir: [{ kind: "unrelated", name: UNRELATED_PACKAGE }], + alone: false, + }, + ), + ...BUILT_IN_NAMES.map((name, index) => + placementOf( + `(f) ${String(1 + index)}`, + `N ${name}, a name the provisioned releases resolve to a built-in ` + + "module, in the type-checking runs alone", + { name: { kind: "fixed", name }, runtime: false }, + ), + ), +]; + +/** `S` for N (SPEC 7.6 Reach): N cut before the first `.` of its last segment. */ +function cutAtLastSegmentDot(name: string): string { + const slash = name.lastIndexOf("/"); + const dot = name.indexOf(".", slash + 1); + return dot < 0 ? name : name.slice(0, dot); +} + +/** + * Hold T7.6-4's placements to its list (module header): its arms' counts, + * each fixed N a name of 7.6's grammar outside its exclusions with the + * feature its arm names, the runtime halves, `alone` exactly where nothing + * else is installed, and each placement's projects the three kinds as + * `stageProject` stages them, all 173 covered setups, its runtime project + * a CommonJS one. A deviation is a harness defect, thrown at module load. + */ +function checkT764Placements(): void { + const problems: string[] = []; + const need = (held: boolean, problem: string): void => { + if (!held) problems.push(problem); + }; + const letters = new Map<string, number>(); + for (const placement of T764_PLACEMENTS) { + const letter = placement.arm.slice(0, 3); + letters.set(letter, (letters.get(letter) ?? 0) + 1); + need( + placement.runtime === (letter !== "(f)"), + `${placement.arm} has a runtime half exactly where its arm is not (f)`, + ); + need( + placement.alone === + (placement.beside.length === 0 && + placement.inImportingDir.length === 0), + `${placement.arm} is declared alone exactly where it installs nothing else`, + ); + need( + placement.projects.length === PROJECT_KINDS.length && + placement.projects.every( + (staged, index) => + staged.project === PROJECT_KINDS[index] && + staged.manifests === undefined && + staged.nearestType === undefined, + ) && + setupCount(placement) === COVERED_SETUP_COUNT, + `${placement.arm}'s type-checking half stages each project kind as ` + + `stageProject stages it, in all ${String(COVERED_SETUP_COUNT)} ` + + "covered setups", + ); + need( + placement.runtimeProject.project === PROJECT_KIND && + placement.runtimeProject.manifests === undefined && + placement.runtimeProject.nearestType === undefined, + `${placement.arm}'s runtime half stages a CommonJS project as ` + + "stageProject stages it, as T7.6-6's runs do", + ); + need( + placement.layout !== "beneath", + `${placement.arm}'s layout is one of T7.6-4's`, + ); + if (placement.name.kind !== "fixed") continue; + const { name } = placement.name; + const problem = moduleNameGrammarProblem(name) ?? moduleNameExclusion(name); + need(problem === null, `${placement.arm}'s N ${name} ${String(problem)}`); + need( + !CANONICAL_MODULE_NAMES.includes(name), + `${placement.arm}'s N ${name} differs from the canonical candidates`, + ); + } + const expected: readonly [string, number][] = [ + ["(a)", 1], + ["(b)", 1], + ["(c)", 7], + ["(d)", 2], + ["(e)", 2], + ["(f)", 2], + ]; + need( + letters.size === expected.length && + expected.every(([letter, n]) => letters.get(letter) === n), + `the arms number (a) 1, (b) 1, (c) 7, (d) 2, (e) 2, and (f) 2, not ` + + JSON.stringify([...letters]), + ); + need(SCOPED_NAME.startsWith("@"), "(c) 1 is scoped"); + need(/^[0-9]/.test(DIGIT_FIRST_NAME), "(c) 2 begins with a digit"); + need( + DASH_UNDERSCORE_NAME.includes("-") && DASH_UNDERSCORE_NAME.includes("_"), + "(c) 3 holds - and _", + ); + for (const name of DOTTED_NAMES) { + need( + cutAtLastSegmentDot(name) === DOTTED_NEIGHBOUR && + name !== DOTTED_NEIGHBOUR, + `${name}'s S is ${DOTTED_NEIGHBOUR}, differing from N`, + ); + } + need( + LONG_UNSCOPED_NAME.length === MODULE_NAME_MAX_LENGTH && + !LONG_UNSCOPED_NAME.startsWith("@") && + LONG_SCOPED_NAME.length === MODULE_NAME_MAX_LENGTH && + LONG_SCOPED_NAME.startsWith("@"), + `(c) 6 and 7 are an unscoped and a scoped name of exactly ` + + `${String(MODULE_NAME_MAX_LENGTH)} characters`, + ); + need( + !UNRELATED_PACKAGE.startsWith("@") && !DOTTED_NEIGHBOUR.startsWith("@"), + "no other package installed is a scoped one, an @types package least", + ); + if (problems.length > 0) { + throw new Error( + `T7.6-4: its placements deviate from TEST-SPEC T7.6-4's list: ` + + `${problems.join("; ")}: a harness defect`, + ); + } +} + +checkT764Placements(); + +// --------------------------------------------------------------------------- +// T7.6-5: Reach's open cases — what each stages (module header) +// --------------------------------------------------------------------------- + +/** T7.6-5's words (module header). */ +const T765: StandInTest = { + id: "T7.6-5", + context: "T7.6-5 (Reach's open cases)", + rule: + "(TEST-SPEC T7.6-5: stagings meeting every condition of Reach while " + + "leaving open what none of them bars — (a) an ancestor package.json " + + 'whose name, "unrelated", TypeScript and Node.js read as neither N nor ' + + "a leading part of it; (b) an ES-module project beneath an ancestor " + + 'package.json holding "type": "commonjs", and a CommonJS project, its ' + + "nearest package.json without type, beneath an ancestor holding " + + '"type": "module"; and (c) a nearest package.json holding "type": ' + + `"commonjs" — each run as T7.6-4's placements are, standing in for the ` + + "canonical one in a run of T7.6-1, of T7.6-2(a) with T7.6-3's " + + "unknown-top-level-key arm paired to it in every covered setup, and of " + + "T7.6-6's exports and identity assertions along every route on every " + + "release E-1 provisions, and faring as the canonical placement does; " + + "SPEC 7.6 Reach, Covered setups)", + unit: "staging", +}; + +/** (a)'s ancestor manifest's name: read as neither N nor a leading part of it. */ +const UNRELATED_NAME: string = "unrelated"; + +/** A manifest at `dir`, staging-relative, holding `members`. */ +function manifestAt( + dir: string, + members: Readonly<Record<string, string>>, +): StagedManifest { + return { dir, members }; +} + +/** (a)'s ancestor manifest, above the files' directory `ancestor/project/`. */ +const UNRELATED_ANCESTOR = manifestAt(ANCESTOR_DIR, { name: UNRELATED_NAME }); + +/** An ES-module project's own manifest beneath an ancestor's. */ +const NESTED_ES_MODULE = manifestAt(NESTED_PROJECT_DIR, { type: "module" }); + +/** A CommonJS project's own manifest, holding no type, beneath an ancestor's. */ +const NESTED_COMMONJS = manifestAt(NESTED_PROJECT_DIR, {}); + +/** + * One of T7.6-5's stagings (module header): the canonical placement in the + * importing files' own directory, nothing else installed, beside + * `project`'s manifests, staged for both halves. + */ +function stagingOf( + arm: string, + what: string, + layout: PlacementLayout, + project: ProjectStaging, +): PlacementSpec { + return placementOf(arm, what, { + layout, + projects: [project], + runtimeProject: project, + }); +} + +/** T7.6-5's stagings, in TEST-SPEC's order (module header). */ +const T765_STAGINGS: readonly PlacementSpec[] = [ + stagingOf( + "(a) 1", + "an ES-module project beneath an ancestor package.json whose name, " + + '"unrelated", TypeScript and Node.js read as neither N nor a leading ' + + "part of it", + "beneath", + { project: "es-module", manifests: [NESTED_ES_MODULE, UNRELATED_ANCESTOR] }, + ), + stagingOf( + "(a) 2", + "a CommonJS project, its own package.json holding no type, beneath that " + + "ancestor package.json", + "beneath", + { project: "commonjs", manifests: [NESTED_COMMONJS, UNRELATED_ANCESTOR] }, + ), + stagingOf( + "(a) 3", + "a CommonJS project whose own directory holds no package.json, beneath " + + "that ancestor package.json, then the nearest — the one the " + + "self-reference lookups read", + "beneath", + { project: "commonjs", manifests: [UNRELATED_ANCESTOR] }, + ), + stagingOf( + "(b) 1", + "an ES-module project beneath an ancestor package.json holding " + + '"type": "commonjs"', + "beneath", + { + project: "es-module", + manifests: [ + NESTED_ES_MODULE, + manifestAt(ANCESTOR_DIR, { type: "commonjs" }), + ], + }, + ), + stagingOf( + "(b) 2", + "a CommonJS project, its nearest package.json without type, beneath an " + + 'ancestor package.json holding "type": "module"', + "beneath", + { + project: "commonjs", + manifests: [ + NESTED_COMMONJS, + manifestAt(ANCESTOR_DIR, { type: "module" }), + ], + }, + ), + stagingOf("(c)", 'a nearest package.json holding "type": "commonjs"', "own", { + project: "commonjs", + nearestType: "commonjs", + manifests: [manifestAt(PROJECT_DIR, { type: "commonjs" })], + }), +]; + +/** + * `rel`, a staging-relative directory, and each of its ancestors below the + * staging root, nearest first. + */ +function chainBelowRoot(rel: string): readonly string[] { + const names = rel.split("/"); + return names.map((_, index) => + names.slice(0, names.length - index).join("/"), + ); +} + +/** + * Hold T7.6-5's stagings to its list (module header): its arms' counts; + * each the canonical placement — a copy in the importing files' own + * directory, nothing else installed — with a runtime half; one project + * staged for both halves, one manifest at most per directory, each in the + * files' directory or an ancestor below the staging root, the declared + * kind (and type) the one its nearest manifest gives; (a)'s ancestor + * manifest naming "unrelated", read as neither canonical candidate nor a + * leading part of one, above an ES-module project, a CommonJS one with its + * own manifest, and one whose own directory holds none, 173 setups in all; + * (b)'s ancestors' types opposite their projects' kinds; and (c)'s nearest + * manifest's type "commonjs", nothing above it. A deviation is a harness + * defect, thrown at module load. + */ +function checkT765Stagings(): void { + const problems: string[] = []; + const need = (held: boolean, problem: string): void => { + if (!held) problems.push(problem); + }; + const letters = new Map<string, number>(); + const shapes = new Map<string, string>(); + let aSetups = 0; + for (const staging of T765_STAGINGS) { + const letter = staging.arm.slice(0, 3); + letters.set(letter, (letters.get(letter) ?? 0) + 1); + const layout = PLACEMENT_LAYOUTS[staging.layout]; + need( + staging.name.kind === "canonical" && + staging.form === "copy" && + layout.holdingDir === layout.importingDir && + layout.link === undefined && + staging.alone && + staging.beside.length === 0 && + staging.inImportingDir.length === 0 && + staging.runtime, + `${staging.arm} keeps the canonical placement, a copy in the importing ` + + "files' own directory with nothing else installed, and has a runtime half", + ); + const [project] = staging.projects; + if ( + staging.projects.length !== 1 || + project?.manifests === undefined || + staging.runtimeProject !== project + ) { + problems.push( + `${staging.arm} stages one project, its manifests its own, for both halves`, + ); + continue; + } + const chain = chainBelowRoot(layout.importingDir); + const manifests = project.manifests; + need( + manifests.every((manifest) => chain.includes(manifest.dir)) && + new Set(manifests.map((manifest) => manifest.dir)).size === + manifests.length, + `${staging.arm}'s manifests lie one at most per directory, each in the ` + + "importing files' directory or an ancestor below the staging root", + ); + const at = (dir: string): StagedManifest | undefined => + manifests.find((manifest) => manifest.dir === dir); + const own = at(layout.importingDir); + const above = chain.slice(1).flatMap((dir) => at(dir) ?? []); + const nearest = own ?? above[0]; + const nearestType = nearest?.members["type"]; + need( + project.project === "es-module" + ? nearestType === "module" && project.nearestType === undefined + : project.project === "commonjs" && + nearest !== undefined && + nearestType === project.nearestType, + `${staging.arm}'s declared project kind is the one its nearest manifest gives`, + ); + const ancestorType = above[0]?.members["type"]; + shapes.set( + staging.arm, + [ + project.project, + own === undefined ? "no own" : `own ${String(own.members["type"])}`, + `above ${String(above.length)}`, + `above-type ${String(ancestorType)}`, + ].join(", "), + ); + if (letter === "(a)") { + aSetups += setupCount(staging); + need( + above.length === 1 && + above[0] === UNRELATED_ANCESTOR && + Object.keys(UNRELATED_ANCESTOR.members).join() === "name", + `${staging.arm}'s one ancestor manifest names ${UNRELATED_NAME} alone`, + ); + } + } + for (const name of CANONICAL_MODULE_NAMES) { + need( + UNRELATED_NAME !== "" && + !name.startsWith("@") && + UNRELATED_NAME !== name && + UNRELATED_NAME !== `${name}/`, + `(a)'s name ${UNRELATED_NAME} is read as neither the canonical ` + + `candidate ${name}, unscoped, nor a leading part of it`, + ); + } + need( + aSetups === COVERED_SETUP_COUNT, + `(a)'s stagings judge ${String(COVERED_SETUP_COUNT)} setups in all, not ` + + String(aSetups), + ); + const expected: readonly [string, string][] = [ + ["(a) 1", "es-module, own module, above 1, above-type undefined"], + ["(a) 2", "commonjs, own undefined, above 1, above-type undefined"], + ["(a) 3", "commonjs, no own, above 1, above-type undefined"], + ["(b) 1", "es-module, own module, above 1, above-type commonjs"], + ["(b) 2", "commonjs, own undefined, above 1, above-type module"], + ["(c)", "commonjs, own commonjs, above 0, above-type undefined"], + ]; + need( + letters.size === 3 && + letters.get("(a)") === 3 && + letters.get("(b)") === 2 && + letters.get("(c)") === 1 && + shapes.size === expected.length && + expected.every(([arm, shape]) => shapes.get(arm) === shape), + "the stagings are (a) an ES-module project, a CommonJS one with its own " + + "manifest, and one with none, each beneath the ancestor manifest; (b) " + + "an ES-module project beneath a commonjs ancestor and a CommonJS one " + + "beneath a module ancestor; and (c) a nearest manifest typed " + + `commonjs, not ${JSON.stringify([...shapes])}`, + ); + if (problems.length > 0) { + throw new Error( + `T7.6-5: its stagings deviate from TEST-SPEC T7.6-5's list: ` + + `${problems.join("; ")}: a harness defect`, + ); + } +} + +checkT765Stagings(); + +// --------------------------------------------------------------------------- +// T7.6-4: its files, and their S-9 records (module header) +// --------------------------------------------------------------------------- + +/** One of T7.6-4's files beside one N: plain TypeScript, and TSX. */ +interface T764Record { + readonly label: string; + readonly ts: StagedTs; + readonly tsx: StagedTs; +} + +/** The three files beside one fixed N, as records. */ +interface T764Records { + readonly declaredExports: T764Record; + readonly valid: T764Record; + readonly unknownKey: T764Record; +} + +/** Every N fixed at module load: the canonical candidates and the fixed names. */ +const T764_FIXED_NAMES: readonly string[] = [ + ...new Set([ + ...CANONICAL_MODULE_NAMES, + ...T764_PLACEMENTS.flatMap((placement) => + placement.name.kind === "fixed" ? [placement.name.name] : [], + ), + ]), +]; + +/** + * T7.6-4's files beside each fixed N (module header), each a staged-source + * record (S-9) as plain TypeScript and, for the `.tsx` name, as TSX of the + * same bytes — composed by section-7.6.ts's `placementFiles`, so each is + * the canonical run's own file but for its specifier. Those beside the + * canonical candidates are T7.6-5's files too, and named for both tests. + */ +const T764_RECORDS: ReadonlyMap<string, T764Records> = new Map( + T764_FIXED_NAMES.map((name): [string, T764Records] => { + const files = placementFiles(name); + const tests = CANONICAL_MODULE_NAMES.includes(name) + ? `${T764.id}/${T765.id}` + : T764.id; + const record = (file: PlacementFile): T764Record => { + const named = `${tests} ${file.label}, importing ${JSON.stringify(name)}`; + return { + label: file.label, + ts: stagedTs(named, file.text), + tsx: stagedTs(`${named}, as TSX`, file.text, "well-formed", "tsx"), + }; + }; + return [ + name, + { + declaredExports: record(files.declaredExports), + valid: record(files.valid), + unknownKey: record(files.unknownKey), + }, + ]; + }), +); + +/** The files beside a fixed N: its records' bytes. */ +function recordedFiles(name: string): PlacementFiles { + const records = T764_RECORDS.get(name); + const file = (record: T764Record | undefined): PlacementFile => { + if (record === undefined || typeof record.ts.source !== "string") { + throw new Error( + `T7.6-4: no record holds its files beside the fixed N ` + + `${JSON.stringify(name)}: a harness defect`, + ); + } + return { label: record.label, text: record.ts.source }; + }; + return { + declaredExports: file(records?.declaredExports), + valid: file(records?.valid), + unknownKey: file(records?.unknownKey), + }; +} + +/** + * The files beside (a)'s N, the name the package's manifest gives, known + * only once the package directory is read (module header): composed by + * `placementFiles`, the composition the fixed names' records hold, then + * judged by S-9's TypeScript check before anything is staged — accepted + * both as module code and as script code under the grammar each covered + * name selects (plain TypeScript, and TSX for `.tsx`) — a failure a harness + * error, as a draw's is. + */ +function composedFiles(name: string, context: string): PlacementFiles { + const files = placementFiles(name); + for (const file of [files.declaredExports, files.valid, files.unknownKey]) { + for (const judged of ["covered-file.ts", "covered-file.tsx"]) { + const problem = tsDeclarationProblem( + judgeTypeScript(file.text, judged), + "well-formed", + ); + if (problem !== undefined) { + throw new HarnessStagingError( + "ts-derivability", + judged, + `${context}: ${file.label}, importing ${JSON.stringify(name)}, ` + + `judged as ${judged.endsWith(".tsx") ? "TSX" : "plain TypeScript"}, ` + + `is ${problem} (TEST-SPEC S-9: a generated configuration file is ` + + "judged well-formed before the product is driven on it)", + ); + } + } + } + return files; +} + +// --------------------------------------------------------------------------- +// T7.6-4 and T7.6-5: staging a placement (module header) +// --------------------------------------------------------------------------- + +/** + * An unrelated package's files (module header): a manifest naming it, a + * CommonJS entry exporting one value, and its declarations — a package no + * covered file or importing module names, which neither TypeScript nor + * Node.js reads unless a resolution strays into it. + */ +function unrelatedPackageFiles(name: string): readonly [string, string][] { + const manifest = { + name, + version: "1.0.0", + main: "index.js", + types: "index.d.ts", + }; + return [ + ["package.json", `${JSON.stringify(manifest, null, 2)}${LF}`], + [ + "index.js", + `"use strict";${LF}${LF}exports.unrelated = ${JSON.stringify(name)};${LF}`, + ], + [ + "index.d.ts", + `export declare const unrelated: ${JSON.stringify(name)};${LF}`, + ], + ]; +} + +/** TypeScript 5.9.3's package directory, once read (module header). */ +let typeScriptPackage: Promise<string> | undefined; + +/** + * TypeScript 5.9.3's package directory, by its physical path: the harness's + * own `typescript-5.9.3`, the release the TypeScript driver runs — the + * parent of its library directory — its manifest read strictly and found to + * give the name `typescript` and the version 5.9.3, else a harness defect. + */ +function typeScriptPackageDirectory(): Promise<string> { + typeScriptPackage ??= guardStep( + "reading TypeScript 5.9.3's package directory (T7.6-4(e))", + async () => { + const directory = await fsp.realpath( + path.dirname(path.dirname(ts.getDefaultLibFilePath({}))), + ); + const reading = await readManifestStrictly( + path.join(directory, "package.json"), + ); + if ( + ts.version !== "5.9.3" || + reading === undefined || + !reading.wellFormed || + reading.members["name"] !== "typescript" || + reading.members["version"] !== "5.9.3" + ) { + throw new Error( + `T7.6-4: ${directory} is not TypeScript 5.9.3's package, whose ` + + "manifest gives the name typescript and the version 5.9.3 " + + `(TypeScript ${ts.version} loaded): a harness defect`, + ); + } + return directory; + }, + ); + return typeScriptPackage; +} + +/** Install `other` at `node_modules/<its name>` in `directory`. */ +async function installOther( + staging: ModuleStaging, + directory: string, + other: OtherPackage, +): Promise<void> { + if (other.kind === "typescript") { + await staging.copyDirectory( + `${directory}/node_modules/typescript`, + await typeScriptPackageDirectory(), + ); + return; + } + for (const [file, text] of unrelatedPackageFiles(other.name)) { + await staging.writeFile( + `${directory}/node_modules/${other.name}/${file}`, + text, + ); + } +} + +/** A placement staged: the placement made, and the importing files' place. */ +interface StagedPlacement { + readonly placement: Placement; + /** The importing files' directory, staging-relative, along its physical path. */ + readonly importingDir: string; +} + +/** A manifest's bytes: its members as JSON, two-space indented. */ +function manifestText(members: Readonly<Record<string, string>>): string { + return `${JSON.stringify(members, null, 2)}${LF}`; +} + +/** + * Read back a T7.6-5 staging's manifests before any tool runs (module + * header): from the importing directory `importingDir` up to the staging + * root, each directory's package.json, read strictly, is exactly the + * manifest `manifests` declares there — well-formed, holding exactly its + * members — or absent where they declare none, so that a staging stands + * for no other. A deviation is a `HarnessStagingError`. + */ +async function confirmManifests( + staging: ModuleStaging, + importingDir: string, + manifests: readonly StagedManifest[], + context: string, +): Promise<void> { + const chain = [...chainBelowRoot(importingDir), ""]; + await guardStep( + `reading back the manifests from ${staging.path(importingDir)} up to ` + + `the staging root (${context})`, + async () => { + for (const dir of chain) { + const file = path.join(staging.path(dir), "package.json"); + const declared = manifests.find((manifest) => manifest.dir === dir); + const reading = await readManifestStrictly(file); + const found = + reading === undefined + ? "no manifest" + : reading.wellFormed + ? `a manifest holding ${JSON.stringify(reading.members)}` + : `a manifest that ${reading.problem}`; + const wanted = + declared === undefined + ? "no manifest" + : `a manifest holding ${JSON.stringify(declared.members)}`; + if (found !== wanted) { + throw new HarnessStagingError( + "module-channel", + file, + `${context}: ${file} is ${found}, where the staging declares ` + + `${wanted}: each staging of T7.6-5 holds exactly the manifests ` + + "it declares, from the importing files' directory up to the " + + "staging root, so that it stages what TEST-SPEC T7.6-5 names", + ); + } + } + }, + ); +} + +/** + * Stage `spec` under `name` for `arm` (module header): `project` in the + * layout's importing directory — a project kind as `stageProject` stages + * it, or exactly the manifests `project` declares, read back once the + * staging is done — the placement in its holding directory, the layout's + * symbolic link, and the other packages. + */ +async function stagePlacement( + staging: ModuleStaging, + spec: PlacementSpec, + name: string, + project: ProjectStaging, + arm: ModuleArm, + context: string, +): Promise<StagedPlacement> { + const layout = PLACEMENT_LAYOUTS[spec.layout]; + if (project.manifests === undefined) { + await staging.stageProject(layout.importingDir, project.project); + } else { + await staging.makeDirectory(layout.importingDir); + for (const manifest of project.manifests) { + await staging.writeFile( + `${manifest.dir}/package.json`, + manifestText(manifest.members), + ); + } + } + const placement = await staging.place({ + name, + holdingDir: layout.holdingDir, + arm, + form: spec.form, + }); + if (layout.link !== undefined) { + await staging.link(layout.link.at, layout.link.to); + } + for (const other of spec.beside) { + await installOther(staging, layout.holdingDir, other); + } + for (const other of spec.inImportingDir) { + await installOther(staging, layout.importingDir, other); + } + if (project.manifests !== undefined) { + await confirmManifests( + staging, + layout.importingDir, + project.manifests, + context, + ); + } + return { placement, importingDir: layout.importingDir }; +} + +// --------------------------------------------------------------------------- +// T7.6-4 and T7.6-5: the body (module header) +// --------------------------------------------------------------------------- + +/** A placement as the body runs it: its N and its files. */ +interface ResolvedPlacement { + readonly spec: PlacementSpec; + readonly name: string; + readonly files: PlacementFiles; + /** Leads its diagnoses. */ + readonly context: string; +} + +/** + * `spec` as `test`'s body runs it beside `pkg` (module header), or undefined + * for T7.6-4(a) where the manifest gives no name of 7.6's grammar outside + * the exclusions every arm has — TEST-SPEC stages (a) only where it does. + */ +function resolvePlacement( + test: StandInTest, + spec: PlacementSpec, + pkg: PackageDirectory, +): ResolvedPlacement | undefined { + const describe = (name: string): string => + `${test.context}, ${test.unit} ${spec.arm} (${spec.what}), N ` + + JSON.stringify(name); + switch (spec.name.kind) { + case "canonical": { + const name = canonicalModuleName(pkg.manifestName.name); + return { + spec, + name, + files: recordedFiles(name), + context: describe(name), + }; + } + case "fixed": + return { + spec, + name: spec.name.name, + files: recordedFiles(spec.name.name), + context: describe(spec.name.name), + }; + case "manifest": { + const name = pkg.manifestName.name; + if ( + name === undefined || + moduleNameGrammarProblem(name) !== null || + moduleNameExclusion(name) !== null + ) { + return undefined; + } + const context = describe(name); + return { spec, name, files: composedFiles(name, context), context }; + } + } +} + +/** + * The releases `resolved`'s runtime half runs on (module header): every + * release for a fixed or the canonical N — the placement itself confirming + * that none resolves it to a built-in module — and, for T7.6-4(a)'s, the + * manifest's name, each release that resolves it to none, each release + * asked. + */ +async function runtimeReleases( + resolved: ResolvedPlacement, + releases: readonly NodeRelease[], +): Promise<readonly NodeRelease[]> { + if (!resolved.spec.runtime) return []; + if (resolved.spec.name.kind !== "manifest") return releases; + const admitted: NodeRelease[] = []; + for (const release of releases) { + const builtIn = await builtInNamesOn( + release, + [resolved.name], + resolved.context, + ); + if (!builtIn.has(resolved.name)) admitted.push(release); + } + return admitted; +} + +/** Where a placement stands in `test`'s body, for a diagnosis (module header). */ +function standing(test: StandInTest, held: readonly string[]): string { + return held.length === 0 + ? `the first ${test.unit} the body runs` + : `run after ${count(held.length, test.unit)} that ` + + `${held.length === 1 ? "fared" : "each fared"} as the canonical ` + + `placement does — ${held.join("; ")}`; +} + +/** Each failing assertion's diagnosis, in order: none where all hold. */ +function placementFailures(checks: readonly (() => void)[]): readonly string[] { + const failures: string[] = []; + for (const check of checks) { + try { + check(); + } catch (error) { + if (!(error instanceof HarnessAssertionError)) throw error; + failures.push(error.message); + } + } + return failures; +} + +/** + * A placement's type-checking half (module header): in a staging of each + * of its projects, T7.6-1's covered file, T7.6-2(a)'s file, and T7.6-3's + * unknown-top-level-key arm judged in one program per covered setup of + * the project's kind, the first holding T7.6-1's listing, the second + * type-checking, and the arm failing to type-check paired with it; the + * first setup where any fails ends `test`'s body, diagnosed. + */ +async function runPlacementTypeChecking( + product: ProductBinding, + test: StandInTest, + resolved: ResolvedPlacement, + held: readonly string[], +): Promise<void> { + const { spec, name, files } = resolved; + let judged = 0; + for (const project of spec.projects) { + const context = `${resolved.context}, ${describeProject(project, true)}`; + const staging = await ModuleStaging.create(product, context); + try { + const { placement, importingDir } = await stagePlacement( + staging, + spec, + name, + project, + TYPE_CHECKING_ARM, + context, + ); + const covered = await stageCoveredFiles({ + staging, + directory: importingDir, + project: project.project, + ...(project.nearestType === undefined + ? {} + : { nearestType: project.nearestType }), + placement, + alone: spec.alone, + files: [files.declaredExports, files.valid, files.unknownKey], + listExports: true, + context, + }); + for (const setup of covered.setups) { + const [listed, valid, arm] = covered.judge(setup); + if (listed === undefined || valid === undefined || arm === undefined) { + throw new Error("unreachable: three verdicts"); + } + const failures = placementFailures([ + () => assertDeclaredExports(listed, "T7.6-1's run"), + () => assertTypeChecks(valid, "T7.6-2(a)'s run"), + () => { + if (!valid.typeChecks) { + fail( + "T7.6-3's run: its unknown-top-level-key arm counts nowhere " + + "here, its valid twin, T7.6-2(a)'s file, not type-checking " + + "(TEST-SPEC §7.6 Pairing)", + ); + } + assertShapeViolation(valid, arm, "T7.6-3's run"); + }, + ]); + if (failures.length > 0) { + fail( + `${context}: in ${setup.label}, beside the placement ` + + `${placement.path}, ${String(failures.length)} of the 3 runs ` + + `the ${test.unit} stands in for the canonical placement in ` + + `${failures.length === 1 ? "fails" : "fail"} — the first ` + + "covered setup where any does, after " + + `${count(judged, "setup")} of this ${test.unit} where all 3 ` + + `held; the ${test.unit} is ${standing(test, held)}; the body ` + + `stops here ${test.rule}. ${failures.join(" | ")}`, + ); + } + judged += 1; + } + } finally { + await staging.dispose(); + } + } + if (judged !== setupCount(spec)) { + throw new Error( + `${test.id}: ${String(judged)} covered setups judged beside the ` + + `${test.unit} ${spec.arm}, not the ${String(setupCount(spec))} of ` + + "its projects' kinds; no setup is sampled away: a harness defect", + ); + } +} + +/** + * A placement's runtime half (module header): its runtime project in the + * layout's importing directory beside the placement, and one run per + * release of `releases` and route, each read for T7.6-6's exports and + * identity; the first run not loading ends `test`'s body, diagnosed, as + * the problems the runs found do once all have run. `every` is how many + * releases E-1 lists. + */ +async function runPlacementRuntime( + product: ProductBinding, + test: StandInTest, + resolved: ResolvedPlacement, + releases: readonly NodeRelease[], + held: readonly string[], + every: number, +): Promise<void> { + const { spec, name } = resolved; + const project = spec.runtimeProject; + const runtime: RuntimeTest = { + id: test.id, + context: `${resolved.context}, its runtime runs`, + rule: + `— the ${test.unit}, its type-checking runs having held in all ` + + `${String(setupCount(spec))} covered setups of its ` + + `${spec.projects.length === 1 ? "project" : "projects"}, is ` + + `${standing(test, held)} ${test.rule}`, + clauses: "T7.6-6's (a) and (b)", + effects: false, + read: (run) => + Promise.resolve([...exportsProblems(run), ...identityProblems(run)]), + }; + const staging = await ModuleStaging.create(product, runtime.context); + const found: FoundProblems = { problems: new Map(), runs: [] }; + let made = 0; + let summary = ""; + try { + const { placement, importingDir } = await stagePlacement( + staging, + spec, + name, + project, + runtimeArm(releases), + runtime.context, + ); + const versions = releases.map((release) => release.version).join(", "); + summary = + (releases.length === every + ? `every release E-1 lists (${versions})` + : `each release E-1 lists that resolves N to no built-in module ` + + `(${versions})`) + + ` along each of Node.js's ${String(MODULE_ROUTES.length)} routes, ` + + `each run loading ${name}, placed at ${placement.path}` + + (placement.form === "symlink" + ? `, a symbolic link to its copy at ${placement.copy},` + : "") + + ` from its route's importing module in ${staging.path(importingDir)}` + + (project.manifests === undefined + ? "" + : `, ${describeProject(project, false)}`); + made = await runRoutes( + runtime, + { + staging, + placement, + importingDir, + project: project.project, + ...(project.nearestType === undefined + ? {} + : { nearestType: project.nearestType }), + alone: spec.alone, + }, + releases, + found, + ); + } finally { + await staging.dispose(); + } + failOnProblems(runtime, found, made, summary); +} + +/** + * `test`'s body over `specs` (module header): the package directory checked + * first, every release E-1 lists resolved, then each placement in order, + * its type-checking half, then its runtime half. + */ +async function runPlacements( + product: ProductBinding, + test: StandInTest, + specs: readonly PlacementSpec[], +): Promise<void> { + const pkg = await modulePackageDirectory(product, test.context); + const releases = await resolveNodeReleases(); + const held: string[] = []; + for (const spec of specs) { + const resolved = resolvePlacement(test, spec, pkg); + if (resolved === undefined) continue; + await runPlacementTypeChecking(product, test, resolved, held); + const runtime = await runtimeReleases(resolved, releases); + if (runtime.length > 0) { + await runPlacementRuntime( + product, + test, + resolved, + runtime, + held, + releases.length, + ); + } + held.push(`${spec.arm} (N ${JSON.stringify(resolved.name)})`); + } +} + +const T7_6_4 = defineProductTest({ + id: "T7.6-4", + title: + "each placement stands in for the canonical one, and fares as it does, " + + "in a run of T7.6-1 (T7.6-2(d)'s file, the module TypeScript resolves " + + "its import to declaring exactly defineConfig) and of T7.6-2(a)'s file " + + "type-checking with T7.6-3's unknown-top-level-key arm failing to " + + "type-check paired to it, in all 173 covered setups, and in T7.6-6's " + + "runs, the module loading on every release E-1 provisions along each of " + + "Node.js's four routes with its exports exactly defineConfig and " + + "defineConfig returning its argument (T7.6-6 (a), (b)): (a) a copy " + + "under the name the package's manifest gives, the non-aliased install, " + + "where that is a name of 7.6's grammar outside its exclusions; (b) " + + "node_modules/N a symbolic link to a copy elsewhere in the staging, " + + "under no node_modules; (c) a scoped name, a name beginning with a " + + "digit, a name holding - and _, the dotted names a.js and a.b (each " + + "beside an unrelated package at node_modules/a, no a.ts beside a.js), " + + "and an unscoped and a scoped name each 214 characters long; (d) the " + + "holding directory a strict ancestor of the importing file's directory, " + + "and an ancestor of its physical path alone, the directory also " + + "reachable through a symbolic link, each tool given the physical path; " + + "(e) TypeScript 5.9.3's package at node_modules/typescript and an " + + "unrelated package beside the placement, and, the holding directory a " + + "strict ancestor, an unrelated package in the importing file's own " + + "directory; (f) in the type-checking runs alone, N fs, and N path (SPEC " + + "7.6 Package and installation, Reach)", + run: (product) => runPlacements(product, T764, T764_PLACEMENTS), +}); + +const T7_6_5 = defineProductTest({ + id: "T7.6-5", + title: + "stagings meeting every condition of Reach while leaving open what none " + + "of them bars, each run as T7.6-4's placements are — the canonical " + + "placement, a copy at node_modules/N in the importing files' own " + + "directory, standing in a run of T7.6-1 (T7.6-2(d)'s file, the module " + + "TypeScript resolves its import to declaring exactly defineConfig) and " + + "of T7.6-2(a)'s file type-checking with T7.6-3's unknown-top-level-key " + + "arm failing to type-check paired to it, in every covered setup of the " + + "staging's project kind, and in T7.6-6's runs from the staging's " + + "project, the module loading on every release E-1 provisions along " + + "each of Node.js's four routes with its exports exactly defineConfig " + + "and defineConfig returning its argument (T7.6-6 (a), (b)): (a) an " + + 'ancestor package.json whose name, "unrelated", TypeScript and Node.js ' + + "read as neither N nor a leading part of it, above an ES-module " + + "project, a CommonJS project with its own package.json, and a CommonJS " + + "project whose own directory holds none, that ancestor then its nearest " + + "(173 setups in all); (b) an ES-module project beneath an ancestor " + + 'package.json holding "type": "commonjs", and a CommonJS project, its ' + + "nearest package.json without type, beneath an ancestor holding " + + '"type": "module"; (c) a nearest package.json holding "type": ' + + '"commonjs", judged in the CommonJS ' + + `project's covered setups (SPEC 7.6 ` + + "Reach, Covered setups)", + run: (product) => runPlacements(product, T765, T765_STAGINGS), +}); + +export const section76iiTests: readonly ProductTestEntry[] = [ + T7_6_4, + T7_6_5, + T7_6_6, + T7_6_7, +]; diff --git a/test/suite/registry/section-7.6.ts b/test/suite/registry/section-7.6.ts new file mode 100644 index 00000000..3e329c93 --- /dev/null +++ b/test/suite/registry/section-7.6.ts @@ -0,0 +1,3583 @@ +// TEST-SPEC §7.6 (the `defineConfig` module): T7.6-1, declared exports; +// T7.6-2, valid configurations; and T7.6-3, shape violations. T7.6-4, the +// placements, T7.6-5, Reach's open cases, and T7.6-6 and T7.6-7, the +// runtime's exports and identity and its absence of effects, are +// section-7.6-ii.ts's — T7.6-4 and T7.6-5 staging the files +// `placementFiles` composes here, the canonical runs' own beside any N; +// P-17, installation names, is section-16-p17.ts's, its draws staging those +// files beside each drawn N; and P-18, the type contract over generated +// configurations, is section-16-p18.ts's, its draws read and mutated +// through this module's readings of 7 and of the type-error class +// (`problemsUnder7`, `shapeNodes`, `classViolations`), T7.6-3's kind +// table, and the covered-file read-back (`readBack`, `scanComments`), +// which it exports for that. +// +// 7.6 is tested through H-2's module channel alone (TEST-SPEC §7.6's four +// rules: Placement, Covered setups, Verdict, Pairing). A body here never +// invokes the `xspec` executable: it places the product's package directory, +// the binding's `packageDir`, in a fresh staging under the canonical +// placement (helpers/module-channel.ts) and type-checks covered files there +// with the harness's TypeScript 5.9.3 in every covered setup +// (helpers/module-channel-ts.ts). With no package directory given, the body +// fails diagnosed before anything is staged (H-8: the module channel counts +// as part of the product). +// +// T7.6-1 (SPEC 7.6 Type contract: exports): in every covered setup, the +// module TypeScript resolves the covered file's import to declares exactly +// one export, `defineConfig`, carrying a value meaning and neither a type +// nor a namespace meaning, and no other export, type-only or not. The +// exports are read from the TypeScript driver's export listing +// (helpers/module-channel-ts.ts, `listExports`): TypeScript's own +// resolution of the file's import in that setup's program — the compiler's +// listing of the module's exports, an implicit export of a declaration +// module holding neither `export {}` nor `export =` among them, and, where +// the module declares an export assignment, the members of the assigned +// value that a named import binds — each with its meanings, never probed +// by names the harness chooses. TypeScript's synthetic default is never in +// that listing, so a default import TypeScript admits only through its +// interoperation with CommonJS fails nothing; a declared default export +// (`default`) is listed, and fails. +// +// Conservative operationalizations (noted per H-4): +// - The covered file is T7.6-2(d)'s, the minimal configuration: any +// covered file's import reads the same module in a setup, and (d)'s +// records are named for both tests. T7.6-1 asserts the listing alone; +// whether the file type-checks is T7.6-2's assertion. +// - One staging per project kind, the file written under each covered +// extension beside the canonical placement, nothing else installed, and +// judged in each covered setup of its project, a program of its own each, +// with its listing: each setup is read through its own resolution, so a +// package serving different declaration files to `import` and to +// `require`, or to different resolution modes, is read through each. +// - A listing naming no module — TypeScript resolving the import to no +// module it reads declarations from, as beside S-7's stub package — +// fails as a module declaring no `defineConfig`. A value meaning reached +// only through `export type`, `import type`, or `export type *`, which no +// import may use as a value, is no value meaning. +// - The body stops at the first setup whose listing deviates, failing +// once, diagnosed, with every deviation, the listing whole, and +// TypeScript's errors for the program as a diagnostic aid +// (`assertDeclaredExports`, which T7.6-4's placements and P-17's draws +// reuse); where every setup holds, it confirms that it judged all +// 173. +// +// T7.6-2 (SPEC 7.6 Covered files, Type contract: valid configurations): each +// of these covered files, valid under 7, type-checks in every covered setup +// — 173 programs per file — under the canonical placement: +// - (a) every key and field 7 defines, every value 7 enumerates at each of +// its positions: `specs` and `code` with two groups each (`tests` a spec +// and a code group's name, so a kind is required with it); `markdown` with +// `emit` true and `outDir`; two profiles carrying all eight profile fields, +// between them both `targets`, both `boundaryKind`s, and both `mode`s; +// three rules, of both `type`s, each carrying `kinds`, their selectors in +// all three forms, the group form without `kind` and with each kind; each +// dependency edge kind in each profile's `edgeKinds` and rule's `kinds`; +// - (b) (a) with `defineConfig` imported under an alias and every key a +// string literal; +// - (c) (a) with a line and a block comment before the import, between keys, +// inside lists, and after the export; +// - (d) the minimal configuration, `specs` holding no group; +// - (e) the seven members of TypeScript's global `Object` interface and +// `__proto__`, each a spec and a code group's name — identifier keys in +// one file, string-literal keys in another — each a profile's `target` and +// another's `boundary` (with its `boundaryKind`, each name being both +// kinds'), each a rule's `from` group and another's `to` group (with its +// kind), and each the name of a profile and of a rule; +// - (f) the empty, omitted, and repeated forms: `code: {}`, `coverage: []`, +// `policy: []`, and `markdown: { emit: false }` beside a `specs` group; a +// file like (a)'s with every optional field omitted, its group names +// unambiguous; and (a) with one spec group's and one code group's glob +// list empty and an element repeated in every set-read list (each +// `targetTags`, `edgeKinds`, rule's `kinds`, and selector's `tags`). +// The group, profile, and rule names of (e) are never requirement paths, so +// the accepted residual on `Object`-member path segments is not reached. +// +// Conservative operationalizations (noted per H-4): +// - Each configuration is data — a map per object literal, never a harness +// object literal, since a `__proto__` key would set a JavaScript literal's +// prototype — rendered by one renderer in 7's declarative form, the style +// of SPEC 7's example (double quotes, no semicolons, no trailing commas), +// every object on lines of its own. Before any product exists, module-load +// self-checks hold each file to what TEST-SPEC names: valid under 7 (the +// harness's own reading of 7, 7.3, 7.4, and 7.5 over the data: keys, +// kinds, enumerations, cross-references, required kinds, non-empty +// set-read lists, names, and globs inside the root); each arm's own +// content, as listed above; and 7.6's covered-file conditions, read back +// from the rendered text with the harness's TypeScript — exactly an import +// of `defineConfig` by that identifier, with no `type` or `defer` modifier +// and no attributes, bound to `defineConfig` or (b)'s alias, never +// `require`, `exports`, or a reserved word; a specifier spelling exactly N +// in double quotes; a default export of one call to that binding whose one +// argument reads back equal to the data; no backslash anywhere in the +// file; and no comment carrying `@` or beginning `///`, so that none is a +// directive or pragma. A deviation is a harness defect, thrown at module +// load. +// - N is the canonical name (helpers/module-channel.ts +// `canonicalModuleName`): one of two fixed candidates, whichever differs +// from the name the package's manifest gives. Each file is rendered for +// each candidate at module load. +// - S-9: every rendered file is a staged-source record (helpers/staged-ts.ts +// `stagedTs`) — one per file and candidate N, judged as plain TypeScript, +// for the `.ts`, `.mts`, and `.cts` names, beside a TSX record of the same +// bytes for the `.tsx` name — which test/self/s9-staged-sources.test.ts +// judges well-formed before any product exists. The body stages exactly +// the bytes of the records for the placement's N. +// - One staging per project kind — the ES-module project, the CommonJS one +// with a `package.json`, and the one with none — each the project +// directory beside its canonical placement, nothing else installed (Reach +// verified for each written file, `alone`). Every file is written under +// each covered extension and judged in each covered setup of its project, +// all the files of a setup in one program where that batch is sound +// (the driver's header argues the sharing). +// - The body stops at the first setup where any file fails to type-check, +// failing once, diagnosed, with every failing file of that setup and +// TypeScript's errors for each: against a package that resolves nothing — +// S-7's stub package — the body ends at its first setup, keeping the +// sweep short. A harness error propagates at once. Where every setup +// passes, the body confirms that it judged all 173. +// +// T7.6-3 (SPEC 7.6 Type contract: shape violations; TEST-SPEC §7.6 +// Pairing): in every covered setup, each of these files — T7.6-2(a)'s file +// with violations of 7.6's type-error class applied, that file its valid +// twin — fails to type-check, paired with the twin type-checking in the +// same setup and placement. The arms are edits of (a)'s data, at every +// position of (a)'s file, each a file of its own holding one violation: +// - an unknown key (`extra`) appended to each fixed-key object: the top +// level, `markdown`, each profile, each rule, and each selector; +// - each required key removed from each object requiring it: `specs`, +// `markdown`'s `emit`, each profile's `name`, `target`, `boundary`, and +// `mode`, and each rule's `name`, `type`, `from`, and `to`; +// - at every value of (a)'s file, each kind among a boolean, a string, a +// list, and an object that 7 does not admit there, from the kind table +// (`T763_KIND_TABLE`: one row per position as T7.6-3 lists it, its values +// spelled out, TEST-SPEC's `specs: ["a/*.mdx"]`, `emit: "true"`, +// `targetTags: "a"`, and `from: "src/*.ts"` among them, the boolean both +// `true` and `false` where 7 admits a list or an object), and TEST-SPEC's +// `kinds: [true]` beside them; +// - at every enumerated value, two near misses of it — capitalized, and cut +// by its last letter, so `"Direct"` and `"depend"` among them — and, at +// each element of an `edgeKinds` and of a rule's `kinds`, `"contains"`; +// - at each selector, each selector-form violation — each two of `group`, +// `files`, and `tags`, all three, none (`{}`), and `kind` beside `files`, +// beside `tags`, and alone — the selector replaced whole, its names +// resolving; +// - each list 7.4 and 7.5 forbid empty, emptied; +// - and one file holding seven of these at once, a violation of each member +// of the class among them. +// No arm stages a configuration error outside the class for a verdict: each +// arm is (a) with its edits alone, and the errors outside the class an edit +// entails (the profiles' `target` naming no spec group once `specs` is gone) +// carry no type-level requirement either way (SPEC 7.6). +// +// Conservative operationalizations (noted per H-4): +// - "Every position" is read over (a)'s file: every value it holds — each +// group, glob, profile, rule, selector, field, and list element — rather +// than one value per kind of position; the categories TEST-SPEC names in +// the singular (an unknown key "in a profile", a profile's missing `name`, +// "a selector's `kind`") are staged at each instance alike. 430 arms. +// - Module-load self-checks (`checkT763Arms`) hold the tables to T7.6-3's +// list — 7's shape (`CONFIG_SHAPE`) names exactly its positions, each +// instantiated in (a)'s file; each row of the kind table holds one value +// of each kind 7 does not admit there; the enumerated positions, the +// required keys, the fixed-key objects, the forbidden empty lists, and +// the eight selector-form violations are those it lists; TEST-SPEC's own +// spellings are staged — and each arm to its edits: the harness's own +// reading of the type-error class over the data (`classViolations`) finds +// in each arm exactly the violations its edits make, and none in the +// twin. Each rendering reads back with the harness's TypeScript as its +// data, with no backslash and no comment, its keys identifiers as the +// twin's are, so no arm carries beside its violation an error every +// `defineConfig` type meets (a repeated key, a syntax error): the +// composition residual CERTIFICATIONS.md's exclusions name. +// - S-9: each arm's rendering is a staged-source record per candidate N, +// as plain TypeScript and as TSX, as T7.6-2's are; the twin's records are +// T7.6-2(a)'s, named for both tests. +// - The body stages, per project kind, the twin alone beside the canonical +// placement, and judges it first in each setup: where it does not +// type-check, no arm counts there (Pairing), and the body fails at once, +// diagnosed — in the project's first setup before the arms are staged, +// so S-7's stub package costs the sweep one program. Once the twin has +// type-checked, the arms are staged in the same directory and judged in +// one program per setup where that batch is sound (the driver's header), +// each paired with the twin through `assertShapeViolation`. The body +// stops at the first setup where any arm does not fail to type-check, +// failing once, naming every such arm and spelling out the first three; +// where every setup holds, it confirms that it judged all 173. + +import ts from "typescript-5.9.3"; +import { fail, HarnessAssertionError } from "../../helpers/assertions.js"; +import { + CANONICAL_MODULE_NAMES, + moduleNameGrammarProblem, + ModuleStaging, + PROJECT_KINDS, + TYPE_CHECKING_ARM, +} from "../../helpers/module-channel.js"; +import { + assertShapeViolation, + assertTypeChecks, + COVERED_SETUP_COUNT, + describeErrors, + describeExportListing, + describeListedExport, + stageCoveredFiles, +} from "../../helpers/module-channel-ts.js"; +import type { + CoveredFiles, + CoveredVerdict, + ExportListing, +} from "../../helpers/module-channel-ts.js"; +import { defineProductTest } from "../../helpers/registry.js"; +import type { ProductTestEntry } from "../../helpers/registry.js"; +import { stagedTs } from "../../helpers/staged-ts.js"; +import type { StagedTs } from "../../helpers/staged-ts.js"; +import type { ProductBinding } from "../../helpers/subprocess.js"; + +const LF = String.fromCodePoint(0x0a); +const BACKSLASH = String.fromCodePoint(0x5c); +const REPLACEMENT_CHARACTER = String.fromCodePoint(0xfffd); + +// --------------------------------------------------------------------------- +// Configurations as data, and their rendering +// --------------------------------------------------------------------------- + +/** A value of 7's declarative form: a string, a boolean, a list, an object. */ +export type ConfigValue = string | boolean | ConfigList | ConfigObject; + +/** An array literal of 7's declarative form. */ +export type ConfigList = readonly ConfigValue[]; + +/** + * An object literal of 7's declarative form, its keys in spelling order: a + * map, never a harness object literal, whose `__proto__` key would set the + * literal's prototype (module header). + */ +export type ConfigObject = ReadonlyMap<string, ConfigValue>; + +/** Whether `value` is a list. */ +export function isConfigList(value: ConfigValue): value is ConfigList { + return Array.isArray(value); +} + +/** Whether `value` is an object. */ +export function isConfigObject(value: ConfigValue): value is ConfigObject { + return value instanceof Map; +} + +/** An object from its entries, in order; a repeated key is a harness defect. */ +export function configObject( + ...entries: readonly (readonly [string, ConfigValue])[] +): ConfigObject { + const object = new Map<string, ConfigValue>(); + for (const [key, value] of entries) { + if (object.has(key)) { + throw new Error( + `TEST-SPEC §7.6: the key ${JSON.stringify(key)} is repeated in one ` + + "object of a staged configuration (SPEC 7: a key repeated within " + + "one object literal is a configuration error, outside 7.6's " + + "type-error class): a harness defect", + ); + } + object.set(key, value); + } + return object; +} + +/** How a rendered file spells its keys. */ +export type KeySpelling = + "identifiers" | "string literals" | "group names as string literals"; + +/** How a configuration is rendered as a covered file. */ +export interface ConfigRendering { + /** The import's specifier: N, spelled exactly, in double quotes. */ + readonly specifier: string; + /** The binding `defineConfig` is imported under: itself or an alias. */ + readonly binding: string; + readonly keys: KeySpelling; + /** + * T7.6-2(c)'s comments: a line and a block comment before the import, + * between keys, inside lists, and after the export. + */ + readonly comments: boolean; +} + +/** The comments (c) carries: plain words, no `@`, none beginning `///`. */ +const COMMENTS = { + lineBeforeImport: "// A line comment before the import.", + blockBeforeImport: "/* A block comment before the import. */", + lineBetweenKeys: "// A line comment between keys.", + blockBetweenKeys: "/* A block comment between keys. */", + blockInList: "/* A block comment inside a list. */", + lineInList: "// A line comment inside a list.", + lineAfterExport: "// A line comment after the export.", + blockAfterExport: "/* A block comment after the export. */", +} as const; + +const INDENT = " "; + +/** A key spelled as an identifier: ASCII, never needing an escape. */ +const IDENTIFIER_KEY = /^[A-Za-z_$][A-Za-z0-9_$]*$/; + +/** Whether a key at `path` names a group: a key of `specs` or `code`. */ +function isGroupNameKey(path: readonly string[]): boolean { + return path.length === 1 && (path[0] === "specs" || path[0] === "code"); +} + +/** A key as the rendering spells it at `path`. */ +function spellKey( + key: string, + path: readonly string[], + rendering: ConfigRendering, +): string { + const stringLiteral = + rendering.keys === "string literals" || + (rendering.keys === "group names as string literals" && + isGroupNameKey(path)); + if (stringLiteral) return JSON.stringify(key); + if (!IDENTIFIER_KEY.test(key)) { + throw new Error( + `TEST-SPEC §7.6: the key ${JSON.stringify(key)} cannot be spelled as ` + + "an identifier with ASCII characters alone: a harness defect", + ); + } + return key; +} + +/** A value rendered at `depth`, its object keys at `path`. */ +function renderValue( + value: ConfigValue, + path: readonly string[], + depth: number, + rendering: ConfigRendering, +): string { + if (typeof value === "string") return JSON.stringify(value); + if (typeof value === "boolean") return value ? "true" : "false"; + const inner = INDENT.repeat(depth + 1); + const outer = INDENT.repeat(depth); + if (isConfigList(value)) { + if (value.length === 0) return "[]"; + const scalars = value.every((element) => typeof element !== "object"); + if (scalars && !rendering.comments) { + return `[${value + .map((element) => renderValue(element, path, depth, rendering)) + .join(", ")}]`; + } + const rows = value.map( + (element, index) => + `${inner}${renderValue(element, path, depth + 1, rendering)}` + + (index < value.length - 1 ? "," : ""), + ); + if (rendering.comments) { + rows.unshift(`${inner}${COMMENTS.blockInList}`); + rows.push(`${inner}${COMMENTS.lineInList}`); + } + return `[${LF}${rows.join(LF)}${LF}${outer}]`; + } + if (value.size === 0) return "{}"; + const rows: string[] = []; + let index = 0; + for (const [key, member] of value) { + if (index > 0 && rendering.comments) { + rows.push( + `${inner}${index % 2 === 1 ? COMMENTS.lineBetweenKeys : COMMENTS.blockBetweenKeys}`, + ); + } + rows.push( + `${inner}${spellKey(key, path, rendering)}: ` + + renderValue(member, [...path, key], depth + 1, rendering) + + (index < value.size - 1 ? "," : ""), + ); + index += 1; + } + return `{${LF}${rows.join(LF)}${LF}${outer}}`; +} + +/** + * A configuration rendered as a covered file (module header): the import of + * `defineConfig` from the specifier, then the default export of one call to + * the binding, its one argument the configuration; LF line ends, the last + * line terminated. + */ +export function renderConfiguration( + config: ConfigObject, + rendering: ConfigRendering, +): string { + const lines: string[] = []; + if (rendering.comments) { + lines.push(COMMENTS.lineBeforeImport, COMMENTS.blockBeforeImport); + } + const imported = + rendering.binding === "defineConfig" + ? "defineConfig" + : `defineConfig as ${rendering.binding}`; + lines.push( + `import { ${imported} } from ${JSON.stringify(rendering.specifier)}`, + "", + `export default ${rendering.binding}(${renderValue(config, [], 0, rendering)})`, + ); + if (rendering.comments) { + lines.push(COMMENTS.lineAfterExport, COMMENTS.blockAfterExport); + } + return lines.join(LF) + LF; +} + +// --------------------------------------------------------------------------- +// Reading a rendered file back: the covered-file conditions (SPEC 7.6) +// --------------------------------------------------------------------------- + +/** + * Names no binding of a covered file takes: the reserved words of strict + * module code, `eval` and `arguments`, and the two names TypeScript + * reserves in a file it compiles as CommonJS (SPEC 7.6 Covered files). + */ +export const BARRED_BINDINGS: ReadonlySet<string> = new Set([ + "arguments", + "await", + "break", + "case", + "catch", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "enum", + "eval", + "export", + "exports", + "extends", + "false", + "finally", + "for", + "function", + "if", + "implements", + "import", + "in", + "instanceof", + "interface", + "let", + "new", + "null", + "package", + "private", + "protected", + "public", + "require", + "return", + "static", + "super", + "switch", + "this", + "throw", + "true", + "try", + "typeof", + "var", + "void", + "while", + "with", + "yield", +]); + +/** One key of a read-back file: where it stands and how it is spelled. */ +export interface SpelledKey { + /** The keys of the objects enclosing it, outermost first. */ + readonly path: readonly string[]; + readonly key: string; + readonly stringLiteral: boolean; +} + +/** A covered file read back with the harness's TypeScript. */ +export interface ReadBack { + /** The specifier's value, and its spelling with its quotes. */ + readonly specifier: string; + readonly specifierSpelling: string; + /** The name `defineConfig` is bound to. */ + readonly binding: string; + /** The default export's one argument. */ + readonly argument: ConfigObject; + readonly keys: readonly SpelledKey[]; + /** The parsed file, for the comment positions (c) is held to. */ + readonly source: ts.SourceFile; +} + +/** T7.6-2's premise for each of its files, which a deviation breaks. */ +const T762_PREMISE = + "each of T7.6-2's files is valid under 7 and a covered file (TEST-SPEC " + + "T7.6-2; SPEC 7, 7.6 Covered files)"; + +/** A thrower naming the test, the file, and the premise a deviation breaks. */ +function deviation( + test: string, + what: string, + premise: string, +): (detail: string) => never { + return (detail) => { + throw new Error( + `${test}: the staged covered file ${what} ${detail} — ${premise}: a ` + + "harness defect", + ); + }; +} + +/** A value of 7's declarative form read from its expression. */ +function readValue( + node: ts.Expression, + path: readonly string[], + keys: SpelledKey[], + problem: (detail: string) => never, +): ConfigValue { + if (ts.isStringLiteral(node)) return node.text; + if (node.kind === ts.SyntaxKind.TrueKeyword) return true; + if (node.kind === ts.SyntaxKind.FalseKeyword) return false; + if (ts.isArrayLiteralExpression(node)) { + return node.elements.map((element) => { + if (ts.isSpreadElement(element) || ts.isOmittedExpression(element)) { + return problem("holds a spread or an elision in a list"); + } + return readValue(element, path, keys, problem); + }); + } + if (ts.isObjectLiteralExpression(node)) { + const object = new Map<string, ConfigValue>(); + for (const property of node.properties) { + if (!ts.isPropertyAssignment(property)) { + return problem("holds an object member that is no key and value"); + } + const name = property.name; + if (!ts.isIdentifier(name) && !ts.isStringLiteral(name)) { + return problem("holds a key that is no identifier or string literal"); + } + const key = name.text; + if (object.has(key)) { + return problem(`repeats the key ${JSON.stringify(key)} in one object`); + } + keys.push({ path, key, stringLiteral: ts.isStringLiteral(name) }); + object.set( + key, + readValue(property.initializer, [...path, key], keys, problem), + ); + } + return object; + } + return problem( + `holds an expression outside 7's declarative form ` + + `(${ts.SyntaxKind[node.kind]})`, + ); +} + +/** + * Read a rendered file back (module header): exactly an import of + * `defineConfig` by that identifier — no `type` or `defer` modifier, no + * attributes, one named binding, never `require`, `exports`, or a reserved + * word — from a string-literal specifier, then a default export of one call + * to that binding whose one argument is an object literal of 7's form; a + * deviation goes to `problem`. + */ +export function readBack( + text: string, + problem: (detail: string) => never, +): ReadBack { + const source = ts.createSourceFile( + "covered-file.ts", + text, + ts.ScriptTarget.ESNext, + true, + ts.ScriptKind.TS, + ); + const [first, second, ...rest] = source.statements; + if ( + first === undefined || + second === undefined || + rest.length > 0 || + !ts.isImportDeclaration(first) || + !ts.isExportAssignment(second) + ) { + return problem("is not exactly an import and a default export"); + } + const clause = first.importClause; + const named = clause?.namedBindings; + if ( + clause === undefined || + clause.phaseModifier !== undefined || + clause.name !== undefined || + named === undefined || + !ts.isNamedImports(named) || + named.elements.length !== 1 || + first.attributes !== undefined + ) { + return problem( + "does not import exactly one named binding with no type or defer " + + "modifier and no import attributes", + ); + } + const element = named.elements[0]!; + const imported = element.propertyName ?? element.name; + if ( + element.isTypeOnly || + !ts.isIdentifier(imported) || + imported.text !== "defineConfig" + ) { + return problem("does not import defineConfig by that identifier"); + } + const binding = element.name.text; + if (BARRED_BINDINGS.has(binding)) { + return problem( + `binds defineConfig to ${JSON.stringify(binding)}, a name strict ` + + "module code or a CommonJS file reserves", + ); + } + if (!ts.isStringLiteral(first.moduleSpecifier)) { + return problem("has a specifier that is no string literal"); + } + const call = second.expression; + if ( + second.isExportEquals === true || + !ts.isCallExpression(call) || + !ts.isIdentifier(call.expression) || + call.expression.text !== binding || + call.questionDotToken !== undefined || + call.typeArguments !== undefined || + call.arguments.length !== 1 || + !ts.isObjectLiteralExpression(call.arguments[0]!) + ) { + return problem( + "does not default-export one call to the binding with one object " + + "literal as its argument", + ); + } + const keys: SpelledKey[] = []; + const argument = readValue(call.arguments[0]!, [], keys, problem); + if (!isConfigObject(argument)) { + return problem("has an argument that reads as no object"); + } + return { + specifier: first.moduleSpecifier.text, + specifierSpelling: first.moduleSpecifier.getText(source), + binding, + argument, + keys, + source, + }; +} + +/** One comment of a file, as TypeScript's scanner reads it. */ +export interface ScannedComment { + readonly kind: "line" | "block"; + readonly start: number; + readonly end: number; + readonly text: string; +} + +/** Every comment of `text`, scanned as TypeScript scans it. */ +export function scanComments(text: string): readonly ScannedComment[] { + const scanner = ts.createScanner( + ts.ScriptTarget.ESNext, + false, + ts.LanguageVariant.Standard, + text, + ); + const comments: ScannedComment[] = []; + for ( + let token = scanner.scan(); + token !== ts.SyntaxKind.EndOfFileToken; + token = scanner.scan() + ) { + if ( + token === ts.SyntaxKind.SingleLineCommentTrivia || + token === ts.SyntaxKind.MultiLineCommentTrivia + ) { + comments.push({ + kind: + token === ts.SyntaxKind.SingleLineCommentTrivia ? "line" : "block", + start: scanner.getTokenStart(), + end: scanner.getTokenEnd(), + text: scanner.getTokenText(), + }); + } + } + return comments; +} + +/** Whether the comments in [start, end) hold a line and a block comment. */ +function bothKindsWithin( + comments: readonly ScannedComment[], + start: number, + end: number, +): boolean { + const within = comments.filter( + (comment) => comment.start >= start && comment.end <= end, + ); + return ( + within.some((comment) => comment.kind === "line") && + within.some((comment) => comment.kind === "block") + ); +} + +/** + * Where (c)'s comments stand, read from the parsed file: each place T7.6-2 + * names — before the import, between keys, inside lists, after the export — + * holding a line and a block comment; or why not. + */ +function commentPlacesProblem( + read: ReadBack, + comments: readonly ScannedComment[], +): string | undefined { + const source = read.source; + const [importDeclaration, exportAssignment] = source.statements; + if (importDeclaration === undefined || exportAssignment === undefined) { + return "it holds no import and default export"; + } + const betweenKeys: ScannedComment[] = []; + const insideLists: ScannedComment[] = []; + const visit = (node: ts.Node): void => { + if (ts.isObjectLiteralExpression(node)) { + node.properties.forEach((property, index) => { + const next = node.properties[index + 1]; + if (next === undefined) return; + betweenKeys.push( + ...comments.filter( + (comment) => + comment.start >= property.end && + comment.end <= next.getStart(source), + ), + ); + }); + } + if (ts.isArrayLiteralExpression(node)) { + insideLists.push( + ...comments.filter( + (comment) => + comment.start > node.getStart(source) && comment.end < node.end, + ), + ); + } + ts.forEachChild(node, visit); + }; + visit(exportAssignment); + const places: readonly (readonly [string, boolean])[] = [ + [ + "before the import", + bothKindsWithin(comments, 0, importDeclaration.getStart(source)), + ], + ["between keys", bothKindsWithin(betweenKeys, 0, source.end)], + ["inside lists", bothKindsWithin(insideLists, 0, source.end)], + [ + "after the export", + bothKindsWithin(comments, exportAssignment.end, source.end), + ], + ]; + const missing = places.filter(([, held]) => !held).map(([place]) => place); + return missing.length === 0 + ? undefined + : `it holds no line and block comment ${missing.join(", ")}`; +} + +// --------------------------------------------------------------------------- +// Valid under 7: the harness's own reading over the data (module header) +// --------------------------------------------------------------------------- + +const TOP_LEVEL_KEYS = ["specs", "code", "markdown", "coverage", "policy"]; +const MARKDOWN_KEYS = ["emit", "outDir"]; +const PROFILE_KEYS = [ + "name", + "target", + "targetTags", + "targets", + "boundary", + "boundaryKind", + "mode", + "edgeKinds", +]; +const RULE_KEYS = ["name", "type", "from", "to", "kinds"]; +const SELECTOR_KEYS = ["group", "kind", "files", "tags"]; +const SELECTOR_FORMS = ["group", "files", "tags"]; +export const EDGE_KINDS = ["depends", "embeds", "references"]; +export const GROUP_KINDS = ["spec", "code"]; +export const TARGETS = ["leaves", "all"]; +export const MODES = ["direct", "transitive"]; +export const RULE_TYPES = ["forbidden", "allowedOnly"]; + +/** The configured groups of one kind, by name. */ +type Groups = ReadonlyMap<string, readonly string[]>; + +/** Whether a glob lies inside the workspace root by its spelling (SPEC 7). */ +function insideRoot(glob: string): boolean { + if (glob.startsWith("/")) return false; + let depth = 0; + for (const segment of glob.split("/")) { + if (segment === "..") depth -= 1; + else if (segment !== "." && segment !== "" && segment !== "**") { + depth += 1; + } + if (depth < 0) return false; + } + return true; +} + +/** A list of strings, or undefined where `value` is none. */ +function stringList( + value: ConfigValue | undefined, +): readonly string[] | undefined { + if (value === undefined || !isConfigList(value)) return undefined; + return value.every((element) => typeof element === "string") + ? (value as readonly string[]) + : undefined; +} + +/** + * Every way `config` is invalid under 7 (SPEC 7, 7.3, 7.4, 7.5), as the + * harness reads them over the data; empty where it is valid. Workspace-bound + * rules (a file matched by both a spec and a code group) do not arise: no + * staging holds a file any configured glob matches. + */ +export function problemsUnder7(config: ConfigObject): readonly string[] { + const problems: string[] = []; + const keysWithin = ( + object: ConfigObject, + allowed: readonly string[], + where: string, + ): void => { + for (const key of object.keys()) { + if (!allowed.includes(key)) { + problems.push(`${where} holds the unknown key ${JSON.stringify(key)}`); + } + } + }; + const nameProblem = (name: ConfigValue | undefined, where: string): void => { + if (typeof name !== "string") problems.push(`${where} has no string name`); + else if (name === "" || name.includes(REPLACEMENT_CHARACTER)) { + problems.push(`${where} has the invalid name ${JSON.stringify(name)}`); + } + }; + const groupsOf = (key: "specs" | "code"): Groups => { + const value = config.get(key); + const groups = new Map<string, readonly string[]>(); + if (value === undefined) { + if (key === "specs") problems.push("the required key specs is missing"); + return groups; + } + if (!isConfigObject(value)) { + problems.push(`${key} is no object`); + return groups; + } + for (const [name, globs] of value) { + nameProblem(name, `the ${key} group ${JSON.stringify(name)}`); + const list = stringList(globs); + if (list === undefined) { + problems.push( + `the ${key} group ${JSON.stringify(name)} is no list of globs`, + ); + continue; + } + for (const glob of list) { + if (!insideRoot(glob)) { + problems.push( + `the glob ${JSON.stringify(glob)} lies outside the root`, + ); + } + } + groups.set(name, list); + } + return groups; + }; + keysWithin(config, TOP_LEVEL_KEYS, "the top level"); + const specs = groupsOf("specs"); + const code = groupsOf("code"); + const groupProblem = ( + group: ConfigValue | undefined, + kind: ConfigValue | undefined, + where: string, + ): void => { + if (typeof group !== "string") { + problems.push(`${where} names no group`); + return; + } + const inSpecs = specs.has(group); + const inCode = code.has(group); + if (kind === undefined) { + if (!inSpecs && !inCode) problems.push(`${where} names no group`); + if (inSpecs && inCode) { + problems.push( + `${where} names ${JSON.stringify(group)}, both kinds', without its kind`, + ); + } + return; + } + if (kind !== "spec" && kind !== "code") { + problems.push(`${where} gives a kind outside ${GROUP_KINDS.join(", ")}`); + } else if (!(kind === "spec" ? inSpecs : inCode)) { + problems.push(`${where} names no ${kind} group ${JSON.stringify(group)}`); + } + }; + const setRead = ( + value: ConfigValue | undefined, + where: string, + members?: readonly string[], + ): void => { + if (value === undefined) return; + const list = stringList(value); + if (list === undefined || list.length === 0) { + problems.push(`${where} is no non-empty list of strings`); + return; + } + if ( + members !== undefined && + list.some((element) => !members.includes(element)) + ) { + problems.push(`${where} holds an element outside ${members.join(", ")}`); + } + }; + const enumerated = ( + value: ConfigValue | undefined, + members: readonly string[], + where: string, + required: boolean, + ): void => { + if (value === undefined) { + if (required) problems.push(`${where} is missing`); + } else if (typeof value !== "string" || !members.includes(value)) { + problems.push(`${where} is outside ${members.join(", ")}`); + } + }; + const markdown = config.get("markdown"); + if (markdown !== undefined) { + if (!isConfigObject(markdown)) problems.push("markdown is no object"); + else { + keysWithin(markdown, MARKDOWN_KEYS, "markdown"); + if (typeof markdown.get("emit") !== "boolean") { + problems.push("markdown's emit is no boolean"); + } + const outDir = markdown.get("outDir"); + if (outDir !== undefined) { + const segments = typeof outDir === "string" ? outDir.split("/") : []; + if ( + typeof outDir !== "string" || + segments.some((s) => s === "" || s === "." || s === "..") || + outDir === ".xspec" || + outDir.startsWith(".xspec/") + ) { + problems.push( + `markdown's outDir ${JSON.stringify(outDir)} is invalid`, + ); + } + } + } + } + const listOfObjects = (key: string): readonly ConfigObject[] => { + const value = config.get(key); + if (value === undefined) return []; + if (!isConfigList(value) || !value.every(isConfigObject)) { + problems.push(`${key} is no list of objects`); + return []; + } + return value as readonly ConfigObject[]; + }; + const uniqueNames = ( + objects: readonly ConfigObject[], + what: string, + ): void => { + const names = objects.map((object) => object.get("name")); + objects.forEach((object, index) => + nameProblem(object.get("name"), `${what} ${String(index + 1)}`), + ); + if (new Set(names).size !== names.length) + problems.push(`two ${what}s share a name`); + }; + const profiles = listOfObjects("coverage"); + uniqueNames(profiles, "profile"); + profiles.forEach((profile, index) => { + const where = `profile ${String(index + 1)}`; + keysWithin(profile, PROFILE_KEYS, where); + const target = profile.get("target"); + if (typeof target !== "string" || !specs.has(target)) { + problems.push(`${where}'s target names no spec group`); + } + setRead(profile.get("targetTags"), `${where}'s targetTags`); + enumerated(profile.get("targets"), TARGETS, `${where}'s targets`, false); + groupProblem( + profile.get("boundary"), + profile.get("boundaryKind"), + `${where}'s boundary`, + ); + enumerated(profile.get("mode"), MODES, `${where}'s mode`, true); + setRead(profile.get("edgeKinds"), `${where}'s edgeKinds`, EDGE_KINDS); + }); + const rules = listOfObjects("policy"); + uniqueNames(rules, "rule"); + rules.forEach((rule, index) => { + const where = `rule ${String(index + 1)}`; + keysWithin(rule, RULE_KEYS, where); + enumerated(rule.get("type"), RULE_TYPES, `${where}'s type`, true); + setRead(rule.get("kinds"), `${where}'s kinds`, EDGE_KINDS); + for (const end of ["from", "to"]) { + const selector = rule.get(end); + const at = `${where}'s ${end}`; + if (selector === undefined || !isConfigObject(selector)) { + problems.push(`${at} is no selector`); + continue; + } + keysWithin(selector, SELECTOR_KEYS, at); + const forms = SELECTOR_FORMS.filter((form) => selector.has(form)); + if (forms.length !== 1) { + problems.push(`${at} uses ${String(forms.length)} selector forms`); + } else if (forms[0] === "group") { + groupProblem(selector.get("group"), selector.get("kind"), at); + } else if (selector.has("kind")) { + problems.push(`${at} carries kind without group`); + } else if (forms[0] === "files") { + const files = selector.get("files"); + if ( + typeof files !== "string" || + !insideRoot(files) || + files.includes("$") + ) { + problems.push( + `${at}'s files is no capture-free glob inside the root`, + ); + } + } else { + setRead(selector.get("tags"), `${at}'s tags`); + } + } + }); + return problems; +} + +// --------------------------------------------------------------------------- +// T7.6-2's configurations (module header) +// --------------------------------------------------------------------------- + +/** The three dependency edge kinds, each list holding all of them. */ +const ALL_EDGE_KINDS: ConfigList = ["depends", "embeds", "references"]; + +/** + * T7.6-2(a): every key and field 7 defines, every value 7 enumerates at + * each of its positions (module header). `tests` names a spec and a code + * group, so each reference to it carries its kind; `product` and `app` are + * unambiguous, so the selector naming `app` carries none. + */ +export const T762_EVERY_KEY_AND_VALUE: ConfigObject = configObject( + [ + "specs", + configObject( + ["product", ["specs/product/**/*.mdx"]], + ["tests", ["specs/tests/**/*.mdx"]], + ), + ], + [ + "code", + configObject( + ["app", ["src/**/*.ts", "src/**/*.tsx"]], + ["tests", ["test/**/*.ts"]], + ), + ], + ["markdown", configObject(["emit", true], ["outDir", "docs"])], + [ + "coverage", + [ + configObject( + ["name", "product-tested"], + ["target", "product"], + ["targetTags", ["core"]], + ["targets", "leaves"], + ["boundary", "tests"], + ["boundaryKind", "code"], + ["mode", "direct"], + ["edgeKinds", ALL_EDGE_KINDS], + ), + configObject( + ["name", "product-specified"], + ["target", "product"], + ["targetTags", ["core", "edge"]], + ["targets", "all"], + ["boundary", "tests"], + ["boundaryKind", "spec"], + ["mode", "transitive"], + ["edgeKinds", ALL_EDGE_KINDS], + ), + ], + ], + [ + "policy", + [ + configObject( + ["name", "app-avoids-test-code"], + ["type", "forbidden"], + ["from", configObject(["group", "app"])], + ["to", configObject(["group", "tests"], ["kind", "code"])], + ["kinds", ALL_EDGE_KINDS], + ), + configObject( + ["name", "test-specs-cite-product"], + ["type", "allowedOnly"], + ["from", configObject(["group", "tests"], ["kind", "spec"])], + ["to", configObject(["files", "specs/product/**/*.mdx"])], + ["kinds", ALL_EDGE_KINDS], + ), + configObject( + ["name", "core-avoids-edge"], + ["type", "forbidden"], + ["from", configObject(["tags", ["core"]])], + ["to", configObject(["tags", ["edge"]])], + ["kinds", ALL_EDGE_KINDS], + ), + ], + ], +); + +/** T7.6-2(d): the minimal configuration, `specs` holding no group. */ +const T762_MINIMAL: ConfigObject = configObject(["specs", configObject()]); + +/** + * The seven members of TypeScript's global `Object` interface, then + * `__proto__` (T7.6-2(e)). + */ +export const OBJECT_MEMBER_NAMES: readonly string[] = [ + "constructor", + "toString", + "toLocaleString", + "valueOf", + "hasOwnProperty", + "isPrototypeOf", + "propertyIsEnumerable", + "__proto__", +]; + +/** The name after the one at `index`, cyclically. */ +function nextMemberName(index: number): string { + return OBJECT_MEMBER_NAMES[(index + 1) % OBJECT_MEMBER_NAMES.length]!; +} + +/** + * T7.6-2(e) (module header): each name a spec and a code group's, so each + * reference carries its kind; profile `i`, named the `i`th name, targets it + * and takes the next as its boundary; rule `i`, so named, runs from its + * group to the next name's. + */ +const T762_OBJECT_MEMBER_NAMES: ConfigObject = configObject( + [ + "specs", + configObject( + ...OBJECT_MEMBER_NAMES.map( + (name) => [name, [`specs/${name}/**/*.mdx`]] as const, + ), + ), + ], + [ + "code", + configObject( + ...OBJECT_MEMBER_NAMES.map( + (name) => [name, [`src/${name}/**/*.ts`]] as const, + ), + ), + ], + [ + "coverage", + OBJECT_MEMBER_NAMES.map((name, index) => + configObject( + ["name", name], + ["target", name], + ["boundary", nextMemberName(index)], + ["boundaryKind", index % 2 === 0 ? "code" : "spec"], + ["mode", "direct"], + ), + ), + ], + [ + "policy", + OBJECT_MEMBER_NAMES.map((name, index) => + configObject( + ["name", name], + ["type", index % 2 === 0 ? "forbidden" : "allowedOnly"], + [ + "from", + configObject( + ["group", name], + ["kind", index % 2 === 0 ? "spec" : "code"], + ), + ], + [ + "to", + configObject( + ["group", nextMemberName(index)], + ["kind", index % 2 === 0 ? "code" : "spec"], + ), + ], + ), + ), + ], +); + +/** + * T7.6-2(f)'s first file: `code: {}`, `coverage: []`, `policy: []`, and + * `markdown: { emit: false }` beside a `specs` group. + */ +const T762_EMPTY_FORMS: ConfigObject = configObject( + ["specs", configObject(["product", ["specs/**/*.mdx"]])], + ["code", configObject()], + ["markdown", configObject(["emit", false])], + ["coverage", []], + ["policy", []], +); + +/** + * T7.6-2(f)'s second file: like (a)'s, every optional field omitted, its + * group names unambiguous (the code group `checks` in place of `tests`), so + * that no kind is required. + */ +const T762_OPTIONAL_FIELDS_OMITTED: ConfigObject = configObject( + [ + "specs", + configObject( + ["product", ["specs/product/**/*.mdx"]], + ["tests", ["specs/tests/**/*.mdx"]], + ), + ], + [ + "code", + configObject( + ["app", ["src/**/*.ts", "src/**/*.tsx"]], + ["checks", ["test/**/*.ts"]], + ), + ], + ["markdown", configObject(["emit", true])], + [ + "coverage", + [ + configObject( + ["name", "product-tested"], + ["target", "product"], + ["boundary", "checks"], + ["mode", "direct"], + ), + configObject( + ["name", "product-specified"], + ["target", "product"], + ["boundary", "tests"], + ["mode", "transitive"], + ), + ], + ], + [ + "policy", + [ + configObject( + ["name", "app-avoids-test-code"], + ["type", "forbidden"], + ["from", configObject(["group", "app"])], + ["to", configObject(["group", "checks"])], + ), + configObject( + ["name", "test-specs-cite-product"], + ["type", "allowedOnly"], + ["from", configObject(["group", "tests"])], + ["to", configObject(["files", "specs/product/**/*.mdx"])], + ), + configObject( + ["name", "core-avoids-edge"], + ["type", "forbidden"], + ["from", configObject(["tags", ["core"]])], + ["to", configObject(["tags", ["edge"]])], + ), + ], + ], +); + +/** The lists 7.4 and 7.5 read as sets, by key (T7.6-2(f)). */ +const SET_READ_KEYS: readonly string[] = [ + "targetTags", + "edgeKinds", + "kinds", + "tags", +]; + +/** `value` with an element repeated in every set-read list it holds. */ +function withRepeatedElements( + value: ConfigValue, + key: string | undefined, +): ConfigValue { + if (isConfigList(value)) { + const elements = value.map((element) => + withRepeatedElements(element, undefined), + ); + const first = elements[0]; + return key !== undefined && + SET_READ_KEYS.includes(key) && + first !== undefined + ? [...elements, first] + : elements; + } + if (isConfigObject(value)) { + return configObject( + ...[...value].map( + ([member, inner]) => + [member, withRepeatedElements(inner, member)] as const, + ), + ); + } + return value; +} + +/** + * T7.6-2(f)'s third file: (a)'s, the spec group `tests`'s and the code + * group `app`'s glob lists empty, and an element repeated in every set-read + * list — each `targetTags`, `edgeKinds`, rule's `kinds`, and selector's + * `tags`. + */ +const T762_EMPTY_AND_REPEATED: ConfigObject = (() => { + const repeated = withRepeatedElements(T762_EVERY_KEY_AND_VALUE, undefined); + if (!isConfigObject(repeated)) throw new Error("unreachable: an object"); + const emptied: ReadonlyMap<string, string> = new Map([ + ["specs", "tests"], + ["code", "app"], + ]); + return configObject( + ...[...repeated].map(([key, value]) => { + const group = emptied.get(key); + if (group === undefined || !isConfigObject(value)) { + return [key, value] as const; + } + return [ + key, + configObject( + ...[...value].map( + ([name, globs]) => [name, name === group ? [] : globs] as const, + ), + ), + ] as const; + }), + ); +})(); + +// --------------------------------------------------------------------------- +// Each arm's own content (module header) +// --------------------------------------------------------------------------- + +/** The objects of the list at `key`, or none. */ +function objectsAt(config: ConfigObject, key: string): readonly ConfigObject[] { + const value = config.get(key); + return value !== undefined && isConfigList(value) + ? value.filter(isConfigObject) + : []; +} + +/** Every selector of a configuration's rules. */ +function selectorsOf(config: ConfigObject): readonly ConfigObject[] { + return objectsAt(config, "policy").flatMap((rule) => + ["from", "to"] + .map((end) => rule.get(end)) + .filter( + (selector): selector is ConfigObject => + selector !== undefined && isConfigObject(selector), + ), + ); +} + +/** A selector's form: `group`, `group spec`, `group code`, `files`, `tags`. */ +function selectorForm(selector: ConfigObject): string { + if (selector.has("group")) { + const kind = selector.get("kind"); + return typeof kind === "string" ? `group ${kind}` : "group"; + } + return selector.has("files") ? "files" : "tags"; +} + +/** The keys of the object at `key`, in order, or none. */ +function keysAt(config: ConfigObject, key: string): readonly string[] { + const value = config.get(key); + return value !== undefined && isConfigObject(value) ? [...value.keys()] : []; +} + +/** Whether `keys` are exactly `expected`, in order. */ +function exactly(keys: Iterable<string>, expected: readonly string[]): boolean { + return [...keys].join(",") === expected.join(","); +} + +/** Whether a list of strings repeats an element. */ +function repeats(value: ConfigValue | undefined): boolean { + const list = stringList(value); + return list !== undefined && new Set(list).size < list.length; +} + +/** What a requirement check collects: each requirement the file misses. */ +type Needs = (held: boolean, requirement: string) => void; + +/** Run `check` with a collector; the requirements missed. */ +function missed(check: (need: Needs) => void): readonly string[] { + const misses: string[] = []; + check((held, requirement) => { + if (!held) misses.push(requirement); + }); + return misses; +} + +/** (a)'s requirements: every key and field, every enumerated value. */ +function everyKeyAndValueMissed(config: ConfigObject): readonly string[] { + return missed((need) => { + need(exactly(config.keys(), TOP_LEVEL_KEYS), "every top-level key"); + need(keysAt(config, "specs").length === 2, "specs with two groups"); + need(keysAt(config, "code").length === 2, "code with two groups"); + const markdown = config.get("markdown"); + need( + markdown !== undefined && + isConfigObject(markdown) && + markdown.get("emit") === true && + markdown.has("outDir"), + "markdown with emit true and outDir", + ); + const profiles = objectsAt(config, "coverage"); + need( + profiles.length === 2 && + profiles.every((profile) => exactly(profile.keys(), PROFILE_KEYS)), + "two profiles, each carrying every profile field", + ); + const enumerations: readonly (readonly [string, readonly string[]])[] = [ + ["targets", TARGETS], + ["boundaryKind", GROUP_KINDS], + ["mode", MODES], + ]; + for (const [key, members] of enumerations) { + const taken = new Set(profiles.map((profile) => profile.get(key))); + need( + members.every((member) => taken.has(member)), + `every value of ${key} between the profiles`, + ); + } + const rules = objectsAt(config, "policy"); + need( + rules.length > 0 && + rules.every((rule) => exactly(rule.keys(), RULE_KEYS)), + "rules each carrying every rule field, kinds included", + ); + const types = new Set(rules.map((rule) => rule.get("type"))); + need( + RULE_TYPES.every((type) => types.has(type)), + "rules of both types", + ); + for (const [key, objects] of [ + ["edgeKinds", profiles], + ["kinds", rules], + ] as const) { + need( + EDGE_KINDS.every((kind) => + objects.some((object) => stringList(object.get(key))?.includes(kind)), + ), + `each edge kind an element of some ${key}`, + ); + } + const forms = new Set(selectorsOf(config).map(selectorForm)); + for (const form of ["group", "group spec", "group code", "files", "tags"]) { + need(forms.has(form), `a selector of the form ${form}`); + } + }); +} + +/** (d)'s requirements: `specs` holding no group, and nothing else. */ +function minimalMissed(config: ConfigObject): readonly string[] { + return missed((need) => { + need(exactly(config.keys(), ["specs"]), "specs alone"); + need(keysAt(config, "specs").length === 0, "specs holding no group"); + }); +} + +/** (e)'s requirements: the eight names as groups, references, and names. */ +function objectMemberNamesMissed(config: ConfigObject): readonly string[] { + return missed((need) => { + for (const key of ["specs", "code"]) { + need( + exactly(keysAt(config, key), OBJECT_MEMBER_NAMES), + `exactly the eight names as ${key} groups`, + ); + } + const profiles = objectsAt(config, "coverage"); + const rules = objectsAt(config, "policy"); + const selectors = selectorsOf(config); + for (const name of OBJECT_MEMBER_NAMES) { + need( + profiles.some( + (profile) => + profile.get("target") === name || profile.get("boundary") === name, + ), + `${name} a profile's target or boundary`, + ); + need( + selectors.some((selector) => selector.get("group") === name), + `${name} a selector's group`, + ); + need( + profiles.some((profile) => profile.get("name") === name), + `a profile named ${name}`, + ); + need( + rules.some((rule) => rule.get("name") === name), + `a rule named ${name}`, + ); + } + }); +} + +/** (f)'s first file's requirements: the empty forms beside a group. */ +function emptyFormsMissed(config: ConfigObject): readonly string[] { + return missed((need) => { + need(keysAt(config, "specs").length > 0, "a specs group"); + const code = config.get("code"); + need( + code !== undefined && isConfigObject(code) && code.size === 0, + "code: {}", + ); + const markdown = config.get("markdown"); + need( + markdown !== undefined && + isConfigObject(markdown) && + exactly(markdown.keys(), ["emit"]) && + markdown.get("emit") === false, + "markdown: { emit: false }", + ); + for (const key of ["coverage", "policy"]) { + const list = config.get(key); + need( + list !== undefined && isConfigList(list) && list.length === 0, + `${key}: []`, + ); + } + }); +} + +/** (f)'s second file's requirements: every optional field omitted. */ +function optionalFieldsOmittedMissed(config: ConfigObject): readonly string[] { + return missed((need) => { + need(exactly(config.keys(), TOP_LEVEL_KEYS), "every top-level key, as (a)"); + need( + exactly(keysAt(config, "markdown"), ["emit"]), + "markdown without outDir", + ); + const profiles = objectsAt(config, "coverage"); + need( + profiles.length > 0 && + profiles.every((profile) => + exactly(profile.keys(), ["name", "target", "boundary", "mode"]), + ), + "profiles carrying only name, target, boundary, and mode", + ); + const rules = objectsAt(config, "policy"); + need( + rules.length > 0 && + rules.every((rule) => + exactly(rule.keys(), ["name", "type", "from", "to"]), + ), + "rules without kinds", + ); + need( + selectorsOf(config) + .filter((selector) => selector.has("group")) + .every((selector) => exactly(selector.keys(), ["group"])), + "group selectors without kind", + ); + const code = new Set(keysAt(config, "code")); + need( + keysAt(config, "specs").every((name) => !code.has(name)), + "group names unambiguous", + ); + }); +} + +/** (f)'s third file's requirements: empty glob lists, repeated elements. */ +function emptyAndRepeatedMissed(config: ConfigObject): readonly string[] { + return missed((need) => { + for (const key of ["specs", "code"]) { + const groups = config.get(key); + need( + groups !== undefined && + isConfigObject(groups) && + [...groups.values()].some( + (globs) => isConfigList(globs) && globs.length === 0, + ), + `a ${key} group's glob list empty`, + ); + } + for (const profile of objectsAt(config, "coverage")) { + need(repeats(profile.get("targetTags")), "a repeat in each targetTags"); + need(repeats(profile.get("edgeKinds")), "a repeat in each edgeKinds"); + } + for (const rule of objectsAt(config, "policy")) { + need(repeats(rule.get("kinds")), "a repeat in each rule's kinds"); + } + for (const selector of selectorsOf(config)) { + if (selector.has("tags")) { + need(repeats(selector.get("tags")), "a repeat in each selector's tags"); + } + } + }); +} + +// --------------------------------------------------------------------------- +// The files, their module-load checks, and their S-9 records +// --------------------------------------------------------------------------- + +/** One of T7.6-2's files (module header). */ +interface T762Arm { + /** The arm as TEST-SPEC letters it, with the file's ordinal in (e), (f). */ + readonly arm: string; + /** What the file stages: its records and diagnoses name it. */ + readonly what: string; + readonly config: ConfigObject; + /** How it is rendered, its specifier aside. */ + readonly binding: string; + readonly keys: KeySpelling; + readonly comments: boolean; + /** Each of the arm's own requirements the configuration misses. */ + readonly missed: (config: ConfigObject) => readonly string[]; +} + +/** (b)'s alias: a name strict module code admits, never require or exports. */ +const ALIAS = "configure"; + +const T762_ARMS: readonly T762Arm[] = [ + { + arm: "(a)", + what: "every key and field 7 defines, every enumerated value", + config: T762_EVERY_KEY_AND_VALUE, + binding: "defineConfig", + keys: "identifiers", + comments: false, + missed: everyKeyAndValueMissed, + }, + { + arm: "(b)", + what: "(a) with an aliased binding and every key a string literal", + config: T762_EVERY_KEY_AND_VALUE, + binding: ALIAS, + keys: "string literals", + comments: false, + missed: everyKeyAndValueMissed, + }, + { + arm: "(c)", + what: "(a) with line and block comments before the import, between keys, inside lists, and after the export", + config: T762_EVERY_KEY_AND_VALUE, + binding: "defineConfig", + keys: "identifiers", + comments: true, + missed: everyKeyAndValueMissed, + }, + { + arm: "(d)", + what: "the minimal configuration, specs holding no group", + config: T762_MINIMAL, + binding: "defineConfig", + keys: "identifiers", + comments: false, + missed: minimalMissed, + }, + { + arm: "(e) 1", + what: "the Object interface's members and __proto__ as group, profile, and rule names, group keys spelled as identifiers", + config: T762_OBJECT_MEMBER_NAMES, + binding: "defineConfig", + keys: "identifiers", + comments: false, + missed: objectMemberNamesMissed, + }, + { + arm: "(e) 2", + what: "the Object interface's members and __proto__ as group, profile, and rule names, group keys spelled as string literals", + config: T762_OBJECT_MEMBER_NAMES, + binding: "defineConfig", + keys: "group names as string literals", + comments: false, + missed: objectMemberNamesMissed, + }, + { + arm: "(f) 1", + what: "code: {}, coverage: [], policy: [], and markdown: { emit: false } beside a specs group", + config: T762_EMPTY_FORMS, + binding: "defineConfig", + keys: "identifiers", + comments: false, + missed: emptyFormsMissed, + }, + { + arm: "(f) 2", + what: "a file like (a)'s with every optional field omitted, its group names unambiguous", + config: T762_OPTIONAL_FIELDS_OMITTED, + binding: "defineConfig", + keys: "identifiers", + comments: false, + missed: optionalFieldsOmittedMissed, + }, + { + arm: "(f) 3", + what: "(a) with a spec and a code group's glob lists empty and an element repeated in every set-read list", + config: T762_EMPTY_AND_REPEATED, + binding: "defineConfig", + keys: "identifiers", + comments: false, + missed: emptyAndRepeatedMissed, + }, +]; + +/** Whether two values of 7's form are equal, object keys in order. */ +export function sameValue(a: ConfigValue, b: ConfigValue): boolean { + if (typeof a !== "object" || typeof b !== "object") return a === b; + if (isConfigList(a) || isConfigList(b)) { + return ( + isConfigList(a) && + isConfigList(b) && + a.length === b.length && + a.every((element, index) => sameValue(element, b[index]!)) + ); + } + const entries = [...b]; + return ( + a.size === b.size && + [...a].every(([key, value], index) => { + const entry = entries[index]; + return ( + entry !== undefined && entry[0] === key && sameValue(value, entry[1]) + ); + }) + ); +} + +/** + * The file `arm` stages beside the placement `name` — rendered, then held + * at module load to everything the module header lists; a deviation throws. + */ +function composeFile(arm: T762Arm, name: string): string { + const what = `T7.6-2${arm.arm} (${arm.what}, importing ${JSON.stringify(name)})`; + const problem = deviation("T7.6-2", what, T762_PREMISE); + const rendering: ConfigRendering = { + specifier: name, + binding: arm.binding, + keys: arm.keys, + comments: arm.comments, + }; + const text = renderConfiguration(arm.config, rendering); + if (text.includes(BACKSLASH)) problem("spells a backslash"); + const invalid = problemsUnder7(arm.config); + if (invalid.length > 0) problem(`is invalid under 7: ${invalid.join("; ")}`); + const misses = arm.missed(arm.config); + if (misses.length > 0) { + problem(`misses what its arm names: ${misses.join("; ")}`); + } + const comments = scanComments(text); + for (const comment of comments) { + if (comment.text.includes("@") || comment.text.startsWith("///")) { + problem( + `carries the comment ${JSON.stringify(comment.text)}, which ` + + "TypeScript may read as a directive or pragma", + ); + } + } + const read = readBack(text, problem); + if ( + read.specifier !== name || + read.specifierSpelling !== JSON.stringify(name) + ) { + problem(`spells its specifier ${read.specifierSpelling}, not exactly N`); + } + if (read.binding !== arm.binding) { + problem(`binds defineConfig to ${read.binding}, not ${arm.binding}`); + } + if (!sameValue(read.argument, arm.config)) { + problem("reads back as another configuration than the one rendered"); + } + for (const key of read.keys) { + const stringLiteral = + arm.keys === "string literals" || + (arm.keys === "group names as string literals" && + isGroupNameKey(key.path)); + if (key.stringLiteral !== stringLiteral) { + problem( + `spells the key ${JSON.stringify(key.key)} as ` + + `${key.stringLiteral ? "a string literal" : "an identifier"}`, + ); + } + } + if (arm.comments) { + const places = commentPlacesProblem(read, comments); + if (places !== undefined) problem(places); + } else if (comments.length > 0) { + problem("carries a comment, though its arm stages none"); + } + return text; +} + +/** One file's records for one N: plain TypeScript, and TSX of the same bytes. */ +interface T762Records { + readonly ts: StagedTs; + readonly tsx: StagedTs; +} + +/** One of T7.6-2's files, with its records for each candidate N. */ +interface T762File { + /** The arm as TEST-SPEC letters it. */ + readonly arm: string; + /** Names the file in every diagnosis. */ + readonly label: string; + readonly records: ReadonlyMap<string, T762Records>; +} + +/** + * T7.6-2's files, each rendered and checked for each canonical-name + * candidate at module load, each rendering a staged-source record (S-9), + * judged as plain TypeScript and, for the `.tsx` name, as TSX. (a)'s records + * are T7.6-3's twin too, and (d)'s T7.6-1's covered file, so their names + * lead with both IDs. + */ +const T762_FILES: readonly T762File[] = T762_ARMS.map((arm) => { + const records = new Map<string, T762Records>(); + const ids = + arm.arm === "(a)" + ? "T7.6-2/T7.6-3" + : arm.arm === "(d)" + ? "T7.6-1/T7.6-2" + : "T7.6-2"; + for (const name of CANONICAL_MODULE_NAMES) { + const text = composeFile(arm, name); + const record = `${ids} ${arm.arm} ${arm.what}, importing ${JSON.stringify(name)}`; + records.set(name, { + ts: stagedTs(record, text), + tsx: stagedTs(`${record}, as TSX`, text, "well-formed", "tsx"), + }); + } + return { arm: arm.arm, label: `T7.6-2${arm.arm} (${arm.what})`, records }; +}); + +// --------------------------------------------------------------------------- +// The body +// --------------------------------------------------------------------------- + +/** The project directory each staging holds, staging-relative. */ +const PROJECT_DIR = "project"; + +/** `n` and `word`, pluralized. */ +function count(n: number, word: string): string { + return `${String(n)} ${word}${n === 1 ? "" : "s"}`; +} + +/** The files a staging writes for the placement's N: its records' bytes. */ +function filesFor( + name: string, +): readonly { label: string; text: string | Uint8Array }[] { + return T762_FILES.map((file) => { + const records = file.records.get(name); + if (records === undefined) { + throw new Error( + `T7.6-2: no record holds ${file.label} beside N ${JSON.stringify(name)}; ` + + `the canonical N is one of ${CANONICAL_MODULE_NAMES.join(", ")} ` + + "(helpers/module-channel.ts canonicalModuleName): a harness defect", + ); + } + return { label: file.label, text: records.ts.source }; + }); +} + +/** Each verdict's diagnosed failure, in file order: none where all pass. */ +function failuresOf(verdicts: readonly CoveredVerdict[]): readonly string[] { + const failures: string[] = []; + for (const verdict of verdicts) { + try { + assertTypeChecks(verdict, "T7.6-2"); + } catch (error) { + if (!(error instanceof HarnessAssertionError)) throw error; + failures.push(error.message); + } + } + return failures; +} + +/** T7.6-2's body (module header). */ +async function runValidConfigurations(product: ProductBinding): Promise<void> { + let judged = 0; + for (const project of PROJECT_KINDS) { + const context = `T7.6-2 (valid configurations), the ${project} project`; + const staging = await ModuleStaging.create(product, context); + try { + await staging.stageProject(PROJECT_DIR, project); + const placement = await staging.placeCanonical( + PROJECT_DIR, + TYPE_CHECKING_ARM, + ); + const files = await stageCoveredFiles({ + staging, + directory: PROJECT_DIR, + project, + placement, + alone: true, + files: filesFor(placement.name), + context, + }); + for (const setup of files.setups) { + const verdicts = files.judge(setup); + const failures = failuresOf(verdicts); + if (failures.length > 0) { + fail( + `${context}: ${count(failures.length, "valid configuration file")} ` + + `of ${String(verdicts.length)} fail to type-check in ` + + `${setup.label}, beside the canonical placement ` + + `${placement.path} — the first covered setup where any fails, ` + + `after ${count(judged, "setup")} where every file ` + + "type-checked; the body stops here (TEST-SPEC T7.6-2: each " + + "covered file valid under 7 type-checks in every covered " + + "setup; SPEC 7.6 Type contract, valid configurations). " + + failures.join(" | "), + ); + } + judged += 1; + } + } finally { + await staging.dispose(); + } + } + if (judged !== COVERED_SETUP_COUNT) { + throw new Error( + `T7.6-2: ${String(judged)} covered setups judged, not TEST-SPEC ` + + `§7.6's ${String(COVERED_SETUP_COUNT)}; no setup is sampled away: ` + + "a harness defect", + ); + } +} + +const T7_6_2 = defineProductTest({ + id: "T7.6-2", + title: + "each covered file valid under 7 type-checks in all 173 covered setups " + + "beside the canonical placement: (a) every key, field, and enumerated " + + "value; (b) (a) with an aliased binding and every key a string literal; " + + "(c) (a) with line and block comments before the import, between keys, " + + "inside lists, and after the export; (d) the minimal configuration; (e) " + + "the global Object interface's members and __proto__ as spec and code " + + "group, profile, and rule names, in a file of identifier keys and one of " + + "string-literal keys; (f) the empty, omitted, and repeated forms (SPEC " + + "7.6 Covered files, Type contract)", + run: runValidConfigurations, +}); + +// --------------------------------------------------------------------------- +// T7.6-1: declared exports (module header) +// --------------------------------------------------------------------------- + +/** The one export SPEC 7.6 lets the module declare. */ +const DEFINE_CONFIG = "defineConfig"; + +/** T7.6-1's covered file: T7.6-2(d)'s, the minimal configuration. */ +const T761_FILE: T762File = (() => { + const file = T762_FILES.find((candidate) => candidate.arm === "(d)"); + if (file === undefined) { + throw new Error( + "T7.6-1: T7.6-2(d)'s file, the minimal configuration, is not among " + + "T7.6-2's files: a harness defect", + ); + } + return file; +})(); + +/** + * Each way `listing` deviates from T7.6-1, in a fixed order: none where it + * holds. + */ +function declaredExportsDeviations(listing: ExportListing): readonly string[] { + if (listing.module === undefined) { + return [ + "TypeScript resolves the import to no module it reads declarations " + + "from, so the module declares no export, defineConfig among them", + ]; + } + const deviations: string[] = []; + const entry = listing.exports.find( + (candidate) => candidate.name === DEFINE_CONFIG, + ); + if (entry === undefined) { + deviations.push("the module declares no export named defineConfig"); + } else { + if (entry.typeOnlyValue) { + deviations.push( + "defineConfig's value meaning is reached only through export type, " + + "import type, or export type *, so no import may use it as a value", + ); + } else if (!entry.value) { + deviations.push("defineConfig carries no value meaning"); + } + if (entry.type) deviations.push("defineConfig carries a type meaning"); + if (entry.namespace) { + deviations.push("defineConfig carries a namespace meaning"); + } + } + const others = listing.exports.filter( + (candidate) => candidate.name !== DEFINE_CONFIG, + ); + if (others.length > 0) { + deviations.push( + `the module declares ${count(others.length, "other export")}: ` + + others.map(describeListedExport).join(", "), + ); + } + return deviations; +} + +/** + * Assert T7.6-1 of one verdict (module header): the module TypeScript + * resolves the covered file's import to, in the verdict's setup, declares + * exactly one export, `defineConfig`, carrying a value meaning an import may + * use as a value and neither a type nor a namespace meaning, and no other + * export, type-only or not — read from the verdict's export listing, never + * probed by names. A listing naming no module, as beside S-7's stub + * package, fails too. A failure is diagnosed, naming the setup, the file, + * the placement, every deviation, the listing whole, and TypeScript's + * errors for the program; a verdict carrying no listing (its request did + * not ask for one) is a misuse. + */ +export function assertDeclaredExports( + verdict: CoveredVerdict, + context: string, +): void { + const listing = verdict.exportListing; + if (listing === undefined) { + throw new Error( + `T7.6-1: the verdict for ${verdict.label} in ${verdict.setup.label} ` + + "carries no export listing, which a request asks for with " + + "listExports (helpers/module-channel-ts.ts): a harness defect " + + `(${context})`, + ); + } + const deviations = declaredExportsDeviations(listing); + if (deviations.length === 0) return; + const beside = + verdict.placement === undefined + ? "" + : `, beside the placement ${verdict.placement}`; + fail( + `${context}: in ${verdict.setup.label}${beside}, the import of the ` + + `configuration file ${verdict.label} (${verdict.file}) does not reach ` + + "a module declaring exactly one export, defineConfig, a value with " + + `neither a type nor a namespace meaning: ${deviations.join("; ")}. ` + + `TypeScript 5.9.3's listing for that import: ` + + `${describeExportListing(listing)}. TypeScript's errors for the ` + + `program, a diagnostic aid: ${describeErrors(verdict.errors)} ` + + "(TEST-SPEC T7.6-1: in every covered setup, the module TypeScript " + + "resolves the covered file's import to declares exactly one export, " + + "defineConfig, carrying a value meaning and neither a type nor a " + + "namespace meaning, and no other export, type-only or not; SPEC 7.6 " + + "Type contract, Exports)", + ); +} + +/** T7.6-1's body (module header). */ +async function runDeclaredExports(product: ProductBinding): Promise<void> { + let judged = 0; + for (const project of PROJECT_KINDS) { + const context = `T7.6-1 (declared exports), the ${project} project`; + const staging = await ModuleStaging.create(product, context); + try { + await staging.stageProject(PROJECT_DIR, project); + const placement = await staging.placeCanonical( + PROJECT_DIR, + TYPE_CHECKING_ARM, + ); + const files = await stageCoveredFiles({ + staging, + directory: PROJECT_DIR, + project, + placement, + alone: true, + files: [ + { + label: T761_FILE.label, + text: textFor(T761_FILE, placement.name), + }, + ], + listExports: true, + context, + }); + for (const setup of files.setups) { + const [verdict] = files.judge(setup); + if (verdict === undefined) throw new Error("unreachable: one verdict"); + assertDeclaredExports( + verdict, + `${context}: the first covered setup whose listing deviates, ` + + `after ${count(judged, "setup")} where every listing held; the ` + + "body stops here", + ); + judged += 1; + } + } finally { + await staging.dispose(); + } + } + if (judged !== COVERED_SETUP_COUNT) { + throw new Error( + `T7.6-1: ${String(judged)} covered setups judged, not TEST-SPEC ` + + `§7.6's ${String(COVERED_SETUP_COUNT)}; no setup is sampled away: ` + + "a harness defect", + ); + } +} + +const T7_6_1 = defineProductTest({ + id: "T7.6-1", + title: + "in all 173 covered setups beside the canonical placement, the module " + + "TypeScript resolves the covered file's import to (T7.6-2(d)'s minimal " + + "configuration) declares exactly one export, defineConfig, carrying a " + + "value meaning and neither a type nor a namespace meaning, and no other " + + "export, type-only or not: read from TypeScript's own listing of the " + + "module's exports (implicit exports of a declaration module included) " + + "and, for an export assignment, the assigned value's members, each " + + "setup through its own resolution; TypeScript's synthetic default is no " + + "export, a declared default export is one (SPEC 7.6 Type contract, " + + "Exports)", + run: runDeclaredExports, +}); + +// --------------------------------------------------------------------------- +// T7.6-3: 7's shape as the type-error class reads it (module header) +// --------------------------------------------------------------------------- + +/** A kind SPEC 7.6's type-error class names: what 7 admits at a position. */ +export type ConfigKind = "boolean" | "string" | "list" | "object"; + +/** The four kinds, in T7.6-3's order. */ +export const CONFIG_KINDS: readonly ConfigKind[] = [ + "boolean", + "string", + "list", + "object", +]; + +/** A value's kind. */ +export function kindOf(value: ConfigValue): ConfigKind { + if (typeof value === "boolean") return "boolean"; + if (typeof value === "string") return "string"; + return isConfigList(value) ? "list" : "object"; +} + +/** Where a value stands: object keys and list indices, from the argument. */ +export type ConfigPath = readonly (string | number)[]; + +/** + * 7's shape as SPEC 7.6's type-error class reads it (module header): each + * position's kind, its enumeration, a fixed-key object's fields and required + * keys, a group map's entries, a list's elements, and whether 7.4 or 7.5 + * forbids the list empty or holds the object to a selector's forms. + */ +export interface ShapeSchema { + /** T7.6-3's name for the position: its row of the kind table. */ + readonly position: string; + /** The kind 7 admits there. */ + readonly kind: ConfigKind; + /** The values 7 enumerates there, where it enumerates them. */ + readonly values?: readonly string[]; + /** A fixed-key object's fields, in 7's order. */ + readonly fields?: ReadonlyMap<string, ShapeSchema>; + /** A fixed-key object's required keys. */ + readonly required?: readonly string[]; + /** A group map's entries: each group, under any name. */ + readonly entries?: ShapeSchema; + /** A list's elements. */ + readonly elements?: ShapeSchema; + /** A list 7.4 or 7.5 forbids empty. */ + readonly nonEmpty?: boolean; + /** A selector, held to 7.5's forms. */ + readonly selector?: boolean; +} + +/** A string position, enumerated where `values` is given. */ +function stringAt(position: string, values?: readonly string[]): ShapeSchema { + return values === undefined + ? { position, kind: "string" } + : { position, kind: "string", values }; +} + +/** A group: a list of globs. */ +const GROUP_SHAPE: ShapeSchema = { + position: "a group", + kind: "list", + elements: stringAt("a group's glob element"), +}; + +/** A selector (7.5): a rule's `from` or `to`. */ +const SELECTOR_SHAPE: ShapeSchema = { + position: "a selector (a rule's from or to)", + kind: "object", + selector: true, + required: [], + fields: new Map<string, ShapeSchema>([ + ["group", stringAt("a selector's group")], + ["kind", stringAt("a selector's kind", GROUP_KINDS)], + ["files", stringAt("a selector's files")], + [ + "tags", + { + position: "a selector's tags", + kind: "list", + nonEmpty: true, + elements: stringAt("an element of a selector's tags"), + }, + ], + ]), +}; + +/** A coverage profile (7.4). */ +const PROFILE_SHAPE: ShapeSchema = { + position: "a profile", + kind: "object", + required: ["name", "target", "boundary", "mode"], + fields: new Map<string, ShapeSchema>([ + ["name", stringAt("a profile's name")], + ["target", stringAt("a profile's target")], + [ + "targetTags", + { + position: "a profile's targetTags", + kind: "list", + nonEmpty: true, + elements: stringAt("an element of a profile's targetTags"), + }, + ], + ["targets", stringAt("a profile's targets", TARGETS)], + ["boundary", stringAt("a profile's boundary")], + ["boundaryKind", stringAt("a profile's boundaryKind", GROUP_KINDS)], + ["mode", stringAt("a profile's mode", MODES)], + [ + "edgeKinds", + { + position: "a profile's edgeKinds", + kind: "list", + nonEmpty: true, + elements: stringAt("an element of a profile's edgeKinds", EDGE_KINDS), + }, + ], + ]), +}; + +/** A policy rule (7.5). */ +const RULE_SHAPE: ShapeSchema = { + position: "a rule", + kind: "object", + required: ["name", "type", "from", "to"], + fields: new Map<string, ShapeSchema>([ + ["name", stringAt("a rule's name")], + ["type", stringAt("a rule's type", RULE_TYPES)], + ["from", SELECTOR_SHAPE], + ["to", SELECTOR_SHAPE], + [ + "kinds", + { + position: "a rule's kinds", + kind: "list", + nonEmpty: true, + elements: stringAt("an element of a rule's kinds", EDGE_KINDS), + }, + ], + ]), +}; + +/** The `defineConfig` argument (7, 7.1–7.5): the top level. */ +const CONFIG_SHAPE: ShapeSchema = { + position: "the top level", + kind: "object", + required: ["specs"], + fields: new Map<string, ShapeSchema>([ + ["specs", { position: "specs", kind: "object", entries: GROUP_SHAPE }], + ["code", { position: "code", kind: "object", entries: GROUP_SHAPE }], + [ + "markdown", + { + position: "markdown", + kind: "object", + required: ["emit"], + fields: new Map<string, ShapeSchema>([ + ["emit", { position: "emit", kind: "boolean" }], + ["outDir", stringAt("outDir")], + ]), + }, + ], + [ + "coverage", + { position: "coverage", kind: "list", elements: PROFILE_SHAPE }, + ], + ["policy", { position: "policy", kind: "list", elements: RULE_SHAPE }], + ]), +}; + +/** Every shape below `shape`, `shape` first, each once. */ +function shapesWithin(shape: ShapeSchema): readonly ShapeSchema[] { + const seen = new Set<ShapeSchema>(); + const visit = (at: ShapeSchema): void => { + if (seen.has(at)) return; + seen.add(at); + for (const inner of [ + ...(at.fields?.values() ?? []), + ...(at.entries === undefined ? [] : [at.entries]), + ...(at.elements === undefined ? [] : [at.elements]), + ]) { + visit(inner); + } + }; + visit(shape); + return [...seen]; +} + +/** One value of a configuration, where it stands, and its shape there. */ +export interface ShapeNode { + readonly path: ConfigPath; + readonly value: ConfigValue; + readonly shape: ShapeSchema; +} + +/** + * Every value of `config` at a position 7 gives a kind, the argument first + * (module header): the walk descends only into a value of the kind 7 admits + * at its position, so a misplaced value's insides stand at no position, and + * never into an unknown key, which 7 gives no kind. + */ +export function shapeNodes(config: ConfigObject): readonly ShapeNode[] { + const nodes: ShapeNode[] = []; + const visit = ( + value: ConfigValue, + shape: ShapeSchema, + path: ConfigPath, + ): void => { + nodes.push({ path, value, shape }); + if (kindOf(value) !== shape.kind) return; + if (isConfigList(value)) { + const elements = shape.elements; + if (elements === undefined) return; + value.forEach((element, index) => + visit(element, elements, [...path, index]), + ); + } else if (isConfigObject(value)) { + for (const [key, member] of value) { + const inner = shape.entries ?? shape.fields?.get(key); + if (inner !== undefined) visit(member, inner, [...path, key]); + } + } + }; + visit(config, CONFIG_SHAPE, []); + return nodes; +} + +/** The six members of SPEC 7.6's type-error class. */ +export type ViolationCategory = + | "unknown key" + | "missing required key" + | "kind" + | "enumeration" + | "selector form" + | "empty list"; + +/** + * One violation of the type-error class: its member, and where it lies — an + * unknown or missing key at that key's path, any other at its value's. + */ +export interface ClassViolation { + readonly category: ViolationCategory; + readonly path: ConfigPath; +} + +/** + * Every violation of SPEC 7.6's type-error class in `config`, as the harness + * reads the class over the data (module header): an unknown key in a + * fixed-key object; a required key missing; a value of a kind 7 does not + * admit at its position; a string outside the values 7 enumerates there; a + * selector not in exactly one of its forms; an empty list 7.4 or 7.5 + * forbids. Errors outside the class are not read. + */ +export function classViolations( + config: ConfigObject, +): readonly ClassViolation[] { + const found: ClassViolation[] = []; + for (const { path, value, shape } of shapeNodes(config)) { + if (kindOf(value) !== shape.kind) { + found.push({ category: "kind", path }); + continue; + } + if ( + shape.values !== undefined && + typeof value === "string" && + !shape.values.includes(value) + ) { + found.push({ category: "enumeration", path }); + } + if (isConfigList(value) && shape.nonEmpty === true && value.length === 0) { + found.push({ category: "empty list", path }); + } + if (isConfigObject(value) && shape.fields !== undefined) { + for (const key of value.keys()) { + if (!shape.fields.has(key)) { + found.push({ category: "unknown key", path: [...path, key] }); + } + } + for (const key of shape.required ?? []) { + if (!value.has(key)) { + found.push({ + category: "missing required key", + path: [...path, key], + }); + } + } + if (shape.selector === true) { + const forms = SELECTOR_FORMS.filter((form) => value.has(form)); + if (forms.length !== 1 || (value.has("kind") && !value.has("group"))) { + found.push({ category: "selector form", path }); + } + } + } + } + return found; +} + +// --------------------------------------------------------------------------- +// T7.6-3's violations, as tables (module header) +// --------------------------------------------------------------------------- + +/** + * T7.6-3's positions to which 7 gives a kind, as its list names them, in + * its order: `specs`, `code`, and each group; a group's glob elements; + * `markdown`, `emit`, and `outDir`; `coverage`, each profile, each profile + * field, and each element of its lists; `policy`, each rule, each rule field + * (`from` and `to` being selectors), and each element of `kinds`; and each + * selector, each selector field, and each element of its `tags`. + */ +const T763_KIND_POSITIONS: readonly string[] = [ + "specs", + "code", + "a group", + "a group's glob element", + "markdown", + "emit", + "outDir", + "coverage", + "a profile", + "a profile's name", + "a profile's target", + "a profile's targetTags", + "a profile's targets", + "a profile's boundary", + "a profile's boundaryKind", + "a profile's mode", + "a profile's edgeKinds", + "an element of a profile's targetTags", + "an element of a profile's edgeKinds", + "policy", + "a rule", + "a rule's name", + "a rule's type", + "a rule's kinds", + "an element of a rule's kinds", + "a selector (a rule's from or to)", + "a selector's group", + "a selector's kind", + "a selector's files", + "a selector's tags", + "an element of a selector's tags", +]; + +/** T7.6-3's enumerated positions, as its list names them. */ +const T763_ENUMERATED_POSITIONS: readonly string[] = [ + "a profile's targets", + "a profile's boundaryKind", + "a profile's mode", + "a rule's type", + "a selector's kind", + "an element of a profile's edgeKinds", + "an element of a rule's kinds", +]; + +/** T7.6-3's objects an unknown key is staged in, as its list names them. */ +const T763_UNKNOWN_KEY_POSITIONS: readonly string[] = [ + "the top level", + "markdown", + "a profile", + "a rule", + "a selector (a rule's from or to)", +]; + +/** T7.6-3's required keys, by the object holding them, as it lists them. */ +const T763_REQUIRED_KEYS: readonly (readonly [string, readonly string[]])[] = [ + ["the top level", ["specs"]], + ["markdown", ["emit"]], + ["a profile", ["name", "target", "boundary", "mode"]], + ["a rule", ["name", "type", "from", "to"]], +]; + +/** T7.6-3's forbidden empty lists, as its list names them. */ +const T763_NON_EMPTY_POSITIONS: readonly string[] = [ + "a profile's targetTags", + "a profile's edgeKinds", + "a rule's kinds", + "a selector's tags", +]; + +/** + * The kind table (module header): for each position T7.6-3 lists, the + * values staged there, one of each kind 7 does not admit at it — the + * boolean both `true` and `false` where 7 admits a list or an object — + * TEST-SPEC's own spellings among them (`specs: ["a/*.mdx"]`, + * `emit: "true"`, `targetTags: "a"`, `from: "src/*.ts"`). Each value is + * staged at every value of (a)'s file standing at that position. + */ +export const T763_KIND_TABLE: ReadonlyMap<string, readonly ConfigValue[]> = + new Map<string, readonly ConfigValue[]>([ + ["specs", [true, false, "specs/**/*.mdx", ["a/*.mdx"]]], + ["code", [true, false, "src/**/*.ts", ["src/**/*.ts"]]], + [ + "a group", + [true, false, "src/**/*.ts", configObject(["globs", ["src/**/*.ts"]])], + ], + [ + "a group's glob element", + [true, ["src/**/*.ts"], configObject(["glob", "src/**/*.ts"])], + ], + ["markdown", [true, false, "docs", ["docs"]]], + ["emit", ["true", [true], configObject(["enabled", true])]], + ["outDir", [true, ["docs"], configObject(["path", "docs"])]], + [ + "coverage", + [ + true, + false, + "product-tested", + configObject( + ["name", "product-tested"], + ["target", "product"], + ["boundary", "tests"], + ["boundaryKind", "code"], + ["mode", "direct"], + ), + ], + ], + ["a profile", [true, false, "product-tested", ["product-tested"]]], + [ + "a profile's name", + [true, ["product-tested"], configObject(["name", "product-tested"])], + ], + [ + "a profile's target", + [true, ["product"], configObject(["group", "product"])], + ], + [ + "a profile's targetTags", + [true, false, "a", configObject(["tags", ["core"]])], + ], + [ + "a profile's targets", + [true, ["leaves"], configObject(["targets", "leaves"])], + ], + [ + "a profile's boundary", + [true, ["tests"], configObject(["group", "tests"], ["kind", "code"])], + ], + [ + "a profile's boundaryKind", + [true, ["code"], configObject(["kind", "code"])], + ], + ["a profile's mode", [true, ["direct"], configObject(["mode", "direct"])]], + [ + "a profile's edgeKinds", + [true, false, "depends", configObject(["depends", true])], + ], + [ + "an element of a profile's targetTags", + [true, ["core"], configObject(["tag", "core"])], + ], + [ + "an element of a profile's edgeKinds", + [true, ["depends"], configObject(["kind", "depends"])], + ], + [ + "policy", + [ + true, + false, + "app-avoids-test-code", + configObject( + ["name", "app-avoids-test-code"], + ["type", "forbidden"], + ["from", configObject(["group", "app"])], + ["to", configObject(["group", "tests"], ["kind", "code"])], + ), + ], + ], + ["a rule", [true, false, "app-avoids-test-code", ["app-avoids-test-code"]]], + [ + "a rule's name", + [ + true, + ["app-avoids-test-code"], + configObject(["name", "app-avoids-test-code"]), + ], + ], + [ + "a rule's type", + [true, ["forbidden"], configObject(["type", "forbidden"])], + ], + [ + "a rule's kinds", + [true, false, "depends", configObject(["depends", true])], + ], + [ + "an element of a rule's kinds", + [true, ["depends"], configObject(["kind", "depends"])], + ], + [ + "a selector (a rule's from or to)", + [true, false, "src/*.ts", [configObject(["group", "app"])]], + ], + ["a selector's group", [true, ["app"], configObject(["name", "app"])]], + ["a selector's kind", [true, ["code"], configObject(["kind", "code"])]], + [ + "a selector's files", + [true, ["src/*.ts"], configObject(["glob", "src/*.ts"])], + ], + ["a selector's tags", [true, false, "core", configObject(["tag", "core"])]], + [ + "an element of a selector's tags", + [true, ["core"], configObject(["tag", "core"])], + ], + ]); + +/** + * T7.6-3's selector-form violations (module header): each two of `group`, + * `files`, and `tags`, all three, none, and `kind` without `group` beside + * `files`, beside `tags`, and alone — each replacing a selector whole, its + * names resolving. + */ +const T763_SELECTOR_FORM_VIOLATIONS: readonly (readonly [ + string, + ConfigObject, +])[] = [ + ["group and files", configObject(["group", "app"], ["files", "src/*.ts"])], + ["group and tags", configObject(["group", "app"], ["tags", ["core"]])], + ["files and tags", configObject(["files", "src/*.ts"], ["tags", ["core"]])], + [ + "group, files, and tags", + configObject(["group", "app"], ["files", "src/*.ts"], ["tags", ["core"]]), + ], + ["none of group, files, and tags", configObject()], + ["kind beside files", configObject(["files", "src/*.ts"], ["kind", "code"])], + ["kind beside tags", configObject(["tags", ["core"]], ["kind", "spec"])], + ["kind alone", configObject(["kind", "spec"])], +]; + +/** The unknown key staged in each fixed-key object: no key of 7's anywhere. */ +const T763_UNKNOWN_KEY = "extra"; + +/** The edge kind 5.2 defines and 7.4 and 7.5 leave out (T7.6-3). */ +export const CONTAINS = "contains"; + +/** + * Two near misses of an enumerated value (module header): capitalized, and + * cut by its last letter — `"Direct"` and `"depend"` among them. + */ +export function nearMisses(value: string): readonly string[] { + return [value.charAt(0).toUpperCase() + value.slice(1), value.slice(0, -1)]; +} + +// --------------------------------------------------------------------------- +// Edits of (a)'s data, and how a label names them +// --------------------------------------------------------------------------- + +/** How a label names a position of (a)'s file. */ +function describePath(path: ConfigPath): string { + const [top, second] = path; + if (top === undefined) return "the top level"; + let text = String(top); + let named = 1; + if ((top === "specs" || top === "code") && typeof second === "string") { + text = `the ${top === "specs" ? "spec" : "code"} group ${second}`; + named = 2; + const glob = path[2]; + if (typeof glob === "number") { + text += `'s glob ${String(glob + 1)}`; + named = 3; + } + } else if ( + (top === "coverage" || top === "policy") && + typeof second === "number" + ) { + text = `${top === "coverage" ? "profile" : "rule"} ${String(second + 1)}`; + named = 2; + } + for (const segment of path.slice(named)) { + text += + typeof segment === "number" + ? ` element ${String(segment + 1)}` + : `'s ${segment}`; + } + return text; +} + +/** How a label spells a value: as the file does, on one line. */ +export function describeValue(value: ConfigValue): string { + if (typeof value === "string") return JSON.stringify(value); + if (typeof value === "boolean") return String(value); + if (isConfigList(value)) return `[${value.map(describeValue).join(", ")}]`; + if (value.size === 0) return "{}"; + return `{ ${[...value] + .map(([key, member]) => `${key}: ${describeValue(member)}`) + .join(", ")} }`; +} + +/** A kind with its article. */ +function aKind(kind: ConfigKind): string { + return kind === "object" ? "an object" : `a ${kind}`; +} + +/** `config` with the value at `path` replaced by `edit`'s result. */ +function editAt( + config: ConfigValue, + path: ConfigPath, + edit: (at: ConfigValue) => ConfigValue, +): ConfigValue { + const [head, ...rest] = path; + if (head === undefined) return edit(config); + if (typeof head === "number") { + if (!isConfigList(config) || head >= config.length) { + throw new Error( + `T7.6-3: no list element ${String(head)} to edit: a harness defect`, + ); + } + return config.map((element, index) => + index === head ? editAt(element, rest, edit) : element, + ); + } + if (!isConfigObject(config) || !config.has(head)) { + throw new Error( + `T7.6-3: no key ${JSON.stringify(head)} to edit: a harness defect`, + ); + } + return configObject( + ...[...config].map( + ([key, member]) => + [key, key === head ? editAt(member, rest, edit) : member] as const, + ), + ); +} + +/** An object, or a harness defect. */ +function asObject(value: ConfigValue, what: string): ConfigObject { + if (!isConfigObject(value)) { + throw new Error(`T7.6-3: ${what} is no object: a harness defect`); + } + return value; +} + +/** + * One edit of a configuration (module header): what it does to the data, + * the violation of the class it makes, and how a label names it. A replacing + * edit also records where it replaces and with what, so the module-load + * checks find TEST-SPEC's own spellings among them. + */ +export interface T763Edit { + readonly apply: (config: ConfigObject) => ConfigObject; + readonly violation: ClassViolation; + readonly label: string; + readonly replaced?: { + readonly path: ConfigPath; + readonly value: ConfigValue; + }; +} + +/** Replace the value at `path` with `value`, making `violation`. */ +function replaceEdit( + path: ConfigPath, + value: ConfigValue, + violation: ClassViolation, + label: string, +): T763Edit { + return { + apply: (config) => + asObject( + editAt(config, path, () => value), + "an edited configuration", + ), + violation, + label, + replaced: { path, value }, + }; +} + +/** Remove the required key `key` from the object at `path`. */ +function removeKeyEdit(path: ConfigPath, key: string): T763Edit { + return { + apply: (config) => + asObject( + editAt(config, path, (object) => + configObject( + ...[...asObject(object, describePath(path))].filter( + ([member]) => member !== key, + ), + ), + ), + "an edited configuration", + ), + violation: { category: "missing required key", path: [...path, key] }, + label: `the required key ${key} missing from ${describePath(path)}`, + }; +} + +/** Append the unknown key to the object at `path`. */ +function unknownKeyEdit(path: ConfigPath): T763Edit { + return { + apply: (config) => + asObject( + editAt(config, path, (object) => + configObject(...asObject(object, describePath(path)), [ + T763_UNKNOWN_KEY, + true, + ]), + ), + "an edited configuration", + ), + violation: { category: "unknown key", path: [...path, T763_UNKNOWN_KEY] }, + label: + path.length === 0 + ? "an unknown key at the top level" + : `an unknown key in ${describePath(path)}`, + }; +} + +/** Stage a value of a kind 7 does not admit at `path`. */ +function kindEdit(path: ConfigPath, value: ConfigValue): T763Edit { + return replaceEdit( + path, + value, + { category: "kind", path }, + `${aKind(kindOf(value))} at ${describePath(path)}: ${describeValue(value)}`, + ); +} + +/** Stage a string outside the values 7 enumerates at `path`. */ +function enumerationEdit(path: ConfigPath, value: string): T763Edit { + return replaceEdit( + path, + value, + { category: "enumeration", path }, + `a string outside the values 7 enumerates at ${describePath(path)}: ` + + JSON.stringify(value), + ); +} + +/** Replace the selector at `path` with a selector-form violation. */ +function selectorFormEdit( + path: ConfigPath, + form: string, + selector: ConfigObject, +): T763Edit { + return replaceEdit( + path, + selector, + { category: "selector form", path }, + `the selector form ${form} at ${describePath(path)}: ${describeValue(selector)}`, + ); +} + +/** Empty the list at `path`, one 7.4 or 7.5 forbids empty. */ +function emptyListEdit(path: ConfigPath): T763Edit { + return replaceEdit( + path, + [], + { category: "empty list", path }, + `an empty list at ${describePath(path)}`, + ); +} + +// --------------------------------------------------------------------------- +// T7.6-3's arms: (a)'s file with its edits applied (module header) +// --------------------------------------------------------------------------- + +/** One of T7.6-3's files: (a)'s data with its edits applied. */ +export interface T763Arm { + /** Names the file in every diagnosis and in its records. */ + readonly label: string; + readonly edits: readonly T763Edit[]; + readonly config: ConfigObject; +} + +/** + * The single-violation edits (module header), from a walk of (a)'s data, in + * T7.6-3's order of the class: unknown keys, missing required keys, kinds, + * enumerations, selector forms, empty lists — then TEST-SPEC's + * `kinds: [true]`. + */ +export function singleViolationEdits(twin: ConfigObject): readonly T763Edit[] { + const nodes = shapeNodes(twin); + const edits: T763Edit[] = []; + for (const { path, value, shape } of nodes) { + if (shape.fields !== undefined && isConfigObject(value)) { + edits.push(unknownKeyEdit(path)); + } + } + for (const { path, value, shape } of nodes) { + if (shape.fields === undefined || !isConfigObject(value)) continue; + for (const key of shape.required ?? []) { + if (value.has(key)) edits.push(removeKeyEdit(path, key)); + } + } + for (const { path, shape } of nodes) { + if (path.length === 0) continue; + for (const replacement of T763_KIND_TABLE.get(shape.position) ?? []) { + edits.push(kindEdit(path, replacement)); + } + } + for (const { path, value, shape } of nodes) { + if (shape.values === undefined || typeof value !== "string") continue; + for (const outside of [ + ...nearMisses(value), + ...(shape.values === EDGE_KINDS ? [CONTAINS] : []), + ]) { + edits.push(enumerationEdit(path, outside)); + } + } + for (const { path, shape } of nodes) { + if (shape.selector !== true) continue; + for (const [form, selector] of T763_SELECTOR_FORM_VIOLATIONS) { + edits.push(selectorFormEdit(path, form, selector)); + } + } + for (const { path, shape } of nodes) { + if (shape.nonEmpty === true) edits.push(emptyListEdit(path)); + } + edits.push( + replaceEdit( + ["policy", 0, "kinds"], + [true], + { category: "kind", path: ["policy", 0, "kinds", 0] }, + "a boolean at rule 1's kinds element 1, the list [true] alone", + ), + ); + return edits; +} + +/** The violations the several-violations file holds at once (module header). */ +const T763_SEVERAL_EDITS: readonly T763Edit[] = [ + unknownKeyEdit([]), + kindEdit(["markdown", "emit"], "true"), + removeKeyEdit(["coverage", 0], "mode"), + enumerationEdit(["coverage", 1, "mode"], "Transitive"), + enumerationEdit(["policy", 0, "kinds", 0], CONTAINS), + selectorFormEdit( + ["policy", 1, "from"], + "group and files", + configObject(["group", "app"], ["files", "src/*.ts"]), + ), + emptyListEdit(["coverage", 0, "targetTags"]), +]; + +/** (a)'s data with `edits` applied in order. */ +function applyEdits( + twin: ConfigObject, + edits: readonly T763Edit[], +): ConfigObject { + return edits.reduce((config, edit) => edit.apply(config), twin); +} + +/** T7.6-3's arms: one per single-violation edit, then the several. */ +export const T763_ARMS: readonly T763Arm[] = [ + ...singleViolationEdits(T762_EVERY_KEY_AND_VALUE).map((edit) => ({ + label: edit.label, + edits: [edit], + config: edit.apply(T762_EVERY_KEY_AND_VALUE), + })), + { + label: `several violations at once: ${T763_SEVERAL_EDITS.map( + (edit) => edit.label, + ).join("; ")}`, + edits: T763_SEVERAL_EDITS, + config: applyEdits(T762_EVERY_KEY_AND_VALUE, T763_SEVERAL_EDITS), + }, +]; + +/** How a check compares violations: member and path. */ +function violationKey(violation: ClassViolation): string { + return `${violation.category} at ${JSON.stringify(violation.path)}`; +} + +/** Whether two lists of strings hold the same members, each once. */ +function sameMembers(a: readonly string[], b: readonly string[]): boolean { + const left = [...a].sort(); + const right = [...b].sort(); + return ( + new Set(left).size === left.length && + left.length === right.length && + left.every((member, index) => member === right[index]) + ); +} + +/** + * Hold T7.6-3's tables to its list and each arm to its edits (module + * header); a deviation is a harness defect, thrown at module load. + */ +function checkT763Arms(twin: ConfigObject, arms: readonly T763Arm[]): void { + const problems: string[] = []; + const need = (held: boolean, problem: string): void => { + if (!held) problems.push(problem); + }; + const shapes = shapesWithin(CONFIG_SHAPE).filter( + (shape) => shape !== CONFIG_SHAPE, + ); + const byPosition = new Map(shapes.map((shape) => [shape.position, shape])); + need(byPosition.size === shapes.length, "two shapes share a position's name"); + need( + sameMembers([...byPosition.keys()], T763_KIND_POSITIONS), + "7's shape names other positions than T7.6-3 lists", + ); + const nodes = shapeNodes(twin); + need( + sameMembers( + [ + ...new Set( + nodes + .filter((node) => node.path.length > 0) + .map((node) => node.shape.position), + ), + ], + T763_KIND_POSITIONS, + ), + "T7.6-2(a)'s file does not hold a value at every position T7.6-3 lists", + ); + need( + sameMembers([...T763_KIND_TABLE.keys()], T763_KIND_POSITIONS), + "the kind table's rows are not T7.6-3's positions", + ); + for (const [position, values] of T763_KIND_TABLE) { + const admitted = byPosition.get(position)?.kind; + const kinds = values.map(kindOf); + const booleans = values.filter((value) => typeof value === "boolean"); + const expectedBooleans = + admitted === "boolean" + ? [] + : admitted === "list" || admitted === "object" + ? [true, false] + : [true]; + need( + admitted !== undefined && + sameMembers( + [...new Set(kinds)], + CONFIG_KINDS.filter((kind) => kind !== admitted), + ) && + sameMembers(booleans.map(String), expectedBooleans.map(String)) && + kinds.filter((kind) => kind !== "boolean").length === + CONFIG_KINDS.filter((kind) => kind !== admitted && kind !== "boolean") + .length && + new Set(values.map(describeValue)).size === values.length, + `the kind table's row for ${position} is not one value of each kind ` + + "7 does not admit there (the boolean both ways where 7 admits a " + + "list or an object)", + ); + } + const positionsWhere = (held: (shape: ShapeSchema) => boolean): string[] => + shapes.filter(held).map((shape) => shape.position); + need( + sameMembers( + positionsWhere((shape) => shape.values !== undefined), + T763_ENUMERATED_POSITIONS, + ), + "7's shape enumerates at other positions than T7.6-3 lists", + ); + need( + sameMembers( + shapesWithin(CONFIG_SHAPE) + .filter((shape) => shape.fields !== undefined) + .map((shape) => shape.position), + T763_UNKNOWN_KEY_POSITIONS, + ), + "7's fixed-key objects are not the objects T7.6-3 stages an unknown key in", + ); + for (const shape of shapesWithin(CONFIG_SHAPE)) { + if (shape.fields === undefined) continue; + const listed = + T763_REQUIRED_KEYS.find( + ([position]) => position === shape.position, + )?.[1] ?? []; + need( + sameMembers([...(shape.required ?? [])], listed), + `${shape.position}'s required keys are not those T7.6-3 lists`, + ); + need( + !shape.fields.has(T763_UNKNOWN_KEY), + `${T763_UNKNOWN_KEY} is a key 7 defines in ${shape.position}`, + ); + } + need( + sameMembers( + positionsWhere((shape) => shape.nonEmpty === true), + T763_NON_EMPTY_POSITIONS, + ), + "7's shape forbids other lists empty than T7.6-3 lists", + ); + const keysOf = (shape: ShapeSchema): string => + [...(shape.fields?.keys() ?? [])].join(","); + need( + keysOf(CONFIG_SHAPE) === TOP_LEVEL_KEYS.join(",") && + keysOf(PROFILE_SHAPE) === PROFILE_KEYS.join(",") && + keysOf(RULE_SHAPE) === RULE_KEYS.join(",") && + keysOf(SELECTOR_SHAPE) === SELECTOR_KEYS.join(",") && + byPosition.get("markdown") !== undefined && + keysOf(byPosition.get("markdown")!) === MARKDOWN_KEYS.join(","), + "7's shape names other keys than 7 defines", + ); + need( + sameMembers( + T763_SELECTOR_FORM_VIOLATIONS.map(([, selector]) => + [...selector.keys()].sort().join(","), + ), + [ + "files,group", + "group,tags", + "files,tags", + "files,group,tags", + "", + "files,kind", + "kind,tags", + "kind", + ], + ), + "the selector-form violations are not T7.6-3's eight", + ); + need( + classViolations(twin).length === 0, + "T7.6-2(a)'s file holds a violation of the type-error class", + ); + for (const arm of arms) { + const found = classViolations(arm.config).map(violationKey); + const made = arm.edits.map((edit) => violationKey(edit.violation)); + need( + sameMembers(found, made), + `the arm ${JSON.stringify(arm.label)} holds the violations ` + + `${JSON.stringify(found)}, not exactly those its edits make ` + + `${JSON.stringify(made)}`, + ); + } + const several = arms.filter((arm) => arm.edits.length > 1); + need( + several.length === 1 && + sameMembers( + [...new Set(several[0]!.edits.map((edit) => edit.violation.category))], + [ + "unknown key", + "missing required key", + "kind", + "enumeration", + "selector form", + "empty list", + ], + ), + "no one file holds a violation of each member of the class at once", + ); + need( + new Set(arms.map((arm) => arm.label)).size === arms.length, + "two arms share a label", + ); + const positionOf = new Map( + nodes.map((node) => [JSON.stringify(node.path), node.shape.position]), + ); + const staged = ( + position: string, + value: ConfigValue, + key: string | undefined, + ): boolean => + arms.some((arm) => + arm.edits.some( + (edit) => + edit.replaced !== undefined && + positionOf.get(JSON.stringify(edit.replaced.path)) === position && + (key === undefined || edit.replaced.path.at(-1) === key) && + describeValue(edit.replaced.value) === describeValue(value), + ), + ); + const spellings: readonly (readonly [string, ConfigValue, string?])[] = [ + ["specs", ["a/*.mdx"]], + ["emit", "true"], + ["a profile's targetTags", "a"], + ["a rule's kinds", [true]], + ["a selector (a rule's from or to)", "src/*.ts", "from"], + ["a profile's mode", "Direct"], + ["an element of a profile's edgeKinds", "depend"], + ["an element of a rule's kinds", "depend"], + ["an element of a profile's edgeKinds", CONTAINS], + ["an element of a rule's kinds", CONTAINS], + ]; + for (const [position, value, key] of spellings) { + need( + staged(position, value, key), + `no arm stages TEST-SPEC's ${describeValue(value)} at ${position}` + + (key === undefined ? "" : ` (${key})`), + ); + } + if (problems.length > 0) { + throw new Error( + `T7.6-3: the shape-violation arms drift from TEST-SPEC T7.6-3 — ` + + `${problems.join("; ")} (TEST-SPEC T7.6-3; SPEC 7.6 Type contract, ` + + "the type-error class): a harness defect", + ); + } +} + +checkT763Arms(T762_EVERY_KEY_AND_VALUE, T763_ARMS); + +// --------------------------------------------------------------------------- +// T7.6-3's files, their module-load checks, and their S-9 records +// --------------------------------------------------------------------------- + +/** T7.6-3's premise for each of its files, which a deviation breaks. */ +const T763_PREMISE = + "each of T7.6-3's files is T7.6-2(a)'s file with exactly the violations " + + "of 7.6's type-error class its arm names applied, and a covered file " + + "(TEST-SPEC T7.6-3; SPEC 7.6 Covered files, Type contract)"; + +/** How T7.6-3's files are rendered: as T7.6-2(a)'s, the specifier aside. */ +function t763Rendering(name: string): ConfigRendering { + return { + specifier: name, + binding: "defineConfig", + keys: "identifiers", + comments: false, + }; +} + +/** + * The file `arm` stages beside the placement `name` — rendered as its twin + * is, then read back at module load (module header); a deviation throws. + */ +function composeT763File(arm: T763Arm, name: string): string { + const what = `T7.6-3 (${arm.label}, importing ${JSON.stringify(name)})`; + const problem = deviation("T7.6-3", what, T763_PREMISE); + const text = renderConfiguration(arm.config, t763Rendering(name)); + if (text.includes(BACKSLASH)) problem("spells a backslash"); + if (scanComments(text).length > 0) problem("carries a comment"); + const read = readBack(text, problem); + if ( + read.specifier !== name || + read.specifierSpelling !== JSON.stringify(name) + ) { + problem(`spells its specifier ${read.specifierSpelling}, not exactly N`); + } + if (read.binding !== "defineConfig") { + problem(`binds defineConfig to ${read.binding}`); + } + if (!sameValue(read.argument, arm.config)) { + problem("reads back as another configuration than the one rendered"); + } + if (read.keys.some((key) => key.stringLiteral)) { + problem("spells a key as a string literal, which its twin does not"); + } + return text; +} + +/** T7.6-2(a)'s file: T7.6-3's twin, its records shared with T7.6-2. */ +const T763_TWIN: T762File = (() => { + const twin = T762_FILES.find((file) => file.arm === "(a)"); + if (twin === undefined) { + throw new Error("T7.6-3: T7.6-2 holds no (a) file: a harness defect"); + } + for (const name of CANONICAL_MODULE_NAMES) { + const text = renderConfiguration( + T762_EVERY_KEY_AND_VALUE, + t763Rendering(name), + ); + if (twin.records.get(name)?.ts.source !== text) { + throw new Error( + `T7.6-3: T7.6-2(a)'s record importing ${JSON.stringify(name)} holds ` + + "other bytes than T7.6-3's arms are rendered beside: the twin is " + + "the same file without the violation (TEST-SPEC T7.6-3): a " + + "harness defect", + ); + } + } + return twin; +})(); + +/** One of T7.6-3's files, with its records for each candidate N. */ +interface T763File { + /** Names the file in every diagnosis. */ + readonly label: string; + readonly records: ReadonlyMap<string, T762Records>; +} + +/** + * T7.6-3's files, each rendered and read back for each canonical-name + * candidate at module load, each rendering a staged-source record (S-9), + * judged as plain TypeScript and, for the `.tsx` name, as TSX; no two alike, + * and none its twin. + */ +const T763_FILES: readonly T763File[] = (() => { + const files = T763_ARMS.map((arm) => { + const records = new Map<string, T762Records>(); + for (const name of CANONICAL_MODULE_NAMES) { + const text = composeT763File(arm, name); + const record = `T7.6-3 ${arm.label}, importing ${JSON.stringify(name)}`; + records.set(name, { + ts: stagedTs(record, text), + tsx: stagedTs(`${record}, as TSX`, text, "well-formed", "tsx"), + }); + } + return { label: arm.label, records }; + }); + for (const name of CANONICAL_MODULE_NAMES) { + const texts = new Set([ + T763_TWIN.records.get(name)?.ts.source, + ...files.map((file) => file.records.get(name)?.ts.source), + ]); + if (texts.size !== files.length + 1) { + throw new Error( + `T7.6-3: two of its files importing ${JSON.stringify(name)}, or one ` + + "and its twin, hold the same bytes: a harness defect", + ); + } + } + return files; +})(); + +// --------------------------------------------------------------------------- +// T7.6-3's body +// --------------------------------------------------------------------------- + +/** The bytes of `file`'s record for the placement's N. */ +function textFor(file: T762File | T763File, name: string): string { + const records = file.records.get(name); + if (records === undefined || typeof records.ts.source !== "string") { + throw new Error( + `TEST-SPEC §7.6: no record holds ${file.label} beside N ` + + `${JSON.stringify(name)}; the canonical N is one of ` + + `${CANONICAL_MODULE_NAMES.join(", ")} (helpers/module-channel.ts ` + + "canonicalModuleName): a harness defect", + ); + } + return records.ts.source; +} + +/** How many failed arms a diagnosis spells out in full. */ +const FAILURES_IN_FULL = 3; + +/** T7.6-3's body (module header). */ +async function runShapeViolations(product: ProductBinding): Promise<void> { + let judged = 0; + for (const project of PROJECT_KINDS) { + const context = `T7.6-3 (shape violations), the ${project} project`; + const staging = await ModuleStaging.create(product, context); + try { + await staging.stageProject(PROJECT_DIR, project); + const placement = await staging.placeCanonical( + PROJECT_DIR, + TYPE_CHECKING_ARM, + ); + const request = { + staging, + directory: PROJECT_DIR, + project, + placement, + alone: true, + context, + }; + const twinLabel = T763_TWIN.label; + const twins = await stageCoveredFiles({ + ...request, + files: [{ label: twinLabel, text: textFor(T763_TWIN, placement.name) }], + }); + let arms: CoveredFiles | undefined; + for (const setup of twins.setups) { + const [twin] = twins.judge(setup); + if (twin === undefined) throw new Error("unreachable: one verdict"); + assertTypeChecks( + twin, + `${context}: no shape-violation arm counts in ${setup.label}, ` + + `beside the canonical placement ${placement.path}, unless its ` + + "valid twin type-checks there (TEST-SPEC §7.6 Pairing), so the " + + "body stops at the first setup where the twin does not, after " + + `${count(judged, "setup")} where every arm failed to type-check`, + ); + arms ??= await stageCoveredFiles({ + ...request, + files: T763_FILES.map((file) => ({ + label: file.label, + text: textFor(file, placement.name), + })), + }); + const verdicts = arms.judge(setup); + const failed: string[] = []; + const inFull: string[] = []; + for (const verdict of verdicts) { + try { + assertShapeViolation(twin, verdict, context); + } catch (error) { + if (!(error instanceof HarnessAssertionError)) throw error; + failed.push(verdict.label); + if (inFull.length < FAILURES_IN_FULL) inFull.push(error.message); + } + } + if (failed.length > 0) { + fail( + `${context}: ${count(failed.length, "shape-violation arm")} of ` + + `${String(verdicts.length)} do not fail to type-check in ` + + `${setup.label}, beside the canonical placement ` + + `${placement.path}, while their valid twin, ${twinLabel}, ` + + "type-checks there — the first covered setup where any arm " + + "does not fail to type-check, after " + + `${count(judged, "setup")} where every arm did; the body stops ` + + "here (TEST-SPEC T7.6-3: each " + + "file holding a violation of 7.6's type-error class fails to " + + "type-check in every covered setup, paired with its valid twin; " + + "SPEC 7.6 Type contract, shape violations). The arms: " + + `${failed.join(" | ")}. The first ` + + `${count(inFull.length, "failure")} in full: ${inFull.join(" || ")}`, + ); + } + judged += 1; + } + } finally { + await staging.dispose(); + } + } + if (judged !== COVERED_SETUP_COUNT) { + throw new Error( + `T7.6-3: ${String(judged)} covered setups judged, not TEST-SPEC ` + + `§7.6's ${String(COVERED_SETUP_COUNT)}; no setup is sampled away: ` + + "a harness defect", + ); + } +} + +const T7_6_3 = defineProductTest({ + id: "T7.6-3", + title: + "each arm, T7.6-2(a)'s file with one violation of 7.6's type-error " + + "class applied, fails to type-check in all 173 covered setups beside " + + "the canonical placement, paired with (a) type-checking in the same " + + "setup: an unknown key in each fixed-key object (the top level, " + + "markdown, each profile, each rule, and each selector); each required " + + "key missing from each object requiring it; at every value of (a)'s " + + "file, each kind among a boolean (both values where a list or an object " + + "belongs), a string, a list, and an object that 7 does not admit there, " + + "and kinds: [true]; at every enumerated value, two near misses of it " + + "(Direct and depend among them), and contains at each element of an " + + "edgeKinds and of a rule's kinds; each selector-form violation at each " + + "selector; each list 7.4 and 7.5 forbid empty, emptied; and one file " + + "holding a violation of each member of the class at once (SPEC 7.6 " + + "Type contract, shape violations; TEST-SPEC §7.6 Pairing)", + run: runShapeViolations, +}); + +// --------------------------------------------------------------------------- +// T7.6-4's files: the canonical runs' files beside any N (section-7.6-ii.ts) +// --------------------------------------------------------------------------- + +/** One file a placement's type-checking runs stage: its label and bytes. */ +export interface PlacementFile { + /** Names the file in every diagnosis; unique among the three. */ + readonly label: string; + readonly text: string; +} + +/** + * The files of the runs each of T7.6-4's placements stands in for the + * canonical one in, beside one N (TEST-SPEC T7.6-4): T7.6-1's, T7.6-2(a)'s, + * and T7.6-3's unknown-top-level-key arm's. + */ +export interface PlacementFiles { + /** T7.6-1's covered file: T7.6-2(d)'s, the minimal configuration. */ + readonly declaredExports: PlacementFile; + /** T7.6-2(a)'s file: the unknown-top-level-key arm's valid twin. */ + readonly valid: PlacementFile; + /** T7.6-3's arm: (a)'s file with an unknown key at its top level. */ + readonly unknownKey: PlacementFile; +} + +/** T7.6-2's file lettered `letter`, or a harness defect. */ +function t762Arm(letter: string): T762Arm { + const arm = T762_ARMS.find((candidate) => candidate.arm === letter); + if (arm === undefined) { + throw new Error( + `T7.6-4: T7.6-2 holds no ${letter} file, which T7.6-4's placements ` + + "stage: a harness defect", + ); + } + return arm; +} + +/** T7.6-3's arm with an unknown key at the top level, and its own files. */ +const T763_UNKNOWN_TOP_LEVEL_KEY: { + readonly arm: T763Arm; + readonly file: T763File; +} = (() => { + const arm = T763_ARMS.find( + (candidate) => + candidate.edits.length === 1 && + candidate.edits[0]?.violation.category === "unknown key" && + candidate.edits[0].violation.path.length === 1, + ); + const file = T763_FILES.find((candidate) => candidate.label === arm?.label); + if (arm === undefined || file === undefined) { + throw new Error( + "T7.6-4: T7.6-3 holds no arm with an unknown key at the top level " + + "alone, which T7.6-4's placements pair with T7.6-2(a)'s file: a " + + "harness defect", + ); + } + return { arm, file }; +})(); + +/** + * T7.6-4's three files beside the placement N `name`, a name of 7.6's + * grammar: T7.6-1's covered file (T7.6-2(d)'s), T7.6-2(a)'s file, and + * T7.6-3's unknown-top-level-key arm, each rendered with the specifier + * `name` and held to everything its own test's files are held to at module + * load (`composeFile`, `composeT763File`) — a deviation throws, a harness + * defect. Beside a canonical candidate the bytes are those tests' own + * records' (checked at module load below), so each placement's runs are + * runs of T7.6-1, of T7.6-2(a), and of that arm, N aside. + */ +export function placementFiles(name: string): PlacementFiles { + const problem = moduleNameGrammarProblem(name); + if (problem !== null) { + throw new Error( + `T7.6-4: the placement N ${JSON.stringify(name)} ${problem}; a ` + + "configuration file imports from a name of 7.6's grammar: a harness " + + "defect", + ); + } + return { + declaredExports: { + label: `T7.6-1's covered file, ${T761_FILE.label}`, + text: composeFile(t762Arm("(d)"), name), + }, + valid: { label: T763_TWIN.label, text: composeFile(t762Arm("(a)"), name) }, + unknownKey: { + label: `T7.6-3's arm, ${T763_UNKNOWN_TOP_LEVEL_KEY.arm.label}`, + text: composeT763File(T763_UNKNOWN_TOP_LEVEL_KEY.arm, name), + }, + }; +} + +for (const name of CANONICAL_MODULE_NAMES) { + const files = placementFiles(name); + const own: readonly (readonly [PlacementFile, T762File | T763File])[] = [ + [files.declaredExports, T761_FILE], + [files.valid, T763_TWIN], + [files.unknownKey, T763_UNKNOWN_TOP_LEVEL_KEY.file], + ]; + for (const [file, recorded] of own) { + if (file.text !== textFor(recorded, name)) { + throw new Error( + `T7.6-4: ${file.label} beside ${JSON.stringify(name)} holds other ` + + `bytes than its own test's record (${recorded.label}): each ` + + "placement stands in for the canonical one in a run of T7.6-1, " + + "of T7.6-2(a), and of T7.6-3's unknown-top-level-key arm (TEST-SPEC " + + "T7.6-4): a harness defect", + ); + } + } +} + +export const section76Tests: readonly ProductTestEntry[] = [ + T7_6_1, + T7_6_2, + T7_6_3, +]; diff --git a/test/suite/registry/traceability.ts b/test/suite/registry/traceability.ts index 6a988b32..6a775698 100644 --- a/test/suite/registry/traceability.ts +++ b/test/suite/registry/traceability.ts @@ -530,13 +530,16 @@ export const H7_TRACEABILITY: Readonly<Record<string, readonly string[]>> = { "T6.7-1": ["6.7", "14"], // T7-1: its name-casing probe the byte-wise, case-sensitive comparison of // the configuration entry's name (12.0: paths compare byte-wise and - // case-sensitively, no case folding). - "T7-1": ["7", "14", "12.6", "12.0"], - // T7-2: its `"XSPEC"` specifier arm the configuration import's module - // specifier compared without case folding (12.0: no case folding - // anywhere). - "T7-2": ["7", "2.4", "7.4", "11.6", "12.0", "14"], - "T7-3": ["7", "7.1", "7.2", "14"], + // case-sensitively, no case folding); its configuration-name arms + // `inventory`'s resolved `configuration` view under each name compared + // byte-identical to its twin's (11.6), as T7-2's twins are. + "T7-1": ["7", "11.6", "12.0", "12.6", "14"], + "T7-2": ["7", "2.4", "7.4", "11.6", "14"], + // T7-3: its empty-glob-list arms `inventory`'s resolved view — the empty + // group in its kind's list with `globs` exactly `[]`, as configured (11.6, + // 12.7's view form) — and its `sources`, each discovered file with its + // group memberships, none in the empty group (11.6). + "T7-3": ["7", "7.1", "7.2", "11.6", "12.7", "14"], "T7-4": ["7", "2.4", "11.6", "14"], "T7-5": ["7"], // T7-6: its single-casing arms the byte-wise, case-sensitive name tests @@ -552,6 +555,102 @@ export const H7_TRACEABILITY: Readonly<Record<string, readonly string[]>> = { // refusal its discovery must not meet — 14.25's absence at the read // scope's boundary, rule (c); its twin compares and outcomes are 7's. "T7-8": ["7", "14"], + // T7-9: (a)'s twin compares are 7's reading of the specifier as a static + // string literal spelled as written (2.4), its single-casing arm read + // byte-wise with no case folding (12.0); (b)'s scanner-rejected escapes, + // the file not well-formed (14.20), each answered with the 12.7 error + // document carrying 14.14's stable code; (c)'s twin compares are 7's — + // the specifier never resolved, read, or loaded, whatever it designates + // — its sealed directory staging a refused read (14.25) the product must + // not meet, that condition's absence, rule (c); (d)'s installs are 7's + // (no command's outcome depends, through the import, on the module or on + // whether a project installed it) and 7.6's (no name is privileged: the + // trap and the FIFO manifest staged under `trap`, `xspec`, and the name + // the package's manifest gives, read as T7.6-4(a) reads it), its + // representative commands' outcomes T7-8's. + "T7-9": ["7", "2.4", "7.6", "12.0", "12.7", "14"], + // T7-10: (a)'s clean outcomes and (b)'s findings are 7's (the rules of 4 + // and 14.15 reach the configuration only where a configured group — here + // a code group, 7.2 — discovers it, the configuration staying valid), + // 4's (a spec module import's binding and target, and a relative + // specifier designating a derived-file path: a `.xspec.` name or a path + // under `.xspec/`, 13.4, or the Markdown emit destination emission + // enables, 7.3), and 4.5's (the call, a value-level use it does not + // sanction, 14.18); each finding located byte-exactly (1.7) — by the + // import range of 11.4, or at the call — `path` null (12.7); `inventory` + // listing the configuration among its sources in that code group + // (11.6); the control's whole-file location answering `query edges + // --from` (11.1). (c)'s consequences of a discovered configuration's + // findings: the failing `build` modifying nothing (12.1); the gated reads + // reporting exactly its findings, exit 1, modifying nothing (13.3); the + // file move refused over the configuration's designation of the + // destination's would-be emit path (6.5's `refused-invalid-destination`) + // and, in the converse, refused as an invalid workspace (6.4's + // precondition, which 6.5 shares) while undiscovered its preview lists + // no edit in the configuration (6.6) and the move leaves it unrewritten + // (6.5); and a baseline whose discovered configuration fails validation + // failing `impact --base` and `review create --base` as the code-less + // usage error (6.3, 12.0), `review create` writing no session (10.7). + // (d)'s baselines: a baseline's configuration read as the current one's + // (7, 6.3) — `impact --base` over an undiscovered configuration + // importing from any specifier resolving, its impact information (9.3: + // categories with attributions, collapsed chains, deleted and added + // identities, impacted locations with witness edges and paths) the + // `"xspec"` twin's, the edited section `changed` (5.6); `review create + // --base` and `review status`, which reconstructs the recorded baseline, + // answering the twin's items (10.7); and a baseline whose configuration + // spells a scanner-rejected escape failing as the code-less usage error + // (6.3, 12.0). (e)'s configuration a spec group discovers, read as a spec + // source: 7.1's extension rule (14.19 concerning `xspec.config.ts`), 2.1's + // import rules (its named binding, its specifier designating no spec + // source: 14.15 at the import range) and 2.7's (its export statement: + // 14.16, the statement whole), each located byte-exactly (1.7), `path` + // null (12.7); `inventory`'s `derived` entry (13.1: a spec-group file + // without `.mdx` generating and emitting nothing, `module` and `markdown` + // null; `xspec.config.mdx` generating `xspec.config.xspec.ts`), the + // configuration named by `--config` on every invocation (12.0). + "T7-10": [ + "7", + "1.7", + "2.1", + "2.7", + "4", + "4.5", + "5.6", + "6.3", + "6.4", + "6.5", + "6.6", + "7.1", + "7.2", + "7.3", + "9.3", + "10.7", + "11.1", + "11.4", + "11.6", + "12.0", + "12.1", + "12.7", + "13.1", + "13.3", + "13.4", + "14", + ], + // T7-11: the members of TypeScript's global `Object` interface and + // `__proto__` as configured names (7: a name is barred only when empty or + // containing U+FFFD) — (a)'s groups, each loading and reported by + // `inventory` under its name with its glob and its source (11.6, 12.7's + // view forms); (b)'s profile and rule named `toString`, reported with + // their complete definitions (11.6, 12.7: every default and inferred kind + // explicit), the profile run by `coverage <name>` (8.2), the rule's + // violation reported by `check` under its name (7.5, 14.12, its `path` + // null, 12.7); (c)'s profile target and boundary and rule selector group + // naming them, resolving where such a group is configured (7.4, 7.5) and + // otherwise an unknown group (14.14, its error document's code and path, + // 12.7); (d)'s unknown profile names at `coverage <name>`, the plain + // usage error (12.0, its error document's code and path null, 12.7). + "T7-11": ["7", "7.4", "7.5", "8.2", "11.6", "12.0", "12.7", "14"], // T7.1-1: its wrong-case extension arm the byte-wise, case-sensitive // extension test (12.0: no case folding), and `inventory`'s `derived` // entry for the file without `.mdx` (11.6), `module` and `markdown` null @@ -574,6 +673,51 @@ export const H7_TRACEABILITY: Readonly<Record<string, readonly string[]>> = { "T7.5-4": ["7.5", "7", "14"], "T7.5-5": ["7.5", "14"], "T7.5-6": ["7.5", "12.1", "14"], + // T7.6-1: 7.6's type contract for the module's declared exports, in + // every covered setup, read from TypeScript's listing for T7.6-2(d)'s + // file, a configuration staged valid under 7 (a premise of the staging, + // asserted of no product), so it carries 7.6 alone. + "T7.6-1": ["7.6"], + // T7.6-2: 7.6's type contract for valid configurations, in every + // covered setup; the files are 7's declarative form, staged valid + // under 7, 7.3, 7.4, and 7.5 (a premise of the staging, asserted of no + // product), so it carries 7.6 alone. + "T7.6-2": ["7.6"], + // T7.6-3: 7.6's type contract for shape violations, in every covered + // setup, each arm paired with T7.6-2(a)'s file type-checking; the arms + // are (a) with violations of 7.6's type-error class applied (breaches of + // 7's, 7.4's, and 7.5's rules, a premise of the staging, asserted of no + // product), so it carries 7.6 alone. + "T7.6-3": ["7.6"], + // T7.6-4: 7.6's installation rules and Reach — copy, symbolic-link, and + // aliased installs alike, N across 7.6's grammar, the holding directory + // read along the physical path, other packages installed — through runs + // of T7.6-1, T7.6-2(a) with T7.6-3's unknown-top-level-key arm, and + // T7.6-6's exports and identity under each placement; its files are 7's + // declarative form staged valid under 7 (a premise of the staging, + // asserted of no product), so it carries 7.6 alone. + "T7.6-4": ["7.6"], + // T7.6-5: 7.6's Reach — the cases its four conditions leave open: an + // ancestor manifest giving an unrelated name, ancestor manifests whose + // types differ from the nearest one's, and a nearest manifest typed + // "commonjs" — and its Covered setups' reading of a project's kind, + // through runs of T7.6-1, T7.6-2(a) with T7.6-3's unknown-top-level-key + // arm, and T7.6-6's exports and identity beside the canonical placement; + // its files are 7's declarative form staged valid under 7 (a premise of + // the staging, asserted of no product), so it carries 7.6 alone. + "T7.6-5": ["7.6"], + // T7.6-6: 7.6's runtime contract (Runtime, through Reach's routes) for + // the module's exports and defineConfig's return, on every release E-1 + // provisions along each of Node.js's routes; it stages no configuration + // and asserts no other passage, so it carries 7.6 alone. + "T7.6-6": ["7.6"], + // T7.6-7: 7.6's runtime contract's effect clause (Runtime), in runs of + // T7.6-6's shape on every release E-1 provisions along each of Node.js's + // routes: the runs' output, writes, process state, and FIFOs, each + // absence paired with defineConfig returning its argument, its network + // clause the environment's (E-1); it stages no configuration and asserts + // no other passage, so it carries 7.6 alone. + "T7.6-7": ["7.6"], "T8-1": ["8"], "T8-2": ["8"], "T8-3": ["8"], @@ -1331,4 +1475,25 @@ export const H7_TRACEABILITY: Readonly<Record<string, readonly string[]>> = { // node compared as a canonical identity and presented under its current // identity and presence (10.4). "P-16": ["5.6", "6.3", "9.2", "10.4", "10.5"], + // P-17: 7.6's installation rules and Reach over drawn names, placement + // forms, holding directories, covered setups, releases, and routes, + // through runs of T7.6-1, T7.6-2(a) with T7.6-3's unknown-top-level-key + // arm, and T7.6-6's exports and identity; its files are 7's declarative + // form staged valid under 7 (a premise of the staging, asserted of no + // product), so it carries 7.6 alone. + "P-17": ["7.6"], + // P-18: 7.6's type contract over drawn configurations — valid ones + // type-checking in a drawn covered setup, each paired with a mutant + // holding one drawn violation of 7.6's type-error class failing to + // type-check there; its draws are 7's declarative form staged valid under + // 7, 7.3, 7.4, and 7.5, and its mutants breaches of those rules (premises + // of the staging, asserted of no product), so it carries 7.6 alone. + "P-18": ["7.6"], + // P-19 asserts 7's reading of the configuration's import: its specifier + // any static string literal (2.4), read as spelled and never interpreted, + // resolved, or loaded, so that every answer and every generated file is + // its twin's. Its commands' clean outcomes (12.1, 12.2, 12.3, 11.6) are + // the twin's staging premises, home coverage at T12.1-*, T12.2-*, T12.3-*, + // and T11.6-*. + "P-19": ["2.4", "7"], }; diff --git a/test/suite/section-16-p17.test.ts b/test/suite/section-16-p17.test.ts new file mode 100644 index 00000000..89fc29e5 --- /dev/null +++ b/test/suite/section-16-p17.test.ts @@ -0,0 +1,12 @@ +// TEST-SPEC §16 P-17 (installation names): thin Vitest wrapper over the +// registered property test — the identical body the certification runner +// executes against fixture products (C-2 "one code path"), placing the +// product's package directory under drawn names through H-2's module +// channel, with TypeScript 5.9.3 and on the Node.js releases E-1 +// provisions. Expected to fail as a diagnosed assertion failure until the +// product's package directory meets 7.6 (H-8). + +import { declareProductTests } from "./declare.js"; +import { section16P17Tests } from "./registry/section-16-p17.js"; + +declareProductTests(section16P17Tests); diff --git a/test/suite/section-16-p18.test.ts b/test/suite/section-16-p18.test.ts new file mode 100644 index 00000000..dad49d25 --- /dev/null +++ b/test/suite/section-16-p18.test.ts @@ -0,0 +1,12 @@ +// TEST-SPEC §16 P-18 (type contract over generated configurations): thin +// Vitest wrapper over the registered property test — the identical body the +// certification runner executes against fixture products (C-2 "one code +// path"), type-checking drawn configurations and their mutants beside the +// product's package directory, placed through H-2's module channel, with +// TypeScript 5.9.3. Expected to fail as a diagnosed assertion failure until +// the product's package directory meets 7.6 (H-8). + +import { declareProductTests } from "./declare.js"; +import { section16P18Tests } from "./registry/section-16-p18.js"; + +declareProductTests(section16P18Tests); diff --git a/test/suite/section-16-p19.test.ts b/test/suite/section-16-p19.test.ts new file mode 100644 index 00000000..eeabfde4 --- /dev/null +++ b/test/suite/section-16-p19.test.ts @@ -0,0 +1,10 @@ +// TEST-SPEC §16 P-19 (configuration import spellings): thin Vitest wrapper +// over the registered property test — the identical body the certification +// runner executes against fixture products (C-2 "one code path"). Expected +// to fail as a diagnosed assertion failure until the product conforms +// (H-8). + +import { declareProductTests } from "./declare.js"; +import { section16P19Tests } from "./registry/section-16-p19.js"; + +declareProductTests(section16P19Tests); diff --git a/test/suite/section-7-import.test.ts b/test/suite/section-7-import.test.ts new file mode 100644 index 00000000..f9030307 --- /dev/null +++ b/test/suite/section-7-import.test.ts @@ -0,0 +1,12 @@ +// TEST-SPEC §7 configuration import T7-9 (the import's module specifier, read +// as spelled and never interpreted, resolved, or loaded) and T7-10 (the +// configuration file as a source, only where a configured group discovers +// it): thin Vitest wrapper over the registered bodies — the identical bodies +// the certification runner executes against fixture products (C-2 "one code +// path"). Expected to fail as diagnosed assertion failures until the product +// conforms (H-8). + +import { declareProductTests } from "./declare.js"; +import { section7ImportTests } from "./registry/section-7-import.js"; + +declareProductTests(section7ImportTests); diff --git a/test/suite/section-7-names.test.ts b/test/suite/section-7-names.test.ts new file mode 100644 index 00000000..81e14027 --- /dev/null +++ b/test/suite/section-7-names.test.ts @@ -0,0 +1,11 @@ +// TEST-SPEC §7 configured names T7-11 (the members of TypeScript's global +// `Object` interface and `__proto__` as group, profile, and rule names): +// thin Vitest wrapper over the registered body — the identical body the +// certification runner executes against fixture products (C-2 "one code +// path"). Expected to fail as diagnosed assertion failures until the product +// conforms (H-8). + +import { declareProductTests } from "./declare.js"; +import { section7NamesTests } from "./registry/section-7-names.js"; + +declareProductTests(section7NamesTests); diff --git a/test/suite/section-7.6-ii.test.ts b/test/suite/section-7.6-ii.test.ts new file mode 100644 index 00000000..8ba3ebdf --- /dev/null +++ b/test/suite/section-7.6-ii.test.ts @@ -0,0 +1,16 @@ +// TEST-SPEC §7.6 T7.6-4, T7.6-5, T7.6-6, and T7.6-7 (the defineConfig +// module's placements and Reach's open cases — each standing in for the +// canonical placement in runs of T7.6-1, T7.6-2(a) with T7.6-3's +// unknown-top-level-key arm, and T7.6-6 — and its runtime — its exports +// and identity, and the absence of any effect — through H-2's module +// channel, with TypeScript 5.9.3 and on the Node.js +// releases E-1 provisions): thin Vitest wrapper over the registered +// bodies — the identical bodies the certification runner executes against +// fixture products (C-2 "one code path"). Expected to fail as diagnosed +// assertion failures until the product's package directory meets 7.6 +// (H-8). + +import { declareProductTests } from "./declare.js"; +import { section76iiTests } from "./registry/section-7.6-ii.js"; + +declareProductTests(section76iiTests); diff --git a/test/suite/section-7.6.test.ts b/test/suite/section-7.6.test.ts new file mode 100644 index 00000000..4a758381 --- /dev/null +++ b/test/suite/section-7.6.test.ts @@ -0,0 +1,10 @@ +// TEST-SPEC §7.6 T7.6-1, T7.6-2, and T7.6-3 (the defineConfig module, through +// H-2's module channel): thin Vitest wrapper over the registered bodies — the +// identical bodies the certification runner executes against fixture +// products (C-2 "one code path"). Expected to fail as diagnosed assertion +// failures until the product's package directory meets 7.6 (H-8). + +import { declareProductTests } from "./declare.js"; +import { section76Tests } from "./registry/section-7.6.js"; + +declareProductTests(section76Tests); diff --git a/test/vitest.config.ts b/test/vitest.config.ts index 2bf15cd5..b214db8e 100644 --- a/test/vitest.config.ts +++ b/test/vitest.config.ts @@ -22,6 +22,29 @@ import { defineConfig } from "vitest/config"; // invocable suite, never run in CI and never marked // skipped; this set is currently empty // +// The module channel (TEST-SPEC H-2, C-2, E-1; SPEC 7.6) takes its two inputs +// from the environment, which CI sets at setup and AGENTS.md shows how to set +// locally: +// +// XSPEC_PACKAGE_DIR the product's package directory, exactly as +// distributed, beside the built executable: the +// directory .github/scripts/pack-package.sh prints. +// The harness reads it when the built product's +// binding is made (test/helpers/subprocess.ts, +// `builtProductBinding`: the binding's +// `packageDir`, exactly as spelled). Unset or +// empty, no package directory is given (H-8, S-7). +// XSPEC_NODE_RELEASES_DIR the Node.js releases E-1 lists, which +// test/node-releases.json pins and +// .github/scripts/provision-node-releases.sh +// installs there, each release's executable at +// v<version>/bin/node; the harness reads both +// through test/helpers/node-releases.ts, the +// variable only when a run needs a release. A +// listed release missing there is a harness error +// for every run needing it (E-1, H-11, S-10), +// never a skip. +// // Shared harness machinery (H-3 output adapters, the workspace builder, the // subprocess and TypeScript-tooling drivers, the P-2/P-7 oracles) belongs in // test/helpers/. Certification fixture products (CERTIFICATIONS.md) and