Code Quality Tooling#
Two audiences share this page. The first half is the C++ formatter and linter
guidance that is true for any Kataglyphis C++ project (the configs live here,
the consumers copy them). The second half is this repository’s OWN quality
gates — the scripts under linux/scripts/verify_*.py, docs/scripts/ and
lint-*.sh that preflight.sh runs, the pre-commit hook runs in its fast tier,
and CI runs in full. Every gate ships as a set: the script, its allowlist, a
linux/scripts/tests/test-*.sh suite, a mutations.json entry that proves the
suite can fail, a preflight.sh slug, and a section below. The table of all
slugs with their proof status is generated, not hand-written — see
docs/code-quality-gates.md.
Installer import fixture scope#
Copied installer import tests set their own native build mode before sourcing the Rust preamble. An inherited cross-image mode with no target list cannot replace the expected missing/empty/partial/parse diagnostics with an earlier nounset error. The regression repeats valid cold imports under that ambient cross state; it does not install Rust, fetch archives or qualify any target compiler.
Git Bash symlink prerequisites#
Start Git and Bash with MSYS=winsymlinks:nativestrict when running the Hub’s
Linux fixtures on Windows. The default copy behavior does not satisfy tests
that inspect readlink, including the QNN ORT-home shim. Native symlink creation
must actually succeed; a missing privilege is a prerequisite failure, not a
skipped assertion. This does not make Windows a substitute for Linux-only gates.
See MSYS2’s symlink modes.
Consumer-hook fixtures compare Git’s canonical repository root in hook output.
Native Git may report C:/... for a fixture Bash created under /tmp/....
Preserved local proof workflows#
On Windows Git Bash, compiler-less CMake fixtures still need an installed
generator. If the default NMake generator fails at nmake -? before the cases,
select an existing Ninja with CMAKE_GENERATOR=Ninja for that check or commit
only. Preserve every target/compiler identity, assertion and mutation control;
this environment prerequisite proves neither compilation nor image acceptance.
Python module suites share linux/scripts/tests/python-proof-fixture.sh for module
loading and unittest execution. The wrapper requires raw success, a positive executed
test count and an exact successful summary; a zero-exit empty or failed suite is red.
Fixture-path environment state survives both passing and failing callbacks unchanged.
The WASM pass/cache entry points share allocation and companion staging; cache-specific
cases live in onnx_web_cache_cases.sh, and their expected flags come from the independent
wasm_proof_fixture.py. Copies of those suites must carry their shared companions.
These controls validate test transport, not the production gate’s own assertions.
The WebGPU runtime transport fixture supplies and asserts the FT dependency NumPy version and target architecture before checking every ORT interpreter branch. Both successful and failed factory callbacks must leave a completed transport; argument mutations prove these fixture assertions fail. Stub interpreters do not establish real dependency installation, factory registration or final image acceptance. The SDK dispatch fixture quotes its log redirection and checks complete child argv; space-containing temporary paths must leave no sibling file in the suite TMPDIR. The cache-launcher fixture redirects the shared helper’s actual image fallback, so a real image launcher cannot replace its expected bare fallback. Standalone library checks require a source command; a ShellCheck annotation alone is refused. These source checks do not establish unconditional execution inside a branch. GPU graph fixtures clear inherited accelerator/package defaults before their explicit CPU and conflict cases; a poisoned-image environment replay guards that isolation.
probe-rust-child-under-dart.sh NEW_OUTPUT compiles a Rust FFI fixture with the canonical
native supervisor and runs it in a real Dart VM with an active child. Default mode requires
all64 worker statuses, observed external supervisor reaping and correct raw failure, signal,
timeout and exec-error controls. It retains compiler/VM versions, JSON results and C compiler
cache statistics through lib/isolated-helper-compile.sh and capture-sccache-command.sh.
The same builder compiles the canonical HIP executable and fake runtime with ASan; nine
native-worker checks require normal teardown, including exit86 and an exact17-byte LSan
negative control. These checks execute while the bounded Dart child is live. The wrapper also
requires the real report: --teardown-negative-control uses a compiled early-exit86 fixture
which passes raw status checks but fails without sanitizer teardown. Its report-gate mutation
is caught against a green baseline. The local engine default seccomp profile passes this
actual probe; generic isolated-preflight security settings stay unchanged. Earlier opted-out
container proofs retain their own scope. The C supervisor is not sanitizer-instrumented.
The measured cache covers local C/C++ objects, not Rust or S3.
Both Linux source-CI jobs use .github/actions/native-worker-test-tools, which caches the
SDK by the existing Flutter archive checksum and calls ensure-native-worker-test-tools.sh.
The isolated bootstrap calls the same script. It requires working C/C++, Rust and sccache,
then reuses setup-flutter.sh --keep-cache to retain and execute the pinned bundled Dart.
The existing PE-tool step already supplies Rust/Cargo; test setup adds the cache package.
Fresh ordinary image installs still strip the archive cache. Fixture/archive and YAML wiring
checks do not prove a hosted CI run or the entire fresh isolated bootstrap.
The host parity verifier uses the same parse_cli_value_options owner for its value flags;
its bound +CALLBACK retains help alias binding, complete remaining argv, active errexit and
unknown-option exit. Legacy status-count callbacks retain their existing contract.
The frozen help-receipt matrix and explicit empty/spaced-value controls cover that reuse.
--expect-status-loss selects the original failing runner; --idle-reaper omits the Dart
child. The shared Rust suite also runs this real VM path and retains failures before fixture
cleanup. Use a bounded owned-container unit with the cleanup hook below. These source tests
prove no installed bridge or GPU inference; see the
external-reaper failure.
Compiler-tool fixtures normalize generated source/output basenames, independently of the temporary root.
test-compiler-tool-toggles.sh keeps a synthetic path-with-spaces control outside /tmp; its mutation
restores the old hard-coded prefix and must fail. This tests the argument recorder, not real cache hits.
Regular operational drivers live under linux/scripts/ and are versioned with their tests. The operational toolkit also preserves full-preflight sealing, compiler/SDK qualification, cache diagnostics, checkpoints and authorized host cleanup; its inventory maps former session helpers to their canonical owners.
The operational memory appender shares host transport and evidence utilities, checks controller absence and preserves exact prefix/append snapshots. Its entry, two companions and independent fixture belong to strict type and parameter/return scopes; the synthetic type fixture checks every added path. File locks and name observations do not exclude uncooperative writers or make file/proof updates crash-atomic.
Shared Python test siblings also remain in the type checker’s search roots. The independent synthetic import chain reaches that directory; removing the root must fail without suppressing unresolved fixture imports or reducing file coverage.
Reuse these tools instead of reconstructing a scratch script on each session. Keep each run’s
inputs and evidence under ignored logs/; choose a new directory for a new attempt.
python3 linux/scripts/run-isolated-preflight.py --revision HEAD \
--output logs/test-results/preflight-001 --name ant-preflight-001 --engine nerdctl --jobs 4 --memory 12g
The runner preserves a complete Git clone at the selected commit in source/, even when the
working tree has later edits. It uses that commit’s pinned Ubuntu base and versioned
isolated-preflight/bootstrap.sh and worker.sh, then runs every make preflight slug as a
nonroot user. The engine init reaps orphaned descendants so strict process-group cleanup can
observe disappearance; nerdctl requires tini on the host PATH. A timeout wrapper alone does not
reap adopted children. This keeps the default seccomp profile and capabilities unchanged.
Setup reuses the canonical uv, PowerShell, PE-tool and locked quality-tool installers;
en_US.UTF-8, Python headers, pip and Chromium are checked prerequisites. Setup also installs
free-threaded CPython from the same PYTHON_VERSION pin and passes its managed path through
the clean worker environment. Version drift, a GIL-enabled interpreter or missing FT headers
fails before the gates; the real extension/GIL case must run rather than print its optional skip.
No selection or shard
knob is inherited. preflight.log preserves raw output; run.json, container.cid and reports/
retain source, base digest, bootstrap hash, tool versions and results. This is a local gate proof,
not image acceptance or a hardware test. An apt repository or tool download must remain available.
For a cached family image, pass --image IMAGE and optionally --native-tools-cache PREFIX.
The latter mounts the retained SDK prefix read-only at /opt/preflight-native-tools; the same
pinned installer validates reuse. This avoids reconstructing the runner and its report permissions.
The receipt records the explicit image selection and cache path; such a replay does not establish
fresh Ubuntu provisioning or a newly downloaded SDK. nerdctl still requires host tini on PATH.
For a long unit, generate a fresh UUID hex token before launch and pass --run-id TOKEN so its
independent ExecStopPost cleanup uses the same owner label, token and CID from the start.
Malformed tokens refuse before allocating a run; do not reuse a prior invocation’s token.
The source bind is read-only and separate from writable reports. Rootless uid mapping requires a
temporarily writable report directory; cleanup restores mode 0755 and never changes bind ownership.
Only containers bearing this invocation’s random ownership label can be removed. Worker failures
keep their raw status; an interruption leaves an unobserved command status null and records its
signal exit separately. Missing container evidence or failed cleanup cannot pass. For a user unit,
wrap the same command with systemd-run --user --unit=ant-preflight-001 --property=RuntimeMaxSec=14400 --property=TimeoutStopSec=120; the latter allows bounded cleanup.
If argv contains literal shell expressions, such as a Bash array in bash -c, add
--expand-environment=no. Host quoting preserves argv for systemd, whose own expansion
otherwise runs before Bash; see the observed failure.
Container payloads may live outside the starter unit; verify their owned IDs are stopped or absent.
A native detector survived its starter timeout; preserve the failed evidence and use an owned-container
cleanup runner before another long probe (recovery).
cleanup-owned-containers.py is the independent ExecStopPost hook for long container units.
Generate one fresh uuid.uuid4().hex token before starting, use it in a dedicated
org.kataglyphis.* ownership label on nerdctl run, and pass that same label, token and CID file:
python3 linux/scripts/cleanup-owned-containers.py --engine nerdctl \
--owner-label org.kataglyphis.local-proof --run-id "$proof_run_id" \
--cidfile "$proof_output/container.cid" --output "$proof_output/cleanup.json"
Put the absolute command in the unit’s ExecStopPost= property, without a leading -, and use
TimeoutStopSec=300. Quote paths inside the property as systemd arguments, and retain
--expand-environment=no. The hook then runs even after a killed starter. A manual call after
handoff does not provide that guarantee. Keep the container foregrounded, without a restart policy;
bound the payload itself as well. The hook checks full IDs, live ownership labels and any recorded
CID before a destructive command, then verifies removal against the global container inventory.
--retain stops instead of removing and requires exited/created, Running=false and PID0, preserving
failed filesystems. Engine errors, false-success commands or late owned containers fail cleanup.
An existing output is refused before touching containers; choose a fresh receipt for each invocation.
Cleanup success proves stopped-or-absent only, never a successful workload. The shared owner module
also serves isolated preflight’s finally cleanup; copy owned_containers.py and host_commands.py
beside either entry point. A final receipt and terminal unit state must both be checked.
The local lifecycle proof covers raw workload exits0/37 and SIGKILL starter timeouts with both
removal and stopped-container retention. It does not exercise a model, GPU or published image.
For rootless nerdctl, prepare a private client directory containing config.json
with {"auths":{}} and pass its path as DOCKER_CONFIG for the invocation. The
base is public and pinned; this avoids a Windows credential helper inherited from
the user’s Docker configuration. Select the native Linux CLI and wait for the
existing rootless daemon to become ready. Preserve the user’s authentication and
context files. A hanging preparatory pull is not a started preflight; retain its
failure before a fresh invocation (observed failure).
python3 linux/scripts/watch-build-units.py --unit rebuild-sequence-37.service \
--chain-status chain-status-nvidia.json --log logs/build-logs/rebuild-sequence.log \
--output logs/test-results/build-watch.jsonl --timeout 7200
The watcher only observes existing user units. Result=success on a running unit is not terminal.
Its own timeout leaves producers running. Optional --preflight-container ant-preflight-001
executes the versioned preflight-status.py; that probe locates mutation and script-test outputs by
content, so a changed job order does not silently select another gate. Observations do not create
acceptance receipts. Both Python host drivers require their sibling host_commands.py; the watcher
also needs preflight-status.py. Preserve these companions when copying a tool.
Use linux/scripts/source-ci.py for source CI evidence
and linux/scripts/seal-mutation-unit.py --unit NAME.service --manifest MANIFEST --log LOG --output PROOF
to seal a completed local mutation run before stopping its user unit. --selected requires the exact
selected manifest; the tool compares every executed ID, refuses duplicates, unloaded units and live
processes, and preserves terminal evidence even when stopping fails. Success after stopping is written
separately to PROOF-stopped.json; a terminal-only file is not a completed seal.
capture-sccache-command.sh NEW_OUTPUT -- COMMAND [ARG...] preserves text/JSON cache counters and both
statuses on every command exit. Text counters also go to stderr. A failed command retains its raw
status; failed stats turn an otherwise successful command red. Both shell entry points use lib/cli-value-options.sh and its logging companions for help/argument validation.
Run the cache wrapper inside the image containing sccache; it neither starts a unit nor selects a container. Do not reuse an evidence directory.
For the real tiny AMD ownership regression, run inside the selected image with GPU access:
bash linux/scripts/capture-sccache-command.sh /evidence/ownership-001 -- \
bash linux/scripts/probe-migraphx-ownership.sh /evidence/ownership-001 \
/work/migraphx-001 /work/migraphx-prefix-001 /models/relu.onnx
The model must have one float x input and y output, shape [1], implementing Relu. Use absolute
paths and separate work/prefix/output paths for each attempt. The runner calls the production builder,
compiles shared/native/tests/ort_plugin_runtime_probe.cpp through the guarded cache launcher and
requires CPU plus two V2 GPU sessions with ASan/LSan enabled. The versioned runtime audit requires
three distinct profiles and delegates operator/per-run validation to shared/python/verify_ort_profile.py;
--device migraphx-plugin selects the plugin’s MIGraphX profile name. This is a tiny session and
ownership proof, not full media acceptance, finished packages or detector parity. Old-image and
standalone-module evidence cannot certify a later image. Optional final CORE_DIRECTORY selects the
image’s existing cache/Python companions; the default is /opt/scripts/core.
For a native ORT plugin load/export check, use the permanent probe.
For another consumer platform, preserve the full contract with the plan command.
test-proof-workflows.sh uses an isolated Git fixture and a fake engine to prove source preservation,
raw statuses, container ownership, report permissions and native-probe cleanup; it does not build
images, load a real native module or run a GPU. The corresponding mutations must fail assertions.
Unix mutation commands each receive a fresh XDG_CACHE_HOME, retained until their children have
been reaped. Parallel PowerShell processes otherwise share a .NET startup profile; a corrupt profile
can fail an unmodified baseline with exit 134 and a truncated assembly identity. This matches
PowerShell issue 26528 and
.NET runtime issue 121977. The observed local
profile was removed with its disposable container, so its bytes do not independently prove that
cause. The guard leaves HOME, explicit caches such as UV_CACHE_DIR, raw exit statuses and
Windows environment policy intact. It isolates separate commands on Unix; it does not serialize
PowerShell children inside one command or fix the .NET implementation. test-mutation-cache.sh
checks overlap, timeouts, output and cache lifetime; both cache mutations must bite. No automatic
retry turns a failed baseline green.
Shell fixtures pass environment assignments as individual quoted arguments. The QNN Community fixture exercises plain and spaced PATH/cache/extract values with fake archive bytes. Its three unquoting mutations must fail the planted spaced case even on a clean Linux PATH; these checks do not prove a real SDK transfer or hardware inference. See the failure.
C++ formatters and linters (clang-format, clang-tidy, cmake-format)#
The commands, the traps and the cadence — everything that is true for any
Kataglyphis C++ project. Adopted here 2026-08-07 from a consumer that had it all
in its own docs/code-quality.md; what stayed behind there is that project’s
measured drift figures and its own build-script wiring.
The configs these tools read (.clang-format, .clang-tidy,
.cmake-format.yaml, gcovr.cfg) are owned by this repo too — see
shared/config/README.md
for why they are copied into consumers rather than referenced.
Where the tools are#
LLVM is commonly installed on Windows hosts but not on PATH:
$CF = 'C:\Program Files\LLVM\bin\clang-format.exe'
$CT = 'C:\Program Files\LLVM\bin\clang-tidy.exe'
On Linux there is no equivalent resolution step, and
linux/scripts/lib/code-quality.sh is not one: it is a library you source,
not a wrapper that locates binaries. It invokes bare clang-format -i
(in code_quality_run_clang_format) and bare clang-tidy (in code_quality_run_clang_tidy) straight
off PATH, and there is no CODE_QUALITY_*_BIN knob among its caller
variables (table below). Nothing checks for the binaries first either: the
library sources has_tool/require_tools from 01-core/tool-checks.sh but
calls neither for the LLVM tools, so a missing LLVM tool surfaces as the shell’s
own command not found at the call site. Put LLVM on PATH yourself.
cmake-format is the one tool the library will provision: when it is not on
PATH, code_quality_ensure_cmake_format (code-quality.sh) creates a venv
with uv at CODE_QUALITY_VENV_DIR and installs the hash-locked
quality/cmake-format project through 01-core/python_uv.sh. The installer
exports the lock and installs its packages without removing unrelated venv content.
CODE_QUALITY_UV_VENV_CREATE_SCRIPT and CODE_QUALITY_UV_INSTALL_REQUIREMENTS_SCRIPT
override it. Missing uv, project files or a stale lock fail. The old
linux/scripts/cmake-format.requirements.txt remains a compatibility export while
existing consumers migrate; it must not be removed before the consumer inventory permits it.
CI runs bash linux/scripts/verify-uv-exports.sh to compare both legacy exports
byte for byte against their locked projects; Renovate regenerates them during updates.
clang-format#
Works on the host with no build directory — it needs only the source and
.clang-format.
Scope matters. git ls-files '*.cpp' from a repo root also matches vendored
third-party code under third_party/, which is not yours to reformat. Always
scope to your own sources:
$own = git ls-files 'Src/*.cpp' 'Src/*.hpp' 'Src/*.ixx' 'Test/*.cpp' 'Test/*.hpp'
Check only (CI-style, writes nothing, non-zero exit on drift):
$dirty = @()
foreach ($f in $own) {
& $CF --dry-run --Werror $f 2>&1 | Out-Null
if ($LASTEXITCODE -ne 0) { $dirty += $f }
}
"$($dirty.Count) / $($own.Count) files need formatting"
Apply in place:
foreach ($f in $own) { & $CF -i $f }
Only what you touched — the low-risk everyday version. Reformatting a whole tree at once buries real changes in noise:
git diff --name-only HEAD -- 'Src/*' 'Test/*' |
Where-Object { $_ -match '\.(cpp|hpp|ixx|h)$' } |
ForEach-Object { & $CF -i $_ }
clang-tidy#
Needs compile_commands.json. Two traps that cost real time:
Container paths. A database generated inside a build container records the container’s workspace root (e.g.
C:/ws). Running host clang-tidy against it fails withLLVM ERROR: Cannot chdir into "C:/ws/<build-dir>". Rewriting the paths into a scratch copy gets it running:$db = "$env:TEMP\tidydb"; New-Item -ItemType Directory -Force $db | Out-Null (Get-Content <build-dir>\compile_commands.json -Raw) ` -replace '<container-workspace>', '<host-repo-root>' | Set-Content "$db\compile_commands.json" -NoNewline & $CT -p $db --quiet <a-source-file>
C++23 modules. Even with paths fixed, translation units that
importa module fail (cannot open file '...X.ixx') because module BMIs still reference the container layout. A project’s clang-tidy wrapper should therefore skip files using module syntax. What remains checkable is the non-module surface — still worthwhile:cppcoreguidelines-special-member-functions,modernize-use-trailing-return-typeand friends fire on real code.
The clean alternative is to let the build run clang-tidy, where paths are
consistent by construction. Invoke-ClangTidyFixStep also skips any source
file with no compile command in the database: an option-gated subdirectory is
not compiled, so tidy cannot parse its files and would fail the step on their
first include.
Suggested cadence#
Per change: format the files you touched (the
git diffvariant).Weekly / before a PR: full check across your own sources; fix what is yours.
Periodically: a clang-tidy pass over the non-module TUs. On Linux, drive it from
linux/scripts/lib/code-quality.sh— a library your project’s own quality script sources, exposingcode_quality_run_clang_format,code_quality_check_clang_format,code_quality_prepare_compile_db,code_quality_run_clang_tidy,code_quality_run_iwyuandcode_quality_run_cmake_formatas separate steps to call in whatever order it wants. It is not a command you run: it has nomain. Inside this repo only thecmake-formatpreflight slug (check_cmake_formatinpreflight.sh) and05-frameworks/flutter/flutter_checks.shsource it, for the cmake-format and tracked-file helpers; pershared/config/README.mdthe consumers of its C++ steps are the downstream C++ projects.
include-what-you-use, a report on the files without modules#
The image’s include-what-you-use is built on an older clang than the build, so it cannot load the build’s
module files: a unit that declares or imports a module fails with “PCH file uses a newer PCH format”. The
myproject_ENABLE_IWYU option is OFF, as it only ever set the property on the INTERFACE target
myproject_options, which reaches no compile. Instead code_quality_find_iwyu_files <root>... lists the units
without a module declaration or import, and code_quality_run_iwyu <compile-db-dir> <log> <file>... runs
iwyu_tool from PATH over them (CODE_QUALITY_IWYU_ARGS) and prints how many files have suggestions. It is a
report: suggestions stay green, and only a unit IWYU did not grade is red (owner, CON295 (a), 2026-11-23). The
driver’s exit status cannot say which, so each requested unit must appear in the log with an include list or as
correct; a missing driver, a driver that stopped early and a unit absent from the compile DB all fail that count.
The failure mode to watch for#
A clang-format check that reports a deviating count without failing the build lets drift grow indefinitely while every build stays green. One consumer went from 72 to 142 deviating files that way. If you wire the check into a build, decide explicitly whether it gates — and if it does not, track the number somewhere a test can assert on, so the growth is at least visible.
Reformatting a large accumulated drift is a decision, not a chore: it
touches most of the tree in one commit and collides with in-flight work. Do it
deliberately, ideally right after a merge point, and add the commit to
.git-blame-ignore-revs so history stays readable.
Where the gates run#
Four places run the gates, deliberately not the same set.
when |
what runs |
cost |
|---|---|---|
every |
|
8.0 s one-file, 27.2 s for a 43-file commit (measured 2026-09-04) |
every |
|
16 to 339 s over four replayed commits with 10 to 481 entries (measured 2026-11-04) |
before a rebuild, by hand |
|
minutes (the secret scan alone is ~170 s) |
every push |
|
CI |
Install the hooks once with make hooks: it sets core.hooksPath rather than copying into
.git/hooks, so both hooks are version-controlled and arrive with a clone. git commit --no-verify bypasses the commit hook; then run make preflight before pushing.
The hook is a subset and its mutation step a sample on purpose: a pre-commit gate that takes
minutes teaches everyone to type --no-verify. A sample never reports as full coverage; it prints
how many of how many it ran (§ The pre-commit hook’s cost budget).
A recipe names the narrowest command that still bites (-k <section> through t_sections,
Invoke-HarnessSuite.ps1 -Only <suite>). The unfiltered suite keeps the same cases in preflight,
and a pick naming no section fails.
The hub’s mutation jobs take shard K of a cost plan (--shard-costs) that keeps each test command
on one shard, so its baseline runs once per round. Refresh the table from a green run’s cost lines
(the shard plan). When the gate gets slow, fix the suite that got slow; never
raise a timeout or sample in CI (§ The mutation gate in CI, sharded).
bash linux/scripts/preflight.sh is the single source of the no-build gate list. The inventory is
its KNOWN_SLUGS array; do not enumerate it in a page. A new gate needs a KNOWN_SLUGS entry and a
run_check line, which test-preflight-slugs.sh enforces. Then regenerate the registry with
python3 linux/scripts/verify_gate_registry.py --write, and name its mutations <slug>.<kebab>.
The commit hook runs a subset through PREFLIGHT_ONLY / PREFLIGHT_SKIP; never copy the check
list into a new caller. Slugs, suites and shellcheck runs go side by side; PREFLIGHT_JOBS=1,
RUN_TESTS_JOBS=1 and LINT_SHELL_JOBS=1 run them in turn
(§ The gates run side by side). On a Windows host, run
MSYS=winsymlinks:nativestrict PREFLIGHT_PYTHON="uv run --no-project python" bash linux/scripts/preflight.sh.
Manifest sizes, per-prefix mutation counts and the hook’s own slug list are pinned by
linux/scripts/tests/test-doc-numbers.sh, which reads them out of mutations.json and the hook
and fails on drift (§ Doc numbers are derived). Wall-clock figures
cannot be pinned: write them with the date they were measured, or leave the digit out.
The develop-red watch closes what can no longer pass, never by hand. Prove a change to it with
develop-red-selftest.yml
(A red develop opens an issue).
lint-shell.sh without --root scans linux/ansible/ as well as the build and host trees, and
--list-files owns the warning ratchet’s scope. Keep new Ansible shell scripts in both scans. The
scope suite proves their selection.
This repository’s own gates#
The sections below are the design notes per gate: why it exists (with the
numbers measured when it was added), what it checks, how to fix a finding, and
which suite and mutation guard it. Slugs in parentheses are the preflight.sh
names; PREFLIGHT_ONLY=<slug> bash linux/scripts/preflight.sh runs one gate alone.
Four slugs joined on 2026-09-03, in the order their sections appear below:
gate-registry (the meta-gate — is every other slug provable at all? — plus the
derived table), code-complexity (decision paths and nesting depth, beside
code-size), dead-functions (a shell function nothing anywhere names), and
shellcheck-warnings (a per-file, per-code ratchet over the advisory tier
lint-shell.sh prints but never gated). The same day code-dupes and
env-knobs gained the missing bookkeeping halves of their contracts — an
unrecorded shrink and a knob nobody reads any more now fail — and mutations
learned to refuse a bite recorded while that suite was already red. Before them
(2026-09-01), pkg-names resolves every package name the tree asks apt for
against the live Ubuntu indices, and advert-keys fails when a
version-shaped ENV/ARG is neither checked by the runtime smoke nor excused
with a reason. Before those (2026-08-31), code-dupes — token-normalised
duplication over shell, Dockerfiles and the Markdown outside docs/, so it
catches renamed clones the prose gate cannot see; deliberate twins are
budgeted in docs/scripts/code-dupes.allow. The checks
preflight.sh runs are its KNOWN_SLUGS array; which of them a suite or a
mutation actually proves is generated into docs/code-quality-gates.md, never
hand-maintained here.
The gates run side by side#
preflight.sh records the selected slugs and runs them PREFLIGHT_JOBS at a time (default: one
per CPU) through linux/scripts/lib-ordered-jobs.sh. Two run alone: cmake-format first, because
it builds logs/tools/cmake-format-linux in the tree the other gates walk, and mutations last, because it
copies the tree. Python writes no bytecode meanwhile. Each slug’s output prints whole, in
registration order, so the log reads like a serial run, only sooner. One level down the same runner
drives run-tests.sh (RUN_TESTS_JOBS, suites in name order, same totals), and lint-shell.sh
runs one shellcheck per file LINT_SHELL_JOBS at a time and refuses a run that did not report on
every file. wsl-quality.sh check --jobs N passes the same limit to both nested runners. Each
knob set to 1 restores the serial path. The copied runner fixture clears the inherited
RUN_TESTS_JOBS before applying its case arguments. Its default case supplies serial and
invalid outer caps so either value leaking into the child fails the rendezvous assertions.
The runner’s leftover check (AGENTS.md, no ghosts) cannot see a suite that writes /tmp by name
or clears TMPDIR. Hadolint and actionlint keep their caches in the run’s outer TMPDIR.
Host-executed consumer probes use /usr/bin:/bin and explicit fixture-tool directories.
Their real probe program, fact output and verdict assertions remain in use. This keeps
free-threaded interpreter discovery from scanning unrelated Windows PATH directories
and prevents unrelated tools in the caller’s PATH from affecting the fixture. A harmless host cargo-audit marker
proves isolation; a mutation introduces that one directory and must fail. The outer
runner retains its inherited PATH, including spaces for the QNN fixtures. These tests
do not establish live SDK, image or GPU execution, and the 300-second mutation budget
is unchanged.
PREFLIGHT_ONLY=script-tests bash linux/scripts/preflight.sh runs the Bash suites locally;
Linux x64 CI runs them on pushes and pull requests. Discovery fails when there are no suites,
and a host that permits skips must still run at least one suite successfully.
Wheelhouse failure receipts include GNU find’s exact diagnostic quoting. Their child probes
use C.UTF-8, matching the recorded text, and run beneath both C and C.UTF-8 parent
locales. This keeps LC_ALL=C runs deterministic while preserving the original stdout,
stderr and exit-status receipts. The fixture tests do not build wheels or images.
The scheduler tracks supervising workers before releasing their commands. Its
cancellation marker also covers launches in progress; cleanup joins only recorded
workers and stops their watchdogs and command groups. Nested runners receive a
chance to run their own exit cleanup before forced termination. A lost supervisor
or failed cleanup must reach the job report as an error. Caller-owned background
jobs and returning or ignored signal handlers retain their existing policies.
When a returning INT or QUIT interrupts the command wait, the supervisor waits
again even if the child has just exited, so the report records its actual status.
Supervisor and watchdog diagnostics append to the job log, so a lingering child
cannot retain the caller’s stdout or stderr pipe after the job report finishes.
Commands append too, preserving diagnostics written before the command starts.
Cleanup from a signal or EXIT trap checks the process group until it disappears
without calling Bash wait again. A second wait can reenter the one that the
watchdog interrupted, leaving the supervisor and its command alive after the
timeout marker. test-run-tests-reaping.sh caps its own joins below the mutation
baseline timeout and names the case reached when a regression stalls.
An ignored INT is also retained by the supervisor, watchdog and scheduled command
when a signal reaches their process groups; otherwise an interrupted wait can report 130
despite its caller ignoring INT.
The lifecycle fixtures use bounded local processes; deliberately detached sessions
and kernel signal-delivery failures are outside their coverage.
A background job ignores SIGINT, so the runner hands each command its SIGINT back:
test-renovate-fleet.sh tests its own Ctrl-C handling and failed only side by side until it did.
A suite proves that jobs ran at once by a rendezvous, never by comparing seconds: with
meet_peers (linux/scripts/tests/meet.sh) each job marks itself started and waits for its
peers, so a loaded host slows the run but cannot turn the verdict. Wall-time comparisons went red
in three of thirteen side-by-side runs.
run, |
in turn |
side by side |
|---|---|---|
|
754 s |
~106 s |
|
1125 s |
123 s |
|
77 s |
14 s |
Other agents’ builds shared the host during both columns, so read them as ratios.
Python that lives in shell heredocs#
775 lines of Python sat inside linux/scripts/**/*.sh heredocs as of 2026-09-01
— invisible to lint-python.sh, which only globbed *.py. A syntax error or an
undefined name in one of those blocks would have shipped silently.
linux/scripts/extract_embedded_python.py writes each block to a temp file that
the lint gate then includes. Two distinctions are load-bearing:
A directly-executed block is extracted alone.
python3 - <<'PY'and"$py" - <<'PY'are complete programs. Blocks that arecated (cat <<'PY_TAIL') are FRAGMENTS of one program assembled later — see_smoke_genai_py_verdictin06-packaging/smoke-common.sh— so a family of two or more sharing a marker prefix is concatenated in file order and a lone fragment is dropped, because linting one alone reports undefined names for variables the earlier fragment defines.ast.parsedecides whether a family is Python at all. APY-ish marker is a naming convention, not a guarantee: acat <<'TPL_PY_HEAD'config template assembles into something that does not parse, and is left out rather than guessed at. Without that check the gate reddens on files that are not Python.A comment cannot open a heredoc. Prose that QUOTES an opener (
# use python3 - <<'PY') is not one; the extractor skips lines whose first non-blank character is#.The opener line may carry trailing redirections. The first version of the extractor required the heredoc token to end the line, so it silently skipped
"$py" - <<'PY' 2>/dev/null || echo ...— the shipped-truth probe in06-packaging/smoke-runtime-image.sh, i.e. the largest block that mattered.
Both shapes are pinned in linux/scripts/tests/test-embedded-python-extract.sh,
and the coverage was proven by injecting an undefined name into a real heredoc
and watching the gate go red.
The extractor’s file list has TWO halves, and each is now pinned separately:
find linux/scripts -name '*.sh' (the probe.sh cases plus
python-lint.embedded-file-discovery, which NARROWS the find rather than deleting
it) and find linux/host-config/git-hooks -type f (the git-hook cases plus
python-lint.hook-half-of-discovery). The second half exists because a git hook
cannot carry a .sh suffix; the pre-commit hook’s _mutation_plan is ~15 lines of
embedded Python that would silently leave the gate if that half were dropped.
tests/test-python-lint-gate.sh asserts on the mapped-back shell file and line
(linux/host-config/git-hooks/pre-commit:4: = opener line 3 plus body line 1),
not on the exit code, so
a fixture that never reaches ruff cannot pass the case by accident.
The consumer aggregator now passes its tracked first-party .py and .sh files to the
same lint entry point. Before this, its explicit .py arguments disabled heredoc
extraction, and a shell-only consumer skipped Ruff entirely. An extractor failure or
unreadable selected script fails the lint gate; a valid scan with no embedded Python
passes. Only the heredoc extraction is batched to stay under Windows’ command-line limit;
ruff still gets every file on one command line (CON334). The extractor cannot identify Python assembled
dynamically at runtime.
The fatal Ruff tier also selects B012 (a return, break or continue in finally can
silence an exception) and B023 (a loop variable captured by a closure can bind too late).
It applies to tracked Python and extracted heredocs. The default hub sweep makes the full
Ruff default ruleset fatal; explicitly targeted and named-root calls keep the consumer
adoption tier advisory. test-python-lint-gate.sh checks both defects, a safe form and a
default-rule finding outside the focused selectors. The
python-lint.exception-return-required and python-lint.loop-closure-required
mutations remove each selector independently and must fail.
Proving a gate can go red#
Three slugs read “proven” in the registry while nothing could turn them red:
python-lint, comment-size and masked-decls. Each was proven only by a suite
that asserted the gate’s text — that lint-python.sh mentions the extractor,
that verify_comment_size.py contains .rstrip() — so neutering the verdict
(return rc → return 0) survived the whole suite.
A real negative proof has four parts, and the fixture pattern the other suites already use supplies all four:
A throwaway tree. All three gates derive their root from their own path (
lint-python.shcds to it), so a copy under<tmp>/linux/scriptsscans only what the case plants — never the repo.An offender the gate MUST reject, asserted on the exit code as well as the message. Asserting only the message is how these tests went hollow.
The clean counterpart it must accept with rc 0, so the offending case is not passing for some unrelated reason.
A
mutations.jsonentry that neuters the verdict, proven to make the suite fail.
tests/test-prevention-gates.sh does this for comment-size (a 2-line block
fails naming file:line 2 lines; one line passes; one case per language and per
data shape) and for masked-decls
(local x="$(date)" fails naming the variable; the declare-then-assign split
passes), plus the two-way allowlist contract for both — frozen at its own key the
offender passes, and that same row against the clean subject is STALE. The
subjects are built with printf, not written as literal lines: a real
local x="$(cmd)" in the suite would be a new offender for the gate it tests.
tests/test-python-lint-gate.sh covers the lint tiers. The shared gate tier
(ruff check --select E9,F63,F7,F82,B012,B023) rejects an undefined name, syntax
error, silenced exception or late-bound closure. The default hub preflight sweep also rejects
F401, F841, RUF059, FURB167, ISC004, UP032 and B009 in Python files and extracted shell heredocs;
the regex rule rejects abbreviated re.M, re.S and re.I flags after the 27
existing uses were spelled out. The string rule requires parentheses around the
eight intentional adjacent literals in collections. Thirty string .format() calls
were converted to f-strings before UP032 became fatal. Three constant-name
getattr calls now use direct attributes, and B009 rejects regressions; dynamic
attribute names are unaffected. Explicit
targets and named roots retain their advisory adoption tier. A fixture adds an F541 finding
outside the focused selectors and proves the default full ruleset fails. The unused-assignment
fixture asserts the focused hub unused-binding verdict, so the default sweep cannot hide a
missing F841 selector. Linux CI also
enforces EXE001, which requires a Python shebang file to have its executable bit set. The
fixture writes RUFF_VERSION
from 01-core/tool-pins.env into its own tool-pins.env, so when no ruff is on
PATH it bootstraps the same pinned uvx ruff@<pin> the repo does (a ruff already
on PATH is preferred by the gate and the fixture alike).
The same suite pins the gate’s target set, which the tier cases cannot see: a
tree carrying all three shapes at once — a plain .py, a python3 - <<'PY' block
opened on line 2 of probe.sh, and a cated TPL_PY_* family holding nginx
config — must go red for a gate-tier error in either of the first two and stay
green otherwise. The heredoc finding is asserted down to linux/scripts/probe.sh:3:
(opener line 2 plus body line 1), and the temp name probe__2.py must not
appear — which is how a ruff diagnostic against a temp file maps back to the
shell file and the line it came from. Switching the extraction off, narrowing the find that
feeds it, or dropping the parse check each turn one of those three assertions red;
before this, all three were silent — every suite stayed green while ~775 lines
left the gate. The suite builds its fixture openers as printf ARGUMENTS so it is
never itself an extraction target.
Windows Ruff paths and source-map keys normalize separators before the finding is
mapped back to its shell file and source line.
The relabeler forces UTF-8 for its own output: Windows Python can inherit cp1252 and fail while printing a non-ASCII source line, leaving the advisory report incomplete. The suite forces cp1252 and checks that a Unicode Ruff diagnostic survives.
Mutations: comment-size.verdict-discarded, comment-size.limit-not-enforced,
comment-size.every-language-is-a-subject, comment-size.heredoc-is-data,
masked-decls.verdict-discarded, masked-decls.substitution-required,
python-lint.gate-tier-neutered, python-lint.tier-boundary,
python-lint.hub-unused-import-gate, python-lint.hub-unused-assignment-gate,
python-lint.hub-unused-unpacking-gate, python-lint.hub-regex-flag-gate,
python-lint.hub-string-concatenation-gate,
python-lint.hub-string-format-gate,
python-lint.embedded-extraction-off, python-lint.embedded-file-discovery,
python-lint.heredoc-python-decision (which targets
extract_embedded_python.py, which verify_gate_registry.py counts among
python-lint’s own files because own_files includes the helpers a .sh gate
shells out to), and python-lint.utf8-diagnostic-output (which forces the
Windows source-map helper to print non-ASCII Ruff findings as UTF-8; its fixture
runs under cp1252).
Python refactor preview#
Preview Python refactors before accepting them. bash linux/scripts/refactor-python.sh --check
reports formatter drift; --apply -- <tracked.py> makes pinned safe Ruff edits and saves a patch
under ignored logs/code-quality/. The on-demand python-refactor.yml workflow uploads its patch
with read-only repository permissions. Review the patch and run the relevant gates before
committing it. The general agentic loop drains the whole backlog and may commit; do not use it as
an unattended single-file refactor driver.
bash linux/scripts/refactor-python.sh --root <checkout> --check [-- <tracked.py> ...]
checks tracked Python files in the named Git checkout with the pinned Ruff version in
linux/scripts/01-core/tool-pins.env and that checkout’s Ruff configuration. Without
--root it grades ANTfrastructure; without file names it selects all tracked .py files.
--apply -- <tracked.py> ... runs safe Ruff fixes and formatting on named clean files,
then saves the patch and tool log under the target’s ignored logs/code-quality/.
Dirty, untracked and non-Python inputs are rejected. Review the patch and run the
relevant quality gates before committing. This tool does not refactor
PowerShell, Bash, embedded Python or generated code, and a Ruff fix is not a substitute
for tests.
The first whole-tree formatter audit on 2026-10-25 found 123 of 147 tracked Python
files would change. That is existing formatting debt; the ordinary preflight still
enforces Ruff lint and ty, not whole-tree ruff format --check. The on-demand and
reusable workflow_call .github/workflows/python-refactor.yml accepts one tracked
caller-relative Python path. It previews the edit in a disposable CI checkout, runs
the caller’s lint gates (and the hub’s mutation checks when run here), and uploads the
patch and logs. Consumers call it at @develop; hub-checkout: true serves a repo
without a submodule. It has read-only repository permissions and does not commit or
open a pull request. The patch is the review boundary. Some mutation recipes
match exact source text, so a format edit can require a recipe update before the gates
pass. The workflow syncs the locked quality environment for ty, while general script tests
use the runner Python with pytest and PyYAML as in linux-x64.yml; putting the quality
venv first on PATH changes existing test assumptions about the runner’s pip package.
The existing agentic loop is unsuitable for this narrow CI job because it consumes
the whole backlog, may commit and treats its quality phase as advisory. Its reusable
components are documented in shared/agentic-loop/templates/README.md for a future
scoped AI driver.
The reusable code-quality-report.yml runs duplication, size and complexity in
--report-only mode against a caller checkout on Linux. Findings appear in the job
summary and ignored logs/code-quality/measurements/ artifacts; unusable roots
and scanner failures still fail the job. lint-gates.yml also uploads
logs/code-quality/code-dupes.txt by default. To enforce duplication after removing
existing findings, set code-dupes: true in the lint workflow or pass --code-dupes
to run-lint-gates.sh; no new freeze budgets are allowed to make adoption pass.
The pinned actionlint reuses the hub’s runner-label config when the caller has none.
submodule-pins.yml accepts hub-checkout: true for a caller that has other
submodules but keeps this hub outside its Git tree; the pin suite still grades
the caller root.
The reusable python-static.yml runs the hub’s uv-locked Ruff 0.17.0 and ty 0.0.91
against tracked Python in the caller checkout. It installs no caller dependencies.
ty keeps its own environment discovery and gets two extra search paths: the locked
quality environment’s site-packages, so test-only imports such as pytest resolve,
and the hub’s pinned sphinx-kataglyphis-theme, so a caller’s docs/conf.py resolves
sphinx_kataglyphis. The lane, and code-quality-report.yml’s quality-report step,
fetch the hub’s third_party/DocumANTation for that, since the caller checkout does not
recurse into the hub. Search paths only add
resolution; a caller dependency outside both stays an unresolved import.
Use bash linux/scripts/python-static.sh --root <checkout> --path <file-or-dir> --report-only locally; --strict fails on diagnostics. The default reusable lane
reports findings without failing and uploads logs/code-quality/python-static/.
Tool setup, missing Python scope, and invalid checkout paths still fail. A consumer
can expose strict as a manual workflow input while the automatic lane measures
existing debt. The job summary states diagnostic counts as well as exit statuses.
The next measurement gaps are concrete: the existing size and complexity scanners cover
139 of 147 tracked Python files; eight files in Windows, shared and other Linux locations
are outside their four scan roots. The duplication scanner handles shell, PowerShell,
Dockerfiles and Markdown, but not Python. Its current --report and --explain modes
already rank the languages it does cover for an AI refactor queue. Linux size, complexity
and duplication gates now keep text artifacts, but no structured trend report. Extend these
existing scanners, first measure the added scope, then remove its findings before making
new coverage fatal; do not add quality exceptions or weaken thresholds for the rollout.
Python type analysis#
The Python consumer static-analysis drivers on Linux and Windows already gate ty check
beside Ruff. Each consumer resolves ty from its own lockfile. This repo’s Python scripts
previously had Ruff linting but no type gate. linux/scripts/lint-python-types.sh now uses
the exact TY_VERSION and RUFF_VERSION in 01-core/tool-pins.env:
PREFLIGHT_ONLY=python-types bash linux/scripts/preflight.sh
bash linux/scripts/lint-python-types.sh --docs-conf
bash linux/scripts/01-core/check-webdav-types.sh
lint-python-types.sh passes tracked Python paths to ty rather than scanning a directory of generated
files. It uses the Linux target for Linux and shared scripts and the Windows target for
windows/. The four preflight ty outputs go to ignored logs/code-quality/ty-*.txt; Ruff’s
missing parameter and return annotations go to logs/code-quality/ruff-annotations.txt.
The full-tree Ruff annotation scan writes
logs/code-quality/ruff-annotations-gate.txt. A second full-tree ANN202 gate writes
logs/code-quality/ruff-private-returns-gate.txt. The maintained parameter/return scope has fatal
ANN001/ANN201 checks in logs/code-quality/ruff-parameters-returns-gate.txt.
Compiler image subject and OCI modules belong to both strict scopes. The shared search paths
include media runtime, packaging, script tests, gateway end-to-end tests and local proof tools.
The real-ty fixture imports through every sibling root and rejects type or annotation errors
in either profile module; those source checks do not prove runtime imports or image acceptance.
The Linux x64 workflow uploads
these files after preflight. Any finding in the full Ruff annotation scan or the generic
Linux/Windows ty reports fails preflight. A failed download, invalid configuration or
checker crash also fails CI.
All tracked Python files have fatal ty coverage. The locked quality
environment checks Linux/shared files, and the Windows platform gate checks
the Windows certificate helper. Five files with dependencies absent from the
locked environment are checked in their real workflow or build environments:
docs/conf.py, the WebDAV downloader, venv-version-probe.py, the Jetson webcam
app, and litert-wheel-smoke.py. The common Linux and Windows reports scan the
remaining files whose imports resolve in the locked environment.
quality/pyproject.toml and the committed quality/uv.lock supply pytest,
PyYAML, markdown-it-py and Playwright to a Python 3.14 environment; the gate
syncs it with uv sync --project quality --locked and passes that interpreter
to ty. The Linux and Windows strict results have separate ignored reports. The local FINAL
acceptance companion belongs to both strict ty and ANN001/ANN201 scopes; the isolated
fixture checks type errors and missing annotations for that companion.
Linux x64 checks docs/conf.py with the pinned DocumANTation submodule using
--docs-conf before building and publishing the site. That mode writes
logs/code-quality/ty-docs-conf-gate.txt and fails for a missing theme or a
type finding. Sphinx rendering is checked by the later docs build. The x64 torch
image checks venv-version-probe.py and the Jetson webcam app against its
assembled /opt/venv; the webcam app’s API usage is checked without launching
a camera or GPU. The Windows media wheel build checks litert-wheel-smoke.py
against its installed wheel, NumPy and ml_dtypes. Linux x64 CI checks the WebDAV
downloader against the exact pinned client source commit without installing its
runtime dependencies, writes the verdict to ignored
logs/code-quality/ty-webdav-gate.txt, and uploads it. A local Git fixture
checks a wrong API argument, missing client source and failed fetch. The Flutter
browser smoke joins the strict ty scope through the locked Playwright package;
type checking does not launch Chromium; the Flutter font fetcher and web artifact checker are also in the strict scope. A new
New tracked Python files enter the compatible Linux or Windows report dynamically
and fail CI on ty findings. Files whose dependencies are absent from the locked
quality environment need a dedicated type gate in their real workflow or build environment.
The preflight and x64 image build share 01-core/load-ty-tool.sh for the pinned
ty version and uvx setup. The torch Dockerfile mounts it beside the version loader
and probe script so the build checks the same pin without copying the checker into
the final image. The shared loader clears an ambient TY_VERSION; the preflight
driver also clears RUFF_VERSION before loading its pinned tools. Fixtures and
mutations prove ambient versions cannot replace either pin.
The cache-unavailability fixture masks only the selected command probe and refuses
unexpected direct calls. Its grouped-tool case keeps a fake cache executable beside
real shell utilities: removing that whole PATH directory must fail before a broken
fixture can be mistaken for a production resolver failure.
The fake native-worker SDK suite uses a harness-owned temporary directory so intentionally failed downloads can retain diagnostic archives without leaking into the outer runner. Its command statuses and the runner’s leftover check stay fatal.
The isolated type fixture includes the Cargo native-helper stager selected by both production scopes. Its wrong-return and missing-annotation controls must fail; a new scoped file needs a matching fixture before the fixed production census can pass.
There is no allowlist or raised diagnostic threshold. tests/test-python-types.sh plants
incorrect types and missing annotations in existing and newly discovered Linux and Windows
files, requiring each gate to fail. Mutation cases remove the verdict, path selections,
dynamic report failures and the theme search path; the suite must catch each.
Ty uses declared and inferred types. It does not add annotations or require every
function to have one. Ruff’s eight annotation rules (ANN001-003, ANN201, ANN202, ANN204-206) fail on
every tracked Python file; lint-python-types.sh owns the exact set.
The focused suite injects unannotated signatures, and selector, scope and verdict mutations
prove the gates can fail. The annotation and ty scans preserve their own diagnostics and
exit status so a finding cannot be hidden by another check.
UP031 is clean; its fixtures check the emitted verdicts.
Dockerfile lint: hadolint rule selection (dockerfile-lint)#
Windows Dockerfiles are PowerShell (# escape=`` + SHELL ["pwsh",...]), but hadolint's embedded shellcheck still parses RUN bodies as sh wherever it cannot see the inherited SHELL — e.g. stages whose base is an ARG image (FROM ${MEDIA_CORE_FFMPEG_IMAGE} AS …), where the SHELL set back in common is invisible to a static linter. PowerShell that happens to parse as sh slips through; PowerShell that does not (…; & ‘C:\x.ps1’inwindows/Dockerfile.media-builder`) raises a shellcheck PARSE error, which is
error-severity and so fails the gate on a pure false positive.
Suppress the “shellcheck could not parse this at all” family, and only for windows/*: those diagnostics can never be true for a PowerShell RUN. The Linux Dockerfiles keep the full rule set — a real sh parse error there must still fail. Style/semantic shellcheck rules stay on everywhere.
The list is the whole parse-error family on purpose, not the codes observed so far. The first version of this fix listed only the ones that had actually fired (SC1070 on Dockerfile.media-builder); the very next Windows Dockerfile added to the repo tripped SC1088 instead and broke main again. Which parse error PowerShell happens to provoke is arbitrary — enumerating them one outage at a time is not a policy.
ENV instruction ordering (dockerfile-lint)#
A ${VAR} inside an ENV instruction expands to the value VAR held before
that instruction. A key set two lines up in the same ENV therefore expands
empty, and nothing says so: BuildKit emits no warning, hadolint has no rule
for it, and the UndefinedVar frontend check only runs in the advisory
docker buildx build --check pass, which is skipped on every nerdctl-only host.
Two Dockerfiles shipped that way, both found on 2026-09-04 by reading the ENV of an image already on the host:
file |
written |
what the image actually got |
|---|---|---|
|
|
|
|
|
a bare |
verify_dockerfile_env_order.py runs as pass 0 of lint-dockerfiles.sh — no
download, so like pass 0b below it cannot be skipped. It reports a value that
reads a key assigned earlier in the same instruction. Two references are
deliberately not findings, because both resolve correctly:
a key reading itself (
PATH="/opt/bin:${PATH}") — that is the inherit-and-extend idiom, and the inherited value is exactly what it wants;a name that is also an
ARGin the same stage — the reference resolves from the ARG, which is whyGCC_PREFIX=/opt/gcc-${GCC_VERSION}besideENV GCC_VERSION=${GCC_VERSION}is correct. ARG scope resets at everyFROM, and so does the excuse.
The fix is always the same: split the ENV in two. The second instruction sees
the first one’s keys.
Proof: tests/test-dockerfile-env-order.sh and eight
dockerfile-lint.env-order-* mutations, including one that deletes the call
from lint-dockerfiles.sh — a gate nothing invokes is the copy-media-payloads.sh
defect again.
No build-host setting in an ENV (dockerfile-lint)#
Pass 0b (2026-09-23), verify_image_env.py, the same script whose --env-file mode
grades a built wrapper. What it refuses and why:
build-cache-tiers.md § The shipped image carries no build-host setting.
It parses Windows Dockerfiles by their own # escape= backtick, which the ENV-order
pass above does not. Proof: tests/test-image-env.sh, eleven dockerfile-lint.image-env-*
mutations over the script and its call, and six image-env.* ones: four over the
manifest’s image-env gate in build-runtime-manifest.sh and two over real Windows
Dockerfiles.
Step labels (dockerfile-lint)#
Pass 0c, verify_dockerfile_step_labels.py, over the hub’s linux/Dockerfile.*
only; a consumer’s Dockerfiles are not graded. nerdctl history shows a RUN as
RUN |12 A=… B=…, its ARG list, so a 5 GB Android layer once read as an ORT build.
Every RUN therefore carries its own LABEL kataglyphis.step=<name> before it:
the name is lowercase kebab-case and unique in its Dockerfile;
only instructions that make no layer (
ARG,ENV,SHELL,USER, anotherLABEL) may sit between the label and its RUN; aCOPY,ADD,WORKDIRorFROMthere would take the name instead, so the gate refuses it;a heredoc’s body is not read as instructions.
A label is image metadata: BuildKit keys neither the RUN nor a child’s FROM
on it, so adding or renaming one recompiles nothing. The history then shows
LABEL kataglyphis.step=<name> as the empty entry right above its RUN, and
layer-audit.py prints that name as each layer’s step= (from the manifest’s
config blob, or --config). A RUN that leaves no layer spends its label; a
layer without one keeps the start of its created_by.
What it does not cover: the Windows Dockerfiles, and whether a name describes
its RUN. Proof: tests/test-dockerfile-step-labels.sh, tests/test-layer-audit.sh,
five dockerfile-lint.step-labels-* mutations.
The allowlist contract#
Quality fixes must reduce exceptions. Refactor the underlying code before changing an
allowlist. Adding an entry, increasing a frozen budget, raising a threshold or narrowing
scan coverage requires explicit owner authorization. Existing rationales explain the
current debt; they do not authorize more. Remove an entry when its finding is fixed.
A duplication report may identify shared syntax rather than shared behavior; inspect
--explain before extracting a helper, and keep any remaining exception narrowly scoped.
Windows preparation shares cache, archive and dependency-walk mechanisms while
retaining caller verdicts. Environment scopes and child-only sanitizer overrides
have failure and mutation coverage. Fixture constructors own allocation cleanup;
mutation controls must pass before a deliberately broken implementation can count
as proof. Baseline budgets only decrease after an authoritative whole-tree scan. Windows
DLL graph, debugger transport, temporary environments and local git fixtures now
share their existing owners. Regression controls retain independent expected bytes,
arguments and failure verdicts; missing copied companions remain fatal.
The Windows agentic loop tests now share config defaults and real-child transport;
their measured self-pair budget fell from 39 to 20. The remaining overlay cases
exercise different configuration behavior.
The cleanup separates SBOM construction and comparison, Python extraction, package-index
fetching, dependency dispatch, option parsing and smoke probes from their drivers. Shared
owners now handle compiler lookup, cache addresses, FFmpeg feature tables and SDK dependency
queues. Interpreter priority, archive fallbacks, codec argument order, compiler swaps and NDK object checks
have regression coverage in test-code-quality-refactors.sh.
The comment-size, function-size, complexity and masked-declaration lists are empty. No function exceeds the branch or nesting limit. File-size, ShellCheck and duplication lists still record remaining debt; their files and the gates are the authority for current counts.
Runtime verdict aggregation is separate from row selection, version checks and tree failures.
Consumer symptoms live in a lookup library. The runtime test driver sources boot, consumer
and SDK cases in its original shell and order; all cases still run from the same suite.
Host storage admission and retention live in 01-core/chain-storage.sh; the orchestrator
retains stage order and the between-stage call. Vulkan provisioning lives in a sibling
vulkan-install.sh, copied beside the driver in the SDK image. Their offline regression
suite covers admission ordering, archive layouts, verification failures and source wiring.
The duplication cleanup shares native Python probe transport and result checks while retaining ONNX’s required presence and GenAI’s separate parity policy. TVM shares resolved CMake options and SDK lookup order. ONNX Runtime shares dependency setup and GPU cache selection; package and smoke builds share artifact-context resolution. Compiler signatures share one bounded scan, and Python bundle/package drivers share a mode-aware argument parser. Host tools use one unknown-option diagnostic. Their regression suites and mutations pin the distinct policies.
Distinct nameref names avoid ShellCheck confusing separate functions’ local output arrays. Literal associative-array keys are quoted, and indirect exports include both name and value. These changes remove findings without adding suppressions or weakening scan coverage. LiteRT wheel helpers live in a passive sibling library, and longer embedded Python checks live in standalone probes. GStreamer flag and cargo suites preserve target metadata, host/target compiler separation and conservative plugin exclusions. IREE’s stage helpers live beside the wheelhouse driver on the existing directory mount. Existing build-image inputs still require a rebuild to validate shipped behavior.
Every gate that freezes a baseline uses one of two rules, both owned by
linux/scripts/quality_allow.py so a new gate cannot invent a third:
Counted metrics (
key | count | reason, e.g.function-size.allow) use the four-way rule: a new offender fails, growth past the frozen count fails, an unrecorded shrink fails (the improvement must land in the diff), and a stale freeze fails. The number therefore always equals reality.Set metrics (one tab-separated key per line, e.g.
comment-size.allow) use the two-way rule: a key not frozen is NEW, a frozen key no longer found is STALE.
Keys are chosen to survive unrelated edits — file + name, or file + first
comment line — never a line number. A gate that copies these rules instead of
importing them is the duplication the code-dupes gate exists to refuse.
One reader, keyed from the left. quality_allow.iter_rows(path, keys, fmt)
parses every counted allow file and yields (key, count, reason, line number) per
row, in file order and repeats included; load_rows is its dict view and
load_counts that view minus the reasons. keys names how many columns precede
the count, so everything after it is the reason and a reason may hold | and #
— until 2026-09-04 the count was taken as the second field from the right and an
inline # was stripped before the split, so one | in a hand-written reason
raised ValueError: invalid literal for int() before any gate could report
anything, and a # silently truncated the reason. A row that fits neither shape
is ERROR: <allow file>:<line>: expected '<fmt>' and exit 2 — a verdict naming
the offending row, never a traceback.
Every counted gate declares its arity (2026-09-05). code-complexity.allow
passes keys=3, function-size.allow keys=2, file-size.allow keys=1,
shellcheck-warnings.allow and code-dupes.allow keys=2. keys=None survives
only as the reader’s default and no gate uses it, which closes the last live hole
in this contract: with the count taken from the right, a reason of the shape
… | 90 | … does not raise, it silently keys the row on five columns and the
freeze then reads STALE. A named error was never the worst case; a wrong key was.
Declaring the arity also deleted verify_code_complexity.check_rows’s
len(key) != 3 branch (a short row now fails in the reader, naming its line) and
the code-complexity.allow-row-arity mutation that pinned it, which had become
unkillable.
code-dupes keys on an UNORDERED pair, and that is why the reader yields rows
rather than a table. a | b and b | a are one entry, so
verify_code_dupes.load_allow folds the reader’s two key columns into a
frozenset itself and keeps the line numbers to say duplicate row for A <-> B (first at line N). Two identical rows have to reach it as two, which a dict
view would already have folded — hence iter_rows. verify_doc_dupes.load_allow
reads through iter_rows the same way.
The mutation gate (mutations)#
docs/scripts/verify_mutations.py with docs/scripts/mutations.json, preflight
slug mutations. For each recorded entry it makes a literal edit that neuters
one guarantee, runs the named test, and requires the test to FAIL. A mutation
the tests survive is reported and fails the gate.
Prepare recurring require-removal data with python3 docs/scripts/generate_require_mutations.py --root ROOT --target RELATIVE_PYTHON --test TEST_COMMAND --prefix FAMILY.PREFIX --why LIMITS --output FRESH_JSON. It selects require expressions inside top-level functions and preserves the exact source segment; this is recipe preparation, not proof that every gate is covered or that mutations bite. Independent fixtures cover selection, parse-valid replacements, empty/syntax refusal and output preservation.
Use python3 docs/scripts/merge_mutation_recipes.py <manifest> to preview
adding reviewed recipes; pass --write to apply and --replace <id> for an
intentional change to an existing recipe. It checks unique in-repo anchors before
writing atomically. JSON output escapes non-ASCII characters without changing any
decoded recipe value. Deliberately corrupt strings used by encoding mutations must
remain data: writing them literally makes source encoding checks reject the clean
baseline before the mutation runs. The merger fixture checks semantic preservation,
escaped Unicode and repeated writes; it does not prove that recipe tests bite.
Run the mutation gate afterwards: an applicable anchor does
not prove the test catches the mutation.
--root selects both the files executed and the Git checkout used by --changed or
--push-range. Running a Hub-installed driver against another checkout must not select
from the Hub’s own history. The external-root fixture independently stages and commits
changes in another local repository and requires an actual bite and nonempty coverage;
nothing selected is not a mutation proof. This checks scope, not the consumer’s semantics.
Consumers can call .github/workflows/mutation-gates.yml@develop with a tracked
manifest path and an optional tracked setup-script. The shared validator
rejects missing or empty recipes, absolute or parent-traversal recipe targets,
paths outside the caller checkout and empty shards before running
verify_mutations.py --root <caller>. The runner checks target containment again
before reading or writing, including through a symlinked parent. An optional
setup script runs once inside each disposable mirror before any baseline test;
this makes a local .venv created by uv sync available to that mirror’s tests.
Setup failure is fatal and the caller checkout is not modified. With in-image: true
the proving step runs inside the family CI image (IMAGE_REGISTRY_PREFIX:CI_IMAGE_LINUX_TAG
from versions.env), mounted at the caller’s own path, so a recipe gets the image’s pinned
PYTHON_VERSION and its chain-built wheels: PyPI has no ORT or GenAI wheel for that Python, so
the bare runner cannot install an app extra on it. Mutation logs are
uploaded from ignored logs/code-quality/mutations/. Each consumer owns its
recipes because each recipe must break one of that consumer’s guarantees.
Why it exists. Reading a test cannot tell you whether it can fail. In one
session, eight tests written to guard a fix turned out to pass with the fix
removed: a window-grep that matched the wrong || die, a stub that bypassed the
extraction under test, an if wrapper that suppressed the very errexit it meant
to prove, and a fixture whose short definition came first. Every one was caught
by breaking the guarded code by hand. This gate is that habit, written down.
A recurring shape worth naming: most vacuous tests assert on the failure MESSAGE and never on the exit code, so the tool prints a failure and returns 0. Assert both.
A bite is only evidence if the suite was green first. Until 2026-09-03 a
mutation counted as biting whenever its test came back non-zero — including when
that test was already red, from unrelated drift in a tree several agents were
editing. Every entry under a broken suite then read bites and the gate passed,
which is the same false green it exists to find. Each DISTINCT test command is
now run once unmutated per invocation (cached by command string) before any entry
using it is applied; if that baseline fails, the entry is reported as
FAIL: <id> -- baseline test already fails unmutated (vacuous bite), the gate
exits 1, and the file is never mutated. The cost is one extra suite run per
distinct command, and it is paid once per command, not once per entry. The
manifest holds 8955 entries over 1069 distinct test commands; both digits are
derived, not typed (## Doc numbers are derived). A full uncapped run took 5m58s
on 2026-09-03, when the manifest held 180 entries — a one-off measurement that
scales with the manifest, not a current figure.
If a baseline times out, its failure reports whether the test leader was still running or had exited while a child kept a capture pipe open. It includes at most the first and last three nonblank output lines, clipped to 500 characters per line, so the CI log shows the last case reached without flooding the summary. Cleanup of a retained pipe has its own two-second limit.
On a Git Bash host a skip is a skip, not a vacuous bite (2026-10-05). A suite that
cannot run there exits 77 with its SKIP line (t_skip_unless,
cross-build-verification.md § The linux/scripts/tests suites).
The gate reports such an entry as skip, with that line, and does not fail it. A
survivor is a skip too, never SURVIVED, when its suite skipped or waived any case on
this host (a SKIP line from t_needs or an older _posix_host, or a waived count):
the case that would catch it may never have run. The closing line
then counts the skips instead of claiming every mutation was caught. On Linux, where CI
grades, exit 77 stays a vacuous bite and nothing is ever waived.
test-mutation-gate.sh proves both sides there, running the gate once as itself and
once with sys.platform set to msys.
The gate never edits the tree it is given. Until 2026-09-03 apply_and_run()
wrote the mutated text straight into --root (default: this repo) and restored it
in a finally. Preflight and the pre-commit hook both run it that way, and this
repo builds from its own working directory — buildkit is handed --local context=.. Entries target scripts that are COPY’d into an
image (linux/scripts/01-core/*, 03-media/*, 06-packaging/*), so a cross build
running at the same time could snapshot a deliberately neutered script into a
shipped layer; anything else reading the tree during that window saw a gate with
its guarantee removed. Restoring afterwards does not help — the hazard is the
window, not the end state.
Every invocation now builds ONE throwaway copy of the root (mirror_tree(), an
os.walk + copy2 that skips every git-ignored path plus COPY_EXCLUDES: .git,
external, out, logs, archive, linux/webserver/dist and
linux/llm-stack/ollama-binary.tar.zst), points the whole run at it, and rmtrees it in a
finally. Tests still run with cwd = that copy, so the relative commands every
entry uses (bash linux/scripts/tests/test-*.sh) resolve unchanged. --changed
still asks git about the REAL repo. Measured once, 2026-09-03: 0.58s for 6.4k
files / 131MB, paid per invocation whether it runs one entry or all of them —
under 1% of a full run that day.
One mirror per shard; the proof is still one mutation at a time. Measured
2026-09-04 after the integration wave, all 309 entries biting, each run alone
on an otherwise idle 32-core host: a full serial run costs 12m14s, one process
per mutant. None of that can be batched — two mutations proven in one suite run
prove neither — but they are independent, so --jobs shards drain one shared
queue, each with its OWN mirror_tree copy, each applying, running and restoring
inside it. Since 2026-10-21 a free shard takes the next entry, where round-robin
dealing once queued two slow suites on one shard, and each extra shard copies its
own mirror inside the pool instead of waiting for the others’ copies. Baselines stay shared across shards (one unmutated run
per distinct command, whichever shard reaches it first). Same 309 entries, same
verdicts: 1m59s at --jobs 8, then the default (6.2x), and 1m24s at --jobs 16 (8.7x).
The test transport reaps its session when the test shell exits. A surviving child
can hold captured stdout or stderr open after the shell is gone; waiting for pipe
EOF first used to turn a completed test into a 300-second baseline timeout.
Each test starts with stdin closed, so inherited terminal input cannot stall a
fixture; test-mutation-gate.sh pipes a marker to the parent and proves the
child cannot consume it. test-mutation-pipe-reaping.sh proves the transport
closes captured pipes on both the baseline and its mutant; its own mutation
removes the exit watcher. The Windows harness proof writes its JSON result under
ignored logs/code-quality/ inside its throwaway copy.
Since 2026-09-24 every verdict is printed the moment its entry completes, flushed
and tagged [j/J] with the shard that proved it, and a closing FAILED: n of m entr(ies), in manifest order: … line puts the failures back in manifest order. It
used to be buffered and printed in manifest order at the end, which Python’s block
buffering of a piped stdout turned into NOTHING when CI killed the job — not even
the header (§ The mutation gate in CI, sharded).
Measure one run at a time — two of these racing each other on the same host
report numbers that mean nothing, which is how the first attempt at this
paragraph was thrown away. The default is every CPU the process may use
(os.process_cpu_count(), so taskset counts), capped at the number of entries, so a
one-id run still makes one copy, and at the mirrors a quarter of the temp
filesystem’s free space holds: each shard is a full copy of the tree, which on tmpfs
is RAM a build may need. The run says so when that cap bites. --jobs 1 is the old serial
behaviour; --in-place is always serial.
--workspace-root /mutation-work opts into fixed worker-0, worker-1, … paths
inside a fresh private root. Use the same container-private absolute path in separate
containers: the pinned sccache Rust implementation
hashes Cargo environment values and the compile directory, so random mirror paths
prevent reuse even for unchanged dependency sources. The option still copies and
restores each mutant separately, shares the existing baselines and retains worker,
timeout and disk caps. Worker assignment can still change cache hits.
The root must not exist, overlap the source or use a symlinked parent. Allocation
is exclusive; cleanup checks root identity and the literal parent, and a cleanup
failure fails the run. Each invocation owns its root until cleanup completes.
The option refuses --in-place; check-only modes allocate nothing. Default
temporary mirrors retain their existing behavior. test-mutation-workspaces.sh
checks real child commands, fixed parallel slots, refusals and cleanup failures;
it does not prove compiler hits, concurrent-writer authentication or native Windows
behavior. Measure real cache deltas separately after cleaning only the owned Cargo
target. Source and compiler caches stay outside the disposable root.
Copies of verify_mutations.py carry mutation_workspace.py beside
mutation_parse.py, mutation_push.py and mutation_shards.py; workspace and
relative-target path checks share that owner. The real consumer-hook fixtures carry
the same closure: their local Git pushes check both successful delivery and
stale-recipe refusal. Removing the workspace companion must fail those assertions;
linter doubles and local remotes do not qualify downloaded tools or public pushes.
The fixture clears both inherited Git configuration transports before setting its
own hook paths. Parameter and counted-environment canaries prove this isolation
when the suite itself runs from a hook.
Copy-failure coverage also injects a transport error through the shared Python
fixture, so rootful containers exercise the same fatal-copy verdict as other users.
Symlinks carry TWO properties here, not one. mirror_tree copies with
follow_symlinks=False, so a link stays a link: dereferencing would pull whatever
it points at — a host binary, a device node — into a copy made once per commit,
and would turn a path the tests see as a link into a regular file. This repo has a
live instance inside the copied scope: docs/.venv/bin/python →
/usr/bin/python3, an absolute escape. Keeping such a link AS a link is not
enough by itself — a test running inside the copy can still read and write
through it to the host path — so since 2026-09-04 mirror_tree does not copy a
link whose realpath falls outside the tree at all. Four symlinks exist in the
copied scope, all under docs/.venv, and exactly one of them escapes. And
precisely BECAUSE the copy holds links
rather than contents, a write through one would land outside the copy, so
apply_and_run() refuses a symlink target outright and fails with target is a symlink -- a write through it escapes the copy. The check sits before the
existence test, because os.path.exists follows links and a dangling one would
otherwise be reported as target missing. Restoring afterwards is not a defence:
the outside file would hold the mutation while the test runs, which is exactly
the transient-write hazard this whole rewrite was about. Selection happens first, so a --changed hook run that selects
nothing (the common commit) copies nothing at all.
flag |
use |
|---|---|
(none) |
every entry — CI, or before a release |
|
only entries whose target — or a file their |
|
only entries the committed range changes, plus recipes it adds or edits; repeatable. The pre-push hook’s scope (the pre-push hook) |
|
count entries whose suite needs a real Chrome, or pwsh with Pester on a host without them, as CI’s to prove, and print the count per suite. Refused with |
|
one entry, while writing it |
|
which tree to copy and check. It is copied too — pointing the gate at a mirror is a second belt, not the isolation mechanism |
|
how many mutations to prove at once, one mirror each (default: the CPUs the process may use, capped at the entry count and at a quarter of the temp filesystem’s free space). Every mutation is still applied, run and restored alone, inside its own shard’s copy |
|
fresh private root with fixed per-worker paths; refuses existing paths, source overlap and symlinked parents. Cleanup failure is fatal. Use a container-private path; check-only modes allocate nothing |
|
prove only |
|
with |
|
refuse every selected recipe whose mutant does not parse, and run no test (mutants must parse) |
|
mutate |
Mutants never run stale bytecode#
Python reuses a cached .pyc when its source has the same size and the same
mtime second. Two same-size mutants of one module, run back to back in one
worker, could therefore run the first mutant’s code for the second. That mutant
then survived only on fast hosts (handoff.runtime-source-selected-checkout, seen
in the pre-push hook). apply_and_run deletes the target’s __pycache__
entries after it writes the mutant and after it restores the original. Other
importers of the target are not covered; they read their own unchanged files.
Mutants must parse#
A mutant that no longer parses bites for its syntax error, not for the guarantee
it removed: any test that sources or imports the file fails. Five recipes bit
only that way on 2026-10-31. The gate now refuses such a recipe before its test
runs, with FAIL: <id> -- the mutant does not parse (...), and
verify_mutations.py --parse-check runs that check alone, without a test.
The check (docs/scripts/mutation_parse.py) reads *.sh files and files with a
bash or sh shebang through bash -n after stripping CR, *.py through
compile(), and every *.ps1/*.psm1 text through one pwsh process. It
refuses a recipe only when the original target parses. A missing parser fails
the run; it never skips. It does not read other languages (YAML, JSON,
JavaScript, Dockerfiles, CMake), code embedded in another file (heredocs,
workflow run: blocks), or names that parse but cannot resolve at run time.
A rewritten recipe keeps the edit valid: replace a removed branch body with
true or pass rather than deleting the only statement in it.
test-mutation-parse.sh proves each arm, and the mutations.parse-* recipes
prove that suite.
Mutation fixtures pass temporary paths as Python arguments so native Windows
receives the same path used by the actual gate. Synthetic host-skip cases override
only the gate’s host-skip fact; changing sys.platform also changes executable
lookup and can falsely hide bash.exe from the required mutant parser.
The torchvision patch fixture loads its temporary patched module through
runpy.run_path with explicit compiler and environment facts. It executes the
real patch’s launcher selection, drift refusal and reverse check. Isolated
fixture controls cover this harness; complete source qualification and actual
wheel/cache measurements require their own results.
The mutation gate in CI, sharded#
What happened (2026-09-23). The preflight job of linux-x64.yml (then ubuntu26.04.yml) ran every
slug in one job with a 45-minute timeout, and on fd3a8e1f it was killed inside
the mutation gate. Nothing it had found was in the log: the report was buffered to
the end, and Python block-buffers a piped stdout, so not even the gate’s header
arrived. Behind the timeout sat four deterministic reds, each a suite that failed
unmutated and turned its entries into vacuous bites (CHANGELOG, 2026-09-23).
Why the gate got slow — a regression from 021d5bdd. fix11 ran one awk pass per
rule, test-critical-fixes.sh ran the whole gate once or twice per knocked-out row,
and 68 entries re-ran that suite: 4.4 s became 45-59 s on the runner, and that one
suite became 43% of the gate’s serial cost. It is fixed at the source
(onnxruntime-single-source.md § How G4 runs);
the timeout was not raised and CI does not sample.
The layout since 2026-09-24. preflight.sh stays the one source of the slug:
job |
runs |
timeout |
|---|---|---|
|
|
45 min |
|
|
30 min each |
The nine jobs prove shard K of one deterministic plan, so they prove every entry
exactly once; suites pin that the plan partitions the manifest and that the
matrix lists 0..N-1 for the N its jobs pass. Every mutations job repeats the
preflight job’s setup (uv, pytest, PyYAML): without them the baselines fail
unmutated, as on 2026-09-07. Each job still shards its slice over --jobs
mirrors, and each job runs the baseline of every distinct command it holds.
One build cache per mirror#
Each --jobs worker proves its entries in a mirror of its own and hands every test it runs the mirror’s directory
name as MUTATION_MIRROR (since 2026-11-14). A recipe that keeps a build cache outside the mirror must key it by
that name, CARGO_TARGET_DIR="${RUNNER_TEMP:-/tmp}/<name>-${MUTATION_MIRROR}": cargo names a workspace member’s
artefacts without its absolute path, so two mirrors on one target directory overwrite each other’s fingerprints
and a mutant runs the other mirror’s unmutated binary. OxidANT’s text recipes survived that way in CI while they
bit with --jobs 1. test-mutation-shards.sh holds two jobs to two names; recipe mutations.mirror-name-unset.
The shard plan#
Until 2026-10-31 the jobs proved entries[K::N], so a command whose entries
spread over all eight slices paid its baseline eight times: 2,269 baseline runs
for 469 commands, a third of the gate’s work. docs/scripts/mutation_shards.py
now groups each test command’s entries onto one shard, so its baseline runs once
per round. It packs the commands longest first onto the lightest shard, by the
cost table docs/scripts/mutation-costs.json, and splits only a command that
costs more than a whole shard. Inside a shard it interleaves the commands, so a
free mirror starts another baseline instead of waiting on one command’s baseline
lock. Each job prints its plan line: how many commands it holds and how many had
no recorded cost (they get the median).
The table holds each command’s baseline seconds and seconds per entry. The gate
prints them on stderr, one cost line per command when its last entry ends;
refresh the table from a green run’s log:
gh run view <run-id> -R Kataglyphis/ANTfrastructure --log > logs/code-quality/mutations-run.log
python3 docs/scripts/mutation_shards.py --from-log logs/code-quality/mutations-run.log \
--manifest docs/scripts/mutations.json --write docs/scripts/mutation-costs.json
Measured 2026-10-31. On round-robin slices (run 41183472080, 3,968 entries) the eight jobs summed 11,287 s, 2.85 s per recipe, and the slowest took 1,562 s of its 30 minutes. Over the first six green planned runs (41189788344 to 41204714575, about 4,040 entries) they summed 7,340-8,227 s, a median of 1.92 s per recipe, and the slowest job took 1,060-1,155 s; every id bit exactly once and the shards held 491 or 492 distinct commands between them, one baseline each.
A stale table still proves every entry exactly once; it only balances worse.
Refresh it when a suite got markedly faster or slower, from runs after that change
only: the table takes each command’s median, so older runs keep the old weight. On
2026-10-31 a table built across a speedup of test-runtime-image-gates.sh (25.6 s to
14.9 s per run) planned the shards 26.6% apart; rebuilt from the four runs after it,
they came out even.
Without --shard-costs the gate keeps entries[K::N], which is what consumers
and validate_consumer_mutations.py use. test-mutation-shards.sh proves the
partition, the grouping, the split, the balance and the interleaving.
Keep each job under about 24 minutes. When one gets close, make the costliest commands cheaper first: give a
suite -k sections and prove each recipe on the cheapest section that bites it.
The 30-minute budget includes job setup and cleanup. On 2026-10-22, shard 0 proved all 532 selected entries, printed a passed preflight summary, and was then canceled at the job boundary. Eight shards halve that 532-entry slice without sampling or raising the timeout; baseline failures still fail.
The shards install no Pester, so a recipe whose test is a Pester-style suite
(BeforeAll, Context and the other Pester-only keywords) skips there and fails
every run as a vacuous bite. Put the cases a recipe needs in a harness-style
suite; test-mutation-pester-targets.sh refuses a recipe that names a
Pester-style one.
CMake.CPackDiagnostics.Tests.ps1 runs the CPack export, log selection, sorted tails and
missing-directory cases through the harness on both hosts. It lifts the canonical batch
logger over a state fixture; the remaining CMake Pester cases keep their separate full-run coverage.
The cleanup unit-boundary recipes use Stevedore.StorageUnits.Tests.ps1 through
Invoke-HarnessSuite.ps1; existing Pester reclaim controls remain in the full Windows run.
Copied-module source views use the portable BuildKit.MountStub.Tests.ps1 fixture;
BuildKit.ModuleClosure.Tests.ps1 retains its separate Pester closure checks.
CrossBundle.PackageCheck.Tests.ps1 proves package callback output and failure contracts
under a cold harness on both hosts. Its install fixture is shared with the Windows-only
CMake/batch suite; real archive validation remains in the package licence suites.
A recipe’s cost is one run of its command, so name the narrowest command that
bites: -k <section> on a bash suite using t_sections
(the harness), -k <test>
on a unittest file, or
pwsh -NoProfile -File windows/scripts/tests/Invoke-HarnessSuite.ps1 -Only <suite> for a
harness-style suite that needs only TestHarness.psm1. That driver skips the modules,
Pester detection and tally of Invoke-Tests.ps1; a suite depending on implicit imports
fails its baseline rather than losing a bite. Import required modules in the suite.
The same cases must stay in unfiltered discovery, so preflight and Windows CI still run them.
A failed baseline reports its first three and last three nonempty lines, capped at 500 characters per line. This retains the first diagnostic and final summary when a multiline browser report would otherwise hide the failure. It changes the diagnostic only; a failed or timed-out baseline never counts as a bite.
Locally nothing changes: make preflight and bash linux/scripts/preflight.sh
without the variables run every entry. To reproduce one CI job, set the same two
variables; to time one, give it the runner’s 4 CPUs as well (below).
Measured 2026-09-24 in the CI-parity container (the image as uid 1001, gawk as
awk, the image’s venv python off PATH), one run at a time. The serial cost — one
run of each distinct test command × (entries + 1) — fell from 11469 s on
fd3a8e1f to 6633 s, and test-critical-fixes.sh’s share from 6044 s to
901 s. A second session measured the new tree at 5816 s: sessions differ by up to
17%, so compare numbers from one session only. The whole 1172-entry manifest took
18m39s at --jobs 16 on 32 cores; 1164 entries bite, and the 8 under
test-compiler-cache.sh are vacuous there only because the image ships a real sccache.
Measured before the plan (2026-09-24, four slices). A lab
run pinned to 4 CPUs was not a runner: under taskset, os.cpu_count() still reports
the host’s 32, so verify_mutations.py picked --jobs 8 where the runner’s 4 vCPUs
gave it 4. Since 2026-10-21 it reads os.process_cpu_count(), which honours taskset. An early lab slice timed that way (6m16s) is no CI figure. Run as the
runner runs it — taskset -c 0-3 plus PYTHON_CPU_COUNT=4 — slice 1/4 took
12m09s. For the runner, each slice’s serial cost is scaled by the gate’s measured
CI time on 2943b70d (843 entries: 1333 s on a fast runner, 1693 s on a slow one)
over that tree’s serial cost in the same session. Three sessions put a slice at
10.0-12.4 min on a fast runner and 12.7-15.7 min on a slow one; the spread comes from
the session, not the slice. The one entry that sits out the gate’s 300-s per-entry
timeout (mutations.timeout-kills-tree) is paid by whichever shard holds it. The same scaling puts fd3a8e1f’s whole gate, in one job,
at 66-84 min; CI killed it at 45. The first CI run is the proof.
The pre-commit hook’s cost budget#
The hook advertised ~11 s. Measured on this tree 2026-09-04, the batch commit
06e1e24e (43 files) took it 5m26s, and the mutation step was all of it: a
full uncapped run of the 132 entries those files own measures 322 s. AGENTS.md
was wrong by a factor of thirty, and a hook that slow is the hook its own header
warns about — it teaches --no-verify, which is worse than no hook.
Two things were wrong, and both are fixed in the hook, not in the gate:
Scope. --changed unions three sets, one of which is everything committed
since origin/main. Those are PUSH semantics. In a pre-commit hook they mean
every commit of a batch re-pays for all the commits before it, so the tenth
commit of a session is the most expensive one even if it touched one file. The
hook now selects on the STAGED files alone — the same scoping it already applies
to shellcheck (--files) and to the doc gates. --changed keeps its meaning
for a by-hand proof; the pre-push hook uses --push-range.
Which index. The staged list is read once, from the index git names in
GIT_INDEX_FILE. git commit -a and git commit <path> build the commit’s index in a
lock file (index.lock, next-index-<pid>.lock), and the plain index does not list
their files yet: read from it, the staged shellcheck, the doc gates and the mutation
sample saw no file and the hook said OK. The hook unsets the variable for everything it
starts, so only that one git diff --cached gets the path. A list that cannot be read
stops the commit. tests/test-precommit-hook.sh commits for real with -a, with a path
and plain; recipes pre-commit.commit-a-reads-its-own-index and
pre-commit.unreadable-index-stops.
A host without a parser (CON279). A mutant is parsed before its suite runs, so a host with no pwsh
(a Raspberry Pi dev host) failed every PowerShell sample with pwsh is not on PATH, so .... When the gate’s
output says is not on PATH, so and the clone sets git config kataglyphis.imageRunner "<command> --", the
hook runs the same --only sample once more through that command, and that run decides; a surviving mutant
or a clone without the setting stops the commit as before. It is the pre-push hook’s CON277 rule.
Cost. Even staged-only, the mass is lopsided: the totals above spread over a
handful of suites, and on 2026-09-04 test-code-complexity.sh alone owned more
than a fifth of the manifest. Each entry costs one full run of its suite — 0.5 s for a cheap one,
3.2 s for test-code-complexity.sh (measured 2026-09-03) — so touching one gate script can be a minute on its
own. No selection rule makes that both complete and fast. So the hook samples,
and says so:
at most
PRECOMMIT_MUTATION_CAPentries (default 16;0= uncapped),newest first —
mutations.jsonis appended to, so the newest entries are the ones written in the commit being made, which are exactly the ones most likely never to have bitten,and when it cut, it prints
SAMPLED <n> of <m> entries … NOT full coverage. A green hook must never imply coverage it did not pay for; that rule has cost this repo enough already (## Proving a gate can go red).make preflightand CI still run every entry.
Measured 2026-09-04 against the merged 309-entry manifest, on a 32-core host: the whole hook run end to end against a real staged index, with the parts timed separately.
step |
one-file commit ( |
this wave’s own 77-file diff |
|---|---|---|
18 fast whole-tree slugs |
6.4 s |
6.4 s |
|
0.3 s (1 file) |
14.1 s (45 files) |
doc-duplication gate, only when |
— |
0.2 s (8 files) |
mutation step |
8.7 s — all 9 matched entries, no sampling |
13.4 s — 16 of 264, sampled |
hook, end to end |
15.0 s |
33.0 s |
Neither column is a worst case: the sample is newest-first, NOT cost-aware, so what it costs depends on which suite the newest matched entries belong to, not on how many files are staged. A one-file commit that happens to stage a gate script can cost more than a wide one. A commit that touches no mutation target at all skips the step entirely.
Derived doc numbers (since 2026-09-24). When docs/scripts/mutations.json,
the hook itself or a page that quotes their numbers is staged, the hook also runs
test-doc-numbers.sh. It costs 8.1 s on the Windows dev host (measured 2026-09-24)
and nothing on a commit that stages none of those files. It is here because
adding a mutation changes the total the owning page quotes, and the hook said OK
over a stale one: CI’s preflight and all four mutation shards went red on it
(run 36022089345).
The cap moved 6 → 16 on 2026-09-04, when the gate learned to shard. Same rig, the same newest-first sample of the 77-file diff, measured both ways: 6 entries cost 9.3 s sharded against 15.5 s serial, 16 cost 13.4 s against 44.9 s. Sixteen sharded therefore costs 4 s more wall time than six used to while proving 2.7× as many entries — which is the whole trade: the hook’s budget is seconds of WALL time, and sharding is the only thing that buys coverage without spending more of it. End to end the same commit is 33.0 s at 16 and 29.0 s at 6.
--print-mutation-plan <cap> <manifest> <file-of-staged-paths> prints
plan <run> <matched> and the ids, without running anything; it exists before the
hook’s git rev-parse, so tests/test-precommit-hook.sh can drive the selection
off-target and inside the mutation gate’s own throwaway copy. git never passes
arguments to a pre-commit hook, so it cannot fire by accident.
The suite also drives the hook END TO END — a stub git feeds it a staged-file
list and a stub verify_mutations.py records the argv it is handed — so the
SAMPLED notice, the agreement between the number it states and the ids actually
run, and the abort on a surviving mutation are each pinned by a mutation
(pre-commit.notice-is-printed, pre-commit.notice-count-is-the-run,
pre-commit.uncapped-claims-no-sample, pre-commit.mutation-failure-aborts).
Before that, deleting the notice call left every suite, the registry and preflight
green.
Adding a fix without a mutation entry is allowed; adding a gate without one is
how the next inert check gets in. The gate guards itself: 124 entries (mutations.*)
neuter its survivor-reporting, its file restore, its baseline pass, its use of the
copy, the opt-in-ness of --in-place, the cleanup of the copy, both production
call sites, the exclude list, the single-match rule, copy2, both halves of
the symlink contract, the streamed report and the CI shard split. The isolation proof is
a witness file: the fixture’s test command cps the pointed-at subject somewhere
else while the mutation is applied, and the suite asserts that snapshot still
reads GUARD=on — an after-the-fact byte comparison cannot tell isolation from a
successful restore.
Isolation is a DEFAULT, and a default is one flag from being off. Nothing in
the code stops --in-place being appended to preflight’s run_check mutations
line or to the hook’s verify_mutations.py "${_only[@]}" line; every suite in the
repo survives that edit, and the consequence is precisely the hazard above.
test-mutation-gate.sh therefore reads the call sites out of
linux/scripts/preflight.sh, linux/host-config/git-hooks/pre-commit and
pre-push and asserts that each still invokes the gate — run_check mutations,
the hook’s single verify_mutations.py "${_only[@]}" || staged-file run, and
pre-push’s --stale-check and --changed runs — and that no invocation line
carries --in-place. Four entries
(mutations.preflight-callsite-isolated, mutations.hook-callsite-isolated,
mutations.preflight-runs-the-gate, mutations.hook-runs-the-gate) flip each call
site and must bite. The test only READS those files; they belong to other gates.
Three properties of the copy are pinned rather than assumed. COPY_EXCLUDES is
membership, so emptying it is invisible to every functional test — the run just gets
slower and clones .git. The suite plants a payload in each excluded tree, has the
fixture’s test command list what it can see from inside the copy, and asserts none
of them arrived — against a whole-checkout clone per invocation, at the mirror
cost measured above. copy2, not copyfile, carries the mode across, so a mutated .sh
is still executable in the copy: the suite chmods its subject and has the test command
require -x. Losing that would turn every shell test red for the wrong reason — a
vacuous-bite storm, not a verdict. And a find string matching MORE than once is now
an error (ambiguous, name one edit) instead of a silent first-occurrence edit that
neuters one of several copies, leaves the guarantee half-standing, and reports a false
SURVIVED; zero matches was already stale. Every entry matched exactly once when
the rule landed (2026-09-03).
The pre-push hook#
Like pre-commit, it first clears the GIT_DIR family git exports to hooks; the
gate’s fixtures otherwise act on this repository (failure-modes.md).
The commit hook samples and CI runs everything. The push hook catches recipes that stopped
applying: --stale-check runs applicable() over every entry and runs no test, so it costs one
read per target instead of a suite run. It reports a missing target, a symlink target, a find string that matches zero
times or more than once, and a no-op replace.
What it does NOT do is ask whether a test can fail, and the suite pins that: a
manifest whose mutation the tests SURVIVE passes --stale-check and fails the
gate. A caller that ran only the cheap pass and called it coverage would be the
exact false green the gate exists to find.
linux/host-config/git-hooks/pre-push runs four steps, cheapest first, and stops at
the first red:
The remote’s tip. Git hands the hook the tip it saw at connect time. A tip this clone has not fetched means another push landed since the last fetch; git rejects that push after the hook, so the hook refuses at once and says to rebase.
test-doc-numbers.shandverify_comment_size.pyover the whole tree, about 10 s. A rebase changes both with no commit hook firing: a doc-number mismatch and a two-line comment each reacheddevelopthat way.--stale-checkover the WHOLE manifest, the only thing in the repo, outside CI, that reads every entry: under a second.The mutation gate with
--push-range <remote>...<local> --delegate-chrome, one range per pushed ref. If its only failures are baselines already red on this host and the clone setskataglyphis.imageRunner, the hook proves those ids again through that command, and that run decides (linux/scripts/lib/hook-host-red.sh). The pre-commit sample does the same. On the Windows dev host, where a few suites expect POSIX paths or a Linux interpreter (CON338), a clone setsgit config kataglyphis.imageRunner "bash linux/scripts/run-in-ci-image.sh . -- bash -c".
A new ref counts from origin/develop, or origin/main where no develop exists.
A deleted ref proves nothing. PREPUSH_MUTATION_JOBS caps the gate’s own default, one
job per CPU.
What a push proves. --push-range selects entries whose target or test file the
committed range changes, plus recipes the range adds or edits, since a new recipe on old
code touches neither. Unlike --changed it ignores staged and edited files, which the
push does not carry, and a failed git diff exits 2 instead of reading as an empty
push. The gate’s coverage: line states the result: proved, selected, delegated and
skipped against the manifest total. Only a run that proved every entry says the whole manifest, and only that run closes on every recorded mutation is caught.
Chrome suites go to CI. Headless Chrome stalls on the build host: a suite waits out
each case’s timeout, and its baseline then fails the push. --delegate-chrome keeps
entries out of this run when a script their command names carries
t_skip_unless_chrome or findChrome(, prints one count per suite, and still checks
that those mutants apply and parse. CI’s Linux x64 mutations jobs prove them; Chrome is
on that runner, and Linux treats a suite’s exit 77 as a failed baseline, so a missing
Chrome goes red there. The gate refuses --delegate-chrome --shard, and
test-mutation-push.sh fails if preflight or a CI workflow passes either push flag. To
prove them before CI, run the gate in the image; it prints the line:
bash linux/scripts/run-in-ci-image.sh "$PWD" -- python3 docs/scripts/verify_mutations.py --only <id>.
So do pwsh suites on a host without pwsh. An arm64 dev host has none, so such a recipe
could never bite there. With --delegate-chrome, an entry whose test command starts pwsh, or
names a suite that demands it with t_skip_unless "…" command -v pwsh, goes to CI with the line
needs pwsh, which this host lacks when pwsh is not on PATH (mutation_push.host_has_pwsh,
asked only when such an entry is selected). It is set aside before the parse check, since parsing
a PowerShell mutant needs pwsh too, so CI both parses and proves it. Pester does not matter here:
a recipe names harness suites only, which run without it (test-mutation-pester-targets.sh
refuses a Pester-style one, since the Linux shards would skip it); the Linux image carries Pester at
PESTER_VERSION for running a Pester-style suite by hand.
git push --no-verify bypasses all of it. It is allowed only with a by-hand proof
named in the report: python3 docs/scripts/verify_mutations.py --changed --base origin/develop --delegate-chrome
plus bash linux/scripts/tests/test-doc-numbers.sh and
python3 linux/scripts/verify_comment_size.py. make hooks installs both hooks.
What it does not cover. The checks read the working tree, not the pushed commit, so the hook names any uncommitted paths. A change that reaches a suite only through a file its command does not name selects nothing; CI proves that. A suite that starts Chrome without either marker runs here and fails on its timeout. A push that lands during the proof still loses the race: git rejects, and the retry after a rebase pays again.
Measured 2026-11-04 on 32 cores with load between 5 and 62 from parallel work. Each row replays one past commit as a push; after includes the 10 s of cheap checks.
commit |
entries selected |
before |
after |
|---|---|---|---|
|
10, 1 Chrome |
306 s, failed on the Chrome stall |
16 s |
|
55 |
38 s |
51 s |
|
106 |
331 s |
339 s |
|
481, 50 Chrome |
487 s, failed on the Chrome stall |
205 s |
Half of the last 60 commits selected at most 2 entries. test-runtime-push-queue.sh
owns most of the 3052e9ff row, at about a minute per entry.
tests/test-prepush-hook.sh drives the hook over a stub git for its flags and abort
paths, and over the real gate for a rotted entry. tests/test-mutation-push.sh pushes
for real into a local bare remote: scope, delegation, the coverage line and each refusal.
Doc numbers are derived#
Three waves in a row shipped prose quoting a manifest count that the next wave
invalidated — 180 entries outlived 180 by two rebuilds of this page, in four
places at once. Re-typing the digit is what failed; the fix is the same one
tests/test-preflight-slugs.sh already applies to the slug count.
linux/scripts/tests/test-doc-numbers.sh measures the truth from
docs/scripts/mutations.json, from _FAST_SLUGS in the pre-commit hook, and from
verify_dead_functions.py --census run through its own CLI, and
fails when this page, cross-build-verification.md or AGENTS.md disagrees.
bash linux/scripts/tests/test-doc-numbers.sh --update rewrites the digits in
place, so tracking a new wave is one command rather than a hunt.
Two spellings are load-bearing, because they are what the gate finds:
in prose |
pinned against |
|---|---|
|
the manifest’s length and its distinct |
|
how many ids carry that prefix |
|
the hook’s own list and the lines it spans |
|
the four counts in the |
A count of the whole manifest has ONE owner, the first row above; the other two
pages say “every entry” and the gate fails if a bare all <n> entries comes
back. The dead-function census joined the table on 2026-09-05, for the same reason
the others did: its three figures were re-typed prose and had drifted by 11
functions and 8 rows. Two numbers remain unpinnable and are written as what they
are: a wall clock moves with the machine, and a per-gate offender census belongs to
its allow file. Those carry the date they were measured, or no digit at all — a
figure a reader cannot trust is worse than a sentence without one.
Code size — functions and files (code-size)#
linux/scripts/verify_code_size.py, preflight slug code-size. One contract over
four subjects: shell functions and Python functions over
FUNCTION_SIZE_LIMIT (default 80) against function-size.allow, and shell,
Python and Dockerfile files over FILE_SIZE_LIMIT (default 800) against
file-size.allow. The offenders that exist today are frozen in those two
files, which are the inventory — this page does not keep a second count.
When an oversized file shrinks, update its recorded line count; a stale size freeze fails the gate.
Python functions are read with ast, not a regex: end_lineno is exact, nested
defs are qualified (Class.method), and a decorator or a multi-line signature
cannot fool it. Dockerfiles have no function structure, so they are size-checked
as files only — Dockerfile.media at 1248 lines (2026-09-25) is the largest
Dockerfile in the tree (two files in the gate’s scan set are bigger:
smoke-runtime-image.sh at 2612 and build-app-wheelhouse.sh at 1258) and was
invisible to every gate until 2026-09-03.
One script rather than two: the four-way contract and the allow-file handling are shared, and a second copy would have tripped the duplication gate — correctly.
What a shell function’s extent is#
shell_functions counts braces over code_lines, not over the raw file: comment
text, quoted text and heredoc bodies are blanked first, with quote and $( )
state carried across lines. Until 2026-09-04 it counted raw { and }, and three
things followed. A } in a comment or a string ended the function early —
generate_pkgconfig_file measured 5 lines instead of 37, truncated by the
comment describing the very stray-brace bug it fixes, and
_gst_monorepo_tflite_flags measured 32 instead of 51 for the same reason. An
unbalanced { in a comment or a quoted case pattern meant the count never
returned to zero, so the function was invisible to every extent gate —
override_soundtouch_codeberg_checksum (68 lines, cc 16) and
claude_stream_render (38 lines) had never been measured by anything. And a
column-0 name() { inside a cat <<'SH' fixture read as a definition: 29 names
over 62 heredoc occurrences, four of which had been frozen in
dead-functions.allow as dead code that never existed.
The stripper is strip_line / code_lines, and it lives here rather than in
verify_code_complexity.py, which is where it was first written: code-size owns
scan, DEF_HEAD and shell_functions, and code-complexity, dead-functions,
trailing-conditional and gate-registry all import from it, so the lexer sits at the bottom of the
import graph and every gate that reads shell source shares one copy. Importing
upward from code-size into code-complexity would have been a cycle.
Why it exists. Until 2026-09-03 the repo had no length metric at all. The F1
and F2 queues in docs/refactoring-backlog.md were counted by hand, which is why
their tables went stale between rounds — they had to be re-measured five times in
a single day, and two functions over the limit (_shipped_truth_probe at 121
lines, cmake_build_parse_args at 116) had never appeared in them.
The contract is four-way, and each direction matters:
condition |
verdict |
|---|---|
over the limit, not frozen |
FAIL — split it, or freeze it with a reason |
grew past its frozen number |
FAIL — update the entry and say why |
shrank below its frozen number |
FAIL — update the entry |
frozen but no longer over the limit |
FAIL — stale, delete the line |
Growth is allowed, but never silent. An outright ban would block a needed
addition to an already-oversized file and push it into the wrong one instead — the
gate caught exactly that within an hour of existing, when ten ADV probes were
added to smoke-runtime-image.sh for WC. What the gate guarantees is that the
number always matches reality, so a size change lands in the diff next to a reason.
The last two rows are what stop the baseline becoming cover for the next offender:
an improvement has to be recorded, and a freeze cannot outlive its subject. Same
shape as comment-size and masked-assignments.
Length is weak evidence on its own. This gate does not argue that a long function is wrong; it argues that the queue should stay honest without a human re-counting. The judgement about whether to split lives in the backlog.
Covered by linux/scripts/tests/test-code-size.sh, over throwaway
trees, each case proven to go red by disabling the matching branch. One of them exists
because a mutation slipped through — asserting on the FAIL message alone let a
variant pass that printed the failure and still exited 0, so the file half now
asserts the exit code too.
README length (readme-length)#
The README rule holds a root README to 100 lines, badges included, 700 words and 160 characters a
line (repository-family.md § The README rule).
linux/scripts/verify_readme_length.py checks all three and names the rule’s page. A missing
README.md fails too.
Fix a finding by moving a procedure, table or piece of history to docs/ and linking it:
lines: over 100 lines fails at once. No census row can hold it.grew: move the new detail to the page that owns it.fell: lower the row in the same commit withpython3 linux/scripts/verify_readme_length.py --write. It lowers rows and deletes a row that reached its limit. It never raises a row or adds one.over the … a README without a row may have: shorten the README until it fits.
metric |
what it counts |
limit |
|---|---|---|
|
tokens that hold a letter or a digit |
700 |
|
lines over 160 characters |
0 |
|
the characters past 160, summed over those lines |
0 |
Lines: newline characters, plus an unterminated last line, as an editor numbers them.
Exempt lines: a line of badges, and a line that is one link (alone, in a list item, as an autolink, a bare URL or a link definition). They count neither words nor width.
The badge block: the generated block from
<!-- readme-badges:start -->to the next<!-- readme-badges:end -->, markers included, counts as one line and neither words nor width. A start marker without an end below it exempts nothing.The census: a README over a limit has a row for that figure, in the format of the
doc-prosecensus. A row may only fall. A figure without a row meets its limit. A row at its limit, or a row of another page, fails until--writedeletes it.
Where it runs:
Here as a preflight slug in the commit hook’s fast set, against
docs/scripts/readme-length.census. The hub fails without its census.In every consumer through
run-lint-gates.sh, solint-gates.ymland the consumers’ pre-push template run it. The line limit binds at once. Words and width only report until the consumer seeds<root>/readme-length.censuswithpython3 third_party/ANTfrastructure/linux/scripts/verify_readme_length.py --root . --seed. A seed writes a row for each figure over its limit and refuses to overwrite a census.
Not covered: any other README (docs/, linux/llm-stack/, a crate’s), and the order and content
of its sections.
tests/test-readme-length.sh drives fixture repos and a fixture hub; -k <section> picks one
group. The readme-length.* mutations prove the three limits, the exempt lines, the ratchet in
both directions, --write and --seed, the missing file and census, and the run-lint-gates.sh
wiring.
README badges (readme-badges)#
The README rule puts the CI lanes’ badges at the top of a root README
(repository-family.md § The README rule).
linux/scripts/verify_readme_badges.py holds the badges to the workflows, both ways:
A file under
.github/workflows/(*.ymlor*.yaml) without a badge inREADME.mdfails.A badge naming a workflow file that does not exist fails.
A badge is a link or image whose URL holds actions/workflows/<file>/badge.svg, GitHub’s own, or
img.shields.io/github/actions/workflow/status/<owner>/<repo>/<file>, with or without a query.
The file name must end the path, so a badge of GitHub’s dynamic workflows
(github-code-scanning/codeql, dependency-graph/auto-submission) names no file and is neither
required nor stale. A link to the workflow page alone is no badge.
Exempt:
A workflow whose only trigger is
workflow_call. It never runs on its own, so its badge would only say “no status”. The gate reads the top-levelon:as a mapping, a flow list or a scalar, with the stdlib YAML subset ofverify_workflow_conventions.py. A workflow it cannot read needs its badge.A name in
<root>/readme-badges.allow: one workflow file name a line,#starts a comment. The file is two-way. A row fails when its workflow has a badge now, when its file is gone, whenon: workflow_callexempts it already, or when it repeats.
Where it runs: in every consumer through run-lint-gates.sh, beside README length. It is opt-in:
without readme-badges.allow it prints one line and passes, so no repository turns red before it
adds the file. An empty file turns it on with no exemption. The hub has no such file, so the gate
is off here and not a preflight slug.
Not covered: the badge’s order, its label, its branch query, and whether the owner and repository in the URL are this repository’s, unless the README holds a generated block (README badge table).
tests/test-readme-badges.sh drives fixture repos; -k <section> picks one group. The
lint-gates.readme-badges-* mutations prove both directions, both URL forms, the dynamic-workflow
paths, the three on: forms, the opt-in, the four stale-row checks and the run-lint-gates.sh
wiring.
README badge table (readme_badge_table.py)#
linux/scripts/readme_badge_table.py writes a README’s badge block. It is a centred table, one row per
group, and every family README carries one. The README length gate counts the block as one line:
python3 third_party/ANTfrastructure/linux/scripts/readme_badge_table.py --root . --write
--writereplaces the lines between<!-- readme-badges:start -->and<!-- readme-badges:end -->inREADME.md. Without both markers, in that order, it exits 2 and says where they go.--checkexits 1 and prints the diff when the block differs from what--writewrites.With neither, it prints the block.
The groups are Build, Release, Quality, Security, Tools and Community, in that order; an empty one has
no row. A workflow badge links the workflow page and shows shields.io’s status with
branch, label and style=flat-square. workflow_call-only workflows and the rows of
readme-badges.allow get none.
The group: RULES in the script is one ordered table of patterns. The first match wins, tried on the
workflow’s name: and then on its file name, and anything unmatched is Tools:
Words |
Group |
|---|---|
on request, release: at the head of the name, anywhere in the file name |
Release |
security, audit, codeql, dependency, renovate |
Security |
lint, pins, code quality, mutation, static, format, powershell, quality |
Quality |
Linux x64, Linux arm64, Linux, Windows x64, Windows arm64, Windows, macOS, build, test, lane |
Build |
A group lists its badges in the table’s order, then by file name, so Linux x64 precedes Linux arm64.
A workflow whose group an override sets ranks by the first rule its label, then its name, matches,
of any group, so Linux x64 moved into Build sorts with the Linux lanes. Matching none, it goes last.
The label is the name without a · build + test suffix (Linux x64). In Build a platform head is the
label (Windows arm64 · test + wheels is Windows arm64). Elsewhere, after a platform head it is the
rest (Linux x64 · mutation gates is Mutation gates), otherwise the head (Release · every lane is
Release). A workflow without a name takes its file name.
The branch is --branch, the override file’s branch, origin/HEAD, then develop. A CI clone
has no origin/HEAD, so a repository whose default is not develop sets branch in the override
file. A workflow whose push names only main, and that has no pull-request trigger, reports main.
The repository is --repo, the override file’s repo, the origin URL, then GITHUB_REPOSITORY.
The override file .github/readme-badges.json is optional:
{
"workflows": {"python-static.yml": {"label": "Python static", "group": "Quality", "branch": "main"}},
"extra": [{"path": "github-code-scanning/codeql", "label": "CodeQL"}],
"community": false
}
extra badges GitHub’s dynamic workflows, which have no file; they carry no branch unless one is
given. An override for a workflow without a badge, an unknown key, or the group Community exits 2.
The Community row is the family’s: shared/config/readme-community.json holds the top-language
badge of {owner}/{repo} and the YouTube, X and PayPal links. "community": false drops it.
The readme-badges gate grades the block: when readme-badges.allow exists and the README holds the
start marker, a block that differs from --check’s, or that cannot be generated, fails.
tests/test-readme-badge-table.sh drives fixture repos; -k <section> picks one group. The
lint-gates.readme-badges-table-* mutations prove the grouping, the labels, the branch rules, the
overrides, the extras, the order, --check, the markers and the gate.
Consumer lanes (consumer-lanes)#
Every family repository calls the hub’s quality lanes its tree needs; the lint gate cannot tell a
repository with no lane from one whose lane passed. linux/scripts/verify_consumer_lanes.py --root DIR
grades the tracked tree (third_party/ left out) against this table:
Lane |
Required when |
|---|---|
|
always |
|
|
|
always |
|
a lockfile |
|
a |
|
a |
|
a |
A lane is called when a tracked .github/workflows/*.yml has an enabled job (no if: false) with
uses: Kataglyphis/ANTfrastructure/.github/workflows/<lane>.yml@<ref>, and that workflow runs on
both push and pull_request. A workflow called through uses: ./.github/workflows/<file> runs on
its callers’ events too, at any depth. Every caller in the family, BeschleunigerBallett’s
mutation-gates.yml and security-audit.yml included, runs on both; workflow_dispatch and
schedule may come on top. A lane called only by hand or only on push fails, named with the events
it has. A workflow the stdlib YAML subset cannot read fails when its text calls a lane.
In the hub, a lane is called when its own workflow file runs on push and pull request, or a push and
pull-request workflow calls it as ./.github/workflows/<lane>.yml.
<root>/consumer-lanes.allow exempts a lane: one <lane> | <reason> a line, # starts a comment
line. It is two-way: a row fails when a workflow calls its lane on push and pull request now, when
the tree does not require its lane, when it has no reason, when it names no lane, or when it repeats.
Without the file the gate is on: unlike readme-badges, the point is no gap in any repository. The
hub’s file names what runs instead of four lanes (preflight slugs, the Windows lane’s PowerShell lint).
A missing lane prints the caller workflow to add, shaped like BeschleunigerBallett’s: push and
pull_request on main and develop, workflow_dispatch, contents: read, one job per lane, one
mutation-gates job per manifest, lint-path set to the folder that holds the PowerShell, and
hub-checkout: true when .gitmodules has no third_party/ANTfrastructure.
Where it runs: in every consumer through run-lint-gates.sh, after README badges, and here as a
preflight slug.
Not covered: branch and path filters on the triggers, a lane’s inputs (the ratchet arguments are
verify_consumer_quality_wiring.py’s), and whether the lane passes.
tests/test-consumer-lanes.sh drives fixture repos and a fixture hub; -k <section> picks one
group. The consumer-lanes.* mutations prove each condition, the printed caller, the trigger rule, local calls, the
allow file both ways, the hub mode and the run-lint-gates.sh wiring.
Pattern limits (pattern-limits)#
A kind = "pattern" row of quality-report.toml is counted and reported; with max it also
binds. linux/scripts/verify_pattern_limits.py --root <repo> fails when such a row matches more
often than its max, and prints every match as file:line: text. An AGENTS.md rule that is one
pattern (“no std::cout in Src/”) holds by gate this way, not by habit.
[[metric]]
name = "direct_stdout_in_src"
kind = "pattern"
pattern = '\bstd::cout\b'
include = ["Src/*"]
max = 0
Where it runs. In every consumer through
run-lint-gates.sh, solint-gates.ymland the pre-push template run it. A repo withoutquality-report.toml, or without a row that hasmax, prints one line and passes.Malformed. A
maxthat is not a whole number of zero or more (true,-1,"0"), a broken regex or a malformed TOML fails the gate; it is never read as no limit.Not covered. A match in an untracked file, and
kind = "ruff"rows: Ruff’s own gate binds those.A recipe: exception-free filesystem calls (CON295). A C++ tree built without exceptions aborts in a throwing
std::filesystemoverload on any OS error other than not-found (a 300-byte path component gives ENAMETOOLONG even as root). The row catches the one-argument throwing overloads, the iterator declaration (recursive_directory_iterator it(root)) and a barecurrent_path();current_path(ec), the non-throwing getter, passes, and a two-argument throwing call such ascopy(from, to)is not caught. AccelerANTgine and BeschleunigerBallett bind theirSrc/with it (2026-11-21), each with a planted-tree test and a recipe; BeschleunigerBallett’s BuildIntegrity check for the same rule could not fire oncreate_directories(ordirectory_iterator(, as both names contain “ec”:[[metric]] name = "throwing_filesystem_calls" kind = "pattern" unit = "lines" pattern = '(std::filesystem|\bfs)::((exists|absolute|canonical|weakly_canonical|proximate|relative|is_directory|is_regular_file|is_empty|is_symlink|create_directory|create_directories|file_size|hard_link_count|last_write_time|remove|remove_all|read_symlink|status|symlink_status|space|(recursive_)?directory_iterator(\s+\w+)?)\([^,()]*\)|(current_path|temp_directory_path)\(\s*\))' include = ["Src/*"] max = 0
tests/test-lint-gates.sh plants a match in a fixture tree; the lint-gates.pattern-limits-* mutations prove
the limit, the malformed max, and that run-lint-gates.sh registers the gate.
AGENTS drift (agents-drift)#
linux/scripts/verify_agents_drift.py --root <consumer> [--json PATH] fails when a consumer’s
AGENTS.md, docs build list or BACKLOG.md no longer names what its tree holds. Exit 0 is clean,
1 has findings, 2 cannot grade (no quality-report.toml, a declared file missing, a malformed
manifest). --json writes totals.findings, totals.checks and the items rows
quality-report.sh reads as agents_drift_findings.
check |
fails on |
|---|---|
|
a tracked |
|
a |
|
a top-level Python package, a Cargo crate, a Dart package at most two directories deep, or a first-level |
|
the numbered headings of |
|
a line over 40 characters repeated verbatim |
|
a |
|
an open |
|
a consumer’s parity manifest or support matrix page that breaks the parity rules |
Where it runs. In the four AI consumers through
run-lint-gates.sh --agents-driftandlint-gates.yml’sagents-drift: true, off for every other caller. Here as the preflight slugagents-drift, which only runsduplicate-lineover the hub’sAGENTS.md: the rulebook has no numbered sections.Not covered. Prose accuracy: a stale sentence that still names the right file passes. A name counts wherever it stands in its section, and a CMake target built from a variable no literal
set()orproject()defines is not counted.
Fix a finding by naming the thing where the check looks, or by deleting what no longer exists;
there is no allowlist. tests/test-agents-drift.sh takes group names so each agents-drift.*
recipe proves its check in under a second.
Parity manifest (parity)#
A consumer declares [parity] manifest and matrix in quality-report.toml. The manifest is one TOML file.
It has [[target]] rows (id, name, accelerator) and [[feature]] rows (id, title).
A [cells.<target>] table holds one cell per feature. A cell takes one of four forms:
{ test = ... }: a tracked path, orpath::textthe file must contain; a string or a list.{ test = ..., gap = ... }: the test proves part, and the row closes the rest.{ gap = ... }: nothing proves it yet.{ na = "why", approved = "<who> <YYYY-MM-DD>" }.
A gap names an ID that BACKLOG.md keeps open, outside a ticked (- [x]) line. Deleting a done row
therefore fails every cell that still waits on it.
check |
fails on |
|---|---|
|
|
|
a target without a cell for a feature, an empty or unknown-keyed cell, an n/a without a dated approval, an approval on anything but an n/a |
|
a test path that is not tracked, or a file without its |
|
a gap ID the backlog does not keep open |
|
a page without the |
python3 linux/scripts/parity_manifest.py --root <consumer> --write renders the block: features as rows, targets
with their accelerator as columns, yes/part/no/n/a, then the open cells with their rows and the n/a cells
with their approvals. Without --write it runs the same checks alone. tests/test-agents-drift.sh parity proves them.
Consumer pages against the hub (doc-dupes --against-hub)#
docs/scripts/verify_doc_dupes.py --against-hub --root <consumer> grades a consumer’s tracked
pages against every tracked page of the hub the script ships in, records excluded, by the plain
mode’s rule: a consumer paragraph and a hub paragraph sharing more than 12 eight-word shingles is a
copy, and a shingle held by more than five paragraphs is vocabulary. Only consumer ↔ hub pairs
count; pairs inside either tree are the plain mode’s. In both modes a badge or image line is
markup, not prose, so the badge row every family README opens with matches nothing; so is
everything between the readme-badges markers, the table readme_badge_table.py writes.
Where it runs. In every consumer, through
run-lint-gates.sh --ratchets. Never in the hub, which is the reference:--against-hubwithout a consumer--rootexits 2.Off until seeded. Without
<root>/doc-dupes-hub.allowit says so, reads nothing and exits 0, so a hub git cannot list (the mutation mirror) never fails it;--reportlists what it would find and still exits 0. An empty file turns it on. Rows areconsumer page | hub page | budget | reason, in that order, budgeted at the measurement; a row whose overlap is gone fails.Fixing a finding. Replace the consumer’s passage with a link to the hub page (
INDEX.mdmaps topic to page). Budget a pair only when the consumer must say it too, and say why.Not covered. A copy reworded below the threshold, code blocks and tables, and a hub passage restated in other words.
tests/test-doc-dupes.sh drives the mode against a fixture hub, and the aggregator’s call; the
doc-dupes.hub-* mutations prove the off switch and its git-free short cut, the failure once seeded, the consumer-side budget,
the stale row, the cross-side rule, the refused hub root and the wiring, and
doc-dupes.badges-are-not-prose and doc-dupes.badge-block-not-prose the markup rule.
Doc prose (doc-prose)#
linux/scripts/verify_doc_prose.py holds the prose of every tracked .md and .rst page to its
rows in a committed census. A value may only fall. The style it measures is in
writing-docs.md.
Fix a finding by its word:
grew: rewrite the new text. Use shorter sentences, move dates and ids to the records, and drop bold.fell: lower the row in the same commit withpython3 linux/scripts/verify_doc_prose.py --write. It lowers rows and deletes the rows of pages that are gone. It never raises a row or adds one.over the … a page without census rows may have: rewrite the page until it fits the limits.
metric |
per page |
|---|---|
|
words per sentence |
|
percent of sentences over 30 words |
|
ISO dates, |
|
bold spans per 1000 words |
|
the root |
What counts as prose: paragraphs and list items. A sentence never runs across two of them, so a list item without a full stop is its own sentence, and a fragment under three words is none. Code fences, inline code, tables, headings, HTML comments, link targets and generated blocks are skipped. In reST, so are directives other than admonitions, literal blocks and simple tables.
Short pages: a page with under 100 words of prose is not graded. A page under 1000 words counts as 1000 for the two rates per 1000 words.
Not graded:
CHANGELOG*,BACKLOG*and the other backlogs, archives,decisions.md, licence texts,third_party/, vendored and upstream trees, and a page whose first five lines say it is generated.A new page: without census rows, a page must stay within 22 words per sentence, 15 % of sentences over 30 words and 2 dates or ids per 1000 words. Bold has no fixed limit. A row for a new page is an exception, and only the owner grants one.
The
AGENTS.mdbudget: its word count is a census row and may only fall. The hub’s target is 6000 words, a consumer’s 3000, and every run prints the distance. Without a row, the target is the limit.
Where it runs:
Here as the preflight slug
doc-prose, in the commit hook’s fast set, againstdocs/scripts/doc-prose.census. The hub fails without its census.In every consumer through
run-lint-gates.sh. It only reports until the consumer seeds<root>/doc-prose.censuswithpython3 third_party/ANTfrastructure/linux/scripts/verify_doc_prose.py --root . --seed, which refuses to overwrite an existing census.--reportlists every page’s figures, longest sentences first.
Not covered: whether a sentence is true or clear, run ids and hashes, prose inside a table, and Markdown’s indented code blocks, which count as prose.
tests/test-doc-prose.sh drives fixture repos and a fixture hub; -k <section> picks one group.
The doc-prose.* mutations prove the splitter, the skipped parts, the exemptions, the ratchet in
both directions, --write and --seed, the limits at their edges, the word targets and the
run-lint-gates.sh wiring.
Code-to-docs pointers (doc-links)#
The comment rule above produces one artefact per shortened comment: a
docs/<page>.md#<anchor> pointer in code. 286 of them in 131 files as of
2026-09-03 — more than every Markdown link in docs/ combined — and nothing
rendered them, so nothing noticed when a page or heading moved. The first census
found one dead page and five dead anchors, two of them written that same week
under the very directive that created the convention.
docs/scripts/verify_doc_links.py therefore scans code as well as docs (one
owner for every kind of cross-reference): linux/, docs/scripts/, .github/
and the Makefile, all suffixes except .md/.patch/.diff. A pointer’s page
must exist and its #anchor must be a heading slug or an <a id="…"> in that
page. Anchors are matched exactly — code pointers are written by hand to a
known slug, so the prose-abbreviation tolerance of the § check does not apply.
When a heading is long or likely to be reworded, give it a stable id
(<a id="qairt_headers_dir"></a> above the heading) and point code at that
instead of the slug. windows/ is not scanned: it is its own lane.
Fixtures for both failure directions live in
linux/scripts/tests/test-doc-links.sh; mutation doc-links.code-pointers
proves the scan is still running.
A section number with prose after it#
The § check reads what follows the sign as a heading name, up to 70 characters or the
next . , ; ) | " [ ]. A sentence that goes on after a section number was therefore one
long name that no heading has, and the gate failed it with (no such heading):
`AGENTS.md` § 5 re-records the golden from five or more runs.
Such a reference passes when the page it names has a numbered heading with that number
(## 5. Build, run, test), the rule a bare (§ 1a) already follows on its own page. A
number no section carries still fails, and so does a renamed heading cited by name.
Not covered. Behind a number that still exists the words are not compared: a reference to section 5 by its old title passes after that section was renamed. A number that names a list item or an unnumbered heading still fails; write the heading’s name.
Fixtures in test-doc-links.sh; recipes doc-links.numbered-mention-passes and
doc-links.numbered-mention-number-checked.
The secret scan scans from inside the tree#
lint-secrets.sh runs gitleaks detect --no-git with a relative --source .
after cd-ing into the scan root, and that is load-bearing rather than stylistic:
gitleaks matches an allowlist’s paths regex against the path it reports, so an
absolute --source makes every path-anchored rule stop matching, silently.
.gitleaks.toml allowlists ^out/ — build logs and artefacts, which .gitignore:4
already keeps out of every commit, so nothing there can reach the thing this gate
grades (“what the NEXT commit would ship”). When the consumer-repo refactor swapped
the relative source for --source "${SCAN_ROOT}", that anchor stopped matching and
the gate went from 2.42 GB in 3m37s, clean to 8.22 GB in 12m48s with 10801
findings — every one of them ROCM_GPG_KEY_SHA256 in a gitignored build log, i.e.
the checksum of a public GPG key.
The same config excludes logs/ and Python __pycache__/: script tests create
synthetic credentials and downloaded dependency code there while preflight slugs
run concurrently. These are ignored outputs, not source shipped by a commit.
Consumer support is unaffected: a consumer’s own .gitleaks.toml anchors its paths
relative to its own tree too, which is exactly what scanning from inside gives it.
The retry classifier: anchor every status, and DNS is transient#
_cross_stage_push_error_is_transient (01-core/cross-stage-build.sh) decides
whether a failed stage is worth retrying, by grepping the log tail. Two defects
found by real chains on 2026-09-08, both now pinned by mutations:
Anchor every HTTP status to its status TEXT or to a
status:label. A bare[^0-9]429[^0-9]matched BuildKit’s own elapsed-time prefix —#15 429.0 <cmd>— so any step that had been running 429.x seconds made the NEXT deterministic failure look rate-limited. A smoke that could never pass was rebuilt three times before the cap. The(500|502|503|504)arm beside it always required the status text and so never had the bug; that asymmetry is the tell. The same trap waits at 4290–4299 s, which is where a long LLVM step sits.DNS belongs in the list. A source stage clones from github, and a blip reading
Could not resolve hostkilled a whole chain atsdk-riscv64— the STAGE BARRIER takes every arch down with it, so one failed lookup cost the run.could not resolve host,temporary failure in name resolution,name or service not knownandnetwork is unreachableare all retryable now.
Both survived because test-cross-stage-build-cmd.sh STUBBED the classifier to
[ "${TRANSIENT:-0}" = "1" ], so its regex had zero coverage while the file
looked well tested. Twelve assertions now drive the SHIPPED function. A stub of the
unit under test is not coverage of it — the same shape the code-size.*
mutations had while every one of them drove a fixture tree and none could see the
real SCAN (code-size.llm-stack-is-a-subject now does).
Generated data is not source, and git alone cannot say so#
A benchmark result under OrchestrANT’s benchmarks/benchmark_results/ holds MODEL
OUTPUT. A model that writes a plausible docs/<page>.md link into its answer is
not making a repo reference, and two such lines once failed the gate with
findings nobody could act on. _ignored_paths() therefore drops output trees
before scanning, and UNTRACKED_OUTPUT names the ones this repo still has
(linux/webserver/dist, linux/llm-stack/.env,
linux/llm-stack/ollama-binary.tar.zst); under a consumer --root the gate
lists tracked files and applies neither.
It is a floor under both answers, not a git-free fallback, because git is
wrong here in two separate ways. Without .git — the mutation gate mirrors the
repo minus .git before mutating — check-ignore exits 128 and answers
nothing, which once turned 566 scanned files into 5,467. And WITH .git,
check-ignore never reports a tracked file, while .gitignore deliberately
re-admits dated run directories (benchmark_results/* then
!benchmark_results/20*/) so a run can be committed as a record. The first
commit to use that (28280c43, 68 files) put 66 model-output files back into
the scan while git reported nothing ignored at all. The answer is
git ∪ UNTRACKED_OUTPUT; test-doc-links.sh pins the two to be equal on the
real tree, which is what caught it.
Header pointers must name a section#
A pointer with no #anchor passes every check above and still rots: rename the
section it meant and nothing complains, because the page it names still exists.
That is CL4 in the backlog, and it was found the hard way — a header pointing at
the quarantined general-Linux cheat-sheet, a page that said nothing about the
script pointing at it.
A gate over every bare pointer is not worth having: re-derived on 2026-09-05
there are 463 code pointers, 197 anchored and 266 bare, and most of the bare
ones are prose naming a whole page, which is not a broken reference. So the rule
is narrowed to where the house comment convention already promises an anchor —
the header of a .sh/.py file, meaning the first HEADER_LINES (10) lines.
A page.md § Heading on the line is not bare: the § check already validates
where that lands.
Of the 110 distinct file-header pointers measured on 2026-09-05, 96 name a
section, 6 use the § spelling, and 8 are bare — frozen two-way in
docs/scripts/doc-header-pointers.allow, keyed <file> + TAB + <page> so a
header moving within its block does not re-flag it.
The 38 rows of debt the rule shipped with are closed. The allow file opened at 45 rows in three groups, and the two that were debt are gone:
group |
then |
now |
|---|---|---|
the page IS the subject |
7 |
8 — unchanged in kind, plus |
into |
9 |
0 — each re-pointed at a durable page, because an OPEN entry is archived when it closes, so an anchor there is built to rot |
into a large multi-subject page |
29 |
0 — one anchor each, at the section that actually owns the file |
Nine of those needed a section that did not exist yet, so the section was written
rather than the pointer bent to fit: three failure classes in failure-modes.md
(errexit suppressed inside an if ! condition, an unreachable checksum probe
reading as “nothing to verify”, a soname resolved by an apt-cache prefix guess),
four in cross-build-verification.md (the 01-core layer table, the cross
gobject-introspection wrapper names, gstreamer-env.sh, and the wrapper
generation gate), one in shared-script-libraries.md, and one promotion of an
already-written paragraph — “Verify the shipped BYTES, never the push” — into the
heading it always deserved. That is the point of the rule: a pointer that
cannot name a section is usually telling you the doc has a hole, not that the
anchor is optional.
And that class cannot come back. UNFREEZABLE_PAGES in the gate makes a
header pointer at refactoring-backlog.md a finding whether it is frozen or not,
and the message carries the fix: re-point at the durable page. Freezing is what
the nine rows did, and every one of them rotted the way the group comment said it
would. Mutation doc-links.header-open-backlog proves the rule is live.
Its blind spots, named. The header window stops at line 10. Dockerfiles and
.env files sit outside the header rule (it reads only .sh/.py headers),
though their pointers are still checked for page and anchor. An anchor can resolve and still be the
wrong section for the file quoting it. And the 266 pointers living in ordinary
prose were declined on purpose, not overlooked.
One consequence of the scan set, and it is deliberate. The manifest and the
three allow files under docs/scripts/ are inside this gate’s own scope, so a reference
quoted in a mutation entry is held to the same rule as one in code. Break a
pointer there and the real tree goes red — which is why
doc-links.flutter-checks-anchor neuters the target heading rather than the
pointer text. dead-functions exempts the manifest; this gate does not, on the
grounds that a stale pointer is stale wherever it is written.
Links a build resolves from another directory#
DocumANTation’s data/book/chapters/11-template-demo.md links data/book/images/figure1.jpg. pandoc
runs from the repo root with --resource-path . (md2pdfLib/pandoc_builder.py), so the PDF finds it;
read from its page it is no such file. <root>/doc-link-roots.allow declares such a root, one
<page glob> | <directory> row each (fnmatch, so * crosses /; the directory relative to the
root): a link its page does not resolve may resolve from that directory, for matching pages only, so
a README GitHub renders keeps page-relative links. Two-way: a row no link needs is STALE, and a
directory that does not exist is a finding. The hub declares none (its file would sit beside the
gate). Mutations doc-links.link-roots-*.
Gate proof registry (gate-registry)#
linux/scripts/verify_gate_registry.py, preflight slug gate-registry, allowlist
linux/scripts/gate-proofs.allow, generated page
code-quality-gates.md. It is the meta-gate: every other
slug in preflight.sh must be provable, and the table that says so is derived,
never typed.
Why it exists. The failure this repo keeps finding is a check that looks green
while proving nothing — the same failure the mutations gate exists for, one level
up. A gate with no suite and no mutation is exactly that risk, and nothing used to
count them. This gate counts them, freezes today’s unproven set, and refuses to let
it grow.
What it derives#
It parses KNOWN_SLUGS and every run_check <slug> "<name>" <command> line, and
for each slug emits: script, allow files, proving suites, proving mutations and
hook tier. KNOWN_SLUGS and the run_check set disagreeing is a hard error, not a
partial table; so is more than one surviving run_check line for one slug.
Resolving the script:
the first token that ends in
.py/.shand is a repo file — a file gate;otherwise the last shell function the command names, resolved to its defining file — an inline gate. Several files may define that name, so the tie-break is
preflight.shfirst, then a file therun_checkcommand itself names, and only then alphabetical. The function’s line extent is kept, so the allow-file scan sees the function body and not the whole host file;the
if [ -f X ]; then run_check … else run_check … MISSINGpair collapses to the real arm.
Proof rules#
These are printed in the generated page’s intro too, because a reader’s first question is always “why does that suite count?”.
A suite proves a gate by mentioning its needle. The needle is the script basename for a file gate and the function name for an inline gate. The match is a left-bounded word (
(?<![\w.-])needle\b), not a substring: a suite namingnot-delta.shdoes not provedelta.sh.Why a mention and not “the suite executes the script”. Suites here legitimately copy a gate into a throwaway tree and run it from there; an execution-based rule would report the best-tested gates as unproven. The price is stated openly: an incidental mention counts. The
mutationsgate is the backstop that turns a mention into evidence.Why the function name for an inline gate. An inline gate’s script column is its host file — usually
preflight.sh, which eleven other suites mention in passing (four did when this rule was written). Keyed by the file,crlf-guardread “proven” while neutering its awk pattern survived all four. Keyed bycheck_crlf_guard, onlytests/test-crlf-guard.shcounts.A
mutations.jsonentry is credited to the gate its id prefix names — ids are<slug>.<kebab>— and only when itstargetis one of that gate’s own files — its script, a module that scriptimports, or a helper a.shgate runs as a separate program — or a call site: a file the gate does not own that names the gate’s script, in an entry whosetestruns one of the gate’s own suites. The prefix is the claim, the target the evidence; both must agree, so no entry can prove two gates.Why not “the suite that proves this gate runs it”. That was the first rule and it was circular: “proves” is mention-based, and three suites mention
verify_code_size.pyonly because theycpit into a fixture as a dependency of the gate they actually test.code-sizetherefore claimed 7 mutations owned bygate-registry,code-complexityanddead-functions. Keying on the id ended it;shellcheck,artifact-parityandstage-graphlost the mutation half of their proof (all three keep a suite, none dropped to UNPROVEN).The convention is enforced in both directions, over every entry. The rule is about the ID, not about which files happen to be registered. A prefix that names a preflight slug is a claim of ownership: it fails unless the
targetis one of that slug’s own files or a call site credited to it (the rule above) — over an ordinary build script just as much as over another gate’s file. A prefix that names no slug fails when it pins a registered gate’s file at all (that entry belongs to the gate, under the gate’s name), and otherwise must be a declared descriptive family. A typo’d or copied prefix would otherwise stop proving anything in silence, which is the exact failure this whole gate exists to catch. The message names the prefix, the target and who does own it. The escape is a freeze under themutation-id:namespace ingate-proofs.allow, which ratchets down like the slug list.Why not “every id must start with a slug”. Many entries pin ordinary build scripts no gate owns (
wheels.,qairt.,boot.,sccache., …); forcing those under a slug would put false credit in a generated table. They keep descriptive prefixes, declared once asmutation-family:lines, so an invented or misspelled namespace still fails loudly and a family nothing carries any more reads STALE.The hook-tier column follows the hooks — every versioned hook under
linux/host-config/git-hooks/, pre-push included, the widest scope winning — not one string in them.hook+CI= the slug is listed in_FAST_SLUGS, so the whole gate runs on every commit;hook (whole tree)+CI= a hook names the gate at its top level and runs it unconditionally (mutations, via pre-push);hook (scoped)+CI= a later hook block hands the gate the staged file list (shellcheck,shellcheck-warnings);hook (whole tree, when relevant)+CI= a block runs the whole-tree gate but only fires when the commit touches its inputs (doc-dupes, behind[ -n "${_staged_md}" ]);CI= preflight and CI only. The two block tiers are not interchangeable to a reader: one says “only what you staged was checked”, the other says “everything was checked, this time”. A block is scoped when its body expands the guard variable or passes--changed; otherwise it is whole-tree. The needle is the same one the suite scan uses, sonot-delta.shin the hook does not promotedelta.sh.script-testsandmutationsare by construction: they are the proof machinery, so they can never read UNPROVEN.
The allowlist#
gate-proofs.allow is a set metric under the two-way rule (see
The allowlist contract): a slug with no proof that is
not frozen is NEW and fails; a frozen slug that has since gained a proof is STALE
and its line must be deleted. The list only ratchets down. Baseline 2026-09-03: 15
of 33 slugs — the four gates added that day all shipped with a suite, so none of
them is on it. Lines prefixed mutation-id: are the second namespace, counted and
reported on their own line: mutation ids that break the <slug>.<kebab>
convention. The check found two on 2026-09-04 —
shellcheck-warnings.pin-only-path-bin and shellcheck-warnings.list-files-first,
both pinning lint-shell.sh, which shellcheck owns — and both were renamed to
shellcheck.<kebab> in mutations.json and their freezes deleted in the same
change: renaming without deleting reports STALE, deleting without renaming reports
the prefix that cannot own it.
Lines prefixed mutation-family: are the third namespace and are NOT debt: they
declare descriptive prefixes for implementation files no gate owns. 16 declared
on 2026-09-04, covering 43 ids. An undeclared prefix fails as
NEW; a family no id carries any more is STALE. If a family name is ever adopted as
a preflight slug, every id under it starts being judged by ownership and the
declaration goes stale in the same run. The file therefore holds three counts —
frozen slugs, mutation-id: freezes and mutation-family: declarations — which
the gate prints live on every run.
The five ids frozen here on 2026-09-04 were the shape the file-ownership model
could not then express: four mutations.* ids pinning that gate’s CALL SITES in
preflight.sh and the pre-commit hook, and python-lint.heredoc-python-decision
pinning extract_embedded_python.py, the helper lint-python.sh shells out to.
The registry now credits both shapes (calls_the_gate(), shelled_out()), so all
five are credited and their freezes are gone. The last one went on 2026-10-31:
shared-config.exact-mode-is-declared-in-the-manifest pinned
shared/config/shared-assets.manifest, a data file no ownership edge reaches, so
it is now shared-assets.exact-mode-is-declared-in-the-manifest, in the declared
shared-assets family, with the same edit and test. No mutation-id: row is left.
The cheapest proof per slug, by shape — the recipes that emptied the list (every slug below is proven now; see The two that stay frozen, with better reasons):
Tree-consistency checkers (
copy-coverage,critical-fixes,patch-integrity,arg-consistency,mirror-consistency,runtime-paths,android-parity,pkg-names,version-snapshot): a fixture tree with one planted offender and one clean twin, asserting the exit code and the message — most vacuous tests assert only the message.stdout-returnsleft this list on 2026-09-04 by being written that way; it is the worked example below.Third-party linter wrappers (
dockerfile-lint,workflow-lint,secret-scan): the wrapper is what is untested, not the linter. Feed it a file the linter must reject and assert the wrapper propagates a non-zero exit.doc-dupes: mirrortests/test-code-dupes.sh.sbom: assert--checkfails on a hand-edited SBOM, the way this gate asserts a hand-edited registry fails.
crlf-guard, the worked example#
linux/scripts/verify-shell-eol.sh [<root>] (preflight’s check_crlf_guard calls it on
the hub, run-lint-gates.sh on a consumer) asks lint-shell.sh --list-files
which of the tracked files are shell scripts, reads git ls-files --eol over exactly
those, and fails naming every one whose working-tree bytes carry CR. With
--staged, the consumers’ commit hook, it reads the i/ column of the staged scripts
instead: the bytes the commit carries.
Which column decides. git ls-files --eol prints i/<eol> w/<eol> attr/<attr>
— the index shape and the working-tree shape. Only w/ counts here, because
buildkit builds from the working directory (--local=context=.): a file that is
i/crlf but w/lf ships LF bytes and is not an offender, and flagging it would be
a false positive on any tree mid-git add. A file missing from the working tree
prints an empty w/ column and is likewise not an offender.
Which files are in scope. The pathspec used to be -- '*.sh', which cannot see
an extension-less script on a shell shebang — including
linux/host-config/git-hooks/pre-commit, the hook that runs this very gate. The
neighbouring shellcheck gate admits those files explicitly, so the repo held two
gates with two different answers to “what is a shell script”. There is now one
owner: lint-shell.sh --list-files, the same scope the shellcheck warning ratchet
consumes. Feeding it git ls-files -z classified the whole tracked tree in ~68 ms
on 2026-09-03,
which is inside the budget for a _FAST_SLUGS member. A tracked file that is not a
shell script (prose, a patch, a fixture) may carry CR and is not an offender.
Which shapes are offenders. w/crlf is only emitted when every line ends
CRLF. The realistic accident — an editor or a merge that rewrote some lines — is
w/mixed, and a bare CR with no LF after it makes git report w/-text. All three
put a \r into a line bash will execute, which is exactly the container failure
$'\r': command not found. w/-text is also git’s shape for a genuinely binary
file, which a tracked *.sh never legitimately is, so it is flagged too; w/none
(no line endings at all) and w/lf are clean. The awk therefore splits the eol
prefix into fields and compares the second one, rather than substring-matching the
whole prefix — an attr/ value is in the same tab-delimited field and must not be
able to vote.
tests/test-crlf-guard.sh extracts the function with t_fn_src and runs it inside
throwaway git repos, one per shape: LF-only passes; wholly-CRLF, one-CRLF-line-among-LF
(w/mixed) and a lone CR (w/-text) are each named with their shape and return 1
while the LF sibling is not named; w/mixed is still caught under a
.gitattributes *.sh text eol=lf pin, because that attribute normalises the
next checkout, not the bytes on disk now; CRLF-in-index-with-LF-on-disk and a
deleted file both pass; an extension-less git-hooks/pre-commit is caught while an
extension-less NOTES is not; and a directory that is not a repo, or a tree with no
lint-shell.sh to answer the scope question, returns 1 printing
__git-ls-files-FAILED__ instead of reading as clean.
The .gitattributes pins documentation, workflow YAML, docs-site templates and
GPU fixture sources to LF because those tests compare full lines under WSL.
That last guarantee holds only under pipefail — a failing stage fails the
pipeline only because preflight.sh sets set -uo pipefail. The suite used to
hard-code those options when it ran the extracted function, so deleting pipefail
from preflight.sh survived every suite in the tree. It now derives the options from
preflight.sh’s own set - line and asserts that line pins pipefail, which puts
the dependency where it lives; crlf-guard.pipefail-pin proves it.
Seven mutations pin it, all survived by every suite that merely mentions
preflight.sh: crlf-guard.pattern-neutered (the awk condition → never-matches),
crlf-guard.mixed-blind (drop the w/mixed arm — the original bug),
crlf-guard.lone-cr-blind (drop the w/-text arm), crlf-guard.index-column
(read i/ instead of w/), crlf-guard.scope-sh-suffix-only (back to the
'*.sh' pathspec), crlf-guard.scope-not-classified (take every tracked path
instead of asking the owner) and crlf-guard.pipefail-pin (set -uo pipefail
→ set -u).
A former limit, closed in the scope owner. lint-shell.sh sniffs the shebang
with head -n 1 and strips the CR before matching, so a wholly CRLF
extension-less script (#!/usr/bin/env bash\r) is in scope for this gate and for
shellcheck alike; shellcheck.crlf-shebang pins it. The fix was one edit in
lint-shell.sh, that gate’s scope owner, not a second classifier here.
Flags#
flag |
use |
|---|---|
(none) |
check mode — fails on a stale page, a NEW unproven slug, or a STALE frozen line |
|
regenerate |
The page is data, not prose: regenerate it, never hand-edit it. It must be
regenerated whenever a slug, a suite name, a mutation entry or the hook’s
_FAST_SLUGS changes.
Known limits#
Mention-based proof is a heuristic. A suite that names a gate and asserts nothing about it still counts; only the
mutationsgate can tell the difference.Only slugs wired into
preflight.share visible. A checker that exists but is not wired in is invisible to this registry.The hook-tier column sees
_FAST_SLUGSand any hook — a guarded block or its top level, in any versioned hook — that names the gate. A hook that ran a gate without naming its script or its inline function — behind a variable, say — would still read CI-only.Scope is read from the block, not from the gate’s own argument parser. A block that named the gate and then scoped it through some third spelling of “the staged files” would read whole-tree.
Pinned by tests/test-gate-registry.sh over a thirteen-slug fixture
plus ordinary.sh, a build script no run_check registers (one per shape: file
gate proven by a suite, by its own mutation, by an inherited mutation credited by
id prefix, the same import under another gate’s prefix, unproven, [ -f ]
fallback pair, inline in preflight.sh, inline in a sourced lib, inline with a
same-named stub in a lib nobody sources, run whole-tree by a staged-docs block,
scoped by --changed rather than the guard variable, named at the top level of a
second hook (pre-push), by-construction) plus the shelled-out-helper and
call-site credit rules, the
mutation-id: and mutation-family: ratchets in both directions and all three
convention breaches they catch, 32 in tests/test-crlf-guard.sh,
and 28 entries (gate-registry.*).
Python test report integrity#
linux/scripts/02-toolchain/python/verify-test-reports.py is called after every
successful stable ci_tests.sh pytest leg. It requires a JUnit report with at least
one passing test and a Cobertura report with measured, covered package lines. The
driver removes prior XML for that leg before pytest, so stale output cannot certify
a new run. Pass coverage-min to python-ci-linux.yml to require a percentage; the
default 0 still rejects zero covered lines. The check accepts skipped tests when
another test passed. Experimental legs annotate failures. Run it separately with
python3 linux/scripts/02-toolchain/python/verify-test-reports.py --junit logs/test-results/report-3.14.xml --coverage logs/test-results/coverage-3.14.xml --min-coverage 70. The fixture suite checks missing, malformed, empty and low reports;
it cannot prove that test assertions cover important behavior.
Generated quality reports#
Build transcripts, resource measurements, test results and coverage reports live under the
Git-ignored logs/ directory. Linux and Windows Python CI put their reports in
logs/test-results/; Linux stage logs use logs/build-logs/, and Windows BuildKit uses
logs/windows-build-logs/. The docs build copies selected reports into its generated site
assets for publication. The live chain-status*.json files remain at the repo root because
the chain reads them there. PowerShell complexity JSON belongs under ignored
logs/code-quality/.
The Windows test runner writes a JSON summary for each parent run to
logs/windows-tests/summary-<timestamp>-<pid>.json; child runs do not write durable copies.
An explicit child -ResultFile creates its parent and fails on a write error, so a
fresh mutation mirror can run the actual PowerShell baseline before testing a mutant.
Recipes invoke that runner directly: a Unix mkdir -p ... && prefix fails under
Windows command parsing before any baseline assertion runs.
Measurements as JSON#
verify_code_size.py, verify_code_complexity.py, verify_code_dupes.py and
verify_hub_reuse.py accept --json PATH. Without it, their output and exit status are
unchanged. With it, they also write one record through gate_scope.write_json. A missing
parent directory is created. A write error exits 2.
key |
content |
|---|---|
|
|
|
|
|
the absolute tree that was graded |
|
the thresholds the counts use |
|
counts for the whole scan |
|
the same counts per repo-relative path |
|
present only with |
|
code-dupes and hub-reuse only: one |
scanner |
|
per file |
|---|---|---|
code-size |
|
|
code-complexity |
|
the same, without |
code-dupes |
|
|
hub-reuse |
|
|
The counts are measurements, not verdicts: oversized_*, over_* and pairs ignore the
freeze files. They equal the --report-only lines, and functions:/files:/cc:/nesting:
in gate mode. A code-dupes file pair counts once for each of its two files, so per-file
pairs do not sum to the total. Complexity lists only files that hold a function.
--explain and --baseline refuse --json. test-scanner-json.sh checks each total
against the text verdict on a fixture tree.
Extra-language readers (report-only)#
--extra-languages adds units that never change the exit status:
verify_code_size.pyprintsREPORT-ONLY:for each Rust (.rs), Dart (.dart) and C/C++ (.c .cc .cpp .h .hpp .ixx) function overFUNCTION_SIZE_LIMIT, and a total line. A Dartmain()in a*_test.dartfile is atest bodyand counted apart (oversized_test_bodies): its length is the number of tests in it, not product code.verify_code_dupes.pyindexes Python files apart from the gated kinds and prints file pairs over the threshold. Units are outermost functions, with decorators, and blank-line chunks. Comments are dropped and strings reduced before shingling. A shell or PowerShell count cannot move.
No complexity reader exists for these languages. Complexity stays Python and shell, with
PowerShell in Invoke-CodeComplexity.ps1.
linux/scripts/lang_units.py holds the readers. It is standard-library Python and is
imported only with the flag. It blanks comments and literals, newlines kept: nested
/* */ in Rust and Dart, raw strings in Rust (r#"…"#) and C++ (R"d(…)d"), Dart ${…}
interpolation, char literals, Rust lifetimes and C++ digit separators. It then walks braces.
A function body is counted, not descended. A namespace, class, impl or mod body is
descended. A C++ member initialiser list is a single : after the parameter list, so a :: in a
trailing return type and an access label’s colon start none (before 2026-11-30 both did, and the
reader swallowed the functions after them). Blind spots:
macros and preprocessor-split headers (
#ifaround a signature);K&R C parameter lists;
Dart
=>bodies, which have no braces;C++ brace member initialisers other than
Foo() : a{1} {;Python files the running interpreter cannot parse.
test-lang-units.sh pins hand-counted fixtures for each language.
The one graded number. The scanner’s exit status never moves, but quality-report.sh --compare
grades functions_over_80_lines_extra_languages (class code): a new oversized Rust, Dart or C/C++
function, test bodies left out, reads regressed. The Python duplicate units, file size and
complexity for these languages stay report-only.
quality-report#
bash linux/scripts/quality-report.sh --root . [--compare FILE|previous-develop] [--offline]
measures one checkout and writes three ignored files under logs/code-quality/:
measurements.json, queue.md and summary.md. A consumer runs it through its one-line
scripts/linux/quality-report.sh. It runs no tests and no builds: test, coverage and
mutation numbers come from files the lanes already wrote.
measurements.json holds schema_version (1), repo, sha, hub_sha, tools (Python,
git, Ruff, ty, pwsh versions), the declared docs and outputs, the baseline it compared
with, and per metric its value, unit, better (lower or higher), class (code is
graded, report is not), source command, status and, for a set, sorted members.
Tree metrics, from the checkout wherever it runs:
metric |
source |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
rows per tracked |
|
one set per marker in |
|
line counts |
|
|
A set member is path|marker|whitespace-normalised line|n, where n counts earlier identical
lines in the file. A moved line keeps its key; a new member regresses even when the count holds.
quality-report.toml (tracked, optional in the hub) holds every repo specific:
[docs] build_listandsource: the docs build list file; a declared file that is missing makes the run incomplete.[[output]]rows (kindbenchmark, golden or latency,path, optionalartifact): recorded indeclaredfor other readers.[[artifact]]rows:name,kind,pathglob, optionalartifactname glob andworkflowfile. Kinds:junit(tests_passed.<name>,tests_skipped.<name>),coveragewithformatcobertura,lcovorjson(coverage.py, llvm-cov or gcovr summary;line_coverage.<name>,branch_coverage.<name>),mutation(mutations_selected.<name>,mutations_caught.<name>fromverify_mutations.pyreport lines),clang-tidy(clang_tidy.<name>, afile|checkset) andcount(<name>, lines matchingpattern, located throughlocation).[perf]and[[perf.command]]: the--perf-hostlatencies (declaration).[[metric]]rows:kind = "pattern"(a regex over tracked files underpaths, filtered byincludeandexcludeglobs, set-valued) orkind = "ruff"(the locked Ruff overpathswithconfigoverrides). A pattern row withmaxis also a gate: pattern limits.
An artifact source is read from the checkout first. Otherwise, unless --offline, the GitHub CLI
downloads the newest matching artifact of a run at the same SHA. No file, no run or no login
gives not-collected, never 0 and never held. A download the artifact store refuses is tried
three times, 5 s apart (quality_report_github.download); one that still fails leaves the
verdict incomplete, as before. An API lookup is not tried again.
Output and exit status. Exactly one
quality-report: verdict=<ok|regressed|incomplete> regressed=<n> improved=<n> metrics=<n> line,
a compare: line, one REGRESSED <metric> <before> -> <now> line per regression and one
not-collected: <metric> (<reason>) line per metric without a value. Exit 0 is ok, 1 regressed
and 2 incomplete. Incomplete means a collector’s tool is missing or failed, or a present input
(the toml, a compare file, a found artifact, a scanner record) is malformed. Only collected
code metrics that the baseline also collected are graded.
--compare previous-develop takes measurements.json from the newest unexpired
code-quality-measurements artifact of a successful develop run other than the current one.
Having none yet is not a problem; a failed GitHub lookup or download is.
queue.md lists, for every nonzero lower-is-better code metric, up to ten path:line items,
worst first: most shared shingles, longest or most complex function, largest budget, or the
file with most findings.
CI. code-quality-report.yml takes quality-report: true (default false). It installs
uv, runs the script with --compare previous-develop, appends summary.md to the step summary
and uploads measurements.json and queue.md as code-quality-measurements for 90 days. The
job fails on exit 2, or on exit 0 or 1 without the matching verdict line; a regression is
reported, not enforced. Lane artifacts of the same push are often still running, so their
metrics are commonly not collected there.
Blind spots: suppressions are literal marker text, so another spelling is not counted, and other
languages (PowerShell, YAML, TOML) are read with their strings;
summary.md is not graded; a metric absent from the baseline is not graded; nothing attributes
a change to a commit. --perf-host [--update-baseline] instead runs the repo’s declared
latencies in the CI image against a per-CPU baseline:
fleet-health.md § perf-host. test-quality-report.sh covers a rise, a fall, a direction, a set swap, a
moved set member, a missing collector, an absent artifact, a malformed compare file and the queue.
Benchmark-history fetch fixtures bind the private CLI resolver to their fake
and invoke that script explicitly through Bash. The Python subprocess boundary
rejects other commands, so Windows cannot silently select an installed gh.exe.
This replay checks pagination, retry and report behavior, not CLI authentication
or the live artifact service. Run the complete suite on Linux; Windows fetch
controls do not grade Criterion’s host-dependent path rendering.
Windows Pester coverage#
Captured child diagnostic checks use ConvertTo-TestDiagnosticText from
TestHarness.psm1 to remove ANSI escapes and wrapped continuation gutters.
Python CI transport and Torch refusal fixtures share it; raw exit status, the
expected reason and the no-download assertion remain independent. The ORT
census-path fixture clears both inherited twin-wheel overrides, with both
deliberately populated in its control. These tests prove fixture isolation,
not real GPU inference or a consumer environment.
The shared PE-icon fixture also links actual x64 and ARM64 executables and reads
their resources. Linux preflight and mutation runners call
bash linux/scripts/ensure-pe-icon-test-tools.sh --install-missing first: it
reuses existing LLVM/Clang, LLD, Ninja, Rust, Cargo, CMake, Python and PowerShell, and
installs missing Ubuntu packages only when asked. Missing PowerShell and failed
installation remain fatal; this fixture does not run Windows executables.
pwsh -NoProfile -File windows/scripts/tests/Invoke-Tests.ps1 measures command coverage
for fifteen modules, each with a focused Pester suite:
Module |
Minimum command coverage |
|---|---|
|
85% |
|
90% |
|
60% |
|
90% |
|
100% |
|
85% |
|
90% |
|
80% |
|
80% |
|
65% |
|
80% |
|
90% |
|
80% |
|
100% |
|
80% |
The target-inventory test pins every suite/module pair and floor, and mutations prove
that removing the ONNX, wasm-opt, WebDAV, MSIX signing, container-image bootstrap or Vulkan target or lowering its floor fails the test.
The hub runner requires at least one passing test per Pester file. The reusable
run-pester-suite action requires at least one pass across its selected path, which may be a
file or a directory. Individual skipped tests remain allowed alongside a pass.
The runner rejects a missing, empty, malformed or wrong-module Cobertura XML report,
zero measured files or commands, inconsistent counts, a missing or duplicate target,
or a score below its floor. Parallel child suites pass their results to the parent, which writes the verdict
in its JSON summary. The XML
reports and summary live under ignored logs/windows-tests/; Windows x64 CI uploads
them even when a suite fails. Coverage counts show executed commands, not whether test
assertions prove the intended behavior. Failure-path tests plant missing, empty,
duplicate and low reports so a zero-work or wrong-inventory run cannot pass.
Windows PowerShell complexity#
pwsh -File windows/scripts/Invoke-CodeComplexity.ps1 parses tracked .ps1 and
.psm1 files under windows/, shared/windows/ and .github/actions/ with the
PowerShell 7 AST. It excludes archived trees, reports each script, function and
class method, and fails on parse errors or an incomplete file scan. It counts
decision paths, deepest control-flow nesting and code-bearing function lines.
The limits are 15, 5 and 80 respectively; there is no Windows exception list.
WindowsAst.Common.psm1 owns the parse and token result shared with the
structural test harness; the scanner owns file selection and metric rules, and
the harness keeps its rooted-path and missing-file policies.
The default command prints a nonblocking report. Windows x64 CI runs the full
tracked-tree scan with -Strict after the PowerShell lint gate, writes the JSON report
under ignored logs/code-quality/complexity/, and uploads it even when the gate fails. Use
-Path <file-or-dir> -Strict to include a new file before Git tracks it, and
save local JSON results in the Git-ignored logs/code-quality/complexity/ folder:
New-Item -ItemType Directory -Force logs/code-quality/complexity | Out-Null
pwsh -File windows/scripts/Invoke-CodeComplexity.ps1 -Strict -JsonPath logs/code-quality/complexity/windows-full.json
The PowerShell gate is pwsh -File windows/scripts/Invoke-Lint.ps1 + pwsh -File windows/scripts/tests/Invoke-Tests.ps1 (CI: .github/workflows/windows-x64.yml). The suite
guards classes of defect, not instances: when you fix a bug here, prefer a guard for its class.
Invoke-CodeComplexity.ps1 -Strict enforces the 15/5/80 cyclomatic, nesting and function-line
limits across every tracked Windows PowerShell file in hub CI. The reusable
powershell-quality.yml job reports the consumer’s lint-path under -Root and gates it when
strict: true is set. Python Windows CI calls that same job through complexity-strict. Parse and
scan failures are fatal. Do not add exceptions or raise limits to silence findings.
-JsonPath remains optional for local runs; CI supplies it to the strict gate.
For a consumer checkout, pass -Root <consumer-root> -Path <relative-file-or-dir>;
relative paths and JSON report names then use the consumer root. -Root requires
-Path, and a selected file outside the root fails.
The optional lint-powershell job in python-ci-windows.yml runs the scanner
on the consumer’s lint-path after PSScriptAnalyzer. Set complexity-strict: true
in a consumer’s workflow to fail on findings; parse and scan failures are fatal
even in report mode. The default stays report-only while existing consumer code
is brought under the same limits.
The BuildKit driver keeps
stage solves, optional child arguments, preseed setup and teardown in separate
functions; focused variant, media, solve-order and publish-gate fixtures check
those handoffs. The driver and LiteRT wheel builder validate the ty pin in
focused helpers; the wheel still fails before Bazel starts. Pester fixtures
test the metric counts, malformed input and strict failure. This scanner does not measure duplication,
runtime-generated code or call graphs; verify_code_dupes.py --kind ps separately
checks PowerShell duplication.
Shell complexity (code-complexity)#
The Renovate bootstrap is copied into consumers that run this gate over their own tracked shell
files. test-renovate-template-bootstrap.sh measures a copied fixture and plants an oversized
function to prove that the consumer limit rejects new decision paths there.
linux/scripts/verify_code_complexity.py, preflight slug code-complexity,
~0.4s over the whole tree. Two numbers per function — cyclomatic complexity
(COMPLEXITY_LIMIT, default 15, in decision paths) and nesting depth
(NESTING_LIMIT, default 5, block levels below the function body) — over the
same scan set as code-size (linux/scripts, linux/host-config,
docs/scripts, linux/llm-stack), frozen in code-complexity.allow under the
four-way contract.
The current gate reports zero complexity or nesting offenders and no frozen
exceptions. linux/llm-stack remains in the scan.
Why, next to code-size. Length is the cheap proxy. A 60-line function with
a case inside a while inside two ifs is the one that actually resists
change, and it never shows up in a line-count queue. The two gates share
quality_allow.py and verify_code_size.shell_functions, so there is one scan
set, one allow contract, and no second copy of either.
What counts as a path#
Shell: if, elif, while, until, for in command position; the &&
and || operators anywhere in code; and one per case arm. An arm is the )
closing a pattern at the paren depth its case opened at — which is how it is
told apart from the ) of a $(...), including a $(...) inside an arm body.
Python: an ast walk — If/IfExp/For/While/With one each, Try one per
handler, match one per case, a BoolOp len(values) - 1, a comprehension one
per if. Nested defs are excluded from their parent and measured on their own.
What counts as nesting#
Shell openers if for while until select case {, closers fi done esac }. The
function’s own brace is subtracted, so a body statement is depth 0. Python blocks
are the branch nodes plus try and match; an elif is an If inside its
parent’s orelse and continues that parent’s depth instead of adding a level, so
a five-arm elif chain reads as depth 1, not 5.
What the shell counter cannot see#
Before tokenizing, a body is reduced to code text by verify_code_size.code_lines
(that module owns the stripper; see code-size). Heredoc bodies are dropped in
every spelling (<<WORD, <<'WORD', <<"WORD", <<-WORD; <<< is a
here-string and is not one). Comments are dropped from # to end of line —
${#x} and $# are not comments. Quoted text is blanked, and quote state is
carried across lines, so a multi-line awk '...' program is one string, while
a $( ) inside "..." re-enters code: the && in "$(a && b)" is a real path.
Command position — the fix that moved the numbers#
The first cut fed every bare word to the walker and matched reserved words by
equality alone. So err Could not resolve TFLite host tools ... for cross wheel build scored a path for for and opened a block that never closed. Exactly
fifteen such hits lived in build-litert.sh and nowhere else in the tree:
_litert_wheel_cross_args measured 24/4 where it is really 21/2, and
_litert_wheel_run 6/4 where it is 4/2 — its nesting inflated by two log lines.
A reserved word now counts only in command position: at a line start, or
after ;, ;;, ;&, ;;&, &&, ||, |, &, (, $(, {, the ) that
opens a case arm, or one of then else do elif if while until ! time that was
itself in command position. Out of position the word is text — no path, no block,
and no command position of its own for the token after it. Newlines are tokens
for exactly this reason: without them a line start is invisible, and a done
ending one line decides whether the keyword starting the next one counts.
Membership of that set is pinned element by element. Deleting just | from
CMD_OPS used to survive the entire suite — cmd | while read -r x; do … done
then measured cc 1, nesting 0 — because every case that exercised command
position gave the walker several other ways to re-enter it. There is now one
case per member, each a construct that only that member enables: a pipe-fed
while, an && if and an || if, a backgrounded a & if, the first word of a
subshell, of a $( ) and of a { … } group, x=1; if … for the bare ;, a
plain line start for the newline — and, for the three arm terminators ;; ;& ;;&,
the esac that closes the arm, proven by a second case that would otherwise
be measured as nested inside the first.
Three parser traps, closed in the same pass#
$(( a << b ))read as a heredoc.<<matched the heredoc pattern with terminatorb, that terminator never appeared, and the rest of the function was swallowed — complexity silently collapsing toward 1. Arithmetic now pushes its own frame ($((anywhere,((after a delimiter) and heredoc detection is off while one is open. The delimiter set" \t;(|&"is pinned one character per case:if (( x << n )), a tab-indented(( x = y << n )),x=1;((y << n)),cat <(((x << n))),true|((x << n))andsleep 1 &((x << n)). Collapsing the whole set to" "used to survive the suite; the tab case alone now bites, and each of the six is a mutation of its own. A line start is the seventh delimiter and had no case of its own: a((in column 0 has nothing before it, so dropping thei == 0arm sent the guard reading the line’s last character and turned the shift back into a heredoc.The
}of an unquoted${x:-$(cmd)}. The)ends the substitution token and leaves a bare}that closed a block never opened, so nesting read one level too shallow for the remainder of the function. A}is a block end only when preceded by a line start, whitespace or;— what bash requires of it anyway. The guard is deliberately one-sided: gating{the same way cost a real level in$({ objdump …; } | awk …), and a bare{token that is not a group opener does not arise, because${…}tokenizes as one word. That delimiter set is its own four-character constant (DELIM: space, tab, newline,;), unrelated toCMD_OPS; its;— the{ : ;}spelling — is the member a case can miss, because dropping it only shows up in what the unclosed group does to the nesting of everything after.Escaped quotes.
\"inside"..."and a\'in code were handled but unasserted. Both have a case now, and the first one had to be rewritten: with a single||inside the string, deleting the guard gained one path from inside the string and lost the&&on the line after, for the same total — the mutation survived. Two interior||make it bite.
The allow file#
<path> | <function> | cc|nesting | <count> | <reason>. The metric is part of the
key, so a cc row does not cover the same function’s nesting or vice versa. A row
whose third field is neither cc nor nesting used to be filtered out of both
passes and ignored — not even reported STALE — and a row missing the metric column
crashed the gate with an IndexError before either summary line printed. The
first now fails naming the row; the second is a named shape error
(code-complexity.allow:<line>: expected '<path> | <function> | cc|nesting | <count> | <reason>',
exit 2).
Known limits, not fixed here#
Function extents come from
verify_code_size.shell_functions, which since 2026-09-04 counts braces over stripped code — the fix belongs there and landed there, together with the stripper this gate used to own. A nestedname() { … }is still swallowed by its parent, becauseDEFis anchored at column 0 by design. See what a shell function’s extent is.(( … ))is recognised only after a delimiter, and&&/||inside arithmetic still count as paths — in bash they do short-circuit, so that is arguably right rather than a bug.An unterminated quote, or a heredoc whose terminator never appears, poisons the rest of that one function. This is a heuristic tokenizer, not bash’s parser; where it is wrong the number is frozen with a reason and stays honest in both directions, which is the point of the contract.
Tests#
linux/scripts/tests/test-code-complexity.sh. Each case installs
the gate with its three imports (verify_code_size.py, quality_allow.py,
gate_scope.py) into a throwaway tree and reads the number back
through the real CLI with COMPLEXITY_LIMIT=0 NESTING_LIMIT=-1, so nothing
asserts on the parser’s internals. Its last case runs the gate on the real tree,
and that case is what caught the gate tripping its own limit: _code_char reached
cc 20 while gaining the arithmetic handling and had to be split into
_open_group / _close_group / _code_char.
49 mutation entries (code-complexity.*) carry it: the four contract directions (in quality_allow.py),
the tokenizer guarantees (heredocs, here-strings, quotes, cross-line quote state,
comments, case arms, the Python walk, elif depth, the metric split,
the surviving verdict), and one for each fix above — including both directions
of the command-position rule, so that neither “every word is a keyword” nor “no
word ever is” can pass. Twenty of them delete a single element from CMD_OPS, a
single character from the arithmetic delimiter set (its line-start arm included) or
the ; from the } delimiter set, so no member of any of the three can be dropped
without a case going red.
Dead shell functions (dead-functions)#
linux/scripts/verify_dead_functions.py, preflight slug dead-functions. Every
shell function defined under linux/scripts or linux/host-config must be named
at least once somewhere in the scanned code. Definitions come from
verify_code_size.shell_functions(), the extent walker code-size uses too, so the two gates cannot disagree about what a
definition is — including the function name { form and a one-liner on a file’s
last line, both of which an earlier brace walker missed, and excluding the
column-0 definition heads inside heredoc fixtures, which that same walker counted
as definitions until 2026-09-04. Every function it finds no use for is frozen in
linux/scripts/dead-functions.allow — the gate is what makes “all of them” true —
and the run prints its own totals rather than this page re-typing them, because the
one count that WAS re-typed here went stale by 106 in a day. The whole pass costs
under a second, which is why it is in the pre-commit tier.
What counts as a use. The corpus is every text file under linux/, .github/
and docs/scripts/, plus the Makefile. A Dockerfile RUN bash -c "… && fn" is
a use — that is how stages call helpers. Before matching, each file has its
comments and its definition heads stripped, so neither a mention in a comment
nor a second copy of the same function keeps the first one alive. Matching is on
word boundaries: used_fn_extra is not a use of used_fn, run-used_fn is.
Shared bootstrap calls across repositories. A consumer can carry an exact copy
of shared/linux/templates/antfrastructure.sh while another consumer calls one
of that template’s functions. For a tracked antfrastructure-sh declaration in
.antfrastructure-shared.manifest, the foreign-root gate also reads the validated
shared/config/image-consumers.json acceptance plan. It counts only a bash -lc
command that sources the declared mirror path and then invokes one of its
functions as a shell command. An echo, a quoted name, a call before the source,
an undeclared mirror, and unrelated local dead functions still fail. The gate
does not inspect the mirror’s byte equality; the separate shared-config gate
checks that copy against the canonical template in the same lint run. The plan’s
Flutter command is exercised by test-image-consumer-bootstrap.py, and
test-dead-functions.sh mutates the call and declaration to prove the verdict.
A definition’s mentions of ITSELF are subtracted (2026-09-05). String literals
are not stripped from the corpus, so printf 'export_clang_gcc_toolchain_env: no GCC toolchain at %s\n' inside that function’s own body read as a call to it —
backlog CL3 was the live instance. self_mentions() counts, per name, how many
times its own definitions’ bodies name it and mentions() subtracts that, so a
diagnostic that prints the function’s name is not a caller and neither is
recursion. A call anywhere else still outvotes the discount.
Stripping string literals corpus-wide is the fix that looks obvious and is wrong:
measured on this tree it turns nine live functions dead, among them the
trap 'on_err' ERR / trap '_chain_on_exit' EXIT handlers and helpers named
only inside a generated meson cross file. A name inside a string genuinely can be
a call; a name inside a string in its own body cannot be one from outside. The
narrow rule is the one that holds. It costs one extra walk of the shell scan set
— 0.5s → 0.9s, still the pre-commit tier.
What is not corpus, and why:
excluded |
reason |
|---|---|
|
prose about code is not a caller |
|
quoted upstream source |
|
a gate’s own baseline describes code; counting an |
|
the built Flutter bundle — minified output can name anything. Gitignored since 2026-09-15, but the exclusion stays: the gate WALKS the tree, so a working copy that still has the directory would otherwise be graded |
|
generated, not written by anyone |
|
other lanes (see below) |
The dist exclusion is the exact path linux/webserver/dist, not any directory
called dist, so a future linux/scripts/dist/ is not silently dropped. Two
directories that look generated are deliberately kept: linux/scripts/03-media/build/
and .../onnxruntime/build/ are real source. .pytest_cache was in the corpus
until 2026-09-03 — pytest writes test node ids there, exactly the shape that names
a function nothing calls.
The allow file is two-way (the allowlist contract):
a key not frozen is NEW and fails; a frozen key that gains a caller, or whose
function is deleted, is STALE and also fails. One row is left:
command_not_found_handle, which bash calls and nothing else does.
Consumer API whose callers live outside this tree is not frozen: a contract suite
names it. test-lib-*.sh, test-agentic-loop.sh, test-verify-parity-checks.sh
(the "check_${check_name}" dispatch), test-app-packaging-api.sh and
test-flutter-lane-api.sh run each function against stub tools that log their
argv (lib-contract-fixture.sh) and pin its argv, status and output, and a recipe
inside each body proves its suite. A defect such a suite finds goes to
BACKLOG.md, not into the function: consumers reach it through their submodule
pins.
The DEAD group the file carried until 2026-09-04 — three cpython_ext_* and
verify_shared_lib_optional, frozen only because their files sat inside the
2026-09-03 build closure — was deleted with its rows once that build shipped
(the 2026-09-04 wave). Deleting the two cpython_ext_modules_* wrappers orphaned their
private _cpython_ext_modules_by_class, which went with them.
The limitation: same-name masking#
The gate keeps one name table for the whole corpus. That is what makes it cheap,
and it is also its hole: a function is “used” as soon as any file names it,
so a dead log() in one script is kept alive by a live log() in another. Every
short helper name — log, warn, pass, bad, err, cleanup — is effectively
unguarded, and the gate’s clean run is not evidence about them.
Four real dead functions were invisible to it on the day it was written, and all
four are now deleted: ghcr-delete-tags.sh log() (its sourced ghcr-common.sh
never called it), verify-manifest-freshness.sh pass()/bad() together with the
ok/fail counters they incremented — that script’s Python heredoc prints its own
OK/FAIL lines — and, once the 2026-09-04 build shipped, cleanup() in
linux/scripts/03-media/build/ffmpeg/build-ffmpeg.sh. That last one never got an
allow row: masking hides it from the gate, so a row would have read STALE the
moment it was written. tests/test-dead-functions.sh pins its absence instead.
The unlinked-definer arm: the part of the masking that IS provable#
unlinked() is a second gate arm, added 2026-09-05 (backlog GH6). It fails a
definition when all four hold:
its own file never names it again, once comments and definition heads are gone;
a second file defines the same name, so the live verdict comes from a name this file does not own;
every other file naming it also defines it — no file that merely calls the name exists anywhere in the corpus;
and no corpus file names two of those definers’ basenames, the subject’s own text and the peers’ included.
(4) is the whole argument. If nothing in the tree ever mentions two of these files together, nothing can source or run them into one shell, so no mention of the name can be about this copy — and (3) has already ruled out a caller that owns no definition. It answers scope without a call graph, by asking whether the two definitions could ever be in scope at the same time. It costs one basename scan per surviving candidate, computed lazily; the gate stays under a second.
It found one row on this tree, and it is a true one:
06-packaging/verify-parity.sh’s check_python, the sixth of the six
"check_${check_name}" dispatch targets. Its five siblings have been frozen since
2026-09-03; this one could not be, because 06-packaging/smoke-toolchain.sh defines a
check_python of its own and the name table therefore read it as used — an allow file
that looked complete and was one row short. The arm makes that row writable: a
masked function used to send its own freeze STALE the moment it was written (the
ffmpeg cleanup() precedent), and now the arm that flags it is also what holds it.
How it is disarmed, which is the thing to know before editing near it. Any corpus
file that starts naming both definers’ basenames — a new test, a new runner, a doc
generator under docs/scripts — switches (4) off, the arm goes quiet, and the frozen
row then reads STALE. The STALE message says so. tests/test-dead-functions.sh is the
live instance of the hazard and assembles the name and both basenames from printf
arguments for exactly that reason, the same trap arg-consistency and lint-env-knobs
fixtures carry. The failure direction is a false negative plus a loud, explained
gate failure — never a false positive against correct code.
What it deliberately does NOT do. It is not the source_module-aware call graph
the next section prices, and it does not try to be. Two other rules were built and
measured against this tree first, and both are ruled out:
rule |
result |
|---|---|
resolve |
with unresolvable |
the same graph with the hubs dropped, restricted to files nothing else names by basename |
20 rows, 20 false positives. Every one is a suite stub for a unit under test that the file loads through a path no resolver follows: a function body cut out with |
That second measurement is the reason this arm asks whether two files can ever MEET rather than trying to resolve what a call site sees.
--census: the per-file pass, and why it is advisory#
python3 linux/scripts/verify_dead_functions.py --census runs the pass masking
defeats: a definition whose own file never names it again. It cannot be a gate
on this tree, and the numbers say why. 1158 definitions qualify, and nearly all are
alive: library helpers called by whoever sources the file, stubs a suite defines
for the code under test, "check_${name}" dispatch. Filter to files that are
self-contained — they source nothing, and no other corpus file names them by
basename — and 0 rows remain. A gate on the unfiltered set would be a
false-positive machine; a gate on the filtered set would be inert.
So there is a second tier, added 2026-09-04, and it is the one that pays. It
is keyed on (file, name) rather than on the file’s reachability: a candidate
whose name a second file also defines. That is exactly the surface where the
gate’s live/dead verdict comes from a name it does not own — the same-name masking
under “The limitation: same-name masking” — and it reports 468 rows today where the reachability
tier reports 0. The header also carries the slice of that list the unlinked-definer
arm can decide: the arm reaches 0 of them today, and the arm, not the census, is
what fails it. --census prints all four counts, lists both sets, and always exits 0.
Reading it: a row in either list is a deletion candidate, the masked list more
strongly than the other because the gate is provably blind there; the “never names
again” count is context, not a queue. The sourcing guard on the first tier is not
decoration — a library a file sources can call back into that file’s own functions,
which is precisely the command_not_found_handle and check_${name} shape.
The four numbers in this section are DERIVED, not re-typed. They moved by 11
functions and 8 rows between two groomings before anyone noticed, so
tests/test-doc-numbers.sh now runs --census and compares its header against the
prose here — the considered count, the reachability tier, the masked tier and the
unlinked-definer count — and --update rewrites the digits. Nothing else in the repo
may quote them.
What closing the masking hole actually costs. The census is a watch list, not a
fix: it says where the verdict is untrustworthy, never whether a given definition
is dead. A verdict needs scope, and scope here means resolving, for each call site,
which definition of that name is in scope at that point — which is a call graph
over a source/source_module topology this repo builds at RUNTIME. Concretely it
needs: the sourcing graph (source_module <name> resolved through
SCRIPTS_ROOT, plus the container-vs-repo dual layout media_load_arch_flags
already switches on), the Dockerfile stage graph, because a RUN inherits only
what its stage COPYed, and a rule for the ~40 helper names two files define on
purpose. That is a second tool the size of the gate, and it would still guess at
bash -c strings — the 20-row measurement in the arm’s section above is what that
guessing costs. What shipped instead is the corner of the problem that needs no
graph: the unlinked-definer arm decides the cases where the definers can never meet,
and the census keeps reporting the rest of the masked list as a watch list to delete from by
hand with the ffmpeg cleanup() precedent — pinning the absence in
tests/test-dead-functions.sh, since a masked function the arm does NOT reach can
never hold an allow row (it would read STALE the moment it was written).
The quoted ' #' trap. Comment stripping removes from a # preceded by
whitespace to end of line. $# and ${#arr[@]} are safe (no whitespace before the
#) and both are tested, but a call sitting after a quoted ' #' earlier on the
same line is not seen. That direction is a false negative: it can hide a use,
never invent one.
shared/ is out of the corpus for the same reason windows/ is — it is a template
lane shipped to consumer repos, not a caller in this tree. The cost is visible:
two lib/agentic-loop.sh rows (init_agentic_loop, complete_agentic_loop) are
frozen with shared/agentic-loop/templates/Run-AgenticLoop.sh named in their reason
instead of being seen. Adding shared to CORPUS would send those two rows STALE;
that is the deliberate trade, not an oversight.
Coverage#
linux/scripts/tests/test-dead-functions.sh, over throwaway trees —
each case copies the gate plus the three modules it imports and plants a subject,
callers and an allow file. 34 mutations (dead-functions.*), every one proven
to bite, covering the
corpus boundaries one at a time (Dockerfiles in; .allow, .patch, .diff,
patches/, linux/webserver/dist, .pytest_cache, .dart_tool and
mutations.json out; dist narrow), both re.MULTILINE flags (without them only
a comment or a definition head at byte 0 is stripped — every fixture used to sit at
byte 0, so the flags were previously proven only by the real tree), the (?<=\s)
lookbehind that keeps a tab-indented comment a comment, linux/host-config being a
subject and not merely a caller, the two-way freeze contract, both --census
tiers — the reachability filter and the masked (file, name) keying (that the
pass reports and never fails is pinned by the suite alone) — and every clause of the unlinked-definer
arm, each shown by a fixture the arm must stay quiet on: the two definers linked by
a third file, by the peer, and by the subject; a caller that owns no definition; a
definition its own file names again.
Stdout-return gate (stdout-returns)#
A shell function whose STDOUT is its return value cannot log on fd 1.
logging.sh routes log()/info() to fd 1 and warn()/err()/die() to fd 2,
so the moment someone adds a log() to such a function every x="$(f)" caller
captures the log line together with the value. It shipped twice — the
compiler_cache_launcher() leak that configured GCC with an [INFO] line glued
to sccache gcc, and normalize_llvm_cmake_dir() logging into three call sites
that consumed its stdout as a path.
verify_stdout_returns.py pins the CLASS rather than either instance: it collects
every name used in a $( … ) anywhere under linux/scripts, then reports each
definition of one of those names that opens a line with log or info and does
not redirect it. Both halves are load-bearing and both are mutated: dropping the
consumed-set filter reports functions whose stdout nobody reads, and dropping the
>&2 check reports the documented fix. The logger must OPEN the line — matching
mid-line would flag every message that merely mentions a log file.
Proof (2026-09-04). tests/test-stdout-returns.sh, over
throwaway trees at the gate’s own depth (it derives its root from parents[2]),
plus 6 mutations (stdout-returns.*), every one proven to bite (the fifth,
root-argument-is-the-tree, arrived 2026-09-15 with --root). This was the
first of the fourteen gate-proofs.allow slugs to be closed rather than
re-frozen; the shape generalised to the tree-consistency checkers listed above,
all proven since 2026-09-05.
Shellcheck warning ratchet (shellcheck-warnings)#
linux/scripts/verify_shellcheck_warnings.py, preflight slug
shellcheck-warnings, baseline linux/scripts/shellcheck-warnings.allow, suite
linux/scripts/tests/test-shellcheck-warnings.sh.
shellcheck -x -f json1 -S warning analyzes exactly the file set
lint-shell.sh --list-files prints, counted per (file, SCxxxx) and checked
against the frozen rows with the shared four-way rule. Windows runs split that
set into commands below 24,000 characters and merge their JSON findings; -x
keeps sourced-file analysis enabled in every batch. On 2026-09-04, after the
row review below: 319 files in scope, 174 warning-level findings in 72 files, 92
frozen rows — SC2034 (84), SC2155 (19), SC2154 (16), SC2178 (12), SC2046 (11),
SC1090 (9), SC2163 (8).
Every row carries a verdict (2026-09-04). The 95 rows the baseline
froze on 2026-09-03 all read not yet reviewed; each has now been read against the
finding in its file and the reason column says why the code is right, or names the
defect and why it is not being fixed without a build. Three rows were closed by
fixing the code instead: an unguarded cd before exec in lib/app-runner.sh and
another in ctest_run_execute (both libraries set no -e, so a failed cd ran the
app or the suite in the caller’s directory — test-lib-modules.sh now asserts no
bare cd survives anywhere under lib/), and a dead arch local in
lint-dockerfiles.sh. Four families account for most of what remains and none of
them is a defect: local -n namerefs SC2178/SC2034 cannot see, associative-array
subscripts SC2154 misreads as variable references, export "${__varname}" indirect
exports SC2163 misreads, and variables a sourced consumer reads. Two verdicts are
worth reading before anyone “cleans up” the rest: verify.sh’s SC2155 is
load-bearing (version_major returns 1 on an empty version, so splitting the
declaration would turn a tolerated empty GCC_WANTED into a set -e abort), and
the SC2034 rows that CL6 held open were dead code in build-closure files, kept
only because nothing static can prove a chain still runs. Four are closed on
2026-09-05 — stage-defs.sh and python_uv.sh lost their rows entirely,
pre-setup.sh and gstreamer-env.sh their SC2034 rows, and build-runtime-manifest.sh
re-baselined 3 → 2 — each deletion landing with a suite that executes what
survives it, not with a grep. package_archive.sh stays at 4 by DECISION, not
by inertia: nothing in this repo invokes it and no stage copies it, so its three
parsed-and-ignored flags are a CLI contract for callers outside this repo — one
exists (OxidANT’s Linux lane runs the hub path directly, found 2026-09-18)
— and no build can rule on them either. The last frozen SC2206 row, in
cross-env.sh, closed on 2026-10-25: its operator-provided CMake policy value
now stays one argument, proven by test-cross-cmake-argv.sh and a mutation that
restores the unsafe split. This does not exercise a cross compiler build.
Why it exists. lint-shell.sh gates at -S error and prints warnings as
advisory noise (only with --warning), so those 177 findings were watched by nothing: the 178th was
free, and a fix nobody recorded left no trace. That the advisory tier is not
harmless is already written into lint-shell.sh itself — SC2215 (a \
followed by a comment, so the command runs with no arguments) is warning-level,
and on 2026-08-28 it dropped every flag from an android ONNX Runtime build and
cost four hours of chain time. SC2215 got its own hard-fail arm there; this gate
is the general form.
One owner per input. The gate computes neither its scope nor its binary:
The default lint-shell.sh sweep includes linux/ansible/ along with its existing roots.
Its --list-files mode and the error-level ShellCheck run use the same selection; the warning
ratchet reads that list. test-lint-shell-scope.sh checks every Ansible .sh in the tree against
the list, so dropping the directory makes the suite fail. This checks selection, not backup
behavior; the Ansible suites exercise that behavior. The newly selected files have no warning
findings at the pinned ShellCheck version, so the frozen baseline did not grow.
input |
owner |
why |
|---|---|---|
the file set |
|
a ratchet over a scope of its own would drift away from the linter it ratchets. List mode prints repo-relative paths and nothing else — it now returns before the |
the binary |
|
different shellcheck versions count different warnings, and a frozen count is meaningless without a frozen tool |
SHELLCHECK_BIN still overrides everything (the suite uses it to inject stubs);
the gate’s own shutil.which lookup is gone.
Version pinning, and why CI stopped installing shellcheck.
shellcheck_ensure used to take any shellcheck on PATH. CI apt-installed
0.9.0 on noble while the baseline was frozen with the pin (then in versions.env,
in tool-pins.env since CON59)
SHELLCHECK_VERSION=v0.11.0, so CI would have gone red on counts that are
correct locally. It now accepts a PATH copy only when its reported version
equals the pin, and otherwise falls through to the bootstrap it already had — the
pinned release, downloaded once into a version-keyed cache and SHA256-verified.
The Install shellcheck step in .github/workflows/linux-x64.yml is therefore
removed: the gate brings its own, verified.
One rename, since 2026-10-05. shellcheck, gitleaks, hadolint and actionlint
install through download_verified_install (01-core/downloads.sh). It downloads,
verifies and unpacks in a stage beside the cache, then moves the binary into place
in one rename. Before that, each tool wrote straight into its version-keyed cache.
Parallel mutation jobs share that cache, so one job could run the binary another
was still writing, and a clean secret scan failed (hub CI run 37329252097).
The commit hook is inside the scope (2026-09-04). lint-shell.sh admitted
extension-less shebang scripts for EXPLICITLY passed paths only, so
git ls-files -z | xargs lint-shell.sh --list-files answered 319 files (hook
included — that is how crlf-guard reached it) while the argument-less default
sweep answered 312 *.sh and this ratchet asked that one. The one file every
commit runs was therefore linted at -S error and watched at warning level by
nothing. The default find now takes \( -name '*.sh' -o -path '…/linux/host-config/git-hooks/*' \); the shebang test downstream still decides
what is a shell script, so a non-shell hook is not swept in. The hook carries
zero warning-level findings, so the baseline gained no rows — the hole was
coverage, not debt.
The set-dependence bug this gate was born with. Without -x, shellcheck
follows a # shellcheck source=… directive only when the sourced file is also
a command-line input. The 300-plus-file run therefore saw a variable consumed by
a sourced sibling as used, while --files linux/scripts/lib-orchestrator.sh
alone reported SC2034 — the same file, two verdicts, decided by who else was on
the command line. Worse, --write-baseline --files then wrote a row the next
whole-set run rejected as STALE. -x makes both modes see the same thing;
whole-set counts are unchanged by it (177 findings, the same 95 rows). A
consequence worth knowing: with -x, editing file B can move file A’s count when
A sources B. That is the truth the whole-set run always reported, and the
recovery is --write-baseline --files A.
flag |
use |
|---|---|
(none) |
the whole scope against the whole baseline — preflight and CI, ~22 s |
|
only these files against only their own rows, ~0.2 s — the pre-commit hook’s staged mode. Counts are filtered to the listed files, so a finding the tool attributes elsewhere is not a staged file’s problem, and other files’ rows are not read as STALE. A path outside the scope is skipped with a visible |
|
freeze the current counts. Existing reasons are kept verbatim; a new row gets |
Exit 2 is never a pass. Three ways this gate can be unable to answer, and all
three are exit 2 with a message rather than zero findings: --list-files fails
(an empty scope would check nothing and pass), --print-bin cannot produce a
binary, or shellcheck emits something that is not json1. Each has a suite case
and a mutation.
A reason may contain | and #. quality_allow.iter_rows — the reader
every counted gate shares through load_rows and load_counts — takes the number
of key columns from the caller; this gate passes 2, so the count is always the
third field and the rest of the line, | and inline # included, is the reason
(only keys=None counts from the right). A row that fits neither shape stops the
gate with exit 2, naming the file, the line and the expected format.
--write-baseline reads the existing reasons through load_rows, the shared
(count, reason) reader, and writes them back verbatim.
Coverage. tests/test-shellcheck-warnings.sh, over throwaway trees whose subjects provoke SC2034,
SC2155 and a source-directive pair, plus stub binaries for the paths a real
shellcheck cannot produce; 22 mutations (shellcheck-warnings.*), every one
proven to bite. tests/test-shellcheck-batching.sh simulates Windows’ process
limit and proves each input is checked once and every batch’s findings are merged.
The suite’s
last case runs the gate against the live tree, and SKIP_REAL_TREE=1 drops it —
which is what every mutation test command sets, so no mutation can be recorded
as biting because the tree drifted rather than because the guarantee was removed.
The rows are reviewed, not just frozen. No row carries not yet reviewed any
more (see Every row carries a verdict above), and SC2034 is still the largest
family and where the real bugs are: a variable that is
genuinely unused is usually a typo’d reference somewhere else. Triage belongs in
docs/refactoring-backlog.md; what this gate guarantees is only that the number
matches reality, so a change lands in the diff with a reason next to it.
Contract tightening 2026-09-03 (code-dupes, env-knobs)#
Two allowlisted gates were leaking in the same direction: their baselines could
only ever get looser. code-dupes froze a budget and never noticed when the
measurement fell below it; env-knobs printed a registry of operator knobs and
never noticed when a knob left the tree. A baseline that can only loosen is not
a baseline, it is a memo. Both now carry the four-way rule from
The allowlist contract, with the bookkeeping half
enforced as hard as the growth half.
code-dupes — the budget must EQUAL the measurement#
docs/scripts/verify_code_dupes.py against docs/scripts/code-dupes.allow,
rows of fileA | fileB | budget | reason. Four ways to fail:
condition |
what the gate does |
|---|---|
new offender |
an unlisted pair over the threshold is a finding |
growth |
a pair above its budget is a finding, printed with |
unrecorded shrink |
the budget is above the measurement — prints |
stale freeze |
the pair is no longer over the threshold — prints |
The stale line names the count measured before the threshold cut, so a pair
that merely dropped under the line reads differently from one that stopped
overlapping entirely (0 shared). The earlier wording, no longer overlaps,
was simply false for the first case and sent the reader looking for a deletion
that had not happened.
The key is an unordered pair, so a | b and b | a are the same row —
which means listing both is a bookkeeping error, not a redundancy. It exits 2
naming both line numbers rather than silently letting the last one win. A
same-file twin collapses to a one-element key and is written with the name
twice.
All bookkeeping is printed before the new-findings early return, so one run shows everything: a stale row does not hide behind a fresh copy you were going to fix anyway.
The suppression side effect, now a mandatory edit. A shingle held by more
than MAX_OWNERS (6) units is treated as idiom and dropped from pair counting.
That makes mass-copying the one reliable way to hide duplication from this
gate: paste a block into a seventh place and every pair count that block feeds
goes down. Before the shrink rule that just made the gate quieter. Now the
drop is an unrecorded shrink, and the gate refuses to pass until the new, lower
budget is written into the allow file — so the mass-copy lands in the diff with
a human’s reason beside it. The widest blocks are still surfaced as a ranked
worklist under --report (widely-copied blocks) rather than being thrown away.
--kind scopes the allowlist too. --kind shell judges only rows whose
files are both shell; other kinds’ rows are neither judged stale nor counted in
the N allowlisted pair(s) total. Two caveats that follow from that:
--kind md on a tree with no Markdown in scope exits 2 (nothing in scope),
and --baseline refuses --kind (argparse, exit 2): it rewrites the WHOLE
file, so a scoped rewrite would drop every other kind’s row. Re-baseline without --kind.
--baseline is destructive by design. It keeps the five header comment
lines and nothing else: rows are re-sorted by budget descending, existing
reasons carried over verbatim, new rows dated baseline <today>, not yet reviewed, and pairs at or under the threshold dropped entirely. The live file
is hand-ordered and carries per-row review notes, so the 2026-09-03 re-baseline
was done in place rather than by running --baseline. Treat the flag as a
first-freeze tool.
--explain <file> [file] answers the question a row review actually asks.
--report gives a pair and a number; deciding whether that number is a deliberate
twin or a real copy needs the units behind it. --explain prints them: which unit in
A overlaps which unit in B, on which lines, the longest identical run, and the head of
each. One path for a self-pair, two for a cross-file pair. Cross-file diagnostics
accept either path order; self-pairs report each distinct unit pair once. These
diagnostic rules do not change enforcement counts or thresholds.
It also prints the half the count hides. Shingles held by more than MAX_OWNERS
units are dropped as idiom BEFORE the pair is counted, so a pair can look small while
sharing a lot that is merely widespread — --explain reports those separately as
(+N dropped as idiom). That is what makes a budget move without any code changing,
and it is the single most confusing thing about this gate to someone reading a diff.
It exists because it was written four times as a throwaway during the 2026-09-09
PowerShell review, each time importing this module to walk _index_units() by hand.
It reads only; it can never write the allow file.
No census number is kept here: the scanned-unit and file counts move with every
file added, so a copy in prose is stale the day after it is written. The gate’s
own OK line prints them — run python3 docs/scripts/verify_code_dupes.py. The
stable parts are the shape: no block over 10 shared 12-token shingles, deliberate
twins budgeted in code-dupes.allow, and shingles with more than 6 owners
suppressed as idiom.
PowerShell function boundaries count braces only outside strings, comments and
here-strings. Literal contents remain in the token stream; masking applies only
while finding the function end, so a regex quantifier or generated source block
cannot absorb later functions. linux/scripts/tests/test-code-dupes.sh covers
unbalanced regex and comment braces plus a here-string terminator followed by code.
Shell function boundaries use verify_code_size.code_lines, so braces inside
quoted strings, comments and here-doc bodies cannot absorb later functions.
The shingle stream still uses the original source text. The regression suite
covers a quoted ${ opener that previously merged every later function into one unit.
PowerShell param blocks are idiom#
Functions that take the same inputs declare the same parameters (owner decision).
So a shingle that reaches into a param(...) block never counts toward a pair.
That holds at script, function and script-block level, attributes, types and
defaults included. The body after the block is compared as before.
The block stays in the idiom census. Dropping it from the census would push
common body shapes under MAX_OWNERS, and unrelated pairs would grow. Kept
there, it can only lower a pair’s count. The gate finds each block on the whole
file before it cuts units, because a blank line splits a script-level block
across loose chunks. --explain lists the dropped shingles as idiom.
Not covered: an inline list such as function Get-X([string]$Name), and the
[CmdletBinding()] attribute before a block. Both still count.
Consumer-to-hub Bash and PowerShell reuse#
python3 docs/scripts/verify_hub_reuse.py --root <consumer> --hub <hub> --report-only compares Git-tracked consumer .sh, .ps1 and .psm1 units with
the hub’s units. It reuses this gate’s tokenization, function and loose-block
readers, shingle threshold and widespread-idiom suppression, so renamed copies
remain visible. Each candidate names both files and lines, the shared-shingle
count and the longest consecutive normalized-line run. These are overlap
measurements, not a claim that every short match is the same behavior.
Submodule contents, generated files and declared bootstrap copies are outside
the consumer’s own code scope. A bootstrap copy is excluded only after the
existing shared-config checker verifies that it is synchronized; drift or a
broken scan exits 2 even with --report-only. The default exits 1 for any
over-threshold pair. The reusable code-quality-report.yml runs report mode
for nonfork callers and writes logs/code-quality/measurements/hub-reuse.txt;
the directory is ignored by Git and uploaded with the other measurements.
Older consumer pins receive an explicit upgrade notice until their hub gitlink
contains the scanner. For owned nonfork repositories, that missing scanner also
fails the job and keeps the upgrade notice in the uploaded report; external
callers may retain the notice without a failed job. The fixture executes the
measurement step with and without a pinned scanner, and a mutation proves the
owned-caller failure cannot be dropped. Refactor matches into a shared API
before changing overlap findings to a strict verdict.
On Windows, the scanner uses the PowerShell shared-config checker first so a
bash command that enters WSL cannot misread Windows checkout paths.
The weekly fleet reuse report
also compares consumers with one another, using the inventory’s existing clones
and the same unit/token readers. Code overlap is advisory; missing owned nonfork
checkouts, tracked source files or shared-copy drift fail. Its bounded report and
API inventory are written under ignored logs/reports/.
env-knobs — a stale allow row always fails#
linux/scripts/lint-env-knobs.sh against linux/scripts/lint-env-knobs.allow,
preflight slug env-knobs. A knob is CONSUMED if some *.sh under
linux/scripts reads it as ${VAR:-...}. It is OWNED by any of four things:
a key in a .env file a build stage SOURCES, a Dockerfile ARG/ENV, an
assignment or : "${VAR:=…}" anywhere in the scripts, or a row in the allow file.
The consumed scan and both script-side owner scans run the one _KNOB_AWK
walker — readers and the : "${VAR:=…}" form through _scan (its line-prefix
mode), command-position assignments through its default mode — so reader and
owner follow the same comment and quote rules.
Which .env files own (2026-09-05). ENV_OWNER_FILES is
01-core/versions.env plus 03-media/core/arch-flags-*.env. The arch-flags files
were missing until 2026-09-05, and that was the gap: MEDIA_SKIP_CSOUND and its
five siblings are knobs whose value is data, not an operator choice — the
riscv64 file sets MEDIA_SKIP_CSOUND=1 and the arm64 file =0, and
media_load_arch_flags (03-media/core/common.sh) sources whichever matches the
target arch. Re-homing them to a : "${MEDIA_SKIP_CSOUND:=0}" at the reader would
have been a second, competing claim on the value; teaching the scan the file that
already owns them retired all six registry rows instead (215 → 209).
04-runtime/runtime-paths.env is deliberately NOT in that list. It is reference
data verify-runtime-paths.sh compares Dockerfile ENV blocks against, and no
stage sources it, so counting its 39 keys would invent an owner for every path
knob. tests/test-env-knobs.sh pins both directions, and a mutation each way
holds them.
The prefix says who owns a knob, and the vocabulary is family-wide:
KATAGLYPHIS_* is a build/tree knob shared by every repo, ANTFRASTRUCTURE_*
configures this hub’s own machinery (the pin suite, the shared-config sync),
AGENTIC_* belongs to the agentic loop, and a consumer-private knob takes that
repo’s name (ORCHESTRANT_*). Written down once in
adopting-in-a-new-project.md § 8; nothing
grades a knob’s prefix — this gate only asks whether each consumed knob has an
owner.
Unowned knobs stay advisory unless KNOB_GATE=1 (preflight always sets it).
A stale row — one whose knob no reader consumes any more — fails
unconditionally, KNOB_GATE or not, because it is bookkeeping, not a judgement
call: the registry claims to describe the operator surface, and a row for a knob
nothing reads describes nothing. For the same reason the
OK: every consumed knob has an owner line is withheld while a stale row is
failing. That line was technically true in exactly that state, which is what
made it worth removing.
A comment is not a reader. The scan drops full-line and trailing comments before extracting knob names, so prose about a knob does not keep its row alive.
Three properties of that filter, stated so nobody rediscovers them:
The comment cut is quote-aware:
_scanruns each line through the_KNOB_AWKwalker (MODE=prefix), which tracks'…',"…"and$( ), so a#ends the line only where it opens a real comment —${#arr[@]}is safe, and so is a knob to the right of a#inside a quoted string (env-knobs.quoted-hash-strip). Quote state resets at each newline.Full-line
#inside a heredoc is dropped like any other comment. For the shell and Python bodies this repo emits that is correct; a heredoc in a language where#is not a comment would lose a reader.$VAR,${VAR}and${VAR:?}readers are invisible by design. The gate is about the default-carrying operator surface:${VAR:-x}is a knob with a documented fallback, a bare$VARis an internal variable.
A comment is not an OWNER either. The fix above was applied to
the consumed side only; the owner scan still grep -o’d the raw file, so one
# FOO=1 written anywhere under linux/scripts made FOO owned and silenced
the unowned check for it. That is the worse half of the bug — the consumed side
fails loud (a live row reported stale), this one fails silent. Owners fell from
1272 to 1219 when the same filter was applied, and fifteen live knobs turned
out to have no owner but prose. None were fixed at the reader; every one is a
real ${NAME:-default} operator switch that nothing in the repo assigns, so all
fifteen were first re-homed as documented rows in lint-env-knobs.allow.
SKIP_REAL_TREE is the one that shows the shape of the hazard: it was
introduced by the same batch that added the consumed-side filter, and its only
owner in the whole tree was the sentence in test-shellcheck-warnings.sh
explaining it.
A row is not a home (2026-09-04, build window). Thirteen of the fifteen were
then given a : "${NAME:=default}" at the reader and their rows deleted with
them, so the default is greppable where it is read instead of in a registry:
IREE_CROSS_BUILD_COMPILER, LINT_DOCKERFILES_BUILD_CHECK,
LLVM_INSTALL_PROFILE, MEDIA_STRIP, NODE_RISCV64_MAJOR_REQUIRED,
OPENCV_GSTREAMER_PASS, PYTHON_LTO, RUNTIME_CLANG_VERSION_SMOKE,
RUNTIME_COMPILER_SMOKE, RUNTIME_IMAGE_SMOKE, SKIP_REAL_TREE,
STV_COMPUTE and the renamed CROSS_GCC_TOOLCHAIN_PATH — that last one deleted
outright on 2026-09-05 with the function that read it (backlog CL3), leaving
twelve. := and :- share
their empty-or-unset fallback rule, so the only behavioural difference is that
the variable is now SET in the reading shell — which is why a knob whose value
is data rather than an operator choice must not be converted. MEDIA_SKIP_CSOUND
is exactly that knob, and it stayed a row until 2026-09-05: its real value comes
from 03-media/core/arch-flags-<arch>.env (=1 on riscv64, =0 on arm64),
sourced by media_load_arch_flags, which the owner scan could not see until it
learned to read those files (Which .env files own, above).
PREFLIGHT_ONLY/PREFLIGHT_SKIP were the other two; preflight.sh now owns
both with : "${…:=}".
Nor is a message, a usage line or a test argument (2026-09-04). The comment
filter above is line-wise, and the owner scan still grep -o’d raw line text, so
an assignment-shaped substring inside a quoted string owned the knob:
err "…; FORCE_LOW_DISK=1 accepts the risk" owned FORCE_LOW_DISK, and
_lane_run FORCE_LOW_DISK=1 — an argument to a test helper — owned it a second
time. Forty-five live knobs had no other owner: 36 real operator escape
hatches (FORCE_LOW_DISK, GCC_REQUIRE_GPG, RUNTIME_REGISTER_BINFMT,
OPENCV_ALLOW_NO_PNG, WRAPPER_CONTENT_GATE, …), 5 test-fixture knobs
(BUILD_RC, DISK_OK, HAS_PINNED_BASE, TRANSIENT, MODRES_POISON_SOURCED),
3 values injected into the smoke container rather than assigned in a shell
(RT_PROBE_SH, SMOKE_ONNX_PY, STV_ASSERT_ONLY), and VERSION, which CI
exports after version_util.sh writes it to $GITHUB_ENV. All 45 are documented
rows in lint-env-knobs.allow; none was silenced by widening the scan.
The owner scan is now a ~50-line awk tokenizer instead of a grep. It drops
comments, single- and double-quoted text and heredoc bodies, and counts a
NAME= only in command position: line start, or after ; && || | (
) {, a case arm’s ), then/else/elif/do/if/while/until,
export/local/declare/readonly/typeset/env/time/! (with their
option words), or another assignment word in an env-prefix chain. Two details
carry their weight: "$( … )" re-enters code, so _out="$(VULKAN_CROSS_STRICT=1 _trace)" still owns — without it four live knobs lost their only owner; and the
{ guard stays, so a ${VAR=x} expansion is not an assignment (the owner form
is the documented : "${VAR:=…}"). Heredoc bodies deliberately own nothing: the
NAME=value lines in runtime_write_artifact_metadata’s artifact.env are data
this repo emits, not settings it applies to itself. Script-side owners fell
1271 → 912.
This is the same command-position idea the shell complexity gate implements in
the complexity gate (verify_code_size.code_lines + _Walker), and it is deliberately
not shared: that one is a Python module that returns metrics for a scan set,
this one is an awk filter inside a bash pipeline, and making the bash gate import
the Python one would buy a duplicated 40 lines at the price of a cross-language
dependency in a 0.5 s gate. If a third consumer ever needs it, extract one
tokenizer then.
Its one limitation is also worth stating: quote state resets at each newline
(the complexity gate’s code_lines carries it across lines; this awk does not).
A NAME=1 line in the middle of a
multi-line '…' argument therefore still reads as an assignment. It can only
add an owner, never remove one, and the heredoc skip already covers the form
this repo actually writes multi-line program text in.
A backslash-escaped \${NAME:-} is not a reader. A sixteenth knob, VAR,
surfaced — the gate’s own output strings say consumed \${VAR:-} knobs:. That
is literal text, not an expansion, so an allowlist row would have been a lie.
_scan now deletes \$ sequences before extracting. Measured over the tree,
VAR is the only name that ever appears escaped-only; LD_LIBRARY_PATH and
SUDO also appear escaped but have real readers elsewhere.
The private-prefix promise lives in the extraction regex. A trailing
grep -vE '^_' used to sit after extraction, where it could never match: the
regex before it already demands [A-Z] first. It is deleted. The _scan
selector is now deliberately loose ([A-Za-z_][A-Za-z0-9_]*) precisely so the
extract pattern is the only thing enforcing the rule, and a mutation that widens
it to [A-Z_] surfaces _PRIVATE_KNOB as unowned.
Scope gotcha. linux/scripts/**/*.sh is a recursive scan and it includes
linux/scripts/tests/. A suite that spells a literal ${MY_FIXTURE_KNOB:-} in
its own source registers as a real consumer of that name in the live census —
this bit while writing test-env-knobs.sh, where two fixture knobs surfaced as
UNOWNED against the real tree. The suite therefore spells every fixture knob
through printf '${%s:-}' NAME, the trick the original _consume helper
already used.
Census at the time of writing (2026-09-03): consumed ${VAR:-} knobs: 643 | owners: versions.env=174 dockerfiles=116 scripts=912 allowlist=225 | stale allow rows: 0.
The owner tokenizer, 2026-09-04#
Two holes in the tokenizer were making the census lie, and both are closed.
A heredoc redirection is matched in the character loop, BEFORE quote state.
<<X, <<-X, <<'X', <<"X" and <<\X all now mark their body as data.
The pre-2026-09-04 code matched the terminator on the post-quote text, so
cat <<'EOT' had already been reduced to cat << by the time the heredoc was
looked for, and the whole usage block was scanned as code. That is how ~45
operator switches came to be “owned” by their own help text. hdpush() parses
the delimiter itself and returns the index past it, so the delimiter never reaches
quote state.
Heredocs are a QUEUE. Several opened on one line end one at a time:
cat <<'ONE' <<'TWO' ends ONE at ONE and TWO at TWO, instead of treating the
second body as code. A heredoc opened inside $( ) works in both nesting shapes,
because $( ) is already a code frame and the detection lives in code state.
Unquoted delimiters must start [A-Za-z_] — the same shape the old regex
demanded. That single rule is what keeps <<< here-strings and $(( a << 2 ))
from opening one; its bail returns past the second <, so a here-string cannot
re-enter as a heredoc. KNOWN LIMIT, unchanged: an arithmetic shift by a NAMED
variable ($(( x << SHIFT ))) still looks like a delimiter. Nothing in the tree
hits it today, and an END-rule probe over every script the owner scan reads
(295 on 2026-09-04) finds no unterminated
heredoc at EOF.
Ownership follows the whole env-prefix chain. FOO=1 BAR=2 cmd credits both.
The match loop no longer truncates the line as it walks it — it fed cmdpos the
VALUE of the previous assignment as the whole prefix, so only the FIRST name of a
chain owned, while the doc already CLAIMED chain support. cmdpos walks the
prefix back over preceding assignments, so cmd A=1 B=2 still credits neither:
a word after a command name stays an argument even when it is assignment-shaped.
Census after (2026-09-04): consumed ${VAR:-} knobs: 643 | owners: versions.env=174 dockerfiles=116 scripts=946 allowlist=225 | stale allow rows: 0. Five script-side
owners were LOST, every one a quoted-delimiter heredoc body (a python3 <<'PY'
program, a versions.env fixture, a <<'EOF' fixture); none of those names went
unowned. 29 were GAINED, all genuine env-prefix chains. Both censuses are dated
snapshots of that one change, kept because the deltas are what they explain; the
live figure after the 2026-09-04 integration wave is 637 | 176 / 116 / 982 / 214,
and the gate is the authority for it, not this page.
Proof#
linux/scripts/tests/test-code-dupes.sh and
linux/scripts/tests/test-env-knobs.sh each copy their gate into
a throwaway tree — the gates derive their root from their own path — and parse
the measured overlap rather than hardcoding it, so the fixtures cannot rot.
31 entries (code-dupes.*) and 30 (env-knobs.*) in
docs/scripts/mutations.json neuter one guarantee each and are proven to make
those suites fail: the shrink and stale detections and their
exit codes, the pre-threshold count, the stale wording, the duplicate-row exit,
the --kind scoping, the bookkeeping ordering, --baseline’s reason carry-over,
the two comment filters, the KNOB_GATE-independence of stale, the withheld
all-clear line, the trailing strip’s cut point, the escaped-\$ deletion, and the
extraction regex that bars _-prefixed privates. The rest neuter one piece each
of the owner tokenizer — quoted text, command position, comments, heredoc bodies,
$( ) re-entry, the keyword prefixes, the env-prefix chain, the case arm, and
the ${VAR=x} guard, plus the heredoc rewrite above: the body-is-data rule, the
quoted delimiter, the <<- tab-stripped terminator, the queue, the here-string
bail, single-quoted text in command position, and both halves of the env-prefix
chain.
Knob default order (knob-order)#
linux/scripts/verify_knob_order.py fails on a bare read of a knob where its in-file
${X:=...} default has not run on every path. Under set -u that read stops the stage: two
GStreamer stops had this shape, one read at top level before the function holding the default, one
in a callback that ran before the sibling callback holding it.
The gate walks each .sh file under linux/scripts, tests/ excluded, in execution order:
top level first, then each function nothing in the file names, then the rest. A name counts as
defined after an unconditional default or assignment, after a call whose every returning path
defines it, and after a compound whose every arm does. A default behind && or ||, in a loop, in
$(...), in a pipeline or in an if without else does not hold after it. A function named as an
argument is walked where it is named. return with a nonzero status counts as an abort, like exit.
The fix is to put the default at the top level, above the first reader. There is no allow file.
Not covered: a read of a variable with no := default in the same file; definitions from a sourced
file, a Dockerfile ENV or a caller in another file; a same-line read ahead of the default; heredoc
bodies. A read after a -n/-z test of ${X:-} counts as handled for the rest of that function,
whichever way the test went. tests/test-knob-order.sh plants each shape and moves both GStreamer
defaults back in a copy of the real script.
Trailing-conditional returns (trailing-conditional)#
A shell function returns the status of its last command. So a function whose
last statement is cond && action returns 1 whenever cond is false — on the
path where there was nothing to do — and a caller under set -e dies there
with no message at all. Two silent build deaths in two days had exactly this
shape: reconcile_local_wheels on 2026-09-03, and the logging.sh ERR-trap case
on 2026-09-02, which is the same bug seen from the trap side.
shellcheck has no check for it. SC2015 is about a && b || c precedence and says
nothing about a function’s exit status; -S error, which lint-shell.sh gates
at, would not fail on it even if it did. linux/scripts/verify_trailing_conditional.py
closes that hole over every .sh file under linux/.
The rule#
For each function the gate takes the last statement of the body and asks what
its status is. The statement is the last non-empty line of stripped code, joined
backwards over continuations (a line ending in \, &&, ||, |, (,
then, do or else continues into the next), then cut at its last top-level
;. Stripping is verify_code_size.code_lines — the one tokenizer the size,
complexity and dead-function gates already share — so comments, quoted text and
heredoc bodies are invisible and a && inside "…" or $( … ) is not an
operator.
Given that statement, in this order:
shape |
verdict |
|---|---|
a bare |
step INTO the block: judge its own last statement instead |
a |
judge its LAST inner statement by these same rules |
a top-level |
judge the last arm by these same rules, and answer with that |
a top-level |
finding |
first word is |
finding |
a bare call to a function this FILE defines that is itself a finding |
finding |
anything else |
not a finding |
“Top level” means at paren depth 0 and outside [[ … ]], so [[ -n "${a}" \|\| -n "${b}" ]] is read as one test — its || is an operator of the test, not a
fallback arm — and x="$(a && b)" returns the assignment, not the inner list.
&& and || bind looser than |, which is why the presence of && is decided
before anything is said about pipelines.
The first and last rows are the 2026-09-05 sharpening (backlog GH3), and each has a limit built in on purpose:
A closer is stepped through only when it is bare.
done | sort -ureturns the pipeline, not the loop body, so a closer carrying any top-level operator is judged as the ordinary statement it is. Inside the block the last live line is taken as the block’s last statement — for anifthat is the last branch, for acasethe last arm, and a;;-only line is skipped rather than read as empty. The other branches are not examined: one hop, not a path enumeration.The delegate hop stays inside one file. A trailing bare call is credited to a definition in the SAME file, iterated to a fixed point, so
is_crossandcross_build_enabledinheritcross_build_is_active’s verdict, which inheritscross_target_is_foreign’s. Reaching across files would resurrect the same-name masking GH6 describes: onelog()anywhere would decide everylog().A
||is no longer blanket cover. The old rule trusted any top-level||; the new one trusts only what the author put in the LAST arm.a && b || truestill passes;do_thing || [ -n "${x}" ]and the SC2015 shapea || b && cdo not. This found nothing in the tree — a rule that closes a hole rather than one that reports a defect.
The fix the gate asks for is to end on the action:
[ -x "${cxx}" ] || return 0
printf '%s' "${cxx}"
The false-positive shape, and why there is an allow file#
A trailing conditional is idiomatic wherever the function’s status is the
answer: cross_mode_requested, best_effort_mode, smoke_is_elf,
ancestry_run_ids_coherent and sixteen more exist only to be read in a
condition. The gate cannot see call sites, so it cannot tell those from a defect
— and it does not try. The predicates that remain frozen, all in image closures
(01-core/ and 03-media/), sit in
trailing-conditional.allow under the two-way rule of
the allowlist contract: a key that is not frozen is
NEW, a frozen function that stops ending on a conditional is STALE. The key is
<file>\t<function> — never a line number, which would re-flag every site
whenever something above it moved. Each group carries the reason it was kept.
Freezing one is a judgement, so make it out loud: every call site must read
the status as an answer. If any caller invokes it bare under set -e, it is a
defect, not a predicate.
The reusable Linux and Windows lane fixtures now use explicit return 0 and
return 1 branches for their upload-step predicates. Their callers still
assert the true and false verdicts, and the gate sees no new implicit trailing
conditional.
Known limits#
The four false negatives this section used to list — last-statement-only, the
block closer, the trusted ||, and the one-line definition — were closed on
2026-09-05. A one-line f() { …; } now presents the same body as a multi-line
one: the definition head comes off the first line and the closing brace off the
last, which is the only thing that trim is for — a } on its own line is already
handled as a block closer. What remains:
One hop, one file. The delegate rule does not follow a call into another file, and it does not follow a call made through a variable or
eval.A block written on ONE line is judged whole.
if [ -n "${x}" ]; then do_thing; fion a single line is not stepped into: its first word isif, and anifwith no matching branch returns 0. Only a bare closer on its own line opens the block.A definition indented inside a block is not scanned at all.
DEFis column-anchored, shared with the size and dead-function gates, so thecross_build_is_activefallbacks defined insideif ! command -v …blocks in01-core/common.shand03-media/build/gstreamer/common/build-gstreamer-monorepo.share invisible here.tests/test-cross-fallback-parity.shis what watches those.A
while trueloop never falls out of the loop, so its body’s trailing conditional is not what the function returns.invoke_agent(lib/agentic-engines.sh) is the one such FALSE POSITIVE in the tree today. It was normalised to anifrather than allow-listed, because abreakadded later would make it a real defect — and the behavioural half of that one is honestly unproven: reverting it fails the gate, not a suite.
Every remaining limit but the last is a false NEGATIVE. The gate is deliberately tuned that way: a noisy gate gets an allow row, and an allow row is cover.
The four the first version found#
All four were live, all four are fixed, and each has a mutation that restores the old shape and a case that catches it:
derive_cxx_from_cc(01-core/compiler-resolution.sh) ended on[ -x "${cxx}" ] && printf …, so a derivedc++that is not executable returned 1 — against the function’s own documented contract of “empty output”. Its caller at:131assigns it inside a||list, where that status kills the script instead of returning the intended 1. Fixing it moved the refusal to_cross_env_resolve_tools, which now tests the value rather than the status._chain_on_exit(build-cross-chain.sh) is the chain’s EXIT trap and ended ondeclare -F cross_cleanup_local_context_workdir … && …. Whenever that helper is not defined the trap returns 1, and underset -ea chain that finished green exits 1.patch_gstreamer_sources(03-media/…/patch-gstreamer-sources.sh) ended on the last of its[ -f … ] && bash apply_patch …lines. Both call sites invoke it bare underset -euo pipefail, so a tree withoutsubprojects/gst-libavwould abort the GStreamer build. Only the last guarded apply (006) is converted to anif; the six[ -f … ] && …lines before it are not the function’s status, and the gate now guards the end of the list against another patch being appended.
The five the sharpening found#
Four are the same defect the gate was built for, one file deeper than the old
rule could see; each is now an if whose false path returns 0, and each has a
case in part B that runs the function off-target under set -e.
csv_each(01-core/guard-helpers.sh) looped[ -n "${_item}" ] && "${_fn}" …, so a CSV with a trailing comma —a,b,— made the loop’s last iteration the empty one and the helper returned 1, against its own documented contract that empty elements are skipped.append_version_build_args(01-core/version-forwarding.sh) did the same over the tracked-version list, andappend_common_build_argsends on a call to it, so an empty value in the LAST versions.env key would have taken the orchestrator’s build-arg assembly down with it. Latent today only because every tracked key currently has a value._dump_gst_build_logs(03-media/…/build-gstreamer-stage.sh) is the GStreamer stage’s ERR trap and ended on the last of four[ -f … ] && echo && catlines — the same shape, from the trap side, as thelogging.shdeath of 2026-09-02.wasm_opt_load_pin(lib/wasm-opt.sh) returned 1 whenever the lastBINARYEN_*key was already exported, which is its documented normal path (“unless they are already set”).invoke_agent(lib/agentic-engines.sh) is the false positive described under Known limits.
The delegate hop and the one-line rule also made three predicates in
01-core/cross-env.sh visible for the first time (cross_build_is_active and
its two aliases), plus is_amd64_arch and one-line stub predicates in suites.
Since 2026-10-31 a predicate outside the image closures ends on explicit
return 0 / return 1 branches instead of a frozen row, so the gate tells intent
from a defect; the stubs and build-cross-chain.sh’s stage_enabled were rewritten
that way and their rows deleted. The rows left are in files an image build mounts,
where an edit re-keys the build.
Proof#
linux/scripts/tests/test-trailing-conditional.sh plants one
subject.sh per rule in a throwaway tree — the gate derives its root from its
own path — and then lifts each of the fixed functions out of its file with sed
and runs it under set -eu, because none of those three files can be sourced
whole. The mutation entries neuter the || escape hatch, the [[ … ]] bracket
tracking, the ; cut and the continuation join, plus one per fix.
The 2026-09-05 wave added a case per new shape (one-line body, each of the three
block closers plus the two shapes a closer must NOT open, the || last arm, the
delegate hop and its cross-file refusal) and one part-B case per fix. It also
retired one assertion: a || b \\ + && c was the old proof that continuations
are joined, and that shape is now a finding on its own, so the join is proven
instead by out="$(a \\ + && b)" — a bare && list read alone, an assignment
once joined.
test-renovate-template-bootstrap.sh also checks the copied bootstrap at a
consumer root. Its clean control must pass this gate, and a planted function
ending in a conditional test must fail. This covers templates that the hub’s
own tracked-source scan does not grade as consumer files.
Cost: 0.49s over the whole tree, next to dead-functions at 0.50s and
code-complexity at 0.66s, both already in the hook’s fast tier.
Nine gates that left the unproven list (2026-09-05)#
gate-proofs.allow froze 12 preflight slugs at the 2026-09-03 baseline with
neither a suite nor a mutation. Three left on 2026-09-04. This wave closed nine
more, each the same way: a characterisation suite driving the REAL gate in a
throwaway tree, every case asserting the exit code and not only the message, plus
mutations over the gate’s own script that turn that suite red.
Two rules shaped every one of them.
A gate has to be able to be GREEN. Each suite opens with a healthy fixture.
Without it a red case proves only that the fixture is broken.
GPU graph dry-runs set a synthetic immutable APP_REF: a moving default otherwise
contacts GitHub before a graph assertion. test-app-ref.sh retains ref-resolution coverage.
Advisory is a contract, not an omission. Four of these gates deliberately report findings without failing — the extraction is heuristic, or the divergence is sometimes legitimate. Each of those has a mutation that makes the advisory FATAL and a case that catches it. A suite that pinned only the message would let the two kinds swap places silently.
Android library stage parity (android-parity)#
01-core/verify-android-stage-parity.sh. The five android-* stages in
Dockerfile.android are copy-paste ON PURPOSE — separate stages are what makes
BuildKit build them concurrently — so the gate makes the copy mechanical:
normalise ARG ANDROID_LIB, drop comments and blanks, require the five blocks to
be byte-identical.
tests/test-android-stage-parity.sh pins the two deliberate differences (the
LIB value, per-stage comments) against six ways to break it, of which two are the
ones a reader would not think of: a divergence in the LAST stage (the first is
the reference, so a loop that stops early lets the tail drift), and a stage the
gate can no longer FIND — a rename that quietly drops a fifth of the Dockerfile
from the comparison. android-parity.stage-list-complete is the same hazard from
the other side: the script’s own STAGES list is the contract.
Patch integrity (patch-integrity)#
verify-patch-integrity.sh. A malformed or orphaned patch only detonates hours
into a cross build, so the gate reads every *.patch statically: it must parse as
a unified diff (---, +++, @@ all three), and some *.sh must name it.
The apply SITE is advisory: a raw git apply reports INFO and still passes,
because some sites legitimately pre-date apply-patch.sh.
patch-integrity.raw-apply-site-is-advisory is what keeps a later tightening from
turning a green tree red for no build reason. The corpus being *.sh is also
pinned: a patch named only in a doc is still applied by nothing.
Script COPY coverage (copy-coverage)#
verify_script_copy_coverage.py. The bug it was written for was TRANSITIVE:
Dockerfile.package COPY’d and RAN install-deps.sh, which sourced
/opt/scripts/03-media/core/common.sh that the image never had — exit 127, deep
inside a build. So the suite’s load-bearing case is the transitive one; a
direct-references-only check calls that image complete.
Four more shapes are pinned because getting any of them wrong makes the gate red
on a HEALTHY tree, which is how a gate gets switched off: a directory COPY
provides everything beneath it, a per-RUN bind mount counts as provided, a COPY
wrapped over backslash-newlines is one logical line, and KNOWN_BASE_PROVIDED is
keyed per Dockerfile so an inherited path cannot leak to every image. Two more
cover the vacuity edges: a tree with no Dockerfiles fails rather than reporting a
clean sweep, and --report-core-usage stays read-only — its own docstring calls
its counts a lower bound.
Dockerfile context paths (context-paths)#
verify_dockerfile_context_paths.py, the other half of the question above:
copy-coverage asks whether a path referenced INSIDE a Linux image was
provided, this one asks whether the host-side source exists at all — every
COPY/ADD source and every --mount=type=bind,source= in every tracked
Dockerfile, Windows lane included.
It exists because two of them stood broken for weeks. An archive sweep moved
Test-SccacheWrite.ps1 into diagnostics/archive/ and left
Dockerfile.sccache-write-probe mounting the old path; #137 deleted
windows/upstream/sccache-nvcc-quote-fix and left Dockerfile.probe mounting
it, which killed EVERY -ProbeScript solve, live probes included. Both fail at
BuildKit’s context checksum — before instruction one, so the message names a
path and not the lane that died — and both were static facts about the tree the
whole time. Both are fixed, and diagnostics/archive/ has since been retired:
Test-SccacheWrite.ps1 is back at windows/scripts/diagnostics/, which is what
Dockerfile.sccache-write-probe and Dockerfile.media-builder now name. The
paths above are the historical ones — kept because they are why this gate
exists, not because the tree still spells them.
The suite’s load-bearing case is the sweep shape: the script exists SOMEWHERE,
just not where the mount says. The rest pin the false-red edges, because a gate
that is red on a healthy tree gets switched off: a --from=/from= source
names a stage and is not judged, a ${VAR} segment is a wildcard (which value
the build arg takes is not a static fact), backslash-spelled Windows paths are
normalised, and a # escape= directive is honoured — read a Windows Dockerfile
with the backslash default and every source after line one is invisible.
CONTEXTS (the three Dockerfiles not solved from the repo root) and GENERATED
(sources a named script produces into the context first) are keyed per
Dockerfile, so neither can widen to another image, and both are mutated to prove
it. Untracked trees are out of scope: external/ is somebody’s local checkout
with its own build contract.
The suite deliberately has NO “the real tree is green” case. verify_mutations.py
mirrors the repo without linux/webserver/dist, so such a case would fail inside
every mutation workspace for a reason unrelated to the mutation. preflight runs
the gate over the real tree; that is where the whole-tree answer belongs.
Ubuntu mirror consistency (mirror-consistency)#
01-core/verify-ubuntu-mirror-consistency.sh. APT-HTTP is why this gate has two
halves. The original check only proved use-fast-ubuntu-mirror.sh was
REFERENCED — and that is exactly how the CA-bootstrap http downgrade shipped with
nothing restoring https for a custom mirror.
So the suite gives each half its own red. The WIRING half: bootstrap_ca must
call restore_mirror_https_scheme, and AFTER the ca-certificates install —
restoring earlier puts apt back into the chicken-and-egg the downgrade existed to
break. The OUTCOME half runs the real downgrade+restore pipeline on a fixture
sources file and requires it to END on https; mirror-consistency.outcome-is-asserted
is APT-HTTP itself, a call site that was present while the sources stayed on
http. A third case guards the fixture’s own PRECONDITION: if the downgrade stops
landing there is nothing left to restore and the outcome check would pass for the
wrong reason.
Runtime path consistency (runtime-paths)#
04-runtime/verify-runtime-paths.sh, and the LOG31 note on it is literal: this
script once NEVER failed, an inner warning swallowed by an outer green. Its
contract is now split down the middle and the suite proves both sides.
Missing INFRASTRUCTURE — runtime-paths.env, versions.env,
Dockerfile.package, Dockerfile.media — is a broken tree and fails hard, all of
them reported in one run rather than one per invocation. Every path-mismatch WARN
stays advisory, because the ENV-block extraction is heuristic and produces false
positives on a healthy tree; runtime-paths.warn-is-advisory and
runtime-paths.warn-scope-is-narrow are the two mutations that keep a
well-meaning tightening from making the gate unusable.
Version ARG consistency (arg-consistency)#
01-core/verify-arg-consistency.sh is seven checks and they are not all fatal.
Fatal: an ARG default that drifts from versions.env (it wins silently on a plain
docker build), a default-LESS ARG naming a versions.env variable (the
LITERTJS_VERSION class — an empty value), the two case-mapped literals in
gcc.sh and common.sh, the inline GCC fallbacks (the gate prints how many it
scanned — 33 today), and a hand-forward
duplicating the auto-forward (XC7). Advisory: the # noforward coverage warning,
and the generic ${VAR:-literal} scan, whose divergence is often deliberate.
The case worth naming is arg-consistency.scan-vacuity-floor. The GCC literal
scan refuses to report OK when it matched fewer than ten sites, because a refactor
that rewrites those literals into a shape the pattern cannot see would otherwise
make the gate find nothing, print a pass, and let the next bump drift unnoticed.
The suite drives that floor directly.
One trap the suite had to dodge, and the next editor will too: this file lives
under linux/, so a literal inline GCC fallback written out in the test source is
scanned as a REAL site. The fixture assembles the expansion from printf
arguments instead. The same rule applies to the version-snapshot generator’s
basename — see below.
Workflow lint (workflow-lint)#
lint-workflows.sh names its own hazard: “a lint gate that checks nothing still
reports green”. Two ways that happens, and both are driven against the real
actionlint. Linting the WRONG TREE: the optional root argument exists because a
submodule checkout puts this script inside the consumer, where the default root
resolves to ANTfrastructure; the suite gives it a broken checkout and a clean one and
requires the verdicts to follow the argument, and a root that does not exist to be
refused rather than fall back. Running an UNPINNED binary: with no actionlint on
PATH and an empty cache, a missing ACTIONLINT_VERSION and a missing
ACTIONLINT_*_SHA256 each have to refuse, driven offline through a fixture tree
that carries its own versions.env.
.github/actionlint.yaml extends the known-runner-label set with the family’s
ubuntu-26.04 / ubuntu-26.04-arm preview labels, which the pinned actionlint
(still the newest release) predates. The config only ADDS labels — a genuinely
unknown label still fails, so the runner-label check stays live. actionlint resolves that config from the project it LINTS, not from this repo.
That is why every consumer that uses the preview labels carries its own copy of
the file — seven of them grew one; lint-workflows.sh runs actionlint from the
linted root and passes no -config-file, so the hub’s copy never applies to a
consumer.
actionlint lints run: blocks by exec’ing shellcheck by name, and when that
name does not resolve it silently disables the rule and still reports clean. So
lint-workflows.sh resolves shellcheck through lint-shell.sh --print-bin,
refuses to grade when it cannot, and requires actionlint to report a planted
SC1010 before it trusts a clean verdict.
The warning census#
A consumer’s CI runs it after a C/C++ build. It is not a preflight slug, and the hub’s lint gates do not call it.
AccelerANTgine’s scripts/linux/ci-run-all.sh runs it on each x64 lane against its committed
scripts/linux/warning-census.txt:
python3 "$(antfrastructure_path linux/scripts/verify_warning_census.py)" --lane "${MATRIX_ARCH}-${COMPILER}" \
--census scripts/linux/warning-census.txt "${BUILD_DIR}/build.log"
--write rewrites that lane’s rows from the logs and keeps the other lanes’ rows; commit the file with the fix.
A Windows lane hands it one build’s output, which Invoke-CmakeConfigureAndBuild -BuildOutputLog <file>
(WindowsCMake.Common) writes beside the combined build log, failed build or not. BeschleunigerBallett’s
Build-Windows.ps1 -WarningCensus runs it per clang-cl configuration (lanes windows-x64-clangcl-debug …).
It holds a lane’s compiler warnings at a committed count per flag, the step between SYSTEM includes and warnings as
errors. It reads GCC and clang path:line:col: warning: ... [-Wflag] lines, clang-cl’s
path(line,col): warning: ... [-Wflag] and MSVC cl’s path(line): warning C4244: .... It reads them from a ninja
log or a verbose one, after stripping the colour codes a clang on a terminal prints. It counts each path:line:flag
once, since a header’s warning repeats in every unit that includes it, after normalising . and .. in the path.
Only the repository’s own code counts. A container’s /workspace/ prefix, a GitHub runner’s checkout prefix and the
family’s Windows container mounts (C:/ws/, C:/ws-mnt/) are stripped first. Then third_party/, _deps/,
external/ and vendor/ paths are foreign, and so is any path still absolute, such as a header under /usr/,
/opt/ or C:/Program Files/. The Windows SDK’s C:/Program Files (x86)/ is foreign too, as its (x86) is not
read as a line number. A warning with no flag (GCC’s “X redefined”) counts under -W(unnamed). A cl warning has no
-W flag either, so it counts under its code, such as C4244; the compiler’s codes are C4xxx and C5xxx. A
clang-tidy or analyzer finding names its check instead, so it does not count: a [modernize-...] tag, or
/analyze’s C6xxx and C26xxx codes. Notes and errors never count, not even cl’s error C4996 under /sdl. No
lane builds with cl yet, so its form is proven on a fixture log only.
The census file holds <lane> | <flag> | <count> rows, one lane per CI job that compiles. A flag above its row
fails the lane. So does a flag below its row until the row is lowered in the same commit, so a fixed warning
cannot make room for a new one. A log with no compile line fails too: an incremental build that compiled nothing
would read as zero. Suite linux/scripts/tests/test-warning-census.sh. On a BeschleunigerBallett GCC log it
counted 37 own warnings over six flags, where the log shows 203 warning lines.
Four fleet workflow conventions (workflow-lint)#
linux/scripts/verify_workflow_conventions.py, run by lint-workflows.sh on the
same terms as verify_ci_image_refs.py — this checkout’s copy, the root it was
handed, its status folded into the one WORKFLOW LINT verdict. Baseline
linux/scripts/workflow-conventions.allow, suite
linux/scripts/tests/test-workflow-lint.sh.
Why it exists. Five rules the fleet agreed on and wrote down, each enforced by nobody:
convention |
how it was transmitted |
why the backlog is what it is |
|---|---|---|
no |
restated in seven workflow headers |
the one already clean fleet-wide, which is why it is enforced from day one with no knob |
job-level |
nowhere but the jobs that happen to have one |
worst in |
a |
nowhere |
included |
|
nowhere |
includes the release-package uploads — the artifacts a tag actually ships, which is where an empty upload is worst |
|
the |
a tag can be moved to code nobody reviewed; local |
|
nowhere; the names were copied as plain text |
every consumer’s |
The counts are deliberately not written here. They live once, as the CENSUS rows
of linux/scripts/workflow-conventions.allow, where they are the gate’s own
output and a gate grades them; a number restated in prose is a number that
drifts, and this pair had already drifted once.
The hub reusable Python CI uploads now require a nonempty combined path set
and keep always() so failed tests can publish logs. On Windows, logs can make
the upload nonempty without dist/; the build verdict separately requires the
distribution artifacts. The resolved hub census entry was removed.
A copied comment is not a convention: it is as strong as the last person who read one, and it says nothing at all about the file it was never copied into.
The ramp. shellcheck-warnings can freeze its individual offenders because
they live in THIS repo. These do not: the corpus is other repositories’
workflows, and a hub-side freeze of named jobs would turn every consumer red the
moment it edited one, then demand a submodule bump to record the fix. So this
follows lint-env-knobs.sh’s ramp — the three checks with a backlog report and
pass until WORKFLOW_CONVENTIONS_GATE arms them (1, all, or a
comma-separated list, so a repository can clear one convention at a time;
0/off/no/none/false/empty disarms them again), while runner-ban is
armed always. preflight.sh runs the gate with permissions and job-timeout
armed, the way it runs lint-env-knobs.sh with KNOB_GATE=1: this repo is
measured clean of both (job-timeout since 2026-10-14), so a workflow added here
without a permissions: block or a job without timeout-minutes is red the day
it lands.
The ratchet, which is what makes “advisory” safe. A report-and-pass check can
grow for ever with nothing turning red, so each repository’s count per RAMPING
check is frozen in a CENSUS | <repo> | <check> | <count> | <reason> row and may
only go down. Above it the gate fails whatever the arming says; a check with
findings and no row fails too, so the ramp cannot be dodged by omission. An
armed check counts zero — its findings already failed on their own, one finding
never gets two verdicts, and arming a check therefore retires its row. Going down
is the point, so it is cheap: in ANTfrastructure, whose commit edits this file
beside the fix, an unrecorded shrink fails like every other allow file here; in a
consumer, which reads the table through the submodule and cannot edit it, the
shrink is printed with the number to write down and passes.
Deviations are declared, not silent. A row in workflow-conventions.allow
reads <repo> | <path> | <check> | <detail> | <reason> — the EXCUSED-with-reason
table verify_ci_image_refs.py carries as a dict, moved into a file because these
rows name other repositories’ files. The gate resolves the tree it is linting from
its origin remote and grades only that repository’s rows, since one table is
shared by every consumer through the submodule. That table ships empty on
purpose: not one finding is excused, because excusing a finding to make a lane
green is the opposite of the job.
What a row is graded on. A row that matches a live finding excuses it and
prints its reason, and lowers the census count above it, so the two tables have to
agree. A row for THIS repository that matches nothing is stale and fails. A row
naming a repository .github/consumers.json does not declare is a typo and fails
— otherwise a mis-spelled first column would grade nothing, for ever, and look
like an excuse that worked. So does a tree whose own origin names an undeclared
repository: no row could ever be keyed to it, and grading its files with the
excuse table and the ratchet both inert is the same silence. A duplicate row
fails: two reasons for one deviation means one of them is unread. A missing or
malformed consumers.json fails rather than returning an empty set, which used
to switch the typo check off without saying so.
sha-pin has no census. It reports and passes wherever it is not armed, with
no CENSUS row needed, so a consumer that never pinned its actions keeps its verdict.
The hub’s preflight arms it, and the reusable lint-gates.yml arms it for a caller
that passes workflow-conventions: sha-pin; ANTfrastructure, AccelerANTgine,
OxidANT, OrchestrANT and OmniAccelerANT are measured clean and armed. It grades
step and job-level uses: in workflows and in .github/actions/*/action.yml. It
does not check what a pinned commit contains, nor actions or images a run: block
fetches. Suite: linux/scripts/tests/test-workflow-sha-pin.sh.
What it cannot see, said plainly. A row about repository A is neither used nor
stale while repository B is being linted, so a deviation that repository A deleted
is only reported the next time A’s own lane runs — and the same is true of its
census row. timeout-minutes is not asked of a job that uses: a reusable
workflow, because GitHub rejects the key there and the only “fix” would be an
invalid workflow.
The parser, and what it refuses. The YAML is read by a hand-written subset
parser, for verify_ci_image_refs.py’s reason: the gate runs on the stdlib alone.
The subset is block mappings, block sequences — indented or at the same column
as their key, which is ordinary Actions YAML and was silently dropped until
2026-09-09 — flow sequences and flow mappings, plain and quoted scalars, and block
scalars kept as one opaque string. Everything else RAISES, and a file that raises
is reported under a parse pseudo-check that never ramps and cannot be excused:
anchors, aliases, merge keys, multi-document files, a flow collection that spans
lines or holds a collection as a key, a top level that is not a mapping, a file
that is empty or all comments, and any line the walk did not consume. That last
one is the truncation guard: whatever is left over was graded by nothing. The
parser was validated against PyYAML over all 49 workflow and composite-action
files of the declared fleet (37 workflows, 12 actions) on 2026-09-09 — same
findings, file for file, no file unreadable.
Secret scan (secret-scan)#
lint-secrets.sh over the working tree with the pinned gitleaks. The suite
plants a synthetic credential — assembled at run time, since this repo scans
itself — and requires four things: the gate FAILS, the finding names the file and
line (it once failed on main saying “leaks found: 2” and naming neither, which is
what --verbose is for), the value is REDACTED so the CI log does not become the
leak, and the scan is scoped to the path it was handed. No case scans the whole
repo: that run is the preflight slug’s own job and would cost this suite minutes.
run-lint-gates.sh first copies the files a commit could take to a temporary tree: tracked, or
untracked and not ignored. It never reads an ignored file, so the out/, logs/ and
quality/.venv/ entries of .gitleaks.toml serve the preflight slug alone.
It scans the copy’s top-level entries side by side (LINT_GATES_SECRET_JOBS,
default one per CPU; 1 is in turn), reports them whole in scope order, and fails an entry that
wrote no status. tests/test-lint-gates-secret-jobs.sh holds that with a stub scanner, and
tests/test-lint-gates.sh holds the file set.
Curated SBOM (sbom)#
generate_sbom.py --check. The curated half of the inventory is the published
corresponding-source record for the copyleft components an image scanner cannot
see, so a document that drifts from versions.env is worse than none.
The gate is only possible because the document is byte-REPRODUCIBLE — hence the
frozen 1970-01-01T00:00:00Z creation stamp, which the suite asserts directly: a
wall-clock stamp would make --check red on every run, and a gate that is always
red gets switched off. The other cases are the ways --check could be hollow: a
missing file is not an up-to-date file, comparison is byte equality rather than
existence, --stdout writes nothing, and a versions.env bump really does move
the document.
The repo’s own cmake-format gate (cmake-format)#
An inline preflight function that drives lib/code-quality.sh end to end:
code_quality_ensure_cmake_format provisions the tool through uv into
logs/tools/cmake-format-linux when it is not on PATH (pins in
quality/cmake-format/uv.lock — pyyaml is included because
cmake-format==0.6.13 does not depend on it and dies with
ModuleNotFoundError the moment it reads a YAML config; after the install
lib/cmakelang-py315.py gives its lexer 3.14’s re.Scanner, which Python 3.15
refuses for capturing groups, as Install-UvRequirements does on Windows),
code_quality_find_cmake_files walks the tree, and
code_quality_run_cmake_format --check is the verdict. In scope is every
repo-owned CMakeLists.txt/*.cmake; excluded are third_party/,
external/, venvs, out/ — and windows/scripts/patches/, whose shim bytes
are Windows layer-cache keys a reformat would invalidate. A walk that returns
zero files is a refusal, not a green: an exclude glob that eats the corpus
must not pass vacuously.
--check is newline-strict, and with line_ending: unix that is the right
strictness for this tree: *.cmake is -text with LF in the index, so the
ten cmake/ files that carried CRLF working trees were autocrlf leftovers
from before the 2026-08-14 attributes rules, and normalising them left
git diff EMPTY. Re-CRLFing them instead would have kept the gate
permanently red.
The two that stay frozen, with better reasons#
Both of them took their route out on 2026-09-05, and gate-proofs.allow’s bare-slug
namespace is empty for the first time: 34 slugs, 34 proven, 0 frozen (36 of 36
once shared-config and cmake-format arrived proven on 2026-09-06, and every
slug added since arrived proven — verify_gate_registry.py prints the live
count). The
heading keeps its name because several files point at this anchor, and because the
two stories are the reason the freeze list was worth keeping honest rather than
deleting.
critical-fixes took the recommended route: the split. It was two scripts in
one trench coat — half greps over the repo tree, half probes of
/opt/python-cross, /opt/litert and friends that exist only inside a built
image. Proving the tree half alone would have credited the slug for a suite that
never touches the checks whose findings gate a rebuild, so the script was cut in
two instead: verify-critical-fixes.sh keeps fix5–fix10 (fix11, the ONNX Runtime
single-source denylist, joined on 2026-09-23) and stays the slug,
06-packaging/smoke-critical-fixes.sh takes fix1–fix4 and is run against a
shipped image by hand. test-critical-fixes.sh then proves BOTH halves — the
host gate in a fixture tree, the image probes under CF_SMOKE_ROOT.
The cache launcher guard checks shared-utility loading and delegation, then executes extracted selector/setup functions with disposable launcher paths and stubbed cache operations. It verifies executable precedence, the sccache fallback and caller launcher preservation; it does not start or prove a real cache daemon.
The split was decided by MEASURING first, not by reasoning about testability, and
the measurement is why it is right. Run in the shipped images for the first time,
the four moved probes reported four failures and all four were the probe being
stale, while the host half’s verdict lost exactly two assertions — fix4’s
amd64-cc-on-an-amd64-host tautology. A frozen slug had been carrying checks that
could not have gone green in the one place they were meant to run. The numbers,
and the real 707-header defect a corrected fix2 then found on all three shipped
arches, are in
cross-build-verification.md.
The generalisable part: before writing the suite a frozen slug is asking for,
run the gate where it is supposed to run. Two of these probes had never
executed anywhere, and no suite written against them would have said so.
version-snapshot got the one-fixture-per-sub-check suite its reason demanded.
sync_versions.py --check is a fan-out: result |= over nine sub-checks plus a
subprocess into generate-website-licenses.py, whose targets span README.md
markers, the deps table, doc literals, Dockerfile ARG defaults,
windows/scripts/**/Build-*FromSource.ps1 and — the eighth, added 2026-09-09 — a
CONSUMER repository’s own pyproject.toml / .pre-commit-config.yaml. Because
the verdict is an OR, a suite that reddens ONE sub-check would un-freeze the slug
while seven stayed unproven — the hollow-proof shape this list exists to prevent.
test-version-snapshot.sh reddens each one independently, plus the
subprocess — the sixth only since its KNOWN GAP (below) was closed on 2026-09-17.
Consumer pins and uv exclusions#
The consumer pin gate parses pyproject.toml as TOML and inspects its string values. The
tool.uv.exclude-dependencies list names packages that uv must not install, so it is not a
dependency declaration and its contents are not pin candidates. A same-named real dependency
or override is still checked; malformed TOML fails the gate. test-consumer-pins-toml.sh
and test-version-snapshot.sh cover exclusions, actual pins and parser failure.
uv’s own floor is read by key, not as a string value: [tool.uv] required-version must be a lower bound,
>=X.Y.Z, at or below UV_VERSION (CON249). An exact pin fails, as a newer image uv would refuse the
project; a floor above the pin fails, as the image’s uv refuses it today.
The eighth arrived unproven, and that is exactly the shape described above.
It shipped with nine mutations in the registry and none of them touching
check_consumer_pins, no fixture, and a registry row still reading
test+mutation — a slug crediting a suite for a sub-check it had never
executed. Worse, the check itself could not run: its only caller was the hub’s
own preflight.sh, which runs in a standalone clone where no consumer root can
be named, so it printed NOT CHECKED and exited 0 on every run in the fleet.
Both halves are closed together, because either alone is still hollow — the
check now runs as run-lint-gates.sh’s consumer pins gate in a CONSUMER’s
lane (that aggregator takes the consumer root as a mandatory argument, which is
the thing the hub lane does not have), and the suite’s 8/8 cases now drive it
(a drifted pin fails through the same result |=, two declarations in one file
are refused, an empty --consumer-pins run is refused) — but until 2026-09-29 no
mutation targeted check_consumer_pins, so the slug was credited on its nine older ids. The generalisable part:
“a check exists” and “a check runs” are different claims, and a registry can
only see the first one.
The fixture is a SYMLINK FARM, and that is what made the wave affordable.
collect_versions() — which render_snapshot() calls, so every --check run
depends on it — hard-reads five fixed files (linux/webserver/Dockerfile and four
under windows/) and raises an uncaught FileNotFoundError on a missing one,
plus it KeyErrors on any of six versions.env keys. A hand-built minimal tree
therefore cannot reach a verdict at all, and a full copy is 8 GB. So the fixture
mirrors the repo as symlinks one directory at a time, materialising only the file
under test as a real copy. sync_versions.py itself must always be a real copy:
it derives REPO_ROOT from Path(__file__).resolve(), and resolve() would
follow a symlink straight back to the real tree. The eighth sub-check’s code moved
out to docs/scripts/consumer_pins.py on 2026-09-10 —
it is the one target whose subject is a file this repo does not own, so it is
detection-only under a different contract from the seven it shared a file with.
That module takes the hub root as a PARAMETER instead of deriving one, and the
farm is precisely why: it is NOT materialised as a real copy, so a
Path(__file__).resolve() there would follow the symlink back to the real tree
and grade a different root than the sync_versions.py that called it. The suite’s own first case is the
green baseline printing all eight verdict lines — without it none of the reds
would mean anything — and its last case proves the perturbations are DISJOINT,
which under an OR is the difference between proving a sub-check and hiding one.
The eighth sub-check is the one the farm cannot supply a subject for: its
subject is a different repository, so the suite writes a two-file consumer of
its own (a matching one that rides along in every case, and perturbed copies for
the reds) rather than reading a sibling checkout that a CI runner does not have.
Since 2026-11-14 it also holds Flet (BACKLOG CON103): Flet’s Python SDK and its client speak
one release’s protocol, so FLET_VERSION in tool-pins.env (no early image stage reads it) is the
pin for OrchestrANT’s "flet[desktop]==…" and "flet-web==…" and its viewer job’s
--with "flet==…" in benchmarks.yml. default.json groups flet, flet-web and flet-desktop into one
Renovate PR. Recipe version-snapshot.consumer-pins-flet-extras proves the extras form is read.
Since 2026-09-29 the eighth also holds torch, torchvision and
onnxruntime-genai. The image build force-installs PYTORCH_VERSION and
TORCHVISION_VERSION over the app lock (enforce_torch_version_pins in
assemble-torch-app.sh). So a consumer pinning an older torch ran one torch on a
dev box and another in the image, and nothing went red: OrchestrANT sat on 2.13.0
against the hub’s 2.14.0 when the rows landed. Each package has two rows, the
PEP 621 "<name>==<version>" pins and the riscv64 pytorch.git@v<tag> /
vision.git@v<tag> source pins. onnxruntime-genai-cuda is graded as
onnxruntime-genai; the deliberately unpinned -directml is not a mention. These
keys carry the GitHub tag (v2.14.0), so _bare() drops a leading v before
comparing. Two mutations prove the rows bite: consumer-pins-tag-prefix (every
correct consumer reads as drifted) and consumer-pins-torch-row (the torch row
skips silently). The consumer’s lint-gates.yml checks the hub out at develop,
not at the consumer’s gitlink, so a lagging consumer goes red on its next push
once a new row is on develop.
Writing that suite found a sub-check that had never checked anything.
script_default_target_files() globbed windows/scripts/build-*-from-source.ps1
while the ten scripts live one directory deeper, in windows/scripts/build/, so
the glob returned an EMPTY list and check_script_defaults printed
Windows build-script -DefaultValue pins match versions.env. having scanned zero
files. The suite pinned the emptiness as a KNOWN GAP until 2026-09-17, when the
glob was fixed to windows/scripts/**/Build-*FromSource.ps1; the case now
perturbs Build-TvmFromSource.ps1 and proves the sub-check reddens, and the
TVM_COMMIT→TVM_REF exception (the same one-entry map the PinParity suite
documents, #134) keeps the tag fallback from being rewritten to the commit hash.
The ten scripts are gate subjects for the first time; the only drift they carried
was that TVM default, which the exception resolves.
A hollow mention nearly happened while writing this. test-arg-consistency.sh
asserted on the gate’s own fix hint, which spells sync_versions.py — and the
registry credits a suite that MENTIONS a gate’s script. version-snapshot flipped
to proven on a suite that asserts nothing about it. The assertion now stops
short of the basename, with a comment saying why.
The scan-root contract#
The ratchet gates used to resolve their scan root from __file__. In a
consumer’s third_party/ANTfrastructure checkout that is the HUB, so each gate
reported green over a tree nobody asked about while roughly 15,700 lines of
consumer shell went ungraded. --root fixes that;
linux/scripts/gate_scope.py is the one owner
of what a root means, after the first attempt left seven copies of it.
Four rules, each of which a copy got wrong somewhere:
A
--rootmust be a git checkout AND its toplevel.git rev-parsesucceeds in any subdirectory, so--root <repo>/third_partypassed and graded a fragment with every relative path anchored one level down — which shifts every allowlist key without saying so. Refused now, naming the real toplevel. Invalid roots exit with status 2 and a named error before any gate work starts.An empty scan is a decision, never a default.
refusewhere every repo must have such files, so an empty list means the scope construction broke;allowwhere a repo may legitimately have none. The caller says which.git ls-files, never a walk. A submodule is a gitlink, so the scope cannot descend into another repo, and untracked build output stays out.A tracked path that is not on disk is reported, not skipped. The old walk could only yield files that exist; the index can name files a sparse checkout never materialised, and
except OSError: continueturned that into a quiet partial grading. A gate that reads only blobs has no such gap:large-filessizes and sniffsgit cat-fileoutput, so a file missing from disk is graded as the index holds it.
A gate’s --root must default to None, never to its own ROOT. resolve_root
maps None to the gate’s own tree without asking git, while a named root must
pass the toplevel check, so default=ROOT makes every bare run demand a git
checkout and fails in the git-less mirror docs/scripts/verify_mutations.py grades.
The freeze file follows the root. Keeping it beside the script would put every repo’s ratchet inside the hub, where no consumer sees it in its own diff.
The three docs gates joined the contract on 2026-09-15. doc-links,
doc-dupes and code-dupes resolved their root from __file__ until then, so
they graded the hub and nothing else. Each now takes --root, keeps its
current behaviour exactly when the root is the hub — the curated page set,
the hub’s own budgets, the docs/index.rst coverage requirement — and under any
other root doc-links and doc-dupes read their scope from
gate_scope.tracked, code-dupes still walks the root, and each reads its
budget from <root>/<gate>.allow. Two consequences worth stating: a consumer is not
required to keep a Sphinx index (that check is hub-only, because inventing the
obligation would fail every consumer on a question nobody asked), and
doc-links is the one of the three wired into the --ratchets step, because it
is the only one with no budget to seed.
Workflow fixture builders#
The workflow-lint suite shares repository initialization, job headers and matrix/include and upload/step YAML builders. The generated baseline bodies retain their exact bytes, while malformed-flow and unsupported-shape cases remain independent inputs. The suite still runs the pinned real actionlint and keeps bootstrap refusal cases; these helpers do not replace the parser or relax a workflow convention.
Fixture search portability#
test-fixture-tool-portability.sh runs the six affected fixture suites with a
restricted PATH that excludes ripgrep. Their complete assertion totals remain
mandatory. Searches use portable grep, and negative checks require its exact
no-match status rather than accepting every failure. Missing helper definitions,
missing commands and malformed search inputs must make the fixtures fail.
Mutation namespace repairs#
Recipe IDs use a preflight slug or a declared descriptive family. Move a misplaced
recipe into its existing owning family while preserving its target, edit, test and
reason. Record a one-to-one old/new ID map with the validation evidence and retain
every recipe. The AMD package-provenance recipes belong to packaging; declaring
a second family for those same checks is unnecessary. Use the canonical mutation
merge driver for the validated additions after removing only the mapped old IDs.
Test harness and lint invariants#
Rules for the test harnesses, the lint lanes and the mutation tooling. Each item is one rule.
A declared shared shell mirror may count a real command from the validated image-consumer plan as a caller. Retain the executable call and the separate shared-config drift gate.
The duplication scanner shares the code-size shell lexer so quoted braces and here-doc bodies do not merge function units.
Mutation –root controls Git change/push selection as well as execution. An empty selection is no coverage receipt.
Runner fixtures clear inherited RUN_TESTS_JOBS before applying explicit case values. Default scheduling controls must exercise the default.
Regex cardinality assertions use the shared harness counter and retain caller-selected patterns and text.
Wrap provisioning deletes the git wraps it extracts. A dependency reached only through a wrap’s
[provide]needs a pinned wrap-file, and its plugin belongs in the contract.Synthetic ELF and gst-inspect test fixtures share their writers. Retain caller-specific
DT_STRSZ, symbol-table andNameoptions.Compiler argv fixtures normalize generated probe basenames under arbitrary temporary roots. Retain the independent path-with-spaces control.
ctest-run.sh --fail-on-skippedfails on every matching JUnit skip but never on ctest’s Disabled tests. A missing or stale report fails rather than passes.Its bootstrap helpers must fit the consumer’s 15-path complexity limit. The copied-template fixture measures that limit and proves a complex mutant fails.
The same fixture runs the consumer trailing-conditional gate and must reject a planted final test.
Renovate planner companions belong in the strict ty and ANN001/ANN201 scopes. The isolated type fixture must detect their removal.
Consumer-hook fixtures retain Git’s canonical root spelling and a checked discovery ceiling above their empty-directory cases. Prove isolation with an owned parent repository.
Shared Python runtime protocols mark unused positional-only arguments with an underscore. Copy the canonical module and retain strict consumer dead-code grading.
Mutation namespace repairs preserve every target, edit and test and record a one-to-one ID map. Keep the registry’s existing coverage.
Use
docs/scripts/generate_require_mutations.pyfor recurring require-removal recipe preparation. It does not replace canonical merge, parse checks or actual mutation runs.Use
docs/scripts/merge_mutation_recipes.pyto preview or merge recurring mutation recipe updates. Stale anchors and unintended replacements fail before writing. Keep serialized registries ASCII-safe and decoded values exact, including deliberately corrupt negative-test strings.Core disk probes share validation without merging zero-disabled and nonnegative-free-space policies.
Invalid temporary-allocation fixtures share the harness emitter and retain failed, empty and missing-path outcomes.
Test workers use the harness optional-function emitter. Keep required definitions mandatory.
Stream receipt suites carry
stream-receipt-fixture.sh. Keep their expected results independent of production code.Wheelhouse stderr fixtures pin child locale to C.UTF-8. Retain both parent-locale controls and original receipt bytes.
Named mutation-check suites carry their case-executor companion. Failed controls and invalid recipes remain failed results.
FT transport fixtures supply and assert both dependency pins before interpreting factory results. Keep raw probe status and each interpreter branch observable.
Standalone native C++ probe libraries import their own logging bootstrap. FT dependency RUNs retain guarded cache setup, the narrow drain mount and a closing drain. SDK dispatch fixtures quote redirects and assert complete argv, including paths with spaces.
Python CI driver tests use
t_python_ci_fixturefor isolated script trees and workspace detection. Keep tool stubs in each suite.Git fixtures share checked local repository setup. Native tool failures must fail the fixture without changing global identity. Renovate bootstrap tests use the shared Git fixture and supply only their driver and wrapper layout.
Python CI suites carry their shared driver fixture. Preserve child status, call logs and parent environment isolation.
Consumer inventory includes shared shell libraries and requirements. Ambiguous consumer basenames remain mentions, not proof of a hub call or absence.
Cache-unavailability fixtures stub the selected tool probe without removing directories that contain shell utilities. Keep the grouped-tool regression and raw fallback verdict.
The strict-type fixture carries every explicitly selected native helper and proves both incorrect returns and missing annotations. Production scope counts remain enforced.
The hub’s full Ruff scan, all-file annotations and compatible Linux/Windows type checks fail on findings. Keep the tracked-file coverage and pinned tools intact. Run dependency-specific checks in the workflow or build that provides their imports. See Python type analysis for the current scopes and test requirements. Ty checks inferred types but does not require annotations.
python-static.shadds the quality site-packages and the pinned docs theme to ty as extra search paths. Do not replace ty’s own environment discovery with--python, which unresolves imports it found before.Dependency-specific checks run in their owning workflow or image build. Keep checker tools out of shipped images. The version probe catches only expected import, metadata, lock-parse and OpenCV failures. Malformed present locks and unexpected runtime exceptions must fail.
Ruff B012 and B023 are fatal for tracked Python and extracted shell heredocs. The default hub preflight sweep makes the full Ruff default ruleset fatal, including F401, F841, RUF059, FURB167, ISC004, UP032 and B009. Python shebangs require executable file modes, so keep Ruff EXE001 in that sweep. Targeted and named-root lint calls keep their consumer adoption tier advisory. Preserve the selector, full-sweep and extraction mutation proofs.
Consumer Python lint maps tracked shell heredocs back to source lines across Windows path separators and forces UTF-8 when it prints remapped findings. Extraction failure is fatal, and a valid no-block scan is green.
Stable Python CI test legs require fresh JUnit and measured, covered package lines. A configured coverage floor must reach every leg.
Bash script discovery fails when no suite runs. The hub runner requires a pass per Pester file, and the shared Pester action requires one across its selected path. Preserve legitimate partial skips.
Detected consumer lint calls keep ratchets enabled and failures fatal. The weekly inventory reports missing calls as advisory. Duplication reporting is available in every reusable lint run, while
--code-dupes/code-dupes: trueis a separate fatal gate for consumers that have removed the measured debt. Do not freeze that debt with new allowances. The report-only size, complexity and duplication lane writes ignored artifacts and keeps broken inputs fatal.A Linux job refused for disk re-runs through
retry-disk-refusalonly. It keys on the exact annotation and the one-job endpoint, so a genuine failure never re-runs.Consumer mutation jobs supply a tracked, nonempty recipe manifest. An empty shard or missing setup file cannot pass as proof. Python refactor previews target the caller root and upload a patch without publishing it.
Negative search assertions require the no-match status
1. Missing-tool127and search-error2must fail the fixture.
Host test jobs use an on-disk TMPDIR outside every Git checkout, so non-Git fixtures cannot inherit an ancestor repository index.
Fixtures unrelated to ref resolution use a synthetic immutable app identity. Moving-ref resolution belongs to
test-app-ref.sh, not a graph dry-run.Chain lifecycle fixtures disable inherited BuildKit and image-store pruning. Sentinel engines prove that isolation.
Graph/runtime fixtures also use disposable context directories and immutable parent pins.
Host-executed consumer-probe fixtures use native utility paths and explicit fixture tools. Keep the outer runner PATH intact.
Opt-in fixed mutation workspace roots are fresh, absolute and outside the source tree. Use container-private paths. Keep exclusive allocation, per-worker isolation, identity-checked cleanup and fatal cleanup errors. Never reuse a writable host checkout as a mutation workspace.
Runtime dry runs start no heartbeat. A live heartbeat kills its current timer child with SIGKILL and waits for it. TERM can be lost while the timer starts, and a separate PID assignment leaves a signal window that leaks output pipes.
Shared Chrome cleanup is asynchronous: callers await child exit and profile cleanup. An immediate process-exit hook only kills. Cleanup failures remain fatal, and every browser finishes cleanup before one peer’s failure is reported (docs-sites.md). The launcher owns cleanup until it returns: endpoint/page discovery, WebSocket connection and initial DevTools failures must release the group, profile and hooks.
Register ownership before suite work starts. Cancellation covers pending launches and joins owned supervisors and watchdogs. Supervisors and watchdogs write to job logs, never to a caller’s captured pipe. Commands append so earlier diagnostics survive. Cleanup in a signal or EXIT trap checks group disappearance without reentering Bash’s
wait. A trapped wait can hang after a watchdog timeout. Supervisors retry an interrupted command wait before recording its status, including when the child has just exited.Rootless nerdctl QA for a pinned public base uses a per-run empty
DOCKER_CONFIGand the native Linux CLI. Retain the user’s authentication/context files and distinguish a failed preparatory pull from a started build (failure).Unix mutation test commands get private
XDG_CACHE_HOMEdirectories, removed only after child reaping. Preserve callerHOME, raw statuses and the Windows environment policy. Mutation test children get closed stdin so caller input cannot stall a proof.Git Bash fixtures need real symlinks. Denied creation remains a missing prerequisite.
Comment size (
comment-size)#The family rule is one line, only the why (
AGENTS.md§ Comments).verify_comment_size.pyfails on any NEW comment block over one line (COMMENT_SIZE_LIMIT) in every tracked source file of the graded repo,third_party/excepted:Languages.
#comments in shell, Python, PowerShell, YAML, TOML, CMake and Dockerfiles;//and/* */in the C family, Rust, Dart, JS/TS and the shader languages.Data, not comments. Heredoc bodies (a
<<inside quotes opens none), PowerShell here-strings and Python strings, found with Python’s tokenizer.Exempt. API docs (
///,//!,/** */, docstrings and comment-based help are not#lines), licence headers, tool directives, generated files and vendored trees (pkg/,cargokit/, Flutter runners,windows/upstream/).The blocks frozen in
comment-size.alloware the exceptions: help text a script prints from its own header. Shrinking one means deleting its line, and a stale entry fails too, so the list cannot rot.Entries are keyed on file + the block’s first comment line, not on a line number — a block must not re-flag because something above it moved. One subtlety cost a debugging round: the key is truncated to 60 characters and must then be
rstrip()ed, because the allowlist reader strips each line, so a key ending in whitespace reported the same block as NEW and STALE at once.A companion gate for cache blast radius (a script COPY’d into a shared stage that only leaf RUNs use) was prototyped and dropped: shared 01-core helpers are legitimately COPY’d into base stages for their descendants, so it produced false positives, and a noisy gate teaches people to ignore gates. The verify-media-artifacts case it was meant to catch is recorded in
docs/refactoring-backlog-archive-2026-09-02.md§ F6 instead.