# Developers' guide This guide captures the local developer workflow for the mxd Hotline server project, with a focus on the commands required to format, lint, and test the codebase, plus the PostgreSQL helper needed for integration coverage. ## Prerequisites - Rust toolchain pinned by `rust-toolchain.toml`. - The application and shared CLI definitions require Rust 1.94.0 or newer; CI checks the supported feature lanes on that stable compiler. - `cargo` and `make` available on your `PATH`. - `cargo-audit` available for `make audit`; CI installs it with `cargo binstall --no-confirm cargo-audit`. - Optional: `pg-embed-setup-unpriv` for PostgreSQL-backed tests. ### Build-tool resolution The `Makefile` applies a conditional fallback for each build tool it invokes. When the named tool is not found on `PATH`, the Makefile checks a fixed well-known location and, if present, promotes it: | Variable | Default | Fallback location | | ---------- | ------------------- | ------------------------------ | | `CARGO` | `cargo` | `~/.cargo/bin/cargo` | | `WHITAKER` | `whitaker` | `~/.local/bin/whitaker` | | `MDLINT` | `markdownlint-cli2` | `~/.bun/bin/markdownlint-cli2` | This avoids silent failures when a tool is installed outside `PATH` and prevents the Makefile from inadvertently resolving to an unintended binary earlier in `PATH`. Override any variable at invocation time if the tool lives elsewhere: ```sh make lint WHITAKER=/opt/custom/bin/whitaker ``` The fallback is a one-time check at parse time; it does not introduce a runtime dependency on shell availability. ## Python docstring coverage `make lint` depends on `make interrogate`, which requires a docstring on every module, class and function that interrogate scans in the Python files under `scripts` and `tests`; interrogate skips some path prefixes by default, so check a new file against the verbose report. The target runs interrogate 1.7.0 through `uv tool run` with `-vv --fail-under 100`, so it needs `uv` on the path, and it also fails on any `MISSED` row because the rounded percentage can hide a single gap. CI lints Rust per feature set rather than through `make lint`, so the documentation job runs `make interrogate` as its own step after setting up uv. `tests/workflow_contracts/interrogate_gate_test.py` holds the wiring. ## Dependency auditing Run the dependency vulnerability audit with: ```sh make audit ``` The `audit` target delegates to `rust-audit`, which walks every `Cargo.toml` outside generated or vendor-like directories and runs `cargo audit` from manifest directories that have an adjacent `Cargo.lock`. Workspace member manifests without their own lockfile are covered by the root workspace lockfile and are reported as skipped rather than failing the audit before the root check runs. This keeps the root workspace, auxiliary crates, and standalone lockfiles under the same advisory check used by CI. ### Makefile PATH handling via `TOOL_PATH_PREFIX` `TOOL_PATH_PREFIX` is built from the resolved Cargo binary directory, the resolved Whitaker binary directory, and `~/.local/bin`. The Makefile resolves the executable token first, records the directory only when lookup succeeds, and then joins the non-empty entries: ```make TOOL_PATH_PREFIX := $(shell printf '%s\n' \ "$(CARGO_BIN_DIR)" "$(WHITAKER_BIN_DIR)" "$(LOCAL_BIN_DIR)" \ | awk 'NF { printf "%s%s", sep, $$0; sep=":" }') ``` The Makefile exports the prefix once, ahead of the caller's `PATH`, for every recipe, so the lint targets run the selected Whitaker (`$(WHITAKER)`, which a caller can override) behind a plain `RUSTFLAGS` assignment, with `CARGO_ENCODED_RUSTFLAGS` removed because Cargo gives it precedence: ```sh env -u CARGO_ENCODED_RUSTFLAGS RUSTFLAGS="-D warnings" \ CARGO_UNSTABLE_CODEGEN_BACKEND=true CARGO_PROFILE_DEV_CODEGEN_BACKEND=llvm \ whitaker --all -- --no-default-features \ --features "postgres test-support legacy-networking" --all-targets ``` The build-standard rule reads that shape as an isolated Whitaker route; a `PATH=` prefix written out in the recipe with Make functions in it is not read, and the route then counts as a gate build that lost the fast flags. The export keeps the same Cargo executable family, the resolved Whitaker binary, and user-local tools ahead of the ambient shell `PATH` while avoiding an empty current-directory entry. The Clippy lines still use `$(CARGO)` directly. Whitaker receives `--all-targets` so test-only modules compiled behind `#[cfg(test)]` are linted by the same structural rules as library and binary targets. To inspect the effective prefix for a local shell, ask `make` to print it: ```sh make -pn | grep '^TOOL_PATH_PREFIX :=' ``` For a local lint invocation, the effective command shape is: ```sh PATH="${TOOL_PATH_PREFIX:+$TOOL_PATH_PREFIX:}$PATH" RUSTFLAGS="-D warnings" \ CARGO_UNSTABLE_CODEGEN_BACKEND=true CARGO_PROFILE_DEV_CODEGEN_BACKEND=llvm \ whitaker --all -- --features "sqlite test-support" --all-targets ``` That prefix means Cargo subcommands installed under `~/.cargo/bin`, Whitaker installed under its resolved directory, and user-local tools under `~/.local/bin` are found before system defaults during the Whitaker lint pass. ## Embedded PostgreSQL in tests Every PostgreSQL test, locally and in CI, runs against an embedded cluster started by `pg-embed-setup-unpriv` 0.7.0. There is no external database option: the `POSTGRES_TEST_URL` override and the CI `postgres:15` service container that fed it are gone, and a cluster that fails to start fails the test rather than skipping it. `make test-postgres` needs no database running. ### The postgres leg runs in parallel pg-embed-setup-unpriv 0.6 gives each cluster its own data directory on the install root, so concurrent clusters no longer share data directories. The 0.6.3 slot-claim race can still return `slot lock ... is already held`. The `pg-embed` single-slot test group that 0.5.x needed is gone, the `all()` override that applied it is gone, and so are the 22 `#[serial_test::file_serial(postgres_embedded_setup)]` attributes. The leg runs at the default parallelism; `tests/postgres_harness_isolation.rs` holds two fixtures alive at once and asserts their databases are separate. The harness retries a lost slot race in `retry_slot_contention`, with up to eight start attempts and a backoff increasing in 25 ms steps. The `is_slot_contention` check searches the full error chain for both `slot lock` and `is already held`. Template startup uses the upstream shared-cluster initializer normally; if it reports this contention, `shared.rs` starts a separate shared cluster through the retry path, caches the fallback result, and registers its shutdown hook. Structured tracing records numeric `attempt`, `max_attempts`, and `delay_seconds` fields with bounded `error_category`, `outcome`, `source`, and `cache_state` values. It does not record raw errors, database URLs, or credentials. Terminal causes are returned to the caller and appear in the failed test's bootstrap error chain. After retry exhaustion or a cached fallback failure, inspect that chain for the underlying startup cause before choosing a fix and rerunning `make test-postgres`. The harness emits these metrics: - `mxd_test_postgres_retry_attempts_total` counts scheduled retries. - `mxd_test_postgres_retry_exhausted_total` counts exhausted slot-contention retries. - `mxd_test_postgres_fallback_selected_total` counts fallback selections. - `mxd_test_postgres_fallback_cache_total` counts fallback cache results. Its bounded `outcome` labels are `success` or `failure`; `state` is `initialized` or `reused`. - `mxd_test_postgres_bootstrap_seconds` records elapsed time for a retry-managed bootstrap through success or terminal failure, including retry delays. It has no labels. The `postgres` profile in `.config/nextest.toml` remains, because a cold cluster start is slower than the default 60 second slow timeout: one took 156 seconds on a quiet host. It allows 300 seconds per test and 60 minutes for the run, and `make test-postgres` and each CI step running the PostgreSQL tests select it through `NEXTEST_PROFILE=postgres`. A fixed superuser password is still required, though for a different reason than in 0.5.x. 0.6 stores the password with the cluster and reuses it, so a process can only join a cluster another process created if both agree on the password; it does not generate one per process and then refuse its own cluster. `make test-postgres` and each CI job running the PostgreSQL tests set `PG_PASSWORD` to a fixed throwaway value. It is not a secret: the clusters listen on localhost and live only as long as the run. ### The bundle is not pinned pg-embed-setup-unpriv 0.7.0 depends on `postgresql_archive` 0.22.0, which extracts tar hard links. The October theseus rebuilds (18.6.1 and later) express their time-zone aliases as hard links, which the 0.6 extractor skipped; every diesel connection then failed with `invalid value for parameter "TimeZone": "UTC"`, and the repository pinned `PG_VERSION_REQ` to `=18.6.0` to avoid it. With 0.7.0 the pin is gone: the Makefile and the CI jobs leave `PG_VERSION_REQ` unset and the harness selects the newest bundle. `tests/workflow_contracts/test_embedded_postgres.py` and `test_postgres_make_targets.py` assert that neither sets it. To try a specific bundle, export `PG_VERSION_REQ` with an exact requirement, such as `=17.11.0`. pg-embed-setup-unpriv caches a cluster bootstrap failure for the rest of a test process, so a download failing inside the suite would fail every later test in that process. CI installs the `pg_embedded_setup_unpriv` binary at the crate's version (`cargo binstall pg-embed-setup-unpriv@0.7.0`) and runs `make warm-postgres` first. That target runs setup with throwaway install and data directories under `.pg-embedded/warm`, which selects the same bundle as the tests and fills the binary cache named by `PG_BINARY_CACHE_DIR`. It then fails if the cache is still empty, because the tool skips caching silently when it cannot take the cache lock. Each job sets `PG_BINARY_CACHE_DIR` once, so the warm-up and the tests read one cache. There is no binary-cache restore across CI runs, by design. Every job warms the cache from scratch, which keeps the warm-up's cost visible and its failure attributable to that run rather than to a stale cache entry. The warm-up step sets `GITHUB_TOKEN: ${{ github.token }}`. postgresql_embedded lists the PostgreSQL releases through the GitHub API, which rate limits anonymous callers by runner address, and one such 403 failed the coverage job's warm-up, and with it the only PostgreSQL run in the job. The contract asserts the token on the warm-up step of both coverage jobs; removing it, or replacing it with a literal, fails the named case. ### The warm-up repairs the time-zone alias The pinned August bundle is intact, but a cache or install tree written by an earlier, broken download can still hold a dangling `share/timezone/UTC` link. `make warm-postgres` therefore does two things after setup succeeds: it fails if the cache is still empty, and it walks both `PG_BINARY_CACHE_DIR` and the throwaway `.pg-embedded/warm/install` tree for `share/timezone/UCT`, creating the `UTC` alias wherever it is missing. The scan uses `find -H`. That follows a symbolic link named on the command line, which is exactly the `PG_BINARY_CACHE_DIR` case when a deployment keeps the cache on another volume, while leaving any links found beneath the root alone. A dangling `UTC` link is removed before the replacement is created: plain `[ -e ]` is false for a link whose target is gone, so an existence-only guard would leave the broken link in place while still reporting success. A failed scan or a failed `ln` fails the target rather than being swallowed. `tests/workflow_contracts/test_postgres_make_targets.py` drives this against a stand-in downloader. It asserts that a filled cache gains the alias in both roots, that a dangling link is replaced, that a cache reached through a symbolic link is still scanned, and that a missing install root or an empty cache fails the target. ### The contract `tests/workflow_contracts/test_embedded_postgres.py` asserts that no job declares a service container, that no workflow mentions `POSTGRES_TEST_URL`, and that no Rust source reads it. For each job that runs the PostgreSQL tests, it asserts that the job pins `PG_PASSWORD` and leaves `PG_VERSION_REQ` unset, that the step sets the `postgres` profile, and that `make warm-postgres` runs once earlier in the same job. It asserts that the profile declares no `pg-embed` group and no `all()` override, and keeps its 300 second and 60 minute budgets. It also asserts that both workflows install the helper version `Cargo.lock` holds, so the warm-up cannot fill a cache the tests will not read. The jobs it covers are the two coverage jobs, `coverage` in `ci.yml` and `coverage-upload` in `coverage-main.yml`; the `build-test` postgres leg no longer runs the PostgreSQL tests. `tests/workflow_contracts/test_postgres_make_targets.py` holds the local twins of those steps. It reads the `test-postgres` recipe from `make --dry-run` and asserts the `postgres` profile and the default and overridden `PG_PASSWORD`, and that neither `test-postgres` nor `warm-postgres` sets `PG_VERSION_REQ`. It runs `make warm-postgres` against a stand-in `pg_embedded_setup_unpriv` under a fake home and asserts the throwaway directories, success when the cache fills and the `UTC` alias is created or repaired, and failure when the cache stays empty, an alias root is missing, or `PG_BINARY_CACHE_DIR` is unset. ## PostgreSQL migration strategy (v0.6.0) The migration to pg-embed-setup-unpriv 0.6 (now 0.7.0) keeps the handle/guard split, `test_support::shared_cluster_handle()`, the template helpers, and the `async-api` signatures mxd uses compatible. The harness adds bounded slot-race retries and a cached fallback for template startup; the release changes the cluster isolation model. The full narrative and verification steps are in [`pg-embed-setup-unpriv-v0-6-0-migration-guide.md`](pg-embed-setup-unpriv-v0-6-0-migration-guide.md). - Run every PostgreSQL test against an embedded cluster. The `POSTGRES_TEST_URL` route to an external server, the CI service container that fed it, and the skip taken when a cluster could not start were all removed, so a PostgreSQL test either runs against the cluster it started or fails. - Use template-based provisioning (`postgres_db_fast`) with a process-shared `ClusterHandle` and `CREATE DATABASE ... TEMPLATE` clones so migration amortization remains effective under v0.5.0 cleanup defaults. - Use send-safe split lifecycle APIs (`TestCluster::new_split()` and `TestCluster::start_async_split()`) or `test_support::shared_cluster_handle()` when shared fixtures must cross thread or timeout boundaries. - Prefer default cleanup (`CleanupMode::DataOnly`) for day-to-day runs, use `CleanupMode::Full` for strict filesystem hygiene, and reserve `CleanupMode::None` for explicit forensic debugging sessions. ## Behavioural testing strategy The behavioural suite uses `rstest-bdd` v0.6.0 in both the root crate and `crates/mxd-verification`. - Keep ordinary synchronous scenarios on the default harness. Use `scenarios!` bindings to a specific `.feature` file and `fixtures = [name: Type]` for consistent shared-world injection. - For immediately ready async steps, select the canonical `harness = rstest_bdd_harness_tokio::TokioHarness`. The obsolete `runtime = "tokio-current-thread"` selector is no longer used. - `TokioHarness` polls each async step once. A step yielding `Pending` fails, so `create_user_bdd`, `wireframe_handshake_metadata`, and `wireframe_transaction_encoding` use named `#[scenario(path = "…", name = "…")]` bindings under external `#[tokio::test(flavor = "current_thread")]` async tests. These tests await each step and permit socket I/O, timers, and scheduling without nesting runtimes. This follows the published 0.6.0 API while upstream issue [#820](https://github.com/leynos/rstest-bdd/issues/820) remains relevant. - `tests/bdd_binding_coverage.rs` compares feature scenario names with those explicit bindings. Add a binding when adding a scenario; the coverage check rejects omitted, duplicated, or stale names. - `tests/rstest_bdd_migration.rs` exercises aliased errors and returned values, deliberate underscore fixture keys, and a genuinely suspending step. - The handshake scenarios in `src/wireframe/handshake_bdd.rs` are the reference shape for a world that performs real network I/O. `HandshakeWorld` holds only plain `Option` fields, so the world is an ordinary owned value with no `RefCell`, no owned `Runtime`, and no `block_on`. Steps that touch the socket are `async fn` taking `&mut HandshakeWorld`; steps that only start the server or read recorded state stay synchronous and take `&mut self` or `&self`. The world's `Drop` sends the shutdown signal synchronously and ignores a closed receiver, so teardown never has to await. Prefer this shape for a new suite that needs mutable scenario state across an await. The accompanying compile-time fixture is described under [compile-time scenario contracts](#compile-time-scenario-contracts). - Prefer async behavioural scenarios for async-sensitive suites where async I/O is exercised and fixture setup does not rely on embedded PostgreSQL cluster bootstrapping. - For suites that must initialize embedded PostgreSQL fixtures, keep step handlers synchronous and run async routing calls through a fixture-owned Tokio runtime to avoid nested runtime panics in PostgreSQL setup helpers. - Keep scenario state isolated per scenario. Share only infrastructure with explicit fixture choices; do not depend on scenario execution order. - If a manual `#[scenario]` binding must keep an intentionally unused fixture, use an underscore-prefixed parameter with explicit remapping, for example `#[from(world)] _world: RuntimeWorld`. - Do not add file-wide lint suppressions for scenario glue. Scope lint expectations tightly to the smallest function or statement that requires them. - If a scenario needs a fallible return signature, use explicit `Result<(), E>` or `StepResult<(), E>` in the scenario function signature. ### Compile-time scenario contracts The non-published `tests/rstest-bdd-ui` workspace package uses `trybuild` to check named `TokioHarness` selection, the mutable-world async step pattern, and the diagnostic for an unknown scenario title. Run it directly with `make test-rstest-bdd-ui`; the aggregate `make test` target and the CI test lane include this package. The trybuild fixtures and their contracts are: - `tests/ui/pass_named_harness.rs` must compile: named scenario selection with `harness = rstest_bdd_harness_tokio::TokioHarness`. - `tests/ui/pass_mutable_world_async_steps.rs` must compile: a borrowed world fixture with a synchronous `Given`, an async `When` taking `&mut World`, a synchronous `Then`, and a named scenario bound to an external `#[tokio::test(flavor = "current_thread")]` test. - `tests/ui/fail_missing_scenario.rs` must fail to compile with the recorded `fail_missing_scenario.stderr` diagnostic. It is the control that proves the harness really inspects compilation output instead of always passing. `trybuild` builds pass fixtures with `cargo build --bin`, which type-checks the binary target only. The bodies of `#[test]` functions are not type-checked in that mode, so a scenario declared at the top level of a pass fixture contributes nothing beyond a binary-level compile of its imports and macro use. The scenario wrapper contracts that matter — the macro-generated wrapper for a mutable-world async step, and named selection under both harness paths — are therefore pinned by the `fixture_scenarios` module inside `tests/rstest-bdd-ui/tests/ui.rs`, which is the package's integration-test target and is compiled by `cargo test` in test mode. Add a wrapper contract there, not to a fixture, when the generated function itself is what should be checked. The `path` in `#[scenario]` is relative to `CARGO_MANIFEST_DIR`, so the same `.feature` file needs a different string in each of those two places. A trybuild fixture is compiled in a scratch crate under `target/tests/trybuild/rstest-bdd-ui-tests/` and needs four `../` hops, while the `fixture_scenarios` module is compiled in `tests/rstest-bdd-ui` itself and takes a plain package-relative `tests/ui/...` path. Copying the fixture's string into the module overshoots the workspace root and the macro reports "feature file not found" at the manifest join, not at the `path` literal. The module's `world` fixture carries a tightly scoped `#[allow(unused_braces)]`. That is not incidental: `rustfmt`'s `fn_single_line` setting rewrites a single-expression fixture back onto one line on every `make fmt`, and the `fixture` expansion then trips `unused_braces`, which the workspace denies. The same suppression, with its `#[expect(clippy::allow_attributes)]` companion, appears on the other BDD worlds (`src/wireframe/handshake_bdd.rs` and `tests/wireframe_transaction.rs`); match that shape rather than expanding the body, which does not survive formatting. The mutable-world fixture uses `tokio` directly, so the UI package declares `tokio = "1"` as its own dev-dependency rather than inheriting it from the root package manifest. Extend `tests/ui.rs` whenever a fixture is added; an unregistered fixture silently never runs. The trybuild test compiles separate fixture crates and can take longer than an ordinary unit test on a cold build: trybuild runs `cargo clean --package` before every fixture build, so the fixture package is rebuilt on each run rather than reused from an earlier one. That build also has to queue behind whatever else the host is compiling. `.config/nextest.toml` therefore gives `rstest-bdd-ui-tests` a 900-second slow timeout, and the `rstest-bdd-ui` profile raises the run-wide `global-timeout` to 30 minutes. `make test-rstest-bdd-ui` selects that profile through `NEXTEST_PROFILE=rstest-bdd-ui`, because `global-timeout` is not one of the settings a per-package override can replace. `tests/workflow_contracts/test_rstest_bdd_ui_gate.py` pins those three parts together. It runs the Make target for real, with `CARGO=` standing in for Cargo, and reads the profile from the environment of the process the recipe started. A stub on the caller's `PATH` would not do: the Makefile prepends `$(HOME)/.cargo/bin` to `PATH` on its third line, so the real Cargo would run. Reading the recipe's text would not do either, since `NEXTEST_PROFILE=` moved onto a recipe line of its own still appears in a dry run while the runner inherits nothing. The remaining contracts chain the numbers, so a raised slow timeout that no run ceiling can accommodate fails rather than passing as a larger figure. They also assert `terminate-after`: a period alone only reports a test as slow, so without it an overrunning test would run on until the run-wide ceiling killed the whole run. Keep the pass and compile-fail assertions enabled. Those contracts read the configuration; they cannot show that nextest acts on it. libtest ignores `.config/nextest.toml` entirely, so a `cargo test` run of the UI package would pass whatever the budgets said, and a Cargo stub records the profile without ever applying it. `tests/workflow_contracts/test_rstest_bdd_ui_timeout_routes.py` and `test_rstest_bdd_ui_timeout_profile.py` therefore drive a real nextest over a disposable two-member fixture workspace, with budgets in seconds rather than minutes. One member matches a package override and one deliberately does not. The contracts run each member separately, so every outcome is attributed to the crate that produced it: the matching crate shows the per-package timeout, and the control shows the default route's shorter per-test timeout. The behavioural contracts are split across those two test modules, with the fixture and the nextest runner in `rstest_bdd_ui_timeout_fixture.py` and `rstest_bdd_ui_timeout_runner.py`. The split is by subject, not by line count: one module covers the two routes into the package, the other the named profile and the end-to-end runs of the shipped recipe. They share the fixture, so a budget is stated once and both modules read the shape they need from it. Both test modules are selected by the glob in `make test-rstest-bdd-ui-timeouts` and excluded by the matching ignore-glob in `make test-workflow-contracts`, so a newly added module cannot be filed where nothing runs it. The fixture scales the shape production has, in which *both* routes terminate: the default profile kills at 60 seconds and the override raises that to 900. Because both report `TIMEOUT`, the word alone cannot tell them apart, so the contracts read the second at which the kill landed. That difference is exactly what the override buys - the same test is allowed to run longer - and a fixture whose default route merely warned could not express it. One contract holds a single short sleep to both routes at once: the same test, in crates that differ only by the name the package filter keys on, passes under the override and is killed under the default. The fixture declares the `rstest-bdd-ui` profile too, with second-scale budgets, and further contracts select it by name through `NEXTEST_PROFILE`, as the Make target does. They assert both halves separately: that nextest resolved the profile named, read back from the `with nextest profile:` banner, and that the outcome is the one only that profile's budgets produce. The named period is longer than the default one, so a run that fell back to `default` would report `TIMEOUT` at the shorter default period where the named profile reports it later. A second contract gives the profile a ceiling shorter than its period and shorter than the default ceiling, which makes `TIMEOUT` and `SLOW` unreachable rather than merely unlikely, so their absence is structural and the `SIGTERM` that arrives early can only be the named profile's own `global-timeout`. The fixture's profile name is itself pinned to the target's by reading `NEXTEST_PROFILE=` back out of the Makefile, so a rename on either side fails. The harness sets `NEXTEST_PROFILE` rather than inheriting it, because an ambient value left over from a surrounding run would otherwise choose the profile the contracts are deciding. The contracts assert nextest's result words, and the second at which each was reported where both routes report the same word. The word carries the reason: an overrunning test reports `TIMEOUT` when `terminate-after` kills it at its period, `SLOW` while a period without `terminate-after` merely warns, and `SIGTERM` when neither applies and the run-wide ceiling stops the whole run. One contract removes this repository's `terminate-after` from the fixture and asserts the word changes, which is what makes the setting's contribution visible rather than assumed. Exit codes cannot make the distinction: a per-test timeout and a run-wide ceiling both exit 100, so only the reported word separates them. The same file also runs the shipped `test-rstest-bdd-ui` recipe end to end, with `make -f /Makefile` from a fixture working directory. That is the only arrangement that exercises the recipe itself: the profile assignment and `-p rstest-bdd-ui-tests` come from the shipped target rather than from the test, so a recipe that stopped selecting the profile fails here even though every file-reading contract still passes. The fixture must supply a package by that hardcoded name, and it lives under the repository's `target` directory because rustup resolves the toolchain from the working directory; outside the repository the recipe's nightly-only flags would be handed to a stable toolchain and fail for unrelated reasons. Two contracts cover the two halves the profile exists for: per-test termination at its period, and the run ceiling when that comes first. Each end-to-end contract gets its own scratch directory through a fixture, removed afterwards, so a lockfile or source file left by one cannot be read by another. The fixtures build standalone leaf crates, so they neither touch the UI package nor queue behind the trybuild fixtures. Run them with `make test-rstest-bdd-ui-timeouts`, which fails rather than skips when nextest is absent. `make test-workflow-contracts` excludes the file: running it needs a Rust build and minutes of clock, and the docs-tooling lane that runs those contracts has neither. The suite-level skip therefore covers only a direct `pytest` invocation on a machine without nextest, while the target's own probe is what stops a lane that was meant to have nextest from silently skipping. CI runs the target in the wireframe-only leg, next to `make test-rstest-bdd-ui`, and both steps are gated on that leg. The `build-test` ceiling is derived from the budgets those two steps may take rather than from a warm timing, so a genuinely slow run finishes instead of being cancelled. ## Validator toggles for pending flows The `validator` crate now ships placeholder validators for wireframe flows that are still being implemented on parallel branches. This lets feature branches opt into the required validation early without forcing the main branch to fail before the corresponding server functionality lands. By default, the pending validators are disabled in `validator/validator.toml`: ```toml [validators] chat = false file_download = false ``` Environment variables override the file: - `MXD_VALIDATOR_CONFIG` points at an alternate config file. - `MXD_VALIDATOR_ENABLE_CHAT=true|false` enables or disables the chat validator. - `MXD_VALIDATOR_ENABLE_FILE_DOWNLOAD=true|false` enables or disables the file-download validator. When a pending validator is disabled, the corresponding test prints a clear skip message and exits successfully. When it is enabled before the underlying feature has landed, the validator fails with an explicit "enabled but not implemented yet" error. That makes the opt-in suitable for parallel feature branches that want the validation to go red until the branch completes the flow. Examples: ```sh # Install the pinned SynHX client once for local validator runs. export HX_BIN_DIR="$HOME/.local/bin" ./scripts/install-synhx.sh # Choose one way to expose the installed `hx` binary to later commands. export PATH="$HX_BIN_DIR:$PATH" # or export MXD_VALIDATOR_HX_BINARY="$HX_BIN_DIR/hx" # Run the supported sqlite validator suite against a prebuilt wireframe server. make test-validator-sqlite # Enable the chat validator for the current shell only. export MXD_VALIDATOR_ENABLE_CHAT=true cargo test -p validator --test pending_validators # Use an alternate config file that enables both pending validators. cat > /tmp/validator.toml <<'EOF' [validators] chat = true file_download = true EOF export MXD_VALIDATOR_CONFIG=/tmp/validator.toml cargo test -p validator --test pending_validators ``` The shared validator harness now resolves prerequisites explicitly: - `make validator-sqlite-server` builds `target/debug/mxd-wireframe-server`. - `make validator-postgres-server` builds `target/postgres/debug/mxd-wireframe-server`. - `MXD_VALIDATOR_SERVER_BINARY` overrides the server binary path if the default target location is not suitable. - `MXD_VALIDATOR_HX_BINARY` overrides the `hx` binary path. - `MXD_VALIDATOR_FAIL_CLOSED=true|false` forces missing prerequisites to fail or skip regardless of whether `CI=true`. Keep implemented validators such as login and XOR login coverage always on. The pending toggles exist only for flows whose server-side work is still in progress. At present, chat and file download remain pending, while SynHX file listing and news posting are still blocked by client/server protocol-shape differences rather than missing harness plumbing. ## Validator harness architecture The `validator` crate is structured into five focused modules. Tests in `validator/tests/` import primitives from `validator/src/lib.rs`, which re-exports the public surface of each module. ### Module responsibilities - `config.rs`: loads `validator.toml` and applies environment-variable overrides to determine which pending validators are enabled. - `policy.rs`: decides whether a missing prerequisite causes a hard test failure (`fail_closed = true`) or a graceful skip (`fail_closed = false`). Reads `MXD_VALIDATOR_FAIL_CLOSED` and falls back to `CI=true` detection. - `server_binary.rs`: resolves the path to a prebuilt `mxd-wireframe-server` binary. Precedence is `MXD_VALIDATOR_SERVER_BINARY`, `CARGO_BIN_EXE_mxd-wireframe-server`, then workspace `target/` candidates. - `hx_client.rs`: discovers the `hx` binary, rejecting the Helix editor via a version probe. Spawns a PTY session via `expectrl` and provides helpers to wait for the Hotline prompt and terminate the session. - `harness.rs`: orchestrates these pieces by running policy and prerequisite checks via `ValidatorHarness::prepare()`, launching the wireframe server with `start_server_with_setup()`, opening the PTY client with `spawn_hx()`, and exporting PTY expect/send helpers used directly by tests. ### Key public types ```rust /// Central harness handle. Obtain one with `ValidatorHarness::default()` then /// call `prepare()` before any other method. pub struct ValidatorHarness { /* ... */ } /// Describes whether a missing prerequisite should fail the test or skip it. pub enum PrerequisiteResolution { Fail(String), Skip(String), } /// Errors returned when `hx` cannot be resolved or the PTY session fails. pub enum HxClientError { /* ... */ } /// Errors returned when no prebuilt wireframe server binary can be found. pub enum ServerBinaryError { /* ... */ } ``` ### Typical test structure ```rust #[test] fn my_validator_test() -> Result<(), AnyError> { let harness = ValidatorHarness::default(); let Some(harness) = harness.prepare()? else { // Prerequisite missing and policy says skip. return Ok(()); }; let server = harness.start_server_with_setup(setup_login_db)?; let mut hx = harness.spawn_hx()?; send_line_and_expect(&mut hx, "/server -l alice -p secret 127.0.0.1 …", "…")?; expect_output_with_timeout(&mut hx, "connected", connect_expect_timeout())?; close_hx(&mut hx); Ok(()) } ``` `prepare()` returns `Ok(None)` when prerequisites are absent and the policy is `fail_closed = false` (local developer environment). Tests must propagate the `None` case as a skip rather than a panic. ### Payload-handling methods on `TransactionType` Two const methods control how the wireframe layer handles request payloads: - `rejects_payload(self, payload_is_empty: bool) -> bool` returns `true` when a non-empty payload should be rejected as invalid. Always returns `false` for `GetFileNameList` so directory context payloads pass through. - `bypass_payload_decode(self) -> bool` returns `true` when the parameter block decoder should be skipped entirely and the raw bytes preserved. Used for `GetFileNameList` and any transaction type that does not accept a structured payload. These methods replace the prior ad-hoc `!allows_payload()` checks in `src/commands/mod.rs`, `src/wireframe/compat_layer.rs`, and `src/transaction/params.rs`. ## Presence Runtime Presence state is exposed through the stable crate-level API `mxd::{PresenceRegistry, PresenceSnapshot, SessionPhase}`. The internal `presence` module remains private so transport-specific helper functions do not become part of the public crate surface. `SessionPhase` controls when a snapshot is eligible for roster publication: - `Unauthenticated` means no account has completed login. - `PendingAgreement` means authentication succeeded, but Agreement Acceptance (121) still needs to complete before the session becomes visible. - `Online` means the session may appear in Get User Name List (300) replies and may trigger Notify Change User (301) or Notify Delete User (302) traffic. Sessions granted `NO_AGREEMENT` transition directly to `Online` at login. Agreement-gated sessions stay in `PendingAgreement` until the agreement flow finalizes. Only `Online` sessions should participate in the presence registry. `PresenceSnapshot` is the transport-agnostic value published for an online session. It carries `connection_id`, `user_id`, `display_name`, `icon_id`, and `status_flags`. Adapter code supplies the connection identifier, then calls `Session::presence_snapshot()` to combine that identifier with session state. The snapshot is validated before insertion so field 300 replies and notifications cannot contain unencodable user identifiers or display names. `PresenceRegistry` stores online snapshots by outbound connection identifier. `upsert` inserts or replaces a snapshot and returns the peer connection IDs that should receive a change notification. `remove` deletes a snapshot by connection ID and returns the removed snapshot plus the remaining peer IDs. `online_snapshots` returns all online snapshots in deterministic order. `snapshot_for_user_id` looks up a visible user and, when multiple sessions share the same account user ID, selects the snapshot with the lowest connection ID. The presence transaction builders convert snapshots into protocol replies and server pushes. `build_user_name_list_reply` produces Get User Name List (300) replies with repeated field-300 records. `build_notify_change_user` produces Notify Change User (301) notifications. `build_notify_delete_user` produces Notify Delete User (302) notifications. `build_client_info_text_reply` produces Get Client Info Text (303) replies with the visible name and placeholder info text. ### Error-handling conventions - Both `HxClientError` and `ServerBinaryError` implement `std::error::Error` via `thiserror`. - `ValidatorHarness::prepare()` maps these errors through `ValidatorRunPolicy` and either returns them as `anyhow::Error` (fail-closed) or returns `Ok(None)` (skip). - PTY expect helpers (`expect_output`, `expect_output_with_timeout`, `expect_no_match`) embed the pending terminal output in the error message to simplify debugging failed assertions. - `close_hx()` demotes session-cleanup errors to stderr diagnostics rather than failing the test, consistent with best-effort teardown. ## News schema alignment maintenance Roadmap item 4.1.1 aligned the implemented news storage schema with `docs/news-schema.md` using additive migrations rather than by rewriting historical migration directories. - Keep the SQLite and PostgreSQL migration trees in lock-step with the same version number and equivalent semantics. - When a news schema change requires scoped uniqueness changes or defaulted timestamp columns, prefer explicit SQLite table rebuilds with copy-forward over incremental `ALTER TABLE` drift. The `00000000000007_align_news_schema` migration is the reference pattern. - Preserve stable primary keys during copy-forward migrations so existing threaded article links and bundle/category relationships survive upgrades. - Treat bundle/category GUID backfill and category serial-counter backfill as migration concerns when legacy rows must become structurally complete immediately after upgrade. - Keep `permissions` and `user_permissions` schema work separate from runtime privilege loading and catalogue seeding. Schema alignment belongs to 4.1.1; enforcement and seed data belong to later roadmap items. - Validate news schema changes with the backend-specific migration regression tests in `src/db/schema_alignment_tests/` and with the routing behaviour scenarios that exercise migrated databases. ### Schema alignment test harness (`src/db/schema_alignment_tests/`) The schema-alignment tests are split by shared helpers and backend-specific behaviour: - `mod.rs`: shared migration runners, seed helpers, backfill assertions, and read-only backfill verifiers used by both backends. - `sqlite_tests/`: isolated in-memory SQLite setup, legacy-schema rebuilds, catalogue checks through SQLite PRAGMA queries, GUID/counter tests, and SQLite-specific threading behaviour tests split into focused submodules. - `postgres_tests/mod.rs`: PostgreSQL test entry points for fresh migration, legacy upgrade, scoped category uniqueness, and GUID behaviour. - `postgres_tests/catalogue_helpers.rs`: PostgreSQL catalogue readers and assertions for tables, columns, indexes, constraints, permissions, and the database harness. - `postgres_tests/threading.rs`: article-threading behaviour tests for self-referential `news_articles` links. The shared helper surface is intentionally split between writers and readers: - `run_statements` executes a sequence of SQL statements in order. - `run_sql_script` splits migration SQL into individual statements before execution. - `assert_upgrade_backfills` performs read-only bundle, category, permission, and article-index checks after an upgrade. - `verify_root_category_names_are_unique_with_constraint_insert` performs an insert-based constraint verification and is mutation-driven by design. - `seed_permission_round_trip` inserts the user, permission, and join rows used by permission smoke tests; it is the write path. - `assert_permission_join_count` is the read-only assertion that checks the seeded permission join. SQLite tests run against a fresh in-memory database per test or fixture. PostgreSQL tests run through `with_postgres_test_db`, which creates an isolated database in an embedded PostgreSQL cluster. The 0.6 harness gives each cluster its own data directory, so PostgreSQL tests can start clusters concurrently without file-based serialization. Run only the SQLite schema-alignment tests with: ```sh RUSTFLAGS="-D warnings" \ cargo nextest run --features "sqlite test-support" \ db::schema_alignment_tests::sqlite_tests ``` Run only the PostgreSQL schema-alignment tests with: ```sh RUSTFLAGS="-D warnings" \ cargo nextest run --no-default-features \ --features "postgres test-support legacy-networking" \ db::schema_alignment_tests::postgres_tests ``` ### News model metadata semantics The aligned news schema adds metadata fields that make legacy rows structurally complete after migration: - `guid`: stable external identifier for bundles and categories. It is generated or backfilled during migration, non-empty at rest, and unique per row. Fresh inserts use database defaults or write-model values when provided. - `created_at`: creation timestamp for bundles and categories. It is non-null at rest after migration and is backfilled for legacy rows at migration time. Write models keep the field optional for inserts until runtime enforcement work lands, so callers may rely on the database timestamp default. - `add_sn`: category add serial number. During migration it is initialized from the article count that exists for the category at that moment. No trigger increments it when later articles are inserted, so fresh inserts do not auto-increment `add_sn`. - `delete_sn`: category delete serial number. The migration initializes it to zero for existing categories and new rows rely on schema/write-model defaults unless an explicit value is supplied. No trigger updates it automatically. Tests should distinguish migration-time backfill semantics from runtime insert semantics. A fresh database category can have `add_sn = 0` even after articles are inserted in the same test because no trigger updates the field. Diesel joinables are defined for bundle, category, and article relationships so query code can traverse `news_bundles`, `news_categories`, and `news_articles` without relying on ad-hoc SQL joins for the common schema edges. ## Wireframe adapter context handoff The Wireframe adapter carries Hotline handshake metadata from the asynchronous handshake hook into the synchronous app factory through task-local state plus a task-ID keyed registry in `src/wireframe/connection.rs`. - `scope_current_context(...)` seeds the per-task context for a future and mirrors any initial context into the registry so post-handshake app-factory code can retrieve it after the scoped future exits. - `store_current_context(...)` updates both the task-local slot and the registry for the current Tokio task. - `take_current_context()` consumes the context for the current task. The app factory uses this to fail closed once the per-connection state has been handed off. - `has_current_context()` is the public visibility probe for code that needs to ask whether the current Tokio task can see stored context. The Wireframe server bootstrap converts app-factory failures into the internal `AppFactoryError` enum in `src/server/wireframe/mod.rs`. Current variants are: - `MissingHandshakeContext` when no handshake metadata was stored for the current task. - `MissingPeerAddress` when the handshake metadata exists, but no peer address was attached. - `BuildApplication` when the underlying `WireframeApp` builder returns an error while registering middleware or routes. Use the fallible app-factory pattern when per-connection setup can fail: ```rust,no_run fn app_factory() -> Result { build_app_for_connection(&pool, &argon2, &outbound_registry) } ``` Returning `Result` allows the adapter to preserve typed failure information and propagate setup errors without panicking. Keep these failures explicit in tests so missing handshake metadata, missing peer metadata, and builder failures all remain covered. WireframeServer construction now relies on the `AppFactory` trait rather than a plain `Fn() -> WireframeApp` assumption. Closures still work through blanket implementations, but migration work should make the return type explicit: ```rust,no_run let server = WireframeServer::new(|| WireframeApp::default()); ``` becomes: ```rust,no_run let server = WireframeServer::new(|| -> Result { build_app_for_connection(&pool, &argon2, &outbound_registry) }); ``` Treat this as the preferred migration pattern whenever the adapter needs connection-scoped handshake state or any other fallible setup at factory time. Wireframe v0.3.0 also changed the codec and import surface that this adapter uses: - Add `wireframe = "0.3.0"` to `Cargo.toml`, enabling feature flags such as `testkit` explicitly when the main crate APIs are needed during tests or harness setup. - `FrameCodec::wrap_payload` now takes `Bytes` rather than `Vec`. Codecs that still materialize owned frames can convert with `.to_vec()`, while zero-copy codecs should store the `Bytes` directly and optionally override `frame_payload_bytes(...)`. - Root-level re-exports are no longer the stable import path for most adapter integrations. Prefer module paths such as `wireframe::app::WireframeApp`, `wireframe::codec::FrameCodec`, `wireframe::server::WireframeServer`, `wireframe::hooks::ConnectionContext`, and `wireframe::testkit::...`. - Migration from older imports is mostly mechanical: ```rust,no_run use bytes::Bytes; use wireframe::{ app::{Envelope, WireframeApp}, codec::FrameCodec, hooks::ConnectionContext, server::WireframeServer, }; impl FrameCodec for HotlineFrameCodec { type Frame = Vec; // ... fn wrap_payload(&self, payload: Bytes) -> Self::Frame { payload.to_vec() } } ``` Keep these import-path changes explicit in migration patches so reviews can confirm whether a call site still depends on a compatibility re-export or has been moved onto the intended v0.3.0 module path. ## Database module ### Hierarchical path traversal (`src/db/file_path.rs`) The `file_path` module provides backend-agnostic helpers for resolving slash-delimited paths through the `file_nodes` hierarchy using recursive Common Table Expressions (CTEs) via `diesel-cte-ext`. Symbols: - `CTE_SEED_SQL` (constant): seed row `(idx=0, id=NULL)` that anchors each traversal. - `FILE_NODE_STEP_SQL` (constant): backend-specific recursive step. Postgres uses `json_array_elements_text ... WITH ORDINALITY`, while SQLite uses `json_each`. - `FILE_NODE_BODY_SQL` (constant): terminal select that picks the node whose depth matches the segment count. - `prepare_path` (function): normalizes a path string, trims leading and trailing slashes, and serializes segments as a JSON array alongside the segment count. Returns `None` for root-only paths. Returns `FileNodeLookupError::InvalidPath` for paths containing empty interior segments, such as `/Docs//guide.txt`. - `build_path_cte` (function): constructs the full `WITH RECURSIVE tree ...` query from seed, step, and body fragments. - `build_path_cte_with_conn` (function): convenience wrapper that infers the backend type from a `&mut C` connection parameter. Callers pair `prepare_path` with `build_path_cte_with_conn`: `prepare_path` validates and serializes the input; `build_path_cte_with_conn` builds the parameterized CTE that the Diesel query then drives. ### File-node repository API (`src/db/files.rs`) The following functions are re-exported from `src/db/mod.rs`: - `create_file_node`: inserts a new file, folder, or alias node and returns the generated ID. - `get_file_node`: fetches a single node by ID. - `list_child_file_nodes`: lists all direct children of a folder node. - `list_visible_root_file_nodes_for_user`: returns root nodes visible to a user via direct or group `resource_permissions`, merged with legacy `files` and `file_acl` rows. - `resolve_file_node_path`: walks a slash-delimited path through the CTE and returns the terminal node. - `resolve_alias_target`: follows an alias node to its target file node. - `create_group`: inserts a principal group, idempotent by name. - `add_user_to_group`: assigns a user to a group. - `seed_permission`: inserts a permission catalogue row, idempotent by code. - `grant_resource_permission`: attaches a permission grant to a `file_node` resource for a user or group principal. - `download_file_permission`: returns the `NewPermission` descriptor for the canonical `download_file` entry (code 2). `resolve_file_node_path` returns `Result, FileNodeLookupError>`. `FileNodeLookupError` has three variants: - `InvalidPath`: invalid or malformed path. - `Diesel(diesel::result::Error)`: a database query error. - `Serde(serde_json::Error)`: a JSON serialization error during path preparation. ### Migration timeout (`src/db/migrations.rs`) The `AppConfig` struct exposes a `migration_timeout_secs: Option` field, set via the `--migration-timeout-secs` CLI flag or the `MXD_MIGRATION_TIMEOUT_SECS` environment variable. Behaviour: - When unset or set to `0`, the built-in default of **15 seconds** is used. - Positive values override the watchdog duration directly. - On expiry, `run_with_migration_timeout` cancels the in-progress migration loop via a `CancellationToken` and returns a `SerializationError` wrapping `MigrationTimeoutError(duration)`. ## Quality gates Run the full suite from the repository root after making changes: ```sh make fmt make markdownlint make nixie make check-fmt make check-locked make test-workflow-contracts make lint make test ``` ### Markdown formatting `make fmt` and `make check-fmt` run `mdtablefix` over the Markdown files Git tracks and the untracked files it does not ignore, with the Makefile's flags. They need mdtablefix 0.6.0 or later, the first release with `--check` and `--git`. CI installs 0.6.1 through the shared `install-mdtablefix` action; the pin is in `.github/workflows/ci.yml`. 0.6.1 fixes the 0.6.0 bugs that changed Markdown content: `--wrap` breaking text with no whitespace, Setext headings turned into rules, and `--renumber` changing a list's start. Install the same version locally with `cargo binstall mdtablefix@0.6.1`. `--renumber` treats a fence or bullet at column 0 as the end of an ordered list, so indent the content of every list item under its marker (three columns for `1.` to `9.`, four for `10.` to `99.`) to keep a numbered procedure in one list. ## Fetching dependencies before tests Several tests start their own `cargo`: trybuild, the embedded-server fallback in `test-util`, and the validator harness. Cargo resolves dependencies, and may update the crates.io index, while it holds the package-cache lock in `$CARGO_HOME`. On a host where several repositories share one `$CARGO_HOME`, a nested `cargo` that resolves cold can wait on that lock for many minutes. The fix is to fetch once, before any test starts, so that no nested `cargo` has anything left to resolve: - `make test` depends on the `fetch` target, which runs `cargo fetch --locked`. A failed fetch stops the run. - The `ci.yml` jobs that run tests, and `coverage-main.yml`, run the same `cargo fetch --locked` as an unconditional step before their first test, validator or coverage step. The Loom and fuzz workflows run `make test-concurrency` and `make test-fuzz-harness`, which wait for the `fetch` target through an order-only prerequisite, and the Loom runner, which does not start a nested `cargo` of its own and does not fetch. Do not make the fetch conditional on the matrix leg, and do not add `|| true` to it. The estate lint rule `nested-cargo-offline-tests` reads a fetch as proof only when it is unconditional and its failure stops the run. ## The Rust build standard Development builds use the parallel `rustc` frontend (`-Zthreads=8`) and, on Linux, the `mold` linker (`-Clink-arg=-fuse-ld=mold`). `.cargo/config.toml` holds both: `[build] rustflags` carries the frontend flag, and a Linux-only target table repeats it beside the linker flag, because Cargo selects one `rustflags` source rather than merging them. An assigned `RUSTFLAGS` replaces every source, so each place that assigns it restates both flags: - the Makefile's gate recipes use `GATE_RUSTFLAGS`, which keeps any inherited `RUSTFLAGS`, adds `-D warnings` and the standard flags, and refuses a `CARGO_BUILD_TARGET` because the linker flag is chosen from the host; - the `build-test` job's `setup-rust` step installs `mold` and exports the same flags through its `rustflags` input; - the Rust 1.94 compatibility step clears `RUSTFLAGS`, because a stable toolchain rejects `-Z` flags; - the Whitaker recipes and steps keep a bare `-D warnings`, because Whitaker builds its lint driver on another toolchain, which must not inherit development flags. Coverage runs and release builds assign `RUSTFLAGS` without them on purpose. The Concordat `rust-build-defaults` rule is the check; the repository keeps no contract test of its own for it. Any job that runs a gate recipe on Linux needs `mold` installed, because `GATE_RUSTFLAGS` names the linker: `loom-check.yml` and `fuzz.yml` install it for `make test-concurrency` and `make test-fuzz-harness`. ### Cranelift backend support The estate standard is LLVM, which is the default backend here; review is due 14 May 2027 under the [estate ADR](https://github.com/leynos/concordat/blob/main/docs/adrs/adr-0004-cranelift-is-not-part-of-the-rust-build-standard.md). The `[profile.dev] codegen-backend = "cranelift"` selection in `.cargo/config.toml` is commented out. The `[unstable] codegen-backend` gate and the `rustc-codegen-cranelift-preview` component in `rust-toolchain.toml` stay, so an opt-in remains possible: uncomment the key, or pass `--config 'profile.dev.codegen-backend="cranelift"'` for one build. Cranelift does not unwind, so no test may rely on a caught panic under it. An inherited `CARGO_PROFILE_DEV_CODEGEN_BACKEND` can still select Cranelift. Coverage runs and the Whitaker recipes select LLVM explicitly with `CARGO_PROFILE_DEV_CODEGEN_BACKEND=llvm`, because instrumentation and Whitaker's driver need it. ## Runner placement `coverage-main.yml` runs on every push to `main` as three jobs. `coverage-upload` measures coverage and uploads it to CodeScene on a hosted `ubuntu-24.04` runner, which is free on a public repository. It saves no baseline (`publish-baseline: never`), because a hosted runner writes GitHub's cache store and the Ubicloud pull-request lanes never read it, and it hands the figures on as the `coverage-baseline-handover` artefact. `coverage-baseline` (`ubicloud-standard-2`, only after `coverage-upload` passed) checks them against the stored baseline and saves them under the key the ratchet restores. `coverage-warmup` (`ubicloud-standard-2`) compiles the instrumented tests without running them and is main's only writer of the build caches the lane reads on Ubicloud (the compiler cache and the llvm-cov archive); `coverage-baseline` writes the ratchet baseline. None of the three has a fork arm: they run on push only. `ci.yml`'s `docs-tooling`, `build-test`, `validator-sqlite` and `coverage` run on `ubicloud-standard-2`; `build-test-result`, a trivial aggregate, stays hosted. `runs-on` selects it with the runner-selection expression: ```yaml runs-on: >- ${{ (github.event.pull_request.head.repo.fork || github.event.pull_request.user.login == 'dependabot[bot]') && 'ubuntu-latest' || 'ubicloud-standard-2' }} ``` A pull request from a fork cannot obtain an Ubicloud runner, so it falls back to `ubuntu-latest`. So does a pull request Dependabot opened: hosted minutes cost nothing on a public repository, and Dependabot opens many pull requests. The expression tests the pull request's author, not `github.actor`, because the actor is whoever triggered the run, so a person pushing to a Dependabot branch would flip the runner. A push and a dispatch have no pull request, so both values are empty strings (falsy) and the expression selects Ubicloud; a Dependabot pull request therefore builds cold on the hosted pool. Ubicloud's cache proxy is scoped by ref, so a pull request's Ubicloud lane reads a warm main scope only when a main job on Ubicloud writes it: `coverage-warmup` and `coverage-baseline` are those writers. A fork's or Dependabot's pull request runs on the hosted pool and restores a hosted cache that main no longer refreshes, so its baseline goes stale and, after eviction, reads zero; those lanes are rare here, and a second hosted writer would pay double on every main push. `coverage-upload` runs on a GitHub-hosted runner, where the six-hour platform cap bounds it, and keeps its 65-minute ceiling, which the embedded-PostgreSQL leg needs. The `ci.yml` lanes' ceilings are provisional: twice the slowest leg of run 36971925629, their first Ubicloud run (`docs-tooling` 15, `validator-sqlite` 20, `coverage` 60), rounded up to 5. That run restored the cargo registry cache but found no compiled-artefact cache, so it is close to a cold build, and the ceilings are resized from three green runs of the new shape. `build-test` is sized differently, at 100, because its two UI gates are bounded by configuration rather than by host speed: `rstest-bdd-ui` carries `global-timeout = 30m` and `test-rstest-bdd-ui-timeouts` runs three end-to-end builds under successive 900-second timeouts. Sizing on a warm leg would cancel the cold run those raised budgets exist to permit, and a cancelled leg fails `build-test-result`. The ceiling is the pre-gate cold figure (24) plus both gates' own limits. `tests/workflow_contracts/test_runner_placement.py` pins it in the same table as every other ceiling and records the reasoning there. Each of those four lanes ends with a `Record the lane's placement` step, under `always()` so a failing lane is recorded too. It writes the lane, the runner and its environment, the event, the fork flag, the status so far and whether the lane's cache had an exact hit (`cache-hit`; a partial restore reports `false`) to the job summary. `tests/workflow_contracts/test_lane_placement_record.py` holds the step, its condition, each input's exact expression, the cache step it reads and that step's action (`actions/cache` for `docs-tooling`, `Swatinem/rust-cache` for the others), and runs the script for a success with a cache hit, a failure with a miss and a cancelled job whose cache step never ran (rendered `n/a`). Queue wait and duration are not knowable from inside a job, so read them from the API, as the placement pull requests did: - The workflow-jobs API, `GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs`, gives each job's `started_at` and `completed_at`, so duration is `completed_at` less `started_at`. Its response also carries a `created_at` that the API's documented schema does not list, so the method below does not rely on it where the run object will do. - The workflow-run API, `GET /repos/{owner}/{repo}/actions/runs/{run_id}`, gives the run's `created_at`. Queue wait is the job's `started_at` less the later of the run's `created_at` and the last `completed_at` among the jobs it needs. `tests/workflow_contracts/test_runner_placement.py` pins the labels of every lane in both directions and requires each conditional placement to be guarded by the fork test or the Dependabot author test, with the hosted arm first, so a pair under another guard (or `github.actor`) fails. ## CodeScene coverage is owned by `main` `coverage-main.yml` runs on a push to `main` and uploads the merged lcov report to CodeScene. No workflow a pull request can run calls a CodeScene action, runs a `cs-coverage` command, contacts `codescene.io`, or reaches `CS_ACCESS_TOKEN` at any scope. The reason is that a pull request cannot upload: CodeScene accepts coverage only for analysed branches. What a pull-request lane could do instead was hand CodeScene the token and ask it to judge the branch, which is a different operation wearing the same name. It put a secret on a lane that fork traffic reaches, and it produced a verdict nobody reading `main` ever saw. Removing that step also removed the reason for `fetch-depth: 0` on the coverage job's checkout. The full history was there so `cs-coverage check` could diff against the merge base; the coverage ratchet keeps its baseline in `actions/cache` and reads no history at all, so the job now takes the default shallow checkout. `make test-codescene-boundary` asserts the boundary in both directions, and the `docs-tooling` job runs it. One direction alone would be satisfied by deleting the publisher and leaving CodeScene with no coverage at all, which is the worse failure of the two. The three prohibitions are matched differently, and the difference is the point. An action is matched against each step's `uses` value and a command against each `run` body, so that naming CodeScene in a step name or a comment, which is how the boundary gets explained where people read it, does not itself read as a breach. The first draft of this contract matched the file and failed on its own CI step's name. `CS_ACCESS_TOKEN` and the `codescene.io` host are matched instead against every key and scalar of the parsed workflow. The parser has already dropped the real comments; a line beginning `#` inside a block scalar is data, which Actions still expands, so stripping such lines from the source text would hide `# ${{ secrets.CS_ACCESS_TOKEN }}` in a comment body. A secret reaches a step through `env`, through `with`, through a job-level or workflow-level `env` block, through a named `secrets:` forward, or through an expression inside a `run` body, and a reader that walked only one of those routes would pass on the others. Unlike an action or a command, there is no legitimate reason for either name to appear on a pull-request lane at all. Two routes name nothing, so they are read separately. An expression over the whole secrets context (`toJSON(secrets)` or `secrets[...]`) is refused. So is `secrets: inherit` on any call, local or not: a local callee is read in turn, but it would still receive every secret, and a called workflow has `GITHUB_TOKEN` without being forwarded it. `release-dry-run.yml` calls `release.yml` and forwards none. The job walker descends into each job's `steps` and also treats a job carrying its own `uses` as a step, because a job that calls a reusable workflow has no steps and is the one shape that can run another repository's code. The pull-request surface is the set of workflows a pull request can run, not the set it triggers. Its entry points are the workflows answering `pull_request` or `pull_request_target`; the second runs with the base repository's secrets, so leaving it out would exempt the more dangerous of the two. A job calling a local reusable workflow runs that workflow's jobs under the caller's trigger, and `release-dry-run.yml` does exactly that. Local calls are therefore followed transitively, with a seen set so a cycle cannot hang the collection. Without that, every prohibition here could be breached inside `release.yml` and the suite would stay green. A `workflow_run` workflow waiting on a surface workflow joins the surface too, with everything it calls, because it runs after every pull request with the base repository's secrets. It is matched on the waited-on workflow's `name:`, or on its path when it has none. One chained only onto push or scheduled lanes stays out. Constructed cases cover a breach two calls deep, a call cycle, and a chained and an unchained `workflow_run`. The coverage job's checkout is asserted to declare no `fetch-depth`, on that job alone rather than repository-wide, since another lane may have a real reason for a full clone. Reintroducing it there fails; adding one to `docs-tooling` does not. The publisher's `on:` block is asserted by equality to a push to `main` and nothing else, so a publisher that also answered `workflow_dispatch` could not upload from any branch while a check on the push entry alone still passed. The publisher's concurrency block is asserted whole: `group: ${{ github.workflow }}-${{ github.ref }}` and `cancel-in-progress: false`, at the workflow scope, with no job declaring one of its own. Runs never overlap, and a newer push replaces an older run still pending rather than queueing behind it. A cancelled publisher would abandon both its upload and the ratchet baseline it writes. A group keyed on the event would let an earlier dispatch finish after a newer push. A run-unique key would group nothing. GitHub does not promise to start runs in trigger order, so no commit-order promise is made beyond that. A manual "Re-run jobs" on an older main run keeps its `run_id`: it republishes that commit's coverage, but replaces no baseline saved under a run-keyed cache key. Two gaps are known and accepted. A Dependabot automerge merged with `GITHUB_TOKEN` fires no push, so no publisher runs for that commit, and the next push publishes. There is no `schedule` trigger to cover it. The upload is guarded by a token check rather than by the token itself. A step with the id `codescene-token`, in the upload's own job and before it (a step output does not cross jobs), with no `if` and no `env`, runs exactly `echo "available=${{ secrets.CS_ACCESS_TOKEN != '' }}" >> "$GITHUB_OUTPUT"`. The expression is evaluated before the shell runs, so the step writes `true` or `false` and the token enters no process. The upload's whole condition is `steps.codescene-token.outputs.available == 'true' && github.ref == 'refs/heads/main'`, compared by equality, so an appended `||` cannot widen it. The upload action takes `access-token: ${{ secrets.CS_ACCESS_TOKEN }}` directly, and the token is refused in every `env` on the publisher. The action is composite and passes a step's `env` on to its nested steps, and a guard on `env.CS_ACCESS_TOKEN` passes with the binding deleted while the upload skips forever. Requirements are read differently from prohibitions. A prohibition is a substring test, because over-matching is the safe direction there. A requirement is not: `echo make test-codescene-boundary` contains the target and runs nothing. So the rule that `docs-tooling` runs this contract reads each `run` body as the shell would, through `tests/codescene_boundary/shell_commands.py`, and counts the target only when a simple command begins with its words. The rule that the publisher uploads finds the step whose `uses` path names the upload action and requires that step's `access-token` input to carry `secrets.CS_ACCESS_TOKEN` directly; the action named in an `echo`, or the token named anywhere else, does not satisfy it. The publisher is found by searching rather than named. Asserting that `coverage-main.yml` uploads leaves a second push-to-main workflow with its own upload step invisible: coverage would be published twice and the work done twice. The set of workflows carrying the upload action is asserted to be exactly the publisher. Proved by adding each forbidden element back. A CodeScene action, a `cs-coverage` command, and the token each fail exactly one case; a `cs-coverage` command in a different job of the same workflow fails the same one, which is what says the walk is over jobs rather than over one of them; giving the publisher a `pull_request` trigger fails three; deleting its upload step fails two, the single-upload case and the upload-with-token case. Each of these fails exactly one case: - deleting the token check, conditioning it, or making it write a literal `true`; - binding the token in the upload step's `env`, or reading `access-token` from `env`; - widening the upload's condition with `|| github.event_name == 'workflow_dispatch'`; - keying the group on the event or on `github.run_id`, or setting `cancel-in-progress: true`. Two shapes are normalized before any of that can run. `on:` is read as a mapping, a string, or a list, because `on: [push, pull_request]` is as valid as the mapping form and stringifying it produced one key named `"['push', 'pull_request']"`; a workflow written that way was not recognized as a pull-request lane and escaped every prohibition, while the other workflows kept the non-empty guard passing. An unsupported shape is refused rather than coerced, since coercion is what caused that. So is a workflow declaring both a bare `on:` and a quoted `'on':`. GitHub merges the two, and a reader that picked one would be blind to the events under the other. A local call is recognized by shape: a leading `./` or `$/` (the two spellings GitHub documents for a same-repository call) is stripped and what remains is asked whether it is a path under this repository's workflow directory. Enumerating prefixes means extending the matcher for every variant anyone proposes, and each omission is a workflow silently outside the surface. A local action and a call carrying a ref both stay out, and both are asserted. Every workflow is loaded through a strict `SafeLoader` that refuses a mapping declaring the same key twice. PyYAML otherwise keeps the last value in silence, so a lane declaring `runs-on` or `uses` twice would be judged on a value GitHub may not use. Every file in `.github/workflows/` ending `.yml` or `.yaml`, in any case, is read. A reader globbing `*.yml` would skip `release.yaml` or `CI.YML` in silence, and a workflow it never opens is one every prohibition passes over. The readers live in `tests/codescene_boundary/workflow_surface.py` and take parsed documents and source text rather than reading the repository. `test_codescene_boundary.py` applies them to this repository's workflows, and `test_workflow_surface.py` drives them with constructed ones. This repository declares only the shapes the contract accepts, and a reader proved only against those would pass with every refusal deleted. The constructed cases include the closure probe measured elsewhere in the estate: a `workflow_call`-only workflow, called with `secrets: inherit` from a pull-request job, curling `codescene.io` with the token, in both call spellings. The reach of the collection is proved the same way. A CodeScene action added inside `release.yml` fails two, the token added there fails one, disabling call-following in the reader fails the case that names `release.yml`, and a second copy of the publisher fails the single-upload case. ### The uploader contract `tests/codescene_uploader_contract.rs` runs in the normal test job, under `cargo test` or `cargo nextest`. It holds four rules about main's CodeScene upload. From the pinned revision, the uploader treats its committed `cli-manifest.json` as the trust anchor for the CLI archive. It rejects a non-empty `installer-checksum`, which is why these rules exist: - no workflow passes `installer-checksum`; - no workflow names the `CODESCENE_CLI_SHA256` variable that fed it; - every active `uses:` of `upload-codescene-coverage` names the approved revision, and at least one exists. A comment or a commented-out step does not count as a reference, so commenting out the upload fails the contract rather than satisfying it; - no `get-codescene-sha` workflow exists under any extension the workflow reader accepts, in any case. The approved revision is an allowlist, not a floor. A floor would need to order two commit SHAs, which a checkout cannot do. ## The workflow contracts `make test-workflow-contracts` asserts that the CI workflows place and gate what this guide says they do. The `docs-tooling` job runs it, because that is the cheapest lane on a pull request and already installs Python and uv. A contract here asserts what would break a gate rather than what its author meant. Three rules follow from that, and each exists because a weaker reading passed against a tree it should have refused somewhere in this estate. **Whole-value equality.** A gate step's entire `run` body must be the gate command. A step whose body merely contains `make check-fmt` is satisfied by `make check-fmt || true`, which reads as a gate in a diff and gates nothing. A step carrying `if` or `continue-on-error` is not counted either, and nor is any step in a job carrying them, since a job-level `continue-on-error` discards every verdict inside while leaving each command untouched. Nor is a step whose command is run differently from how it reads: a step declaring `shell` or `working-directory`, or any step under a `defaults.run` that sets either, at the job or the workflow scope. `shell: python {0}` turns `make check-fmt` into a Python syntax error, and a different directory runs a different Makefile, and neither changes the body. **Both directions.** Placements, ceilings and reusable-workflow calls are compared as sets, not as subsets. A subset assertion in one direction lets a new lane appear unpinned; in the other it lets a pin outlive the lane it named, so a rename leaves the pin reading and the lane running with nothing between them. A call is compared on the workflow it names, with any ref stripped, and a call to another repository is separately required to name a forty-character commit. Moving a pin forward is a decision this repository already makes through Dependabot, and a contract naming the commit would redden every such pull request and teach people to edit the contract to make a bump pass. A branch or tag ref is the defect worth refusing: it moves under the workflow with no pull request here at all, so a lane can change what it runs between two identical trees. **The placement is pinned where it is decided.** `build-and-package.yml` takes its label from `inputs.runner`, so its own file decides nothing. `release.yml`'s `build-linux` passes the label, and that is where the contract reads it. A contract reading the callee's `runs-on` would pass while the caller sent the package build to any runner it liked. **Each Linux target is built natively.** `release.yml`'s `build-linux` matrix names a `runner` per target and passes `${{ matrix.runner }}`, and `test_each_linux_target_builds_natively` judges each target by architecture. Any free GitHub-hosted label of the target's own architecture passes (`ubuntu-latest` for x86_64, `ubuntu-24.04-arm` for aarch64); a cross build, the other architecture's label or an unlisted label is refused. A hosted x86_64 runner cannot start the privileged podman container a cross build needs (`podman missing CAP_SYS_ADMIN`), which failed the first dry run that ever started. ### What the reader refuses Every placement contract rests on one reader, so a shape it reads wrongly is a lane placed by something no contract can see. Four `runs-on` shapes appear in this estate and the reader models three of them deliberately: a bare label, a list of literal labels, and a guard choosing between two literal arms. A fourth, a placement taken from a workflow input, names no label here at all, so the record says only which input carries it. Anything else raises `WorkflowShapeError` rather than being recorded as a literal. A runner group selects by membership and names no label. A dynamic matrix expression resolves at run time to labels this reader cannot know. A list is the subtle case, because GitHub permits a variable among its entries: an entry recorded as a literal would read to every contract as a runner named `${{ inputs.chosen-os }}`, which no job can be placed on, while the runners the expression can actually select stay invisible to the contract that exists to pin them. The loader refuses a mapping that declares the same key twice, reporting it as a `WorkflowLoadError`; PyYAML would keep the last value and the contracts would judge a document that discarded the first `runs-on` or `with`. Workflow files are collected by suffix in any case, so `CI.YML` and `release.yaml` are read, and a call is taken to name this repository whether it is spelt `./.github/workflows/` or `$/.github/workflows/`, the two forms GitHub documents. Triggers are read under both spellings of the key, since a bare `on:` parses to the boolean `True` and a quoted `'on':` to the string, and in all three forms GitHub accepts: a mapping, one event name, and a list of event names. A workflow declaring both spellings, neither, or any other shape raises `WorkflowShapeError`. GitHub merges the two spellings, so a reader that picked one would be blind to the events under the other. `tests/workflow_contracts/test_workflow_placement_unit.py` and `test_workflow_reader_unit.py` drive the reader with mappings and constructed files rather than with this repository's workflows, because these are shapes mxd does not declare. A contract parametrized over the workflows as they stand exercises only the accepted shapes, and would pass unchanged with every refusal deleted. ### Ceilings Every job that declares steps declares `timeout-minutes`. A job calling a reusable workflow, such as `release.yml`'s `build-linux`, cannot declare one; its ceilings are the called workflow's own jobs'. A job without a ceiling inherits GitHub's six-hour default, which bounds nothing: it is the point at which a wedged job stops costing money, not a statement about how long the work takes. Ceilings are sized as the estate sizes them, at roughly twice the worst observed successful duration plus a quarter of an hour of reporting margin. Two are sized differently and say so in the contract: `tlc-image` is sized on a real image build rather than on the 24-to-29-second skip it performs on nearly every run, because a ceiling sized on the median would cancel the only run that matters; and the release path's ceilings are placeholders, generous enough not to cancel a real run and tight enough to catch a wedged one, until `release-dry-run` runs and can be measured. ### The lockfile gate `make check-locked` runs `cargo metadata --locked`, which refuses a `Cargo.lock` the manifest does not admit. `cargo fetch --locked`, which `make test` and CI run first, refuses a missing or stale lockfile in the same way. Every other cargo invocation may rewrite the lockfile, and silently resolves such a mismatch away rather than reporting it. The gate exists because the mismatch has reached `main` three times, each time from a lockfile-only dependency bump that crossed a major boundary the manifest declares. Between such a merge and the next lockfile write, `main` carries a lockfile nothing builds from, and no lane says so. It runs as the first step of `build-test`, before anything long. Placed after a build it would assert a file that build had already rewritten, which is the one arrangement in which the gate reads green while the defect is present in the tree under review. The contract asserts that ordering as well as the command. ### The build-test result The ruleset requires `build-test-result`, not the `build-test` matrix legs. GitHub truncates the legs' check names, and the names change whenever the matrix does. A required leg would therefore either go stale or block every pull request after a matrix edit. `build-test-result` depends on `build-test` and runs under `always()`. Without `always()` it would be skipped when a leg fails, and GitHub counts a skipped required check as passing. Its single step runs exactly `test "${{ needs.build-test.result }}" = success`, so a failed, skipped or cancelled matrix fails it. The requirement exists because `build-test` was not required, and automerge landed a Dependabot lockfile bump (#575) that `make check-locked` had refused. `tests/workflow_contracts/test_build_test_result.py` asserts that shape. It refuses a job without `always()`, a dependency other than `build-test`, a `continue-on-error` on the job or the step, and any command other than the exact one; `!= failure`, for instance, would pass a skipped matrix. It also refuses a `shell` or `working-directory` on the step or under `defaults.run` at the job or workflow scope, since a shell template such as `bash {0} || true` masks the command's status. The job must declare `permissions: {}`, because it reads only the matrix result. Seven mutations of `ci.yml` each fail the contract, and unit cases drive the same judgement with constructed jobs. ### Each backend runs once per event SQLite and PostgreSQL are both first-class backends, and a deduplication must never drop one. The coverage job runs each backend's suite, so the `build-test` matrix legs do not run them again: - The `sqlite` leg used to run the suite of the coverage job's SQLite step (`--features sqlite,test-support`, default features on). - The `postgres` leg used to run a suite the coverage job's Postgres step did not: it built `legacy-networking`, which the step did not. The coverage step, in `ci.yml` and in `coverage-main.yml`, now builds `postgres test-support legacy-networking`, so it compiles and runs `tests/integration.rs` and `tests/runtime_selection_bdd.rs` and the two suites are one. - Only the `wireframe-only` leg keeps a `Test` step, `if: matrix.name == 'wireframe-only'`, because nothing else builds `--no-default-features --features sqlite,toml,test-support`. Both legs stay in the matrix for their Clippy and Whitaker passes, which are the only lint of those feature sets, and the postgres leg keeps `make audit`. The coverage job's steps are the surviving runs; the SQLite step carries the coverage ratchet. `tests/workflow_contracts/test_backend_runs_once.py` applies a query, `ci_backend_runs.suite_runs`, that lists every suite `ci.yml` runs as a feature set, from the build-test matrix legs whose test step runs and from every `generate-coverage` step. It asserts that: - no feature set is run twice, so the default-feature SQLite suite and the PostgreSQL suite with `legacy-networking` each run once, at `coverage`; - `coverage-main.yml` builds the same PostgreSQL suite as `ci.yml`; - no run sits in a step or job that declares `continue-on-error`, and no run's `run` body swallows the command's status (`|| true`, `; exit 0`, `set +e`), so a failing test fails the job that holds it, and through `coverage` or `build-test-result` the pull request's required checks; - a run counts only when neither its step nor its job carries an `if`, so a constant `if: false` cannot leave a run that never executes; - the `sqlite` and `postgres` legs build their exact feature sets, and both lint steps are unconditional and lint `${{ matrix.cargo_flags }}`. A condition on the test step other than `matrix.name == 'x'` or `matrix.name != 'x'` fails the contract instead of being guessed at, so a cleverer condition cannot make a running leg look skipped. Mutations of `ci.yml` each fail the cases named for them, in both directions. Too many runs: the guard deleted (both suites then run twice), and the `legacy-networking` feature added back to a second PostgreSQL run. Too few: the `legacy-networking` feature dropped from the coverage Postgres step, default features switched on for it, and the leg's tests skipped on every leg. Tolerated failure: `continue-on-error` on the SQLite coverage step, and `|| true` on the nextest command. Hollowed out without being removed: `if: false` on the SQLite coverage step, either lint leg's flags narrowed, and the Whitaker step's flags dropped. Unit cases drive the same query with constructed copies of the workflow. ### Pinned Whitaker installer `ci.yml` pins `install-whitaker` to the shared-actions revision whose default installer is 0.2.11. Earlier revisions build the Dylint driver against a fresh clone of rust-clippy and check out that repository's `master` branch; upstream renamed it to `main`, so that bootstrap stopped resolving and every `build-test` lane failed in the install step. Installer 0.2.11 provisions a verified Clippy snapshot bundle instead, so the driver build no longer reads a mutable upstream branch. The pin is a commit, like every other `leynos/shared-actions` reference here, so a Dependabot bump is what advances it. The pin records one observed bootstrap incident, not a rule about every three-lane failure: a shared source defect can fail all three lanes just as a broken installer does. Inspect the failing step and its diagnostic before assigning a cause. A bootstrap error in the install step points at the pinned revision and the installer; a compile or lint diagnostic from the changed code points at the diff. Keep Whitaker enabled while investigating; do not skip the lanes to make the check green. ### Authenticated binstall `cargo binstall` resolves a crate's release through `api.github.com`. An anonymous request is rate limited by the runner's address, and a 403 makes binstall wait 120 seconds and then build the crate from source, with only a `WARN` to say so. On one CI leg that turned a one-second `Install cargo-nextest` step into 348 seconds; the legs that already held the binary took a second, so the defect hides behind any warm cache and returns when it expires. Nothing fails, so only the step's duration shows it. Every step that runs `cargo binstall` therefore sets `GITHUB_TOKEN: ${{ github.token }}`: `Install cargo-nextest`, `Install cargo-audit` and `Install pg-embed-setup-unpriv` in `ci.yml`, `Install pg-embed-setup-unpriv` in `coverage-main.yml`, and `Install cargo-audit` in `audit.yml`. The `setup-rust` action installs cargo-binstall itself but never runs it, so the token belongs to each consumer step. The PostgreSQL warm-up sets it for the same reason; see "The binaries are downloaded before the tests". `tests/workflow_contracts/test_binstall_token.py` asserts three things. No step running `cargo binstall`, with or without a `+toolchain` between `cargo` and `binstall`, may receive anything but the exact workflow token expression as its `GITHUB_TOKEN` (or `GH_TOKEN`). The value judged is the effective one, with workflow, job and step `env` merged in that order, so a step that overrides a valid job token with an empty value or a literal is refused. Every job running `cargo binstall` holds `permissions` of exactly `contents: read`, in its own block or the workflow's, so the token binstall sends can read the repository and nothing more; `build-test` and `coverage` in `ci.yml` declare it for that reason. And the query still sees the five steps, so an empty result cannot pass for a clean one. Three workflow mutations each fail the named cases: the token removed from the nextest step, replaced with a literal in `audit.yml`, and a new anonymous step added to `coverage-main.yml`. Unit cases drive both queries with constructed steps, including a multi-line `run` body, a toolchain-qualified command and each override of a valid token. `tests/workflow_contracts/test_binstall_token_execution.py` covers what a table cannot. A Hypothesis property test generates the workflow, job and step `env` with `GITHUB_TOKEN` and `GH_TOKEN` each absent, the exact expression, empty or a literal, and holds the query to a separately written oracle: the most specific scope wins per variable, then `GITHUB_TOKEN` outranks `GH_TOKEN`. An execution test runs each of the five real `run` scripts under `bash` with the environment GitHub builds for the step (a sentinel replacing the token expression, no inherited token) and a `cargo` shim that records the token `cargo binstall` receives. It cannot show what cargo-binstall then does with the token, which needs the network; it does show the token reaches the process. Hypothesis is a test-only pin on the `test-workflow-contracts` target. ### Adding a lane A new job fails the contracts until it is pinned: its coordinate must appear in `PINNED_PLACEMENTS` or `PLACEMENT_FROM_INPUT`, and in `PINNED_CEILINGS` with a ceiling sized from three green runs. That refusal is the point. A lane nobody pinned is a lane nobody decided the placement or the bound of. ## The AFL++ fuzz lane `.github/workflows/fuzz.yml` builds `fuzz/Dockerfile` and runs AFL++ against `parse_transaction` every night. See [fuzzing.md](fuzzing.md) for how to run it. The lane stayed red for months because no part of it had been run end to end, so the parts below are each held by a test. - **Base image.** Both stages start from the AFL++ image pinned by digest. A moving tag let the lane drift unnoticed. Bump the digest on purpose, with a run of the workflow. - **Build dependencies.** The image provides cargo but neither `libsqlite3` (the corpus generator links the SQLite backend) nor the `cargo afl` subcommand. The Dockerfile installs `libsqlite3-dev` and `cargo-afl`, whose version must match the minor of the `afl` crate in `fuzz/Cargo.toml`. - **Runtime and paths.** `cargo afl config --build` builds the AFL runtime for the toolchain this repository pins, and runs after the sources are copied in. The `fuzz` crate is a workspace member, so its binary is `target/debug/fuzz`, not `fuzz/target/debug/fuzz`. The image carries the seed corpus from `make corpus` at `/corpus`; a host mount there would shadow it with an empty directory. - **Harness.** `fuzz/src/main.rs` is only `afl::fuzz!`, which links the AFL runtime, calling `fuzz::handle_case` from `fuzz/src/lib.rs`. That function returns an `Outcome`: an input over `MAX_INPUT_LEN` is `Skipped`, not truncated; a parser `Err` is `Rejected`, a normal outcome, because a parser rejecting a malformed frame is working and counting it as a crash made AFL save nearly every mutation; and `Accepted` is the rest. Only a panic, an abort or an overflow inside the parser is a crash, and a panic propagates. `make test-fuzz-harness` tests all of it without the AFL runtime, and runs in `make test` and ahead of the image build. - **Run and triage.** The run is interrupted with `timeout --signal=INT`, for the `FUZZ_DURATION` the job env names (five hours nightly, two minutes on a pull request), so the upload steps run before the job ceiling cancels them. A pull request that touches `fuzz/`, the triage script or the workflow runs the lane end to end for that short interval, which is the lane's integration test. `timeout` exits 124 after it interrupts AFL, which the run accepts as its expected end, and a following step requires `execs_done` and `corpus_found` above zero in AFL's `fuzzer_stats`: a harness that did nothing with its input executes cases but never finds a new path, so this is the check that the built harness reaches the parser. A replay step then runs `scripts/replay_harness.sh` against the built harness: with `MXD_FUZZ_TRACE` set, `main.rs` prints the outcome of each case, and the script requires `Accepted` for a baked-in seed, `Rejected` for a malformed frame and `Skipped` for an oversized input, so a `main` that does nothing with its input fails even though AFL counts its executions. A saved crash fails the lane, after the archive and uploads have run, because AFL reports a crash as output rather than as a failed run. The run and the triage use the runner's user, because root-owned output cannot be read by the check or the uploads, and the triage and upload steps run after a failure. The image's entrypoint is `afl-fuzz`, so the triage step overrides it with `--entrypoint bash`, and `scripts/triage_crashes.sh` gives `afl-cmin` the `-C` flag because every input in a crash directory crashes. A run with no crashes leaves nothing to reduce, which the script reports and accepts. The output travels as `tar` archives because AFL's file names hold colons, which the upload action refuses. `tests/workflow_contracts/test_fuzz_lane_scripts.py` runs the lane's own shell logic against fixture directories (the checks, the crash gate, the archive step and the replay script, against stub harnesses), asserting both sides of each gate. `tests/workflow_contracts/test_fuzz_lane.py` holds the workflow flags, the Dockerfile pin, dependencies, ordering and paths, and runs the triage script against stub `afl-cmin` and `afl-tmin` tools for its success, missing-directory, non-executable-harness and tool-failure paths. It does not test AFL itself, and it does not compile the harness against the AFL runtime: the image build that opens every run of the workflow does that, and a failure there turns the lane red. The end-to-end check is the workflow itself on a pull request: image build, a two-minute run of the baked-in corpus, the `execs_done` check and the triage, so a change to the lane is exercised before it merges. ## Cancelling superseded pull-request runs Every push to a pull request starts a fresh run of each gate. The run already in flight is answering a question about a commit nobody will merge, and left alone it holds a runner until it finishes, so the branch pays twice for one answer. Every workflow a pull request can start, currently `ci.yml`, `release-dry-run.yml`, `tlc.yml`, `tlc-image.yml` and `loom-check.yml`, therefore carries this block: ```yaml concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} ``` Two halves matter, and each fails in a way nothing else would notice. - **Only a pull request shares a group.** The group keys on the pull request number, so a newer push to one branch cancels that branch's older run and no other. Every other event falls back to its own run id. A fallback of `github.ref` would put every push to `main`, schedule and dispatch of a workflow in one group, and a third trigger would replace a pending second run that was meant to complete. `tlc.yml` and `tlc-image.yml` also run on pushes to `main`, and `tlc-image.yml` publishes the image the verification jobs pull, so this is load-bearing there. - **Cancellation is conditioned on the event.** A literal `cancel-in-progress: true` reads as the stricter setting and is a regression for any event that shares a group. `pull_request_target` workflows are out of scope. `dependabot-automerge.yml` automates pull-request housekeeping rather than building, and cancelling an auto-merge mid-flight is a hazard with no minutes to win. `release.yml` keeps its own `release-${{ github.ref }}` group, which queues rather than cancels. `tests/workflow_contracts/test_pull_request_concurrency.py` discovers every workflow declaring a `pull_request` trigger and asserts that its concurrency block is exactly the one above, by whole-value equality, so a run id anywhere but the fallback position, a `github.ref` fallback, a constant group, and a literal `true` all fail. A floor of the five known workflows keeps discovery from emptying into a vacuous pass, and unit cases drive the judgement with each refused shape, since the workflows as they stand exercise only the accepted one. ### A callee may not request more than its caller grants GitHub checks a reusable-workflow call before it starts any job. If a job of the called workflow requests a token scope the calling job does not grant, the run fails at startup: no job is listed and no check appears on the pull request. `release-dry-run.yml` capped the token at `contents: read` while `release.yml`'s `release` job requests `contents: write`, so the dry run never started on any pull request. The calling job now grants `contents: write` itself; the job is skipped in a dry run, so write is never exercised. `tests/workflow_contracts/test_reusable_permissions.py` holds every local call to the rule, and unit cases drive the judgement with each shortfall shape and each accepted shape, since the workflows as they stand exercise only one. The calling job's grant is the ceiling for the whole called workflow, so a second contract holds the dry-run chain to least privilege: every job that `release-dry-run.yml` reaches, through local calls in turn, declares its own `permissions`, and only a job skipped by the dry-run condition (`should_publish`) may hold write. Deleting one job's block, or its skip condition, fails the contract. ## Dependabot and the Cargo toolchain floor mxd is a server application, so the workspace declares no `rust-version`: the repository's pinned nightly toolchain is the only toolchain it supports, and no other crate in the estate depends on it as a library. The declaration was removed because Kani's bundled toolchain is older than the one the workspace builds on, and Cargo refuses to compile a package whose `rust-version` exceeds the compiler's (see "Kani proofs"). CI no longer checks a separate stable floor. Dependabot's Cargo updater does not raise `Cargo.toml`. Its `versioning-strategy` accepts only `lockfile-only` and `auto`. The `increase-if-necessary` value that other ecosystems accept fails the file's schema, and an invalid file stops Dependabot for every ecosystem in it. So a bump across a boundary the manifest forbids arrives as a lockfile-only change. `make check-locked` refuses such a lockfile, and a manifest raise is made by hand, as in pull request #554. serial_test 4 shows the same boundary. The manifest requires serial_test 3, so a bump to 4 arrives as a lockfile-only change that `make check-locked` refuses. Dependabot proposed it twice, in pull requests 566 and 575, when the pinned toolchain was also older than serial_test 4's `rust-version = "1.93.1"` and Cargo's MSRV-aware resolver resolved the bump back to 3.x. Automerge landed the second while `make check-locked` failed because `build-test` is not a required check, and pull request 576 restored the lockfile. The toolchain has since moved to a dated nightly, so the floor no longer applies, but the manifest still requires 3. The Cargo entry therefore ignores `serial_test` at `>= 4`, with a comment naming the manifest requirement. Raise the manifest to 4 by hand and drop the ignore together. It also ignores `bincode` at `>= 3`, because bincode 3.0.0 is a `compile_error!` stub that no bump to it can build. `make test-dependabot-policy`, run by `docs-tooling`, asserts: - the exact `serial_test` and `bincode` ignore rules; - the manifest requirement the rule depends on, so raising serial_test to 4 fails a case and the ignore is dropped instead of holding serial_test back after its reason has gone; - that any Cargo `versioning-strategy` is one of the two values Dependabot accepts, so the invalid shape cannot return unnoticed; - that there is exactly one Cargo entry, not merely a first one, and that the file carries no repeated key, which Dependabot's own loader would resolve to the last value; - the estate update policy: every entry runs daily, and each has one trailing catch-all group limited to minor and patch updates, with no `exclude-patterns` and no `applies-to` other than `version-updates`, so each major arrives in its own pull request; - that the only other groups are the github-actions `shared-actions` group (`leynos/shared-actions*`, no `update-types`) and Cargo's `rstest-bdd` lockstep group (`rstest-bdd*`, no `update-types`), each listed first. A bump of a shared-actions pin moves one commit SHA to another and has no semver level, so the typed catch-all never takes it. `rstest-bdd` and `rstest-bdd-macros` release together, and Cargo counts a 0.x minor as a major, which the catch-all would leave ungrouped; - that the github-actions entry reaches every composite action under `.github/actions`, at any depth, because Dependabot does not descend there from `/`. ## Loom models The Loom models check the shared-state kernels in `crates/mxd-concurrency`, which `mxd::presence::PresenceRegistry` and the Wireframe adapter's connection-context registry are built on. `docs/verification-strategy.md` states what they assert and what stays outside them. | Target | What it runs | | ----------------------- | --------------------------------------------------------------------------- | | `make test-concurrency` | The kernels' ordinary tests and doctests. Part of `make test`. | | `make check-loom` | Clippy and a `--no-run` build of the models under `--cfg loom`. | | `make test-loom` | The models, at `LOOM_MAX_PREEMPTIONS=3`, checked against the expected list. | | `make test-loom-runner` | Ruff and the tests for `scripts/run_loom_models.py`. | `make test-loom` runs `cargo test` under `scripts/run_loom_models.py`, which compares the models the run reports as passed with `crates/mxd-concurrency/loom-models.txt` in both directions. A run that drops `--cfg loom` compiles every model out and reports zero tests, and a filter that matches nothing does the same; both pass `cargo test` and both fail the runner. So does a passing test the list does not name, so ordinary tests cannot stand in for models. The workflow contracts in `tests/workflow_contracts/test_loom_lane.py` require the list to name exactly the `#[test]` functions in the model targets. Adding a model therefore takes three edits: the test in `crates/mxd-concurrency/tests/`, its name in `loom-models.txt`, and, for a new test file, its target in `LOOM_TARGETS` in the `Makefile`. The models run daily at 17:30 UTC, and on manual dispatch, in `.github/workflows/loom.yml` on a GitHub-hosted runner. The job's 30-minute ceiling is also the models' liveness bound: a model that cannot finish hangs rather than failing. A pull request touching the kernels, their production callers, the runner or the lane runs `.github/workflows/loom-check.yml`, which compiles the models and explores nothing. Both keep their Cargo cache under their own key, apart from the ordinary build's. The kernels' unit tests are compiled only outside `--cfg loom`, because a Loom mutex used outside a Loom model panics. For the same reason the lane selects the model targets with `--test` and never runs the doctests under Loom. ## Kani proofs The `kani.rs` modules under `src/` (header validation, transaction reading, the Wireframe codec, compatibility and compatibility policy) hold nine `#[kani::proof]` harnesses, compiled only under `cfg(kani)`. `make kani` runs them with `cargo-kani -p mxd` and fails if any harness does not verify. `.github/workflows/proofs.yml` runs the same target on pull requests that touch the code, the Kani pin or the workflow, and weekly. Kani comes from the shared `rust-prover-tools` package. The package revision is in `tools/rust-prover-tools/REF` and the Kani release in `tools/kani/VERSION`; CI installs it with the shared `install-prover-tools` action, and `make install-kani` does the same on a developer host. Kani compiles the crate with its own bundled toolchain, which is older than the repository's nightly, so the workspace declares no `rust-version`: Cargo would otherwise refuse the package before Kani compiled anything. Verification takes about ten seconds; most of a run is the compile. ## Spelling policy `make spelling` enforces en-GB-oxendict spelling over tracked text. `make markdownlint` depends on that target, so prose checks cannot bypass the repository-wide spelling policy. Every run regenerates `typos.toml` from the live shared dictionary and the repository overlay in `typos.local.toml`, then scans the tracked tree. Do not edit generated entries by hand; add narrow repository-specific entries to `typos.local.toml` instead. The builder keeps its downloaded shared base in untracked cache files and refreshes the local copy only when the published source is newer, so a valid cache remains usable without network access. Because the dictionary is live, `typos.toml` must never be drift checked in continuous integration. Repository exceptions must protect machine interfaces, formal upstream names, or exact serialized fixtures. Use the narrowest anchored pattern possible and explain why it is required. Do not add broad word-level exceptions for prose. The gate also rejects punctuation-sensitive shared phrase corrections that single-token spelling scans cannot enforce reliably. `make test-spelling-gate` proves that it does. A clean checkout passes `make spelling` whether or not the gate is enforcing anything, so a flag dropped, a scope narrowed or a builder release that stopped reading the phrase policy would leave the lane green and the policy unenforced. The test runs the `spelling` target itself, overriding only `SPELLING_ROOT`, against a fixture tree carrying this repository's policy files and one document holding a prohibited phrase, and asserts the target fails and names the phrase. A second case runs the same fixture with the phrase corrected and asserts it passes, so a fixture broken for an unrelated reason cannot satisfy the first. Wrapping the gate as `|| true`, narrowing its scope or replacing the builder invocation each fail it. The builder is pinned to a release tag by `TYPOS_CONFIG_BUILDER_VERSION` in the `Makefile` (currently `v0.1.3`), as the Concordat baseline requires. Raise it together with the regenerated `typos.toml`, never on its own. ## Presence runtime The presence runtime is the in-memory authority for which users are currently online. It lives in `src/presence.rs` and is threaded through the wireframe server via `Arc`. ### `SessionPhase` `SessionPhase` records whether a connection can participate in presence: - `Unauthenticated`: the connection is established, but no credentials have been verified. - `PendingAgreement`: login credentials have been accepted, but the user must still send the Agreed transaction (121) before becoming visible to peers. - `Online`: the agreement has been accepted, or bypassed via `NO_AGREEMENT`; the user is visible in the roster and receives presence notifications. Only `Online` sessions are included in the presence registry. Sessions in `Unauthenticated` or `PendingAgreement` remain absent from roster replies and presence fan-out. ### `PresenceSnapshot` `PresenceSnapshot` is the transport-facing presence record built from an online session. It carries: - `connection_id: OutboundConnectionId`: the unique per-connection handle used for notification fan-out and registry removal. - `user_id: i32`: the authenticated user's database identifier. - `display_name: String`: the visible nickname, defaulting to the account username. - `icon_id: u16`: the client-selected icon index, defaulting to 0. - `status_flags: u16`: packed presence flags such as admin, away, and refuse-private-message state. Build snapshots from a `Session` with `Session::presence_snapshot()`. The method returns `None` unless the session phase is `Online`, keeping agreement-gated users out of the roster until they complete the login lifecycle. ### `PresenceRegistry` `PresenceRegistry` owns the online snapshot set and exposes deterministic query and mutation operations: - `upsert(snapshot) -> Vec` inserts or replaces the snapshot keyed by `connection_id`. It returns the connection IDs of all other registered peers so the caller can fan out a `301 Notify Change User` notification. - `remove(connection_id) -> Option` removes the entry for the given connection. It returns a `PresenceRemoval` containing the departed snapshot and the remaining peer connection IDs for `302 Notify Delete User` fan-out, or `None` when the connection was not registered. - `online_snapshots() -> Vec` returns all registered snapshots in deterministic ascending `connection_id` order. Roster replies use this to build the `300 Get User Name List` response. - `snapshot_for_user_id(user_id) -> Option` returns the snapshot for the given database user ID. If duplicate sessions share the same user ID, the snapshot with the numerically lowest `connection_id` is returned. ### Transaction builders The presence module also exposes builders for the roster and notification transactions: - `build_user_name_list_reply(header, snapshots)` produces transaction 300. - `build_notify_change_user(snapshot)` produces transaction 301. - `build_notify_delete_user(user_id)` produces transaction 302. - `build_client_info_text_reply(header, display_name, info_text)` produces transaction 303. ## Toolchain updates `rust-toolchain.toml` pins a dated nightly. Dependabot's `rust-toolchain` entry in `.github/dependabot.yml` (directory `/`, daily, the `dependencies` and `rust-toolchain` labels, one `minor-and-patch` catch-all group) opens a pull request when a newer toolchain exists. Review it like any other change: CI builds and tests the project on the new toolchain. Dated nightly versions carry no SemVer meaning, so whether Dependabot groups a bump or opens it alone depends on how it classifies the version; both are normal. The entry sets no cooldown: Dependabot's toolchain fetcher publishes no release date, so a cooldown would delay nothing.