Quality Gates & Enforcement (CRAIG)

Contents

These are CRAIG’s project-specific, mechanically-enforced quality gates — run by cargo xtask validate, cargo xtask quality-budgets, and cargo xtask lints. They cover the project’s DTO-validation rules, workspace lint policy, the nine quality budgets, the function-cohesion gate, context-tier hygiene, and the typed route role gates. The universal Rust style rules (function size, newtype pattern, typed errors, no-panic, no-Value, etc.) live in the coding-conventions standard (and, for agent sessions, in gadhs/pi’s injected Rust profile).

Baselines (#2300)

Every count, list and floor a gate compares the tree against is a ledger: one TOML file under xtask/baselines/, read by one loader (xtask/src/baseline.rs) into the ledger’s own typed record. Reading has no defaults: a missing file, a missing key or an unknown key is an error.

cargo xtask baselines check [--only <name>]…
cargo xtask baselines bless [--only <name>]… [--allow-growth "<why>" | --allow-lower "<why>"]

check runs each registered ledger’s check and names each one that fails; what a check does depends on the ledger’s kind, below. bless rewrites the measured ledgers from the tree and the run-fed ones from their run’s output. One other command writes a ledger: cargo xtask contested-census --bless adds report-only stubs to contested-surfaces. It keeps the file’s order and puts each new stub after the entries of its class and crate, so its diff is the stubs it added (#3213).

Three kinds of ledger:

  • Measured: recomputed by scanning the tree (the quality budgets, the lint allowlists, the authz pins, the two coverage ratchets, the scan floors).

  • Fed by a run: coverage (after cargo xtask coverage) and coverage-signatures (after a full battery). For these check only proves the file loads; the comparison runs with the run itself (cargo xtask coverage, the battery’s coverage-signature check). A bless of one refuses when its run has not happened, and a bless that names no ledger skips both.

  • Declared: written by hand (authz-helpers, contested-surfaces, mutants-baseline). check proves each loads; bless never rewrites one. The audit-write census is declared too, but is not registered with the verb: its reader is test-only, and its tests are its check.

How a record may move:

  • A count or list that may only shrink fails above its record (new debt) and below it (a stale record). A bless lowers it freely. Where a row carries a hand-written reason, a bless only removes rows the tree no longer backs and never adds one.

  • A listing that must equal the scan (the authz pins) moves either way on a bless; the diff is the review.

  • A floor (scan-floors, coverage) fails when the measurement falls more than its slack below the record: one fifth for a scan floor, 0.5 points for coverage. A bless raises it freely.

A move against the direction needs a reason: --allow-growth to raise a shrink-only record, --allow-lower to lower a floor. Each needs exactly one --only, and the reason is written into the file as last_exception, so it is in the diff under review.

Scan floors. A gate that walks the tree must notice a walk that stopped seeing it. scan-floors.toml records what each such walk saw at the last bless, keyed <lint>.<what>; a bless that scans first requires these floors, so a walk that lost the tree cannot empty a ledger.

DTO field-length validation (#486)

Every String-shaped field (String, str, SanitizedText or SsnIdentifier under any Option / Vec / Box / map / set nesting) on a deserialize-side struct or enum variant (request body, query string) carries the garde cap its shape admits (§ Enum / map / Path scope, Garde’s own reach): a [garde(length(max = <CONST>))] on a string, an entry-count and a per-item cap on a sequence, and custom(…) or a reasoned skip where garde cannot reach the string. A string cap carries a mirrored [schema(max_length = <literal>)] (or #[param(max_length = <literal>)] on IntoParams structs). The 13 canonical cap constants live in craig-validation:

Constant Cap Category

NAME_MAX

100

Person / org / court / admin-unit names

PHONE_MAX

32

E.164 + separators + extension

IDENTIFIER_MAX

64

UUIDs, slugs, hex SHA-256 digests

IDENTIFIER_LONG_MAX

1024

S3 / Garage object keys (spec ceiling)

CODE_MAX

64

Ruleset-validated codes, semver+build-metadata

ENUM_STRING_MAX

32

String-typed status / sort fields (Plan D F-022 candidates)

SHORT_TEXT_MAX

500

Query searches, single-line annotations

DESCRIPTION_MAX

2000

Bounded single-concept descriptions

REASON_MAX

1000

Justifications, override reasons

NARRATIVE_MAX

4000

Plaintext multi-paragraph narrative

NARRATIVE_ENCRYPTED_MAX

8000

Encrypted-at-rest narrative; absorbs base64 + AEAD overhead

NAME_ENCRYPTED_MAX

255

Encrypted-at-rest person-name PII envelope

SSN_LAST_FOUR_MAX

256

Encrypted-at-rest envelope; digit-shape via separate validator

utoipa literal requirement. utoipa’s [schema(max_length = …​)] and [param(max_length = …​)] macros reject const-ident expressions — they require integer literals (true of 5.4, 5.5 and 6.0: utoipa-gen 6.0.1 still parses the value as a literal). The garde side stays canonical ([garde(length(max = NAME_MAX))]); the utoipa side mirrors the literal ([schema(max_length = 100)]). This dup is intentional and bounded; a future garde/utoipa cap-sync xtask lint will guard the pair.

Special-cases. Use the named constant unless concrete evidence (DB column ceiling, RFC reference, real-world data) demands a different cap. When deviating, use a literal and add a // #486 special-case: <reason> comment immediately above the attribute pair. CreateCourtOrderRequest.court_name / UpdateCourtOrderRequest.court_name use literal 200 (compound jurisdictional names) — established precedent.

Cousin-field uniformity. Fields with the same semantic role across cousin DTOs (admin_unit on Create/Update for cases / referrals / reports) MUST share one cap — NAME_MAX for admin_unit cousin fields. The MR 5 workflow caught one cousin asymmetry mid-sweep (CreateReportRequest.admin_unit was a survey miss); cousin reviews are part of every per-file sweep.

Handler wiring. Every handler accepting a Validate-derived DTO calls payload.validate()? (or query.validate()?) immediately after the Json/Query extractor and BEFORE the authz check + parent-resource existence checks. The From<garde::Report> for ApiError impl in craig-common::validation converts validation failures into RFC 9457 ApiError::Validation (HTTP 422) with a per-field errors extension. Note: garde 0.22’s Validate::validate(&self) takes NO context arg under Context = () — use body.validate()?, not body.validate(&())?.

Scope as of MR 1-6 (2026-05-29): all 72 String fields in craig-cases-contracts are length-capped. craig-exchange-contracts surveyed in MR 6 contains zero unbounded String DTOs (the crate’s surface is the ExchangeAdapter trait + ExchangeAdapterKind enum; no request/response DTOs). Inline service api/ DTOs (210 fields across 4 stateful services) + partner-* crates (147 fields) + craig-intake-sdk (52 fields) are tracked as a separate follow-up — they fall outside #486’s craig-*-contracts scope and warrant their own audit ticket.

Partner-crate scope (#1461, 2026-08-15): the cargo xtask lints dto-length walk derives its partner-crate list from a crates/craig-partner-* directory glob — every partner crate present AND every future one is lint-covered automatically (the earlier hardcoded list silently omitted four crates: cprs / stars / doe-slds, whose 41 unbounded fields were annotated when the glob closed the gap, and audit, which carries no DTO structs). A unit test pins the glob against the live crates/ listing, and an unreadable crates/ fails the lint loudly rather than passing it vacuously.

Contracts-crate scope (1881, 2026-10-13): the walk derives every crates/*-contracts crate from the same directory glob — the hardcoded list covered only cases / exchange / ledger, leaving financial / intake / placement / plugin / reporting / rules / security unscanned. An unqualified cap const declared in the same file (const INVITATION_CODE_MAX: usize = 64;) resolves before the craig-validation table, as Rust resolves it, so a crate-local cap is checked against its mirror and a local REASON_MAX = 500 is no longer read as the table’s 1000; a path-qualified cap (craig_validation::REASON_MAX) always names the table; and an unqualified cap the lint cannot read as a usize literal is an unknown-cap failure, including a same-file const that shares a table name (const REASON_MAX: usize = 250 * 2; shadows the table, as in Rust, so it is never read as the table’s 1000). The glob surfaced 27 request-side reports: 4 crate-local-const false positives (cleared by same-file resolution); 18 literal caps in subsidy_imports.rs missing their [schema(max_length)] mirror (added); EvaluateRequest.rule_set / context_type, uncapped (now CODE_MAX; an over-long value is a 422); and 3 fields bounded elsewhere that now carry an explicit [garde(skip)] with the reason — the two AFCARS after cursors (their decoders refuse every other length) and ArrangementFacts.arrangement_jurisdiction (trimmed, then capped at 255 characters by the service). It also surfaced 228 MissingGarde fields on response, view, event-payload, plugin-manifest and render-context types (83 structs in 29 files) — types that derive Deserialize only so a typed client or consumer can decode them. They are pinned per struct (file::Struct) in the uncapped table of the dto-length ledger (xtask/baselines/dto-length.toml), reconciled both ways like the #865 allowlist: a higher count fails, a lower count is stale and blesses down in the same MR, and a MissingGarde on an unlisted struct fails field by field, so a new request DTO cannot hide behind an annotated response type in the same file. Annotating a listed type (Validate + [garde(skip)], the craig-cases-contracts precedent) lowers its row. A missing mirror, a mismatched literal or an unknown cap const is never baselined.

Service scope (#2366, 2026-10-21): the walk derives each service’s API module from disk: services//src/api/ and the module-root file services//src/api.rs (service_api_roots), so craig-rules' and craig-intake-keyring’s api.rs and craig-composition’s api/ are covered. It also walks three literal file roots: crates/craig-api/src/admin_replay.rs, the one shared-crate request struct with a String-shaped field (ReplayParams), and the SHINES request views services/craig-intake/src/backend/shines/extra.rs and narrative.rs (ExtraFields, SupportingDocument, NarrativeView), where the lint pins that each String field declares a cap and #2336 owns NarrativeView’s enforcement. A literal root that does not exist fails the walk (`walk_lint_root) instead of scanning nothing. Three exceptions to § Handler wiring’s validate-before-authz order sit in this scope: every handler in craig-rules' api/rule_set_reads.rs, api/rule_set_writes.rs and api/evaluations.rs validates after the bootstrap gate that its // authz: skip waiver pins as the handler’s first statement, the admin replay (replay_handler) validates ReplayParams after require_admin, and the keyring’s PUT /keys/{kid}/approve and /revoke validate the kid after their admin check (#2560). The BFFs (craig-web, craig-portal, craig-bff) stay out of scope: they hold no database and forward to a backend that applies the cap.

Extractor scope (2561, 2026-10-23): location roots guard only the homes they list, so the lint also runs an extractor census (xtask/src/cmd/lints/dto_extractors.rs). It reads every production source except the BFF members (craig-bff, craig-portal and craig-web, per the maintainer ruling of 2026-10-21, #1654 update 13), the [workspace].exclude trees, the src test-support files, any tests, benches or examples tree, and the files a [cfg(test)] mod x; loads (the #2207 resolver). A BFF entry that is no workspace member fails, and so does a census below 1000 files (about 80% of the 1244 it read at landing). A fn, method or typed-closure parameter whose type is, or wraps, a Json<T>, Query<T>, Form<T> or Path<T> with one generic argument is a payload site. T resolves through the file’s use bindings (renames, groups and globs), crate:: / super:: / <crate>:: paths, type aliases, generic arguments and cross-crate pub use re-exports (named, then glob, at most four hops), and each type it reaches is followed through its fields. A reached type outside the location roots is field-checked by the same per-item check; one inside them is traversed but not re-checked. A payload or field type that names no workspace declaration (a non-workspace crate’s type, a handler’s own type parameter, an impl / dyn / macro type) is an UnresolvedType finding keyed file::handler or file::Owner::field, so the census fails closed.

  • Limits. Resolution is a name match narrowed by crate, not a module graph: two same-named types in one crate are both checked (the summary counts them ambiguous), use shadowing across one file’s inline modules is flattened, and a path head that names no workspace crate reads as a module of the file’s own crate. Handlers generated inside macro_rules!, closures with untyped parameters, and an extractor that is neither one of the four segments nor a use rename of one are invisible. A macro-declared type reached through a field is Unresolved.

  • Out of model, pinned. The ledger’s out_of_model table pins one counted class: 17 Multipart parameters (2632). A count off its ceiling fails both ways: growth is out-of-model growth, and a drop lowers the ceiling (shrink-only). Untyped payloads and fields (serde_json types, Bytes; #2633) are no longer counted: each either carries a JSON size bound or is named in the ledger’s untyped table with the bound it does have (four today: the two IV-E determination inputs, which have their own walker, and the two devstack mock-server bodies). The table is reconciled both ways, so a new untyped request field fails lints dto-length until it is bound or listed; its bound text is prose the lint does not verify. An untyped field that carries a JSON size bound, [garde(custom(json_within(…)))] or json_option_within from craig_validation::json_bounds (craig-validation), is in model; the rule name is matched exactly, by the called fn’s last path segment, and only as a rule on the field itself: under inner(…) it bounds each item of a list and not the list, so such a field is not bound.

  • Opaque, admitted by name. A reached type whose Deserialize is hand-written or converts (try_from / from) cannot be field-checked. The ledger’s opaque table names each one with the bound its decoder enforces and the test that pins it; the table is reconciled both ways, so a new opaque type fails until it is derived with garde caps or listed with a bound (#2631).

  • Roots. The literal crates/craig-api/src/admin_replay.rs root is gone: the census reaches ReplayParams through Query<ReplayParams>. The SHINES extra.rs and narrative.rs roots stay, because those views decode from the raw body’s bytes, which no extractor type names.

  • Landing census. 1244 files, 675 payload sites and 332 reached types, 57 of them outside the roots, with no unresolved and no ambiguous type. Its one new finding, craig-mock-server’s CaptureQuery::path, is baselined: the mock server is a devstack-only emulator whose image .gitlab-ci.yml never promotes.

Enum / map / Path scope (#2560, 2026-10-23): the lint reads Deserialize enums' variant fields (keyed Variant::field), positional fields (struct Slug(String) is Slug::0, a V(String) variant V::0), and every inline non-test module, whose own consts resolve its unqualified caps. A type whose Deserialize converts (serde(try_from) / serde(from)) is never field-checked, and a test-support file under a root (a *_tests.rs fixture, a partner mock.rs, by the extractor census’s predicate) is not walked. String-shaped is one structural rule: a string leaf anywhere under a wrapper, a map key or value, a tuple, an array or a type argument. A field’s type is read with its type aliases expanded (#2639), through the extractor census’s resolver: a same-file, same-crate or imported type Name = String; makes a Name field a String field, in the location roots and the census alike, and its cap is judged against the expanded shape. An alias whose right-hand side resolves to no workspace declaration is an UnresolvedType finding keyed file::Owner::field.

  • Garde’s own reach (ruling R1, garde 0.22.1). A plain string takes length(max) (or inner(length(max)) through an Option). A Vec, array or slice of strings needs an entry-count length(max) and a per-item inner(length(max)); under an Option the item cap is inner(inner(…)), because inner steps into the Option first. A string under a map, set, VecDeque, Box<String> or tuple takes only custom(…) or a reasoned skip: garde has no inner there and never validates a map key. A pointer to str (Box<str>, Rc<str>, Arc<str>, Cow<str>) is measured as a string, so length(max) caps it. A gap is a CollectionGap finding, keyed file::Owner::field.

  • Parameters. A payload whose own type holds a string leaf (through wrappers, tuples and type aliases, never through a named DTO, whose fields are checked instead) is an UncappedParam finding, keyed file::handler.

  • Fixed at landing. EmpiAlias::ssns gained its per-item cap, and CapsAckStatus::Rejected.reason its REASON_MAX, now enforced: the CAPS adapter validates each ack it decodes. Nine handler parameters are typed and capped: the keyring’s three kid routes and craig-security’s kid lookup (the same contract route) answer 400; craig-security’s three NIST routes, intake’s kid proxy and craig-rules' by-name read answer the 422 validation problem. Intake’s JWS verification refuses an over-cap header kid as the uniform 401 before any lookup. UserDelta (crates/craig-composition-engine/src/user_delta.rs, a literal root because put_user_delta decodes it from Json<Value>) records three reasoned skips: each slug is bounded by baseline membership.

  • Baselined as the reach widened (the uncapped table 84 → 105 rows), each row with a reason: 7 response or manifest rows (the #1881 precedent), RawText (a stored payload’s contact keys, #2633), 10 handler parameters held by hyper’s request-head ceiling (#2635 caps them) and 3 mock-server handlers (devstack-only). Rows are seeded only when the lint’s reach widens; otherwise the baseline only shrinks.

Lint Policy (workspace [lints] table)

Cargo.toml’s `[workspace.lints.clippy] table turns the §Style + §Errors rules above into mechanically-enforced compiler errors. Member crates inherit via [lints] workspace = true. Today’s set (post-Plan-M Tier 1 + Tier 2, 2026-06-05):

  • Pedantic + cargo + complexity (deny): pedantic, cargo, cognitive_complexity, too_many_lines (threshold 40 via clippy.toml)

  • Panicking calls forbidden (deny, Plan H F-030 sweep): unwrap_used, expect_used, panic, todo, unimplemented, unreachable, dbg_macro

  • Wildcard match arms forbidden (deny, post-Plan-H): wildcard_enum_match_arm — forces explicit match exhaustiveness

  • Panic-surface (Plan M Step 7 / #498) (deny): indexing_slicing, string_slice, unwrap_in_result

  • Overflow-surface (Plan M Step 8 / #499) (deny): arithmetic_side_effects — every +/-/// on integer/Decimal/Duration types must use checked_ / saturating_* / wrapping_*

  • IO-surface (Plan M Step 9 / #500) (deny): print_stdout, print_stderr — library + service code routes through tracing::*

  • Struct hygiene (Plan M Step 10 / #501) (deny): partial_pub_fields — either ALL fields pub or NONE

  • Docs required (deny, Plan H Step 3 burn-down): missing_docs_in_private_items

  • Silent-discard forbidden (deny, Plan H F-051 sweep): let_underscore_must_use, ignored_unit_patterns

  • Reasoned suppression required (deny): allow_attributes_without_reason — every allow / expect must carry reason = "…​"; and allow_attributes (deny, project-owned after the managed block, 2715) — an outer suppression is a self-checking [expect] (§ Lint regimes)

  • Priority=1 allowed (structurally unavoidable): cargo_common_metadata, multiple_crate_versions (dep-graph artifact). The historical style-orthogonal allows are gone: the #630 sweep (2026-08-30) adopted missing_errors_doc/missing_panics_doc/must_use_candidate at ~1,450 sites, and module_name_repetitions turned out to no longer need one — upstream clippy demoted it from pedantic to restriction (toolchain 1.97), so the template’s pedantic = deny stopped reaching it and the allow was vestigial (#1606, closed OBE; CRAIG does not opt into it — its remaining findings are ecosystem-conventional names like ApiError/TestHarness whose "fix" is churn, not clarity)

All deny at workspace level; test code runs under the test regime (§ Lint regimes), leaving production code deny-enforced. xtask validate runs clippy with -D warnings for defense-in-depth (§ The clippy passes).

Lint regimes

Lint policy has two regimes (plan lint-policy-regimes, #2711), and every other suppression is self-checking or registered (#2715). The production regime is [workspace.lints]. The test regime is it minus one set of 13 single lints (no group), applied by one attribute at every crate root:

  • Assertion mechanism: unwrap_used, expect_used, panic, unwrap_in_result. A test fails by panicking.

  • Known-shape fixtures: indexing_slicing, string_slice, arithmetic_side_effects (the correctness class, in test code only), where an out-of-range index or an overflow is the test failure a debug build raises.

  • Discards and partial matches: let_underscore_must_use, wildcard_enum_match_arm. Harness output: print_stdout, print_stderr. Test plumbing: disallowed_methods (§ Disallowed methods). Scenario length: too_many_lines.

Left out, because they are live in test code (measured on 1.97.0 with every test-root allow removed): clippy::pedantic (2,386 hits across 47 member lints), missing_docs_in_private_items (334), module_inception (5) and cognitive_complexity (4). No root allows a group any more, and U5 retired the single-lint pedantic allows the tests/ roots carried in the interim (#2715). The lints with no hit in test code (clippy::cargo, todo, unimplemented, unreachable, ignored_unit_patterns) were deleted from every test-root allow.

The policy file. xtask/lint-policy.toml is the one definition. [test-regime] holds lints (sorted "clippy::<name>"), the reason every regime attribute carries byte for byte, and test-support (craig-test-lib, craig-partner-test-harness). [groups] lists every lint group an attribute can name (clippy’s ten, rustdoc::all, and the groups rustc -W help prints on the pinned toolchain); a set entry that is a group fails. The [[suppression]] tables are the registry (below). The decoder refuses an unknown key or table, an unsorted or duplicated list, and a set lint without the clippy:: prefix.

The check. cargo xtask lints lint-regime (xtask/src/cmd/lints/lint_regime.rs, the blocking lint-regime check validate step) classifies every target of every workspace member from cargo metadata: a target of a test-support package, or one whose kinds hold test, bench or example, is a test root; one whose every kind is a library or binary kind is a production root; a build script carries nothing; any other kind, and a root outside the workspace, fails. It reads each root’s crate-level inner attributes only, through the shared fail-closed reader; an attribute whose allow / expect (plain or under cfg_attr at any depth) carries the policy reason is a regime attribute.

  • R1, a test root: exactly one regime attribute, a plain #![allow(<the set>, reason = "<reason>")], no lint repeated and nothing else in it.

  • R2, a production root: exactly one #![cfg_attr(test, allow(<lints>, reason = "<reason>"))], predicate the bare test, where <lints> is the set minus each set lint the root allows or expects plainly elsewhere (none left: no attribute). Repeating a plainly allowed lint would fail duplicated_attributes, so the check refuses it.

  • R3: no other suppression at a test root names a set lint, and no other production-root suppression under a cfg_attr whose predicate names test does.

Every violation is printed as <path>:<line>: <rule>: <what>, followed by the root’s canonical attribute (R1–R3) or the registry entry a registered form would need (R4).

--fix. cargo xtask lints lint-regime --fix splices each root’s text, never re-printing the file: set lints leave every suppression R3 flags and every misshaped regime attribute; a suppression left with no lint goes, and an attribute left empty goes with the // comment block attached above it; a remainder keeps its other lints, its comments and its reason literal; and the one canonical attribute is written after the last leading inner attribute, in rustfmt’s layout. A set lint under a cfg_attr that names test without requiring it (not(test), any(test, …)) changes production meaning, so --fix leaves it and the check keeps failing. A second run changes nothing, and --fix never edits the policy file. Changing the set is one TOML line plus --fix.

Every other suppression (plan § D3, #2715). The same check parses every .rs file under the lint roots with syn ([workspace].exclude trees included, a file there owned by its own package, read from its manifest; a file syn cannot parse fails) and scans every Macro and Verbatim token stream (lint_regime/walk.rs). A suppression is an allow or expect naming any lint, or a warn naming a rustdoc:: lint (the doc passes run without -D warnings), plain or through cfg_attr at any depth, other than each root’s one validated R1/R2 attribute (another attribute carrying the policy reason is a suppression like any other). A raw identifier reads as the name it spells (r#allow is allow, r#dead_code is dead_code). A lint path is bare (rustc) or clippy:: / rustdoc:: prefixed; rustc and clippy refuse renamed, removed and unknown names themselves under -D warnings, so no lint list lives in the repo (lint_regime/suppressions.rs).

  • R4, registered scope: an outer expect on a non-container item needs nothing, being self-checking; every other suppression matches exactly one registry entry. A container is a mod, an impl, trait or extern block, an item or impl-item macro invocation, or a node (fn, const, static, block, closure, statement) whose body holds, at any depth, an item other than use or extern crate; a suppression on one reaches every nested item. A rustdoc:: suppression, one inside a macro body, and one a proc-macro crate emits fit no category and always fail. Emitted code is scanned only in a package whose lib is proc-macro (from cargo metadata; an excluded package’s from its manifest), outside its tests/, benches/ and examples/: there, any string, byte-string or C-string literal (the byte forms decoded lossily), whatever call takes it, and any quote!-family body that lexes (lint_tokens::lex) to an attribute-shaped suppression or an allow / expect / warn ident before a parenthesised group fails. Elsewhere a parse_str / from_str literal only parses at run time and emits no compiled code, so it is not scanned. The scan is lexical and has limits no lexical scan can close: a suppression assembled by concat!, by format! / format_ident! interpolation or character by character is not caught. A proc-macro author does not build one that way, and review holds that line.

  • R5, groups and meta-lints: no suppression, entry or set lint names a [groups] group, and none lowers warnings, unfulfilled_lint_expectations, unknown_lints, renamed_and_removed_lints or incomplete_include (which would hide an `include!’s trailing tokens from M7, below).

  • R6, correctness class: outside test-regime code, no suppression of indexing_slicing, string_slice or arithmetic_side_effects passes, whatever entry matches it: no category registers the correctness class. An unregistered inner allow of one fails R4 alone. Test-regime code is <pkg>/tests/, a test-support package’s src/, the files a test-only mod x; loads (cfg_test_module_files) and items under a test-only #[cfg] (attrs_are_test_cfg_only). The correctness class is never suppressed in production code: fix the site with a checked op, get, or a commented saturating op.

The registry. One [[suppression]] table per suppressed lint, sorted by key, matched one to one by its identity (file, scope, placement, kind, predicate, lint[, ordinal]). scope is a TOML array of the named items around the attribute, its target included, outermost first (["mod tests", "impl fmt::Debug for Config", "fn insert"]: mod, impl <Type> / impl <Trait> for <Type> with the parts' tokens compacted and generics kept, trait, fn, const, static, struct, enum, union, type), empty for a file’s own inner attributes. predicate is the cfg_attr condition with the spaces between tokens removed, a nested cfg_attr as all(<outer>,<inner>), or none. ordinal is written only when two occurrences share all else (missing means 1). A widened scope, a changed predicate or a second copy is unlisted, and an entry nothing matches is stale. Each entry adds reason, byte-equal to the attribute’s, and category, a closed enum (a new category is a policy change the user approves):

  • macro-output: a file module’s own inner #![expect], the entry declaring the macro (<crate>::<macro>; never std, core, alloc, a tool namespace, a relative root or a builtin such as inline) that emits the lint. The check reads it without name resolution (lint_regime/macro_module.rs, packages.rs, dep_info.rs). M1 is a registry decode error, which aborts the check; M2–M7 each fail as R4 with their M<n>: prefix, every failing rule reported:

    • M1, file module: the entry’s scope is []; decode refuses any other. On stable Rust an attribute macro cannot wrap a file module or any ancestor that holds it (E0658, verified on 1.97.0); it can wrap an inline one.

    • M2, fns only: every item of the module is an fn (no use, extern crate, mod, impl, type, const, item macro or anything else), there is at least one, and the module’s inner attributes are its suppressions and doc strings only.

    • M3, attributes: each fn carries exactly one non-doc outer attribute, a bare path equal to the declared macro (a leading :: dropped, a raw identifier read as it spells: [askama::filter_fn], [::askama::filter_fn]), beside [doc = "…"] string literals (what /// writes); its body block carries no inner attribute of its own (syn folds one into the fn’s attributes; deeper ones are M4’s), and no parameter, generic parameter or lifetime carries an attribute, askama’s [optional] included.

    • M4, no code-introducing node: nothing anywhere in the fn (signature, generics, where clause, body) is an item, a macro invocation in any position, or a verbatim node, and no attribute sits anywhere in the fn besides the declared one and its /// docs (a body statement’s, an expression’s, a nested block’s or a closure’s included).

    • M5, the head is a plain normal dependency: the owning package is a workspace member, and in the full cargo metadata’s resolved graph exactly one of its dependencies has the declared path’s head as its `--extern name; that dependency is declared only as a normal, untargeted one, its package’s name (hyphens as underscores) is the head (a rename, or a lib-name mismatch such as md-5’s `md5, fails), and the manifest entry naming that package is neither optional nor renamed. rustc refuses a macro-expanded extern crate that rebinds an --extern name.

    • M6, no rebinding: no file of the owning package writes, at any depth, extern crate X as <head>; (X may be self). With M7b and M7c every file a unit compiles is a walked file of its package, so M6 sees every written extern crate.

    • M7, source ownership, exact from rustc’s dep-info and held for the whole tree, not only owning packages (lint_regime/dep_info.rs): the workspace clippy invocation validate runs (one shared const) runs again with --message-format=json, which cargo does not fingerprint, so right after validate’s clippy step every unit replays fresh. Each compiler-artifact of a workspace member is a unit, and its dep-info (beside its artifact, the stem’s lib dropped; a build script’s, whose artifact is build-script-<name>, build_script_<name>-<build dir hash>.d with each - in <name> an _) lists every file it compiled after macro expansion; a missing one fails closed. Only paths under cargo’s target directory (OUT_DIR output, dependencies) and the root’s Cargo.toml / clippy.toml / .clippy.toml are skipped; a path outside the repo is classified like any other, so Rust source there fails M7b and M7c. A path is Rust source when it ends in .rs, or when it parses as a non-empty syn::File (a leading shebang line stripped, as rustc strips it from a module or an item-position include!), or it lexes and a prefix of it parses as an expression holding an attribute, an item or a macro (an expression-position include! reads the first expression only, and strips no shebang); the rest is data (.sql, .toml, .html, .json, .ftl, .js, .css, …). M7a: Rust source in a non-.rs file fails (rename it to .rs so the walk and the registry see it). M7b: every Rust source path is in the lint walk’s file set (a pruned src/target/… is not). M7c: every Rust source path is owned by the unit’s package (the deepest package directory holding it). M7d: no macro-output entry’s file is in a build script’s dep-info. cargo xtask lints lint-regime --deps runs M7 after the static checks; plain lint-regime is static, and validate runs M7 as its own step, source ownership from dep-info, right after clippy.

    The threat model. Guaranteed, for the linted build (cargo clippy --workspace --all-targets, default features): every Rust source file a workspace unit compiles, generated code under the target directory aside, is a walked .rs file of that unit’s package, wherever it lives (a file outside the repo fails too), so the registry sees every suppression in it (M7); a macro-only module is compiled only by its own package’s non-build-script targets (M7c, M7d); its expect covers only the declared macro’s output plus the filter fns' signatures and bodies, which that macro consumes and moves into its output (M1–M4; for askama’s filter_fn that is execute’s inputs and body, so an always-`Ok body, for one, is inherently under unnecessary_wraps); and its head is the dependency’s --extern name (M5), a written rebinding is refused (M6) and an expanded one is a rustc error. Out of scope, owned by review and cargo-deny’s sources check: Cargo- and toolchain-level substitution ([patch] / [replace], a path or git source, --extern through RUSTFLAGS or .cargo/config.toml), code generated under the target directory, builds other than the linted one (non-default features, other cfgs), and the macro crate’s own behaviour. craig-web’s and craig-portal’s filters/wrappers.rs and craig-intake’s and craig-bff’s filters.rs declare askama::filter_fn, thirteen entries (§ Suppression vocabulary).

  • cfg-variant: an inner allow of a lint live in some compilations of the same code only. Ten today, all dead_code: per test binary, craig-authz/tests/fixtures/mod.rs, craig-mq/tests/common/mod.rs, craig-financial/tests/support/authority.rs, craig-partner-host/tests/support/mod.rs, and craig-partner-testonia-registry/tests/kit/modules.rs, kit/native.rs and kit/people.rs; lib against bin tree, craig-exchange’s store/agreements.rs, store/partners.rs and events.rs. Not self-checking: removing the dead code removes the entry.

The two categories are the whole vocabulary: U5 retired every transitional debt allow and then the category itself, so the decoder refuses category = "debt" and a row key.

No --fix writes an entry: the registry is edited by hand, and a removed suppression’s entry goes with it.

allow_attributes (plan § D4). allow_attributes = "deny" sits right after the managed lints block’s end marker in Cargo.toml, still inside [workspace.lints.clippy], project-owned with no sync override; it is deleted once the template’s managed block ships the key, which a sync would otherwise duplicate. clippy flags outer [allow] only (never an inner one, never proc-macro output), so an outer suppression is a self-checking [expect], and a lint live in some targets only takes #[cfg_attr(<pred>, expect(…))]. With every outer allow gone and every inner one registered, budget B4 and no-transitional-allows (Plan M Step 6’s crate-root group ban, #497 + #867) retired: R5 bans every group, and R6 refuses every correctness-class blanket outside test code.

Suppression vocabulary

When a workspace lint fires and the site cannot be fixed, the suppression takes one of these shapes; R4–R6 (§ Lint regimes) hold every one of them:

  1. An item [expect(clippy::<lint>, reason = "…")] on a non-container item (a fn, a field, a statement, a const): self-checking, so it needs no registry entry. The reason states the invariant or the §Important-Function carve-out. A lint live in some targets only takes [cfg_attr(<pred>, expect(…))] (a transition-spec predicate live outside test builds takes not(test)). Never on a container (move the nested items out, or narrow onto the firing item), never of a rustdoc:: lint (R4), and never of the correctness class (indexing_slicing, string_slice, arithmetic_side_effects) outside test code (R6): fix the site with get / strip_prefix / checked_* and ?. Examples: federal-spec wire shapes, struct_excessive_bools on EMPI race flags and on craig_reference::RaceResponses (HHS/OMB SPD 15, the eight 45 CFR 1355.44(b)(7) yes/no race answers, #1991); PATCH-payload contracts, option_option on craig-financial’s update DTO (store/rates.rs).

  2. A macro-output entry: askama 0.15.6’s [filter_fn] drops every item attribute, so no item-level expect reaches its output; the suppression is an inner ![expect] in a file module that holds only the [filter_fn] fns (#2713; § Lint regimes, M1–M7). The expect is self-checking: if the macro stops emitting the lint, unfulfilled_lint_expectations fails clippy’s -D warnings. It covers the fns' own signatures and bodies too, which [filter_fn] moves into its output, so they stay thin and call their helpers elsewhere. craig-web’s and craig-portal’s filters/wrappers.rs hold only the wrappers (inline_always, unused_self, unnecessary_wraps; the portal adds trivially_copy_pass_by_ref), spell every path in full (no use) and call the helpers through super::; filters.rs keeps the helpers and tests unsuppressed and re-exports the wrappers. craig-intake’s and craig-bff’s filters.rs hold only t (the first three lints). Each entry declares macro = "askama::filter_fn". utoipa needs none since 5.5.0: its #[derive(OpenApi)] expands modifiers(…) to a for loop, so needless_for_each no longer fires and the nine api/openapi.rs carry no expect.

  3. A cfg-variant entry: an inner allow in the module file compiled into several targets, when the lint is live in some of them only (§ Lint regimes lists the six).

No other crate- or module-level carve-out stands. craig-test-lib’s assertion-mechanism lints are its R1 attribute, not a carve-out. craig-cli carries none: its data lines go to a locked stdout and fail the command on a failed write, its diagnostics go best-effort to stderr (output::data_line! / diag!), request bodies are set through output::set_field, and its subcommand dispatchers carry item `#[expect(clippy::too_many_lines)]`s (§Important-Function).

Estimating surface for new workspace lint promotions

Plan M’s experience: grep-based surface estimates consistently overcount. Plan body §Step 7 estimated ~928 indexing sites from raw grep; actual workspace-clippy emission after cfg_attr(test, allow(X)) test exemption was 119 production-target sites, collapsing further to ~28 after crate-level allows on tool crates (cli, xtask, seed, mock-server). Future tier estimates should grep-and-discount-by-crate-target: count only production-shaped crates first, then subtract tool-crate-allowable patterns.

Plan N Phase B pay-down sweep methodology (2026-06-06)

Phase D blocks on Phase B clear. All 7 OVER budgets must reach historical lock (B1≤8, B2≤49, B3a≤236, B3b≤31, B4≤142, B5≤175, B7≤194) before Step 9 flips the enforcement gate. Gate is report-only during Phase B; pay-down MRs land without the gate firing.

Per-MR cadence:

  1. Run cargo xtask quality-budgets --report for current actual. Note the delta to lock.

  2. Dispatch one Explore subagent to enumerate sites with file:line citations + classify each as (a) TYPE to existing pub DTO, (b) STRUCTURAL-VALUE marker, (c) PARTNER-EDGE-UNTYPED marker, (d) rewrite to drop the annotation (only B3a/B3b — see below).

  3. Apply changes by batch. For marker insertion across many files, use the Python script pattern below.

  4. Re-run cargo xtask quality-budgets --report to confirm the budget reaches lock.

  5. CHANGELOG entry notes the delta + the per-category breakdown.

Marker placement gotcha (Plan N Step 4 lesson): the comment-skip counter looks back exactly one non-empty line. If a serde_json::Value site has an existing doc comment immediately above it, the marker MUST go BETWEEN the doc comment and the Value line — NOT above the doc comment. Otherwise prev_nonempty is the doc comment, not the marker, and the skip doesn’t fire.

// Per-application discovery URL (sandbox-validated against Authentik 2026.2.2)
// STRUCTURAL-VALUE: OIDC provider response — polymorphic per RFC 8414/7517
let disc: serde_json::Value = client.get(...)...;

Reader-readable: the doc comment explains intent, the marker is the lint exemption.

Python script pattern for batch marker insertion (B3b sweep, !600). The script inserts the marker IMMEDIATELY above each Value line, regardless of what’s above. Skips use serde_json::Value; import statements (those are module-level, not call sites).

import re, pathlib
files_and_markers = {
    "path/to/test.rs": "OIDC provider response — polymorphic per RFC 8414/7517",
    # ...
}
VALUE_RE = re.compile(r"serde_json\s*::\s*Value")
MARKER_RE = re.compile(r"//\s*STRUCTURAL-VALUE:")
USE_RE = re.compile(r"^\s*use\s+serde_json::Value")

for fpath, reason in files_and_markers.items():
    p = pathlib.Path(fpath)
    lines = p.read_text().splitlines(keepends=True)
    out = []
    for line in lines:
        if VALUE_RE.search(line) and not USE_RE.match(line) and not MARKER_RE.search(line):
            indent = re.match(r"^(\s*)", line).group(1)
            out.append(f"{indent}// STRUCTURAL-VALUE: {reason}\n")
        out.append(line)
    p.write_text("".join(out))

Always cargo fmt --all after script-driven edits — the inserter doesn’t preserve all rustfmt subtleties.

Marker reason vocabulary (cite ONE of these architectural categories):

  • OIDC — "OIDC provider response — polymorphic per RFC 8414/7517"

  • JDM/zen-engine — "JDM ruleset content — polymorphic per zen-engine spec"

  • Postgres EXPLAIN — "Postgres EXPLAIN plan — polymorphic by design"

  • RabbitMQ envelopes — "RabbitMQ event envelope — polymorphic by design"

  • Remote-verifier / external partner shapes — "remote bot-verifier response — external partner shape (#1331 seam)" / "external partner — Plan L F-064 typed-schema deferred"

  • Encryption envelopes — "encryption envelope {\"v\": \"<ct>\"} — Plan B F-001 shape"

  • CLI plumbing — "CLI input — operator-provided arbitrary JSON"

B3a/B3b TRIVIAL rewrites (Plan N Step 4 lesson — typed_dto_pilot.rs). For let _: serde_json::Value = serde_json::to_value(&x).unwrap(); round-trip assertions, rewrite to serde_json::to_value(&x).expect("<DTO> serializes to JSON");. Drops the binding, drops the annotation, adds explicit error context. The annotation was load-bearing for the round-trip — .expect() preserves intent without triggering the counter.

B7 TYPE strategy (Plan N Step 3 lesson — type to pub-re-exported DTOs). Test-client methods returning Result<ApiResponse<serde_json::Value>> should be typed against an EXISTING pub DTO from a *-contracts crate or craig-intake-sdk. Don’t introduce new contract-crate types as part of the sweep — that’s its own design work. If no pub DTO exists, defer.

Phase B remaining order (after Steps 3–4):

Step Budget Current Lock Delta Strategy

5 (#518)

B5 unwrap_or_default

222

175

47

// SILENT-OK: markers on diagnostic-fallback sites; typed error propagation on real value chains

6 (#519)

B4 #[allow]

332

142

190

2–3 MRs by crate batch; audit each per-item allow for staleness vs. legit reason = "…​"

7 (#520)

B3a Value src

452

236

216

3–4 MRs by service batch; // PARTNER-EDGE-UNTYPED: #441 for partner-edge, // STRUCTURAL-VALUE: for structural

(B1)

route LOC

11

8

3

Incidental — decompose 3 specific route modules during another step’s sweep

(B2)

function LOC

56

49

7

Incidental — decompose 7 specific functions during another step’s sweep

Plan N (Quality-Gate Enforcement) — quality-budget marker comments (2026-06-06)

Plan N Step 2 (#515) introduced three comment markers that the cargo xtask quality-budgets counters honor as documented exemptions. The marker MUST sit on the immediately-preceding non-empty source line (one-line lookback; empty lines are tolerated). Marker above an enclosing attribute is NOT honored — the marker goes immediately above the call/use site:

// PARTNER-EDGE-UNTYPED: #441
let _: serde_json::Value = ...;  // skipped from B3a

#[rustfmt::skip]
// PARTNER-EDGE-UNTYPED: #441
let _: serde_json::Value = ...;  // NOT skipped — marker is above the attribute, not the use

// SILENT-OK: <reason> (B5 unwrap_or_default counter). Use when empty-on-failure is a diagnostic fallback and the empty case is acceptable. Canonical example: extracting an error body for a BadStatus error where the status code already carries the failure signal — an unreadable body shouldn’t mask the diagnosis. Established in crates/craig-partner-*/src/adapter.rs body-extraction sites.

// PARTNER-EDGE-UNTYPED: <ticket> (B3a/B3b serde_json::Value counter). Use for serde_json::Value in partner-edge code awaiting Plan L F-064 typed-schema migration. The ticket reference (#441 for Plan L) makes the exemption time-bound and trackable.

// STRUCTURAL-VALUE: <reason> (B3a/B3b serde_json::Value counter). Use for serde_json::Value that’s structurally untyped by design and cannot be replaced with a typed DTO. Canonical sites: zen-engine rule inputs/outputs (JDM inputs are polymorphic per the rule engine’s contract), authz attributes, encryption envelopes ({"v": "<ct>"}), CLI plumbing where the user provides arbitrary JSON.

-- floor-exempt: <reason> (SQL, the #1307 / ADR-063 D3 destructive-migration floor lint — the one BLOCKING class inside validate-migration-constraints; the FK / NUMERIC-CHECK / session-SET trio stays advisory). A read break — a drop (DROP TABLE / COLUMN / VIEW / MATERIALIZED VIEW / SEQUENCE / TYPE, ALTER TABLE … DROP <col>), a rename, a SET SCHEMA or a column retype (#2369) — in a migration newer than the schema_compat_floor baseline must bump UPDATE schema_compat_floor SET min_required_version = <own version>; in the same file — that is what makes verify-only boot refuse a pre-drop binary. Since #1765 so must a write break on a table the file did not create: an ADD COLUMN … NOT NULL with no surviving DEFAULT (a same-file ALTER COLUMN … DROP DEFAULT counts), or an ADD CONSTRAINT <name> CHECK (…) that drops a quoted literal the name’s earlier definition on that table admitted — an N−1 binary’s write fails 23502 / 23514 (ADR-063 D3 as-built note). Waive ONLY when no released binary reads (or, for the write class, writes) the structure, or still decodes a retyped column (born-and-dropped within one release train — bumping there would foreclose rollback for nothing). Since #2571 so must a binding break on a table the file did not create: a DROP CONSTRAINT the history cannot place as a CHECK (a unique key an N−1 ON CONFLICT targets, a PostgreSQL 18 NOT NULL), a CHECK the same file replaces under a new name, a DROP INDEX of anything but a plain index, DROP NOT NULL / IDENTITY / EXPRESSION, and a DROP DEFAULT on a column the file did not add; so must a routine re-created to raise a refusal under a new constraint name or ERRCODE. Waive when no released binary binds the structure. A bare CHECK drop and a plain-index drop stay out; a same-file DROP DEFAULT on a column added NOT NULL is a write break (#1765). Since #2573 the write class also reads the ALTER statements inside a DO or routine body, as the read class does; a body CREATE owns nothing. The waiver never applies to a break whose statement acts on a runtime-read-only table (a service’s ProcessHooks::with_runtime_read_only list, read from its registration; ADR-063 D4 as amended by #2572). Since #2606 a read break also covers DROP EXTENSION / SCHEMA / DOMAIN, a rename or SET SCHEMA of a domain, schema or extension, and ALTER TABLE … NO INHERIT / DETACH PARTITION; a binding break covers ALTER DOMAIN … DROP NOT NULL / DROP DEFAULT and an unplaceable or replaced domain DROP CONSTRAINT.

Plan N Phase B sweep cadence: each pay-down MR runs cargo xtask quality-budgets --report and notes the delta in CHANGELOG. The gate flips to --fail-on-regression at Plan N Step 9 (the validate quality-budgets gate and the CI car’s quality-budgets line) only after all 7 OVER budgets clear (B1/B2/B3a/B3b/B4/B5/B7 ≤ historical lock).

Validate step numbering and lint carve-outs

cargo xtask validate auto-numbers its steps [N] at runtime via a StepCounter (xtask/src/cmd/validate.rs) — there is no fixed denominator, because the step set varies with --profile and --skip-devstack / --skip-docker (any denominator would be wrong for some invocation); the phase roadmap printed at the top of the run gives the coarse overview instead. Refer to a gate by what it does, never by a step number — the numbers renumber whenever a step is added, removed, or skipped. New workspace clippy lints fire via the existing clippy step and need no new validate step; only behavior-distinct gates (custom subcommands like lint-regime, quality-budgets) are their own steps.

The fast and the full battery (plan merge-trains-gate U1; plan ci-dev-loop D2, #3046). cargo xtask validate --profile fast|full (default full) is a sequencer. full runs the CI car’s lines (§ CI: the car) in the car’s order on the host, each one step of one table, labelled with the line: the gates, then dev clean --any-project (skipped off CI: the stack is the developer’s) and dev start, then the lanes; the battery lane adds the hidden --pre-push debris clear (#1801), which CI’s fresh stack does not need. Each xtask … line runs through the same binary, so a verb re-executes in craig-tools exactly as on CI. fast is the pre-push hook’s battery: fmt, the locked config layers, the fast rows of the gate table (mandatory docs through the host-gateway lint, lint-regime through the four-state contract, the evil-corpus and contention coverage ratchets, the scenario inventory and citation summary, SPDX through the Rust-built HTML gate), machete, clippy, the every-target fetch and cargo nextest --profile ci --lib --bins. It needs no Docker and no devstack, and skips the gates that read the migrations or the hooks (migration-apply isolation, the migration-constraint report, the hooks exec bit), gitleaks, the source-ownership replay, the doc gates, api-docs, the .dockerignore canary, the contested census and the nextest filter terms; the car runs every one of them. The gates are one table, GATES in xtask/src/cmd/validate/gates.rs (§ Precompilation gates); a_fast_run_marks_exactly_the_fast_steps_in_order and a_full_run_marks_one_step_per_car_line_in_order hold dry runs to it. Under full, --skip-docker leaves out the e2e and aux lanes; --skip-devstack leaves out the stack and every lane that needs it, runs the unit tests on the host instead (cargo nextest --profile ci --lib --bins), and lets the canary and gitleaks skip when Docker is unreachable. The developer-machine checks (repository visibility, commit signing) left the battery for cargo xtask doctor (#1739): a runner has no signing key and no glab login.

The clippy passes (#2598, #3057). The clippy lane (cargo xtask test --clippy: the car’s line, and so validate --profile full’s) runs three passes. Two are `cargo clippy --workspace --all-targets --locked — -D warnings. The first pass takes the default features, the set production compiles, so the cfg(not(feature = …)) arms of the battery’s features stay linted. The second adds --features with the battery’s feature set (lanes::BATTERY_FEATURES, the constant the one compile and the battery’s nextest run read), so the code only the battery compiles and runs is held to the same lints: authz-witness, the plugin-* features of craig-web and craig-composition (plugin-ssa-screening ships in release images), craig-intake’s self-signed-tls and its tls_tests. validate --profile fast and bare cargo xtask test’s The third pass is the production graph: `--lib --bins in place of --all-targets (PRODUCTION_CLIPPY_ARGS). With no test target cargo resolves no dev-dependency, so a feature only a dev-dependency turns on is off, as in a production build, and its cfg(not(feature = …)) arm is linted: craig-mq’s no-op fault-injection arms, which both --all-targets passes compile out. It costs about 46 s per car (measured on a 32-core box, after the other two). validate --profile fast and bare cargo xtask test’s lint pre-step run the default pass alone: the car is the blocking gate, and the pre-push hook stays one pass. The default argv is one const (`WORKSPACE_CLIPPY_ARGS), which the second pass and the source-ownership replay derive from. The three are distinct cargo units that sit side by side in the target directory, so the replay after the lane recompiles nothing. the_clippy_lane_lints_the_default_and_the_battery_feature_sets and a_fast_run_lints_the_default_features_only pin this.

Precompilation gates (#3043)

The gates that compile no workspace code are one table, GATES in xtask/src/cmd/validate/gates.rs (plan ci-dev-loop U1). The car runs it as one script: line per row, in order, after fmt and xtask config fetch (§ CI: the car), and validate --profile fast runs its fast rows after publishing the config layers; tests hold both to the table (the_cars_gate_block_is_the_gate_table), and another holds every verb below to the CLI and every cargo xtask lints subcommand to a row. Each gate is a command of its own, which runs the same body; a lints verb marked (#3043) runs the very row. The rows, in run order (fast: the pre-push profile runs it too):

Gate Command Fast

mandatory docs

cargo xtask lints mandatory-docs

yes

plan Status vocabulary

cargo xtask plan-lint

yes

struct method count

cargo xtask lints struct-method-count

yes

silent skips

cargo xtask lints no-silent-skips

yes

sleep polls

cargo xtask lints no-sleep-polls

yes

evil-corpus body-limit probe

cargo xtask lints evil-body-probe

yes

changelog state

cargo xtask changelog check

yes

compose config-source lists current with config-sources.lock (#3143)

cargo xtask config env --check

yes

raw CRAIG_TEST__ env reads

cargo xtask lints test-env-reads

yes

db-error classifier bypass

cargo xtask lints db-error-construction

yes

jurisdiction literals

cargo xtask lints jurisdiction-literals

yes

product-copy jurisdictions

cargo xtask lints product-copy-jurisdictions

yes

DTO cap sync

cargo xtask lints dto-length

yes

secrets in YAML

cargo xtask lints secrets-yaml

yes

Dockerfile hygiene

cargo xtask lints dockerfile-hygiene

yes

host gateway

cargo xtask lints host-gateway

yes

lint regime

cargo xtask lints lint-regime

yes

workspace dependency inheritance

cargo xtask lints workspace-dep-inheritance

yes

advisory-ignore audit

cargo xtask lints advisory-ignore-audit

yes

sops policy

cargo xtask lints sops-policy

yes

release-artifact test-only features

cargo xtask release-artifact-gate

yes

doc-pointer integrity

cargo xtask lints doc-pointer-integrity

yes

docs attribute references

cargo xtask lints doc-attr-refs

yes

quality budgets

cargo xtask quality-budgets --fail-on-regression

yes

fn-name cohesion

cargo xtask lints fn-name-and

yes

four-state contract

cargo xtask lints four-state-contract

yes

migration-apply isolation

cargo xtask lints migration-apply-isolation (#3043)

no

evil-corpus coverage ratchet (§ Coverage ratchets)

cargo xtask validate-evil-corpus-coverage

yes

contention coverage ratchet (§ Coverage ratchets)

cargo xtask validate-contention-coverage

yes

migration constraints (D3 floor blocking)

cargo xtask validate-migration-constraints

no

scenario inventory

cargo xtask scenarios audit

yes

citation audit (summary)

cargo xtask policy audit

yes

SPDX headers

cargo xtask lints spdx (#3043)

yes

JDM rulesets

cargo xtask rules check

yes

authority evidence, both shipped twins

cargo xtask authority-evidence (no arguments, #3043)

yes

authz coverage

cargo xtask validate-authz-coverage --bail-on-bypass

yes

undocumented 403

cargo xtask lints undocumented-403

yes

problem-type status

cargo xtask lints problem-type-status

yes

partner parse-prop coverage

cargo xtask lints parse-prop-coverage

yes

serialize credentials

cargo xtask lints serialize-credentials

yes

tracing PII fields

cargo xtask lints tracing-pii-fields

yes

store-model baseline

cargo xtask lints store-model-baseline

yes

untyped list envelope

cargo xtask lints untyped-list-envelope

yes

Askama template safety

cargo xtask validate-template-safety

yes

BFF query strings

cargo xtask validate-web-query-strings

yes

Rust-built HTML

cargo xtask validate-rust-html

yes

hooks exec bit

cargo xtask lints hooks-exec

no

unused dependencies

cargo machete

yes

Two Docker gates close the car’s gates outside the table: the .dockerignore secret-leak canary (cargo xtask lints dockerignore-canary, #3043) and gitleaks over HEAD’s history (cargo xtask gitleaks, #3043; the verb fails closed without Docker, where validate --skip-devstack skips). Source ownership from dep-info (cargo xtask lints source-ownership, #3043) replays the workspace clippy’s units with --message-format=json, so it is no gate either: the car runs it right after xtask test --clippy, where every unit is fresh (SOURCE_OWNERSHIP). The rustdoc twins compile the workspace, and api-docs --check runs the service binaries, so they are lanes: cargo xtask test --doc runs the twins (testing-reference § Running tests), and api-docs --check reads the binaries dev start compiled, building them itself only where that compile is absent or stale (#3049, testing-reference).

CI: the car (plan ci-dev-loop D2, #3046)

A merge-train car is four jobs: ci-image → xtask → car ∥ docs. The car job is one VM running the developer’s commands, the lines validate --profile full runs on the host (validate::car_lines in xtask/src/cmd/validate/car.rs), each written as the xtask job’s artifact (xtask <verb> is cargo xtask <verb>, #2982). There is no cargo xtask ci: the stages, the registry hand-off between jobs (images*.json, --await-images), the BuildKit container builder and its registry cache retired with xtask/src/cmd/ci/ (#3026). GitLab stops at the first failing line.

Step Lines What it costs and catches

1. Gates

cargo fmt --check --all; xtask config fetch (the locked layers the audits read, #3014); one line per row of the gate table, in order (§ Precompilation gates); xtask lints dockerignore-canary; xtask gitleaks

No workspace compile: a convention break (a missing SPDX header, a stray .rs outside the lint walk) fails here.

2. Stack

if xtask car-scope; then exit 0; fi (the docs-only stop, below; the one line that is not a verb), then xtask dev clean --any-project (the #2946 purge: every container, volume and network carrying the checkout’s compose label, which a reused VM may still hold), then xtask dev start

The one compile in craig-tools (musl, --profile devstack, #3044), the copy-only devstack images, the infra images, identity, health and seed.

3. Lanes

xtask test --unit $CRAIG_UNIT_FLAG (a train sets --leave-to-battery: the battery’s --run-ignored=all runs those tests, #2995); xtask test --clippy (three passes, § The clippy passes); xtask lints source-ownership (replays the default-feature pass, #3043); xtask test --doc; xtask test --integration --profile ci-integration (on CI the every-target fetch, the contested census and the nextest filter terms, then the whole battery body); xtask api-docs --check; xtask e2e, xtask e2e --scenario subsidy-generator-backlog --scenario foster-home-at-capacity --grep @seed-variant (the three tests that skip on the base seed, Testing Reference (CRAIG) § Seed Data, #2610) and xtask e2e --degraded (each reseeds first, after the battery mutated the seed); xtask sdk-test; xtask security --skip-zap --skip-fuzz; xtask perf --profile smoke

Every lane runs from the one compile; cheapest and most deterministic first.

after_script

.stack-teardown (container logs when the car failed, then dev clean)

The stack’s logs for diagnosis (#2939).

.car-rules makes the car block every merge train and every plain MR (allow_failure: false on both, no changes: on either; plan ci-dev-loop D4, #3028, #3101).

A docs-only car stops after its gates (#3101, the plan). No path list decides whether the car runs: a changes: list runs a job when any path matches, so a path it forgot counted as documentation. The car starts every time, runs every gate, and then asks xtask car-scope, which exits 0 only when it has proved both of these:

  • HEAD is the merge commit GitLab made for this pipeline: the event type is merged_result or merge_train, HEAD has two parents, and they are CI_MERGE_REQUEST_TARGET_BRANCH_SHA and CI_MERGE_REQUEST_SOURCE_BRANCH_SHA. A detached pipeline always runs the whole car.

  • Every path the merge changes (git diff --no-renames HEAD^1 HEAD, deletions included) is documentation no lane reads.

On a yes the job ends there as a success, about a minute and a half in: no stack, no lanes, and so no JUnit report. Any other answer, a git failure included, runs the whole car. validate --profile full on a host never stops early.

The definition is is_documentation in xtask/src/car_scope.rs, an allowlist: .adoc, .png and .svg under docs/modules/; .adoc under changelog.d/ and changelog/; the root CHANGELOG.adoc, README.adoc, CONTRIBUTING.adoc and SECURITY.adoc. LANE_READ takes back what a lane reads: pages/api/ (api-docs --check and the route censuses), testing-reference.adoc, deployment-guide.adoc, cli.adoc and everything under operations/ (each read by a test). Everything else is code, including docs/extensions/, docs/antora.yml and the JSON attachments. A census in xtask/src/car_scope_tests.rs lists every tracked Rust file with a line, outside // comments, that names a documentation tree or root file, and how it uses it; a new reader fails there until it has a row, and a lane’s read must be a path the definition rejects. The census reads Rust only, and a path assembled from pieces escapes it.

The car sets GIT_DEPTH: "0" (gitleaks reads the whole history) and NEXTEST_STATUS_LEVEL/NEXTEST_FINAL_STATUS_LEVEL: fail, which craig-tools inherits: GitLab keeps 4 MB of one job’s log, and the JUnit reports keep every result. Leaves outside the car: identity-multibackend runs xtask identity matrix; ci-image runs cargo xtask ci-image --ensure (craig-ci, keyed by the SHA-256 of ci/Dockerfile.ci and rust-toolchain.toml; --tag prints it, --bump re-pins CRAIG_CI_IMAGE_TAG), the one cargo xtask line, since it runs before the xtask job; only release-build pushes images (#3045).

The same line keeps a second job image, craig-docs (ci/Dockerfile.docs, #3100): the Antora image by digest with chromium, mermaid-cli 10.6.1 and @antora/lunr-extension, which docs, pages and stop_review run in, so no docs job downloads a package at run time (the Alpine and npm downloads had stalled jobs for over an hour). Its tag is the SHA-256 of ci/Dockerfile.docs alone, pinned in CRAIG_DOCS_IMAGE_TAG; ci-image --tag prints both tags, --bump re-pins both, and --ensure builds and pushes $CI_REGISTRY_IMAGE/ci/craig-docs:<tag> only when the registry lacks it. Every Antora job needs ci-image, so the first pipeline that carries a new tag builds the image before docs starts, and a merge request that edits the Dockerfile is the pipeline that builds it. If that build fails, ci-image fails and no later job starts. The Antora jobs have timeout: 30m: a build takes 2 to 10 minutes, so a stalled one fails long before the car’s two hours.

xtask/src/pipeline_tests.rs holds the YAML to it: the car’s gate block equals the gate table, one line per gate in its order; the car’s whole script equals validate::car_lines; every car line is cargo fmt, cargo machete or xtask <verb>, and none runs xtask ci, docker, cargo nextest or cargo build; dev clean --any-project precedes dev start and lints source-ownership follows test --clippy; the docs-only stop is the one other line, in its exact text, right after xtask gitleaks and right before the purge; the car blocks a train and an MR whatever either changed, with no changes: on its rules; --push appears only in release-build; every job has needs:; and the file stays under 500 lines. Beyond the car: every other job’s script: line is an xtask verb, on the test’s allow-list (artifact moves, the Antora and release tools, the supply-chain scanners) or one of its own lines (ci-image’s bootstrap, the `xtask job’s one cargo build, the car’s two cargo plugins, release-build’s logins and bake lines), and no other line runs `docker compose, cargo nextest, cargo build or docker build. A job that runs xtask needs the xtask job’s artifact and finds it first on PATH. Every job runs craig-ci, craig-docs, the release tool or a GitLab template’s image and waits on ci-image; CRAIG_CI_IMAGE_TAG and CRAIG_DOCS_IMAGE_TAG each equal the checkout’s input hash (an unbumped Dockerfile edit fails, naming ci-image --bump); the Antora jobs run craig-docs with no before_script and a 30-minute timeout; and no line installs a tool outside the test’s short allow-list. On a GitLab docker executor whose /builds is a Docker volume, a verb that hands paths to the daemon first re-runs itself from the volume’s VM path (xtask/src/builds_alias.rs; testing-reference § CI stages).

Static regex expect() exception: Regex::new(r"…​").expect("static regex") is the one acceptable expect_used carve-out. Failure indicates a programmer typo in the pattern, not a runtime concern. Use [expect(clippy::expect_used, reason = "static regex; failure is a programmer bug")] on the fn or statement (an outer [allow] is denied, § Lint regimes). Prefer LazyLock<Regex> for hot paths.

When a rule conflicts with planned work, follow the "When you can’t comply" protocol in the coding-conventions standard — alert BEFORE writing the violating code; justify the carve-out with a subagent-verified #[expect(…​, reason = "…​")] (§ Suppression vocabulary).

Plan P (Nursery Promotion Sweep) — workspace state additions (2026-06-06)

Plan P (plans/archive/nursery-promotion-sweep.adoc) closed by flipping 12 nursery lints from allow → deny + ADR-031 documents the triage pattern. The 4 workspace allows + 2 crate-level allows that remain are architectural carve-outs, not deferred work:

  • missing_const_for_fn allow — workspace grep confirmed ZERO callers use these fns in const context. Const-promotion is cosmetic; adds maintenance friction without enabling any real const-context use. Decision is permanent, NOT pending future revisit.

  • option_if_let_else allow — 3 per-fn allows on tools/craig-mock-server/{doe,empi,ies}.rs handler match arms (match wins readability for multi-line Response-building bodies) + 1 nursery false-positive on craig-common::pagination::PageResponse<T> where the lint fires on the Vec<T> type-parameter span. Struct- and field-level #[allow] attributes do NOT suppress the lint (the diagnostic span resolves inside a derive-macro expansion). Permanent.

  • redundant_pub_crate allow — Plan D F-023 (#470) migrated 1,065 items to pub(crate) as a deliberate intra-crate API marker. The lint’s pub suggestion would defeat the visibility-marker intent (defense against accidental cross-crate API promotion during refactors). Permanent.

  • future_not_send allow — 140+ emissions across 5 architectural site classes, ALL intentionally !Send by design:

    1. services/craig-cli/src/clients/** (33) — &Transport across awaits; CLI is single-shot one-binary.

    2. crates/craig-test-lib/src/harness.rs (98) — &self methods yielding borrow futures; tests run single-threaded.

    3. crates/craig-test-lib/src/client.rs (4) — same pattern.

    4. crates/craig-zen-eval/src/thread.rs (1) — JDM evaluator is !Send per zen-engine + Rhai engine constraints (ADR-024 § Architectural Constraints dedicates a !Send eval thread).

    5. services/craig-web/src/routes/mod.rs (3) — BFF route helpers hold &AppState across awaits; AppState already wraps shared state in Arc.

      Refactoring 140 sites to Arc<RwLock<T>> would lose borrow-check guarantees for negative perf value. Permanent.

  • too_long_first_doc_paragraph crate-level allows in craig-auth + craig-api — clippy nursery emits this lint with no source span when the trigger is inside a derive-macro expansion (thiserror::Error / utoipa::OpenApi / utoipa::ToSchema / sqlx). All authored doc paragraphs were swept; the macro-expansion sites cannot be locally suppressed via attribute on the item. Crate-level allow scopes the impact.

Macro-expansion lint false-positive pattern (Plan P lesson) — when a nursery lint fires with no source span (or a span pointing at a type-parameter or struct field that has no expression), it’s emitting from inside a derive-macro expansion. A local suppression on the offending item OR field WILL NOT reach it. Two escape hatches: (1) for an attribute macro on fns, a macro-output file module of those fns (§ Suppression vocabulary); a derive’s output fits no registry category, so only (2) reaches it; (2) workspace allow with documented rationale (when the false-positive is widespread). Plan P encountered this on option_if_let_else (PageResponse field — workspace allow retained) and too_long_first_doc_paragraph (craig-auth + craig-api — crate-level allow).

Resuming pre-Plan-M crate authoring (Plan L Step 3 batch 4 lesson, 2026-06-06)

When resuming feature work authored before Plan M closed (i.e., the branch still carries the Plan H Step 2 transitional 6-lint #![allow(clippy::pedantic | clippy::cargo | …​)] block at the lib root), the lint-regime check (xtask validate) will reject the push: R5 fails a group suppression, and every other inner allow must be registered (§ Lint regimes). Fix the lib root before pushing:

  1. Strip #![forbid(unsafe_code)] if present (workspace unsafe_code = "deny" from Plan M Step 11 covers it).

  2. Lift the Plan H Step 2 transitional allow block (the 6-lint #![allow(clippy::pedantic, clippy::cargo, clippy::missing_docs_in_private_items, clippy::too_many_lines, clippy::cognitive_complexity, clippy::ignored_unit_patterns)]).

  3. Run cargo xtask lints lint-regime --fix: it writes the root’s test-regime attribute and moves the set lints out of its other test-scope attributes (§ Lint regimes).

Production code from pre-Plan-M crates typically passes the post-lift workspace clippy check without further changes (Plan M’s clean-up sweeps were per-emission-driven; new crates authored to the Plan H discipline rarely had problematic patterns). Integration test files at tests/*.rs are crate roots too: the lint-regime check holds each to its R1 test-regime attribute, which the same --fix writes.

Quality-budget enforcement gate (Plan N Step 9, #522)

Eight code-quality budgets (B1–B9 less the retired B4 and B6, with B3 split into B3a/B3b) are tracked by cargo xtask quality-budgets, recorded in xtask/baselines/quality-budgets.toml, and enforced as a blocking gate as a gate-table row (the pre-push battery and the car’s xtask quality-budgets --fail-on-regression line). A budget whose count differs from its record blocks merge, in either direction (see § Semantic note).

B9 — the function-length ratchet (2292). The rule is that a function is at most 40 lines. Clippy denies too_many_lines at that threshold, and a longer production function passes by carrying its own [expect(clippy::too_many_lines, reason = …)]; clippy does not limit how many functions do. B9 does: it counts the production functions that span more than 40 lines (B2’s walk and B2’s span, signature to closing brace, test functions and tests/ trees excluded) and is locked at the count on the day it was added, 984. It only shrinks. A new function over 40 lines raises the count and fails the gate, with or without an #[expect]; a long function touched for other work is shortened in the same change and the record is lowered with cargo xtask baselines bless (maintainer ruling, 2026-11-12: ratchet, do not rewrite). B2, the count over 100 lines, stays as the tighter cap on the worst cases.

B8 — duplicate-block budget (copy-paste DRY class, 889). Counts near-duplicate impl/fn bodies in production /src/: each non-test body ≥ 40 normalized tokens is reduced to a structural signature (identifiers + literals erased; control-flow keywords, punctuation, and nesting kept), and the metric is the redundant-copy count — for each group of ≥ 2 identical signatures, group_size − 1. Coarse by design: it caps the *size of the copy-paste class, it does not localize it. Seeded at the current count and shrink-only — a B8 regression is fixed by a real refactor (dedup into a shared helper), never** an autonomous lock-raise. It creates downward pressure on the partner-adapter / CLI-wrapper / registry families the 2026-06-28 prevention-gap analysis flagged. Test code is excluded so volatile test boilerplate can’t flap a merge-blocking gate: tests/ dirs, [test] fns, inline [cfg(test)] modules, and the files a test-only-cfg mod x; loads ([cfg(test)] or [cfg(all(test, …))], with or without [path], and every module file under it; #2045), resolved by the #2207 mount resolver, which lints fn-name-and (#1921) and the contested-surface census (#2475) also use.

Walk and B1 scope (2618, #2467, #2563, #2602). Every source-walking budget walks the lint roots (lint_scan::lint_roots: the workspace members' top-level trees), except B7, which walks its clients directory (crates/craig-test-lib/src/clients) through the shared fail-closed reader, so a walk error, an unreadable file, or for B1, B2, B7 and B8 an unparsable one fails the budget, naming it, and B7 refuses a missing clients directory instead of reading it as 0. A second checkout nested in the tree (a .worktrees/ directory, say) lies outside the roots and is not counted (#2467). B1 counts the route files over 500 lines at any depth. A module-root file (services//src/api/.rs, services//src/api.rs since #2563, services/craig-web/src/routes/.rs) counts whatever it holds. A nested file (below services/*/src/api/<dir>/ or services/craig-web/src/routes/<dir>/) counts unless only a test build compiles it (#2602): a file that a cfg(test) mod x; loads, by name or by [path], and every module file under it, found by the mount resolver B8 uses. A file’s name exempts nothing. So a route module that outgrows the threshold is split into files under its own directory, and its tests go in a file mounted under cfg(test) there.

B4 — retired (2715). B4 counted outer [allow(…)] attributes from tokens (#2599: the allow(…) an outer cfg_attr applied and one in a macro body included). Once allow_attributes was denied and every remaining inner suppression registered one to one (§ Lint regimes), the count added nothing; run_b4, its counter, its threshold, its lock key B4_allow_attributes and lint_tokens::outer_allow_count are gone.

B6 — retired (#2659, 2026-10-24); cargo-deny gates duplicate versions. B6 counted redundant Cargo.lock versions (Σ per-name N−1 over every platform, #991) and capped only the total, so a new duplicate could replace one that went away, while deny.toml’s `multiple-versions = "warn" failed nothing. cargo deny check bans is now the one gate: [bans] multiple-versions = "deny" over the [graph] targets CRAIG builds (x86_64 and aarch64 musl, the shipped images; x86_64 gnu, the battery host), so the result is the same on every host, and each accepted duplicate is a [bans] skip entry naming the version and the reason it cannot be deduplicated today. A new duplicate fails the check by name; a skip that stops matching is reported, so the list shrinks as upstreams converge. The windows-* stack is outside those targets. The lock key B6_duplicate_deps is gone.

B5 10→11 lock-raise (2026-06-18, template resync). The +1 came from adopting the former agent template’s doc-sync engine source byte-verbatim: it used .unwrap_or_default() on an Option display. The engine was byte-synced from upstream, so rewriting it to satisfy a local budget would have forked it — the sanctioned lock-raise applied instead. (The same resync raised the since-retired B4 88→89.) The engine left the tree in #635 and the build in #2880.

When the gate fires

The validate step prints the budget table, then bails. An OVER row is a budget above its record; a STALE row is one below it (§ Stale records). Typical responses to OVER:

  1. Fix the regression (default). Drop the new violation back below the locked floor. For most budgets the answer is mechanical: extract a helper to bring B2 back under 100 LOC, replace serde_json::Value with a typed DTO for B3a, swap unwrap_or_default() for explicit error handling for B5, etc. Marker comments (// SILENT-OK, // PARTNER-EDGE-UNTYPED, // STRUCTURAL-VALUE) documented in the xtask/src/cmd/quality_budgets.rs module doc exist for legitimate exemptions per budget (the marker must sit on the immediately-preceding non-empty line of the call site).

B3a scope is path-based, not attribute-based. B3a counts the literal serde_json::Value text on any line under a src/ path — including occurrences inside an inline [cfg(test)] mod tests module (those count as src/B3a, not B3b, which only counts tests/-directory files) and even occurrences inside comments. The counter is a per-line text match, not an AST walk, so it does not skip test modules or commented-out code. Exempt a genuine occurrence only with an immediately-preceding // STRUCTURAL-VALUE: (or // PARTNER-EDGE-UNTYPED:) marker on the prior non-empty line — the marker is the sole way to suppress a match; there is no [cfg(test)] carve-out. Prefer serde_json::json! / typed shapes in test code so the marker is reserved for genuinely-polymorphic sites.

  1. Raise the record (only with rationale). When the regression is intentional and approved — e.g. shipping a deliberately wide one-screen orchestrator that fits the §Style "decompose unless decomposition makes the codebase worse" carve-out — raise the record with:

    cargo xtask baselines bless --only quality-budgets --allow-growth "<why>"

    The reason is required, covers the one ledger --only names, and is written into the ledger file as last_exception, so it is in the diff under review. The MR description MUST also document (a) which budget changed, (b) why the regression is structurally correct, (c) why the §Style carve-out applies. Without that rationale, reviewers reject the raise; the gate is a tripwire, not a rubber stamp.

Stale records

A count below its record fails the gate as STALE (#2300): a record above the truth is headroom nobody reviewed. The change that lowers a count lowers the record with it:

cargo xtask baselines bless --only quality-budgets

Lowering needs no reason. The ledger file commits alongside the cleanup.

Semantic note

The record is the only ceiling. The ledger is read with no defaults (xtask/src/baseline.rs): a missing file or a missing budget key is an error, and a recorded 0 is a ceiling of 0. Two earlier formulas failed open and are gone: max(threshold, locked) masked B1 (8→11) and B2 (49→56) behind their thresholds (#515), and its successor read a locked 0, a missing key or a missing file as "not locked" and fell back to the threshold (#2300).

Function cohesion enforcement gate (Plan R Step 4, #543)

cargo xtask lints fn-name-and is enforced as a blocking gate as a gate-table row (the pre-push battery and the car’s xtask lints fn-name-and line). The lint scans every production fn name under the production roots (lint_scan::production_roots: crates/, plugins/, services/ and tools/ today; xtask is dev tooling and is not walked, 2299; the walk excludes target/ and test code in each shape the tree uses: a tests/ directory; an inline fn or module whose cfg predicate requires test, i.e. [cfg(test)] or [cfg(all(test, …))]; a file such a test-only mod x; declaration mounts, at file scope or inside an inline module (not one that itself carries [path]), with or without [path = "…"], together with every module under it (#1921); and a whole-file ![cfg(test)]. A cfg_attr(test, …), cfg(any(test, …)) or cfg(not(test)) item still compiles in production and is scanned) for and outside the operand-pattern allowlist (and_or / _and_one / _and_two / _and_three / _and_n / _and_back / _and_friends). Drift in either direction blocks merge: new violations not on the opt-out list, OR stale opt-out entries whose fn has been renamed/decomposed/removed.

This gate is a proxy, not a cohesion proof. It catches only the and naming tell — it cannot catch a single-noun-but-multi-purpose function, e.g. a process_record that secretly validates, persists, AND emits an event. A green gate does not establish that a function does one thing; that remains a human-review concern (the J6 cohesion question in the pre-commit protocol), with the workspace clippy::cognitive_complexity = "deny" lint as a partial multi-branch backstop.

When the gate fires

The lint prints the offending entries + remediation instructions. Two paths forward:

  1. Rename or decompose (default). The "no and" rule says a function should do one thing; the and in the name admits two responsibilities. Typical fixes:

    • Split into two single-purpose helpers; the caller composes (e.g. parse_and_validate_X → parse_X + validate_X).

    • Rename to a single-verb concept that captures the shared abstraction (e.g. log_and_generic_500 → emit_internal_500).

    • For 2-tx orchestrators, rename to a single noun-phrase that captures the orchestration ("pipeline", "cascade", "round-trip").

  2. Add to opt-out with rationale. Plan R only when decomposition makes the code WORSE — Plan Q’s §Style "decompose unless decomposition makes the codebase worse" doctrine applies. Add the path::fn_name to the opt_out table of xtask/baselines/fn-name-and.toml, with the reason as its value, citing the specific §Style carve-out:

    "crates/foo/src/bar.rs::do_X_and_Y" = "§Style §Important-Function — fuses (...) so the (...) control flow is reviewable on one screen; splitting fragments (...)."

    The MR description must reference the carve-out. Without the reason + MR justification, reviewers reject the opt-out addition, and the gate itself fails an entry whose reason is blank. cargo xtask baselines bless --only fn-name-and removes entries whose fn is gone, each with its reason; it never adds one.

Stale opt-out (the inverse failure)

When a fn on the opt-out list is renamed, decomposed, or deleted, the entry becomes stale. The lint fails on this too — it’s the same monotonic-shrinkage discipline as the coverage-signature baseline (see § Coverage-signature gate). Remove the obsolete entry from the opt-out file (or re-bless if a sweep cleared multiple entries at once).

Existing rationale categories (Plan R Step 3 baseline)

One baseline entry survives (verify_jws_and_dedup_replay, category 1); categories 2 and 3 have no entry since xtask left the walk (#2299) and stay valid for future entries:

  1. §Style §Important-Function — fns with existing #[expect(clippy::cognitive_complexity)] rationales that defend a single converge point (uniform-401 boundary, response-buffering ownership thread, two-phase compensation tx).

  2. Lint-internal naming — helpers OWNED by a lint whose name reflects what the lint does; renaming hides the lint’s domain.

  3. Bootstrap with one-screen narrative arc (Plan Q §Style carve-out) — phase orchestrators that run sequential gates in execution order; the and lists the gates in run-order; splitting fragments a phase boundary.

New entries that don’t fit one of these three categories require a NEW rationale category articulated in the MR description.

Coverage ratchets: evil-corpus and contention (#880, #886, #2674)

Two gate-table rows hold handler coverage to a shrink-only baseline. Both run in validate --profile fast (the pre-push hook) and in the car, and each is a verb of its own:

Gate Handlers in scope (#[utoipa::path] fns under services//src/api/* and services/*/src/api.rs) Covered when the fn name appears in Baseline

cargo xtask validate-evil-corpus-coverage

every post, put and patch handler

a evil.rs file under the service’s tests/

xtask/baselines/evil-corpus-uncovered.toml

cargo xtask validate-contention-coverage

every put and patch handler, and a post handler whose name holds a transition verb (TRANSITION_VERBS)

a concurrent.rs or toctou.rs file under the service’s tests/

xtask/baselines/contention-uncovered.toml

A handler is waived by // evil-corpus: skip — <reason> or // contention: skip — <reason> in the comment block directly above its first attribute (the block // authz: skip shares, § Authz coverage gate); the reason is required. A handler in scope that is neither covered nor waived is uncovered.

The rule. The uncovered handlers of each gate must be exactly the lines of its baseline. The comparison is a set comparison on the key <workspace-relative file>::<fn>:

  • An uncovered handler with no baseline line fails, by key. The three ways out: name the handler in a hostile-input test (or a concurrency test, for the contention gate); waive it with the skip comment and a reason; or add its line to the baseline with a reason, by hand, where a reviewer sees it.

  • A baseline line whose handler is not uncovered fails as stale, by key: the handler is now covered or waived, or was renamed, moved or deleted. Delete the line in the same change. A line that stayed would excuse the same handler if it lost its coverage later.

So a baseline only shrinks, and a new mutating handler arrives with its tests. A covered handler whose test mention is removed becomes an uncovered handler with no baseline line, so it fails: that is how a falling covered count fails. The covered count itself is not pinned, so deleting a covered handler together with its tests passes.

The baseline file. A ledger under xtask/baselines/: one "<file>::<fn>" = "<reason>" entry per handler. The load refuses a missing file, an entry without a reason, a key that is not a <file>::<fn>, and (by the file format) a duplicate key. The entries present when the ratchet landed share the reason predates the ratchet (#2674); a line added later states its own. cargo xtask baselines bless --only evil-corpus-uncovered (or contention-uncovered) deletes the stale entries and adds none, so it cannot admit a new uncovered handler. Because the key holds the file and the fn name, a rename or a move shows as one stale line and one new uncovered handler.

What the gates do not see. The mapping is by name: a handler whose name appears in the test text for another reason reads as covered, and the ratchet holds the set this mapping reports without making it more precise. Each verb prints the counts, the waivers and the first uncovered handlers (CRAIG_EVIL_COVERAGE_FULL=1 / CRAIG_CONTENTION_COVERAGE_FULL=1 print them all).

Implementation: the scans are xtask/src/cmd/validate_evil_corpus_coverage.rs and validate_contention_coverage.rs; the baseline load and the comparison are xtask/src/cmd/coverage_ratchet.rs, whose tests include the_committed_baselines_are_exactly_the_trees_uncovered_handlers over this repository’s own tree.

SQL data-consistency invariant gate (#860)

craig-manage invariants runs the zero-rows SQL catalog under crates/craig-invariants/sql/<service>/.sql (each file is a SELECT that MUST return zero rows; non-zero rows are a violation) against the seeded + test-exercised devstack DBs. Since #860 it is *wired into the pre-push battery at the xtask validate invariants step (invariants::run_gate), immediately after the integration suite has exercised the DBs. The car’s battery lane runs the same step (xtask test --integration), and on a merge train the car gates the merge (ADR-086).

Curated blocking subset. Only invariant NAMES in BLOCKING_INVARIANTS (in xtask/src/cmd/invariants.rs) fail the gate; every other catalogued invariant is report-only (printed, non-failing). The blocking set holds only invariants that are green by construction against a fresh devstack:

  • ffp_amount_stale — GENERATED-column-enforced (#861).

  • occupancy_mismatch, occupancy_over_capacity — trigger- + CHECK-enforced (#761/#780).

  • day_count_gross_consistent — write-time consistency the seed + handlers satisfy (#760/#773).

Report-only invariants include grace-window/timing checks (retried_never_reterminal, stuck_pending_transactions) and invariants tracking still-open fixes (validated_with_errors → #782, null_rule_output → #785) — a known-open defect must not red-gate the battery. Promote a report-only invariant into BLOCKING_INVARIANTS only once its fix has landed and it is green against a fresh devstack. Preview the gate outcome manually with craig-manage invariants --gate; a full non-gated report is craig-manage invariants. The financial↔placement cross-DB "void every payment on an ended placement" invariant (#776) is not expressible in this single-DB sweeper and is covered by integration tests instead.

Caregiver-coverage report (#1852, report-only). Immediately after the invariants gate, validate prints the summary line of craig-manage caregiver-coverage through the advisory helper (plus its per-county rows): the count of ACTIVE family placements whose unit (the foster home, or the kinship household a home-less row names, #2058) has no caregiver_bindings row current on the business date, per jurisdiction / county / unit kind. It is the data-gap reading the deployment guide’s rollout order requires before CRAIG_FINANCIALSUBSIDY_CAREGIVER_CHECKENABLED is flipped (plan portals Decision 11) and never fails the battery — a missing caregiver_bindings table reads as SKIP, and a failed read prints skipped:. Expect a fresh devstack to report no gap (the seed binds a caregiver on every family unit, #2060), except fixture C before its start on the 15th of the as-of month; --strict is the operator’s opt-in to exit non-zero on any gap.

Field-encryption seed verification gate (epic &66 C6, ADR-048 §D6)

cargo xtask verify-seed --expect {keyless,keyed} verifies the devstack seed’s field-encryption state against the mode the caller asserts (never auto-detected — an auto gate would pass a silent key-mount failure vacuously). It re-checks the craig-seed one-shot completed (a state-aware poll, not the old exit-code-only read that misclassified a still-running container; when the exited container has been pruned — routine docker container prune housekeeping — the durable _seed_marker sql-phase row the seed transaction committed stands in as the completion evidence, #1420) and asserts, on the raw craig_cases DB, that every covered column and crypto_key_lineage.kcv matches the expected mode. It is wired into the pre-push battery at the xtask validate devstack phase (--expect keyed, before the mutating integration suite) and, non-blocking, into the .gitlab-ci.yml pentest job (allow_failure, main/schedule). Both call sites assert --expect keyed since C7 (#987) activated devstack encryption; the CI side receives the key from the repo-committed encrypted store, decrypted by cargo xtask secrets write-field-key with the masked+protected CRAIG_CI_AGE_KEY identity in the pinned devtools container (ADR-048 §D5 as amended by ADR-064 U7, #1385 — an unset variable is a hard error, never a keyless CI devstack). Run manually against a running devstack with cargo xtask verify-seed --expect keyed (add CRAIG_CASES__DATABASE_URL=… to skip port reconciliation).

Context-tier hygiene gates (#615)

Agent context lives in tiers, each pointing DOWN to the next when it doesn’t answer a question:

  • memory (gadhs/pi’s governed memory) — ONLY machine/user-specific facts for agents on this box (preferences, shell/path/devstack quirks). Never work state: that lives in GitLab.

  • AGENTS.md + docs/modules/standards/ — CRAIG’s project map, dated overrides and review rules (AGENTS.md, read by gadhs/pi, which injects the agency-wide rules itself) backed by the full-prose standards (the standards module).

  • Antora (docs/modules/ROOT/) — all project knowledge (architecture, ADRs, plans, service/data-model/crate catalogs) + this project’s convention complements (this page, Testing Reference (CRAIG)). The canonical home; one fact, one home.

The failure this guards against (the #613 right-sizing): a doc re-grows into a catalog that duplicates Antora and drifts stale. The gate targets the structure that lets facts go stale, not the facts themselves (undecidable):

doc-pointer integrity (cargo xtask lints doc-pointer-integrity, blocking). Every markdown link AND every repo-rooted path pointer (e.g. docs/modules/ROOT/pages/services.adoc) in AGENTS.md must resolve to a live file, and a missing AGENTS.md fails the gate (#2652). AGENTS.md is the agent project map — a pointer map into Antora — so this catches pointer-rot (a pointer at a moved/archived page). Scope is AGENTS.md only; glob/template/module/URL tokens + non-rooted bare filenames are illustrative and skipped, and prose docs (this file, Testing Reference (CRAIG), …) are not scanned.

The gate keeps AGENTS.md’s pointers valid so the canonical detail stays in Antora (near the source it describes) where it can’t rot in a second place. Until #2882 it scanned the former agent index, and an advisory `cargo xtask audit-memory reported on the former agent’s per-user memory directory; AGENTS.md and pi’s governed memory replaced them. See the delivery-protocol standard § Context Hygiene for the policy.

Docs attribute-reference gate (#2093)

Wired into cargo xtask validate (blocking, right after the doc-pointer-integrity gate; standalone: cargo xtask lints doc-attr-refs). The docs CI job builds the site with --log-failure-level=warn under Antora’s attribute-missing: warn, so each reference to an undefined attribute fails it with "skipping reference to missing attribute" (#1896, #2387); a reference to a defined one renders that attribute’s value instead. This gate is the job’s local, pure-Rust proxy in the pre-push battery. It reads every tracked .adoc file under docs/modules/ (pages, navs and the plan template) and fails on each unescaped reference to an undefined attribute, reported by file, line and reference. Zero baseline, no allowlist.

  • A reference is Asciidoctor’s: a { followed by a word character, then word characters or -, then }, such as {id}, {case_id}, {j} or {300}. It is read in prose, titles, list items, table cells and attribute-entry values, and inside backticks too: inline code is not verbatim, so a route such as /v1/cases/{id} written in backticks is still a reference.

  • Not flagged: listing, literal, passthrough and comment blocks; Markdown fences; literal paragraphs (an indented line that starts a block and is not a list item or a Markdown thematic break, through the next blank line, ` continuation, block attribute line or delimiter; a block starts after a blank line, block attribute line, ` continuation or compound delimiter, and after a block title, section title, attribute entry, block macro or thematic or page break that itself starts a block, while inside a paragraph each of those is its text); comment lines (// then anything but a third /, so ///text is read); inline passthroughs; a reference escaped by a backslash before its { or its }; and a defined attribute, matched case-insensitively. Defined means a key of asciidoc.attributes in antora-playbook.yml or docs/antora.yml, an attribute entry earlier on the same page, an Asciidoctor built-in such as {nbsp}, {empty} or {docname}, or an Antora page attribute (a name that begins page-). The forms, as source:

    ----  ....  ++++  ////  ```          verbatim block delimiters: never read
    // a comment line                    never read
    +{id}+  ++{id}++  +++{id}+++  $${id}$$  pass:[{id}]   inline passthroughs: not read
    \{id}  {id\}                         escaped: renders {id}
  • Accepted limits, where Antora in CI stays the authority: a block whose subs turn attributes back on is still skipped; the {set:name:value} and {counter:name} forms, a literal (l) table cell and a passthrough that spans lines are not modelled; an attribute entry counts wherever it appears; a defined attribute written as a placeholder renders that attribute’s value unflagged, except {description} and {keywords}, which are flagged because a page defines them only for its metadata (#2406); and a paragraph made verbatim by its block attribute line alone ([source], [literal], [listing], [pass] or [comment] with no delimiter) is still read: add the ---- or …​. delimiters, never an escape; and a preprocessor directive (include::, ifdef:: and the like) is read as an ordinary line.

  • The fix is an escape or literal monospace, as below. Archived plans are frozen, and an escape is the one edit allowed there. The docs/antora.yml attribute shims (#1337) date from when the standards pages were byte-locked syncs that could not be escaped locally; the pages are CRAIG-owned since #2881, so a new token is escaped in place and no new shim is added.

    `/v1/cases/\{id}`    renders  /v1/cases/{id}
    `+/v1/cases/{id}+`   renders  /v1/cases/{id}  (literal monospace)

Implementation: xtask/src/cmd/lints/doc_attr_refs.rs and its tests module.

Plan-completion gate (#1701)

cargo xtask plan-lint --done <plan> is the mechanical completion check the plan-lifecycle rule names — run it at close-out, after the plan moved to plans/archive/, its nav.adoc entry was removed and its plans/archive.adoc row added, and BEFORE Status flips to Done. It is not a validate step: one plan per run, read-only, exit-free inside (plan_done::Outcome), plan_lint::run owns the exit code. The invocation (with its exemptions) belongs in the close-out commit message.

Blocking (exit 1):

  • a #N the plan references that is not closed — one glab api projects/:id/issues/N GET per distinct ref; --allow-open N[,N…] exempts standing trackers (#1073) and the follow-ups the close-out filed;

  • a backticked repo path that does not resolve — a citation resolves when it is a tracked path (git ls-files), a /-suffix of one (the crate-/page-relative "Files Touched" convention: src/events.rs, api/craig-cases.adoc), or, for a trailing-/ token, a tracked directory; --allow-missing PATH[,PATH…] exempts paths the plan records as deleted or renamed (archived plans are immutable in spirit — ADR-030 §2 — so exempt, do not rewrite);

  • the literal TBD / this MR (word-bounded, case-insensitive);

  • an xref:plans/<stem>.adoc still in nav.adoc (the message names the heading path, e.g. Plans / Active).

Advisory (exit 3; --strict promotes every advisory to exit 1):

  • over ~300 lines; a == Review log table with more than two rounds, no rows, or no such section;

  • neither nav-linked nor a plans/archive.adoc row (a repo-only meta plan — nothing to verify);

  • a #N glab answers 404 for — a number that is not in this project OR one the token cannot see (indistinguishable from here): state unknown, one advisory per such ref, never a block;

  • issue states could not be verified — glab missing, unauthenticated or offline, or --offline passed: ONE advisory, lookups stop.

Rounds are table ROWS formed the way AsciiDoc forms them (#2070): every unescaped | opens a cell, and each run of cols cells — the [cols=…] above the table, else the first line’s cell count — is one row, so a one-cell-per-line round and a round whose cells wrap onto a second | line each count once; the first row is the header and an incomplete last row is dropped. Suffix resolution trades precision for the citation convention: any crate’s src/events.rs satisfies src/events.rs; absolute and home-relative tokens (/etc/…, ~/…, $HOME/…) are never citations.

Tracing PII-field gate (#896)

Wired at the cargo xtask validate tracing-pii-fields step (blocking, phase_code_security_lints). A single tracing field interpolating a child’s name/DOB/address/SSN/phone/email is a reportable PII incident for a CCWIS. The 2026-08-24 three-agent sweep (cases 26 sites / financial+placement 61 / intake 38 + fleet census 556) found ONE real finding — intake’s redact_upstream_error logging the full raw upstream body at WARN (SHINES/cases 4xx bodies can echo submitted SSNs/names) — plus two contingent raw-value echoes in the NCANDS export warns; all fixed with shape-only logging (length + SHA-256 prefix). This gate keeps the fleet clean:

  • Surface: every trace!/debug!/info!/warn!/error!/event! AND *_span! invocation (bare, tracing::- or log::-prefixed) over the workspace-member src trees, PLUS #[instrument(fields(…​))] on free fns, impl methods, and trait methods. Field forms covered: ident = …, bare-ident captures, %/? shorthand (leaf-matched), dotted explicit names (person.name = …), and string-literal names. Syn token-stream parsing, never line-based — ~46% of fleet macro sites are multi-line. Recorded out of scope: message-position interpolation (format text is free prose; the field-ident surface is the machine-checkable one).

  • Rule: FIELD IDENTS (and %/? shorthand captures, matched by their final path segment) against the exact denylist name | first_name | last_name | dob | date_of_birth | address | ssn | phone | email | narrative | rationale | body. Value bindings are deliberately out of scope — rule_set = %name is the CORRECT pattern (the census proved every %name binding sits under a safe ident).

  • Escape: // pii-field-ok: <reason> on the line above the macro (one seed: reporting’s S2S problem-details body log, whose PII-safety rationale predates the gate); empty reasons and stale markers fail.

  • Universe floor: the site count at the last bless is recorded as tracing-pii-fields.sites in xtask/baselines/scan-floors.toml (the lint’s own walker — spans + instrument included); more than one fifth below it the macro detection is presumed broken and the gate fails loudly.

Implementation: xtask/src/cmd/lints.rs::run_tracing_pii_fields + tracing_pii_tests.

Serialize-credentials + store-model gates (#879)

Two gates wired at cargo xtask validate (blocking, phase_code_security_lints):

Serialize-credentials (cargo xtask lints serialize-credentials) — a heuristic tripwire over the wire-name surface, and its doc says so. Named fields of Serialize-deriving structs AND enum variants (derives seen through cfg_attr) whose ident or serde(rename) wire name contains secret | password | token | api_key | auth_config | signing_key | client_secret | private_key | credential | bearer | verifier | nonce must either #[serde(skip_serializing)] or carry a per-field // serialize-credential: <reason> marker on the line DIRECTLY above (per-field, never per-struct; stale markers fail; empty reasons fail). The 17 seed markers across 10 files are the auditable inventory of every place credential-shaped material intentionally serializes (sweep tokens, idempotency occurrence tokens, the CLI/test-lib token caches, the encrypted WebSession cookie, PkceState’s PKCE verifier + OIDC nonce, the one-time `IssueKeyResponse.api_key, the hash-only PartnerIntent.auth_config). Test-only items are excluded by cfg predicate; craig-test-lib is deliberately NOT path-exempt here. Recorded false-negatives: flatten chains, manual impl Serialize, non-use aliasing.

Store-model response baseline (cargo xtask lints store-model-baseline) — a COARSE TEXTUAL per-file ratchet over handlers returning store models directly: the ledger xtask/baselines/store-model-responses.toml maps each services/*/src file to its count of lines containing both Json< and store::models:: (48 files / 153 sites at seed). Any file above its count — or any new file above zero — fails and is NEVER blessable; below is stale and a bless (cargo xtask baselines bless --only store-model-responses) rewrites DOWNWARD only. The claim is exactly "no per-file growth of the textual pattern": aliased imports and multiline generics under-/over-count, same-file swaps are the recorded residue, and the empty counts table is the desired end state.

Rustdoc gate (#1522; #1785; widened by #2596; private-item pass #2809)

Wired early in cargo xtask validate (blocking): cargo doc --workspace --no-deps under RUSTDOCFLAGS="-D rustdoc::broken_intra_doc_links" in the isolated target/doc-check dir.

Beside the public twin, concurrently in the same step (#2901: their target dirs and search-index locks are disjoint, so a workspace-wide re-document costs one pass’s wall time, not two), cargo xtask validate runs a second, project-owned pass (#2809, blocking; either failing fails the step with its own verdict): cargo doc --workspace --no-deps --document-private-items --quiet under RUSTDOCFLAGS="-D rustdoc::broken_intra_doc_links -D rustdoc::redundant_explicit_links" in its own $CARGO_TARGET_DIR/doc-check-private directory (private_doc_gate_command, run_doc_gates), on the same scrubbed workspace::cargo_command (plus an explicit CARGO_ENCODED_RUSTDOCFLAGS removal so an inherited --cap-lints=allow cannot override RUSTDOCFLAGS) and DOC_GATE_MAX_JOBS (4) ceiling. Like the public twin, the private-item pass denies every rustdoc lint through [workspace.lints.rustdoc] (all = { level = "deny", priority = -1 }); its RUSTDOCFLAGS state the two link-lint floor flags explicitly. Because --document-private-items and those flags enter every doc-unit fingerprint, isolating the pass in doc-check-private keeps the public twin’s doc-check cache and the main target/ build untouched while catching broken intra-doc links and redundant explicit link targets in private-item rustdoc (which the U5 missing_docs_in_private_items sweep adds across the workspace). private_doc_gate_uses_isolated_target_dir_and_scrubbed_env pins its arguments, target directory, literal RUSTDOCFLAGS, CARGO_ENCODED_RUSTDOCFLAGS removal and environment scrub. Cost (measured 2026-10-28 across the workspace): ~132 s doc-cold (after warm dependency metadata) and 1.69 s warm no-op; a first run into a fresh doc-check-private root also check-builds every dependency (rmeta artifacts) and maintains a second doc target tree on disk, a cost paid by the car’s test --doc line as well as local validate runs.

All three passes (the hook’s, its twin and the private-items pass) deny every rustdoc lint (2596) through the root manifest’s [workspace.lints.rustdoc] table, all = { level = "deny", priority = -1 }, which sits after the managed lints block (that block holds only .rust and .clippy) and which every member reads through [lints] workspace = true (workspace-dep-inheritance refuses a member without it). Cargo passes the table to every rustdoc it runs, so the hook’s and the twin’s RUSTDOCFLAGS stay the template’s floor flag, byte-identical and subsumed. the_workspace_denies_every_rustdoc_lint pins the table. "Every" has two qualifiers. First, a source lint attribute ([allow], [expect] or [warn] naming a rustdoc:: lint) lowers that lint for its item, and since no pass runs with -D warnings a lowered lint passes the gate (none exist today); the lint-regime check fails every such suppression, inner or outer (R4, § Lint regimes). Second, cargo itself passes -A rustdoc::private-intra-doc-links for a bin target, whose private items it documents.

History. #1650 (2026-09-03) swept the workspace clean of the wider rustdoc lints (67 sites across 49 files — private-item links, redundant link targets, angle-bracket tokens read as HTML, a bare URL; those fixes stay) and widened this twin to -D warnings. That flag divergence rewrote every fingerprint on each pass, so BOTH passes re-documented the whole workspace (~30 min each, per push — measured 2026-09-11 as about two thirds of a 91-minute battery). #1785 reverted the widening. By 2026-10-23 the narrow gate had passed 5 rustdoc warnings, and 7 crate roots carried no crate docs (#2596 asked for the wider gate; all 12 are fixed). The manifest table makes both passes see the same flags, so #1785’s double re-document cannot recur; the table enters every unit’s fingerprint once, so the first build and doc pass after it landed were cold. A failure here names the site; a link to a private item is a plain code span, not a link.

Identical flags are not enough (#2135). The twin runs inside cargo xtask, which is cargo run, and cargo run exports its per-package variables (CARGO_PKG_*, CARGO_MANIFEST_*, CARGO) into xtask and so into every cargo xtask spawned. ring 0.17’s build script tracks CARGO_PKG_NAME, CARGO_MANIFEST_DIR and OUT_DIR through rerun-if-env-changed, and cargo compares those values against its own environment, so the twin and the hook’s bare-shell cargo doc each flipped ring’s build-script fingerprint and re-documented every crate downstream of it (about 1600 s per twin per push, measured 2026-10-06). The twin now strips those variables, and every xtask-spawned cargo uses the same scrubbed environment (workspace::cargo_command), so validate’s clippy and nextest no longer flip target/debug against a bare-shell cargo either. doc_gate_twin_matches_the_pre_push_hook_line pins the twin to the hook’s line (args, target dir, flags, and the scrub), and every_xtask_cargo_spawn_goes_through_the_scrubbed_constructor fails on any raw Command::new("cargo") in xtask/src.

An inherited CARGO_ENCODED_RUSTDOCFLAGS (#2810). Cargo takes rustdoc’s extra flags from the first source set among CARGO_ENCODED_RUSTDOCFLAGS, RUSTDOCFLAGS, target.*.rustdocflags and build.rustdocflags (the Cargo book’s build.rustdocflags), so an inherited encoded value such as --cap-lints=allow would replace the gate’s -D flag and let a broken link pass. The twin removes the variable, as the private-item pass does, and doc_gate_twin_matches_the_pre_push_hook_line asserts the removal. With the variable unset, the normal case, the removal changes nothing cargo sees, so the twin’s fingerprints stay the hook’s. The template-synced hook’s own cargo doc line does not remove it: with an inherited value the two passes see different flags, the hook’s later pass re-documents under the inherited value, and the twin, which runs first inside the hook’s validate step, is the pass that gates.

The gate’s memory (#2108). Rustdoc 1.97 merges each crate into the shared doc/search.index/ while holding an exclusive lock on doc/.lock, so a full re-document is serialized on that merge and each rustdoc’s peak follows the index already on disk, not its own crate. Measured 2026-10-13 on the 32-CPU dev host (one full re-document of the 74 workspace crates, other work running): on the live warm index the job count sets the total, not the speed — anon peak 15.6 / 9.5 / 5.9 / 3.9 GiB at 32 / 16 / 8 / 4 jobs, wall time 250-273 s at every count. The index is never wiped and grows about 3 MB per full re-document: three full passes starting from an empty index left it at 17, 20 and 23 MB, took 24, 65 and 87 s, and peaked at 1.5, 1.6 and 1.9 GiB for the largest rustdoc, while the live 41 MB index cost 272 s and 3.0 GiB per rustdoc. The twin therefore sets CARGO_BUILD_JOBS to the smallest of the host’s parallelism, DOC_GATE_MAX_JOBS (4) and a caller’s positive CARGO_BUILD_JOBS. Cargo resolves the job count for scheduling only, so it is not a fingerprint input and the hook’s later run stays a warm no-op. Two costs are accepted: a lower build.jobs in a cargo config file is overridden, and a dependency-cold rebuild of target/doc-check (a toolchain or Cargo.lock bump) also runs at 4 jobs; a doc-cold pass took 42 s at 4 jobs against 24 s at 32. The cap does not bound the index’s growth per rustdoc; the wipe below does.

The index’s growth (#2362). Rustdoc 1.97 merges each re-documented crate into the index on disk and keeps the names of items that no longer exist: on a two-crate scratch workspace, three full re-documents of unchanged sources left the index byte-identical (2 698 095 bytes each time), while three re-documents that renamed 3000 items each grew it 2.63, 2.74 and 2.87 MB against 2.51 MB for the same tree documented into an empty index, with the old names still in its name/ tables. Removing the index does not make cargo re-document anything (it fingerprints a doc unit by its doc/<crate>/index.html; a second cargo doc after removing it stayed a no-op), and the gates read rustdoc’s lints, never the index. Both gates therefore remove doc/search.index/ in their target dirs before each run (doc_gate_search_indexes, wipe_search_index), keeping the rest of the dir and its fingerprints, so re-documentation stays incremental and the hook’s later pass stays a warm no-op. Each run’s index then holds only the crates that run re-documented, at most one fresh full index: on the scratch workspace, three renaming re-documents with the wipe each left 2 505 716 bytes. The live tree’s index was not measured. A child that cargo reports as killed by a signal is named — rustdoc killed (signal 9 — likely OOM) for SIGKILL, <program> killed (signal N) otherwise — instead of the rustdoc lint error(s) text, which stays for every other failure. Both 2026-09 incidents predate #2135, when every push ran two full re-documents and so grew the index twice.

Advisory-ignore audit gate (#891)

Wired at the cargo xtask validate advisory-ignore-audit step (blocking, phase_doc_lints; pure file parse, no subprocess). The advisory-DB layer is cargo-deny’s, CRAIG’s one RustSec scanner since #2658 retired cargo-audit, .cargo/audit.toml and this gate’s parity half (a deviation from standards:coding-conventions, recorded in AGENTS.md § Conventions — Project Overrides). cargo deny check runs in the pre-push hook only when cargo-deny is installed (the hook skips it silently otherwise) and in CI’s cargo-deny job: MR and main pipelines touching a manifest, Cargo.lock or deny.toml, and every scheduled pipeline; not allow_failure. deny.toml sets unused-ignored-advisory = "deny", so an ignore that no longer matches a crate in the graph (upgraded past, or withdrawn) fails cargo deny check advisories: a stale ignore fails closed in the scanner itself.

What cargo-deny cannot do is time-box an ignore that still matches. Each [advisories].ignore entry is cargo-deny’s { id, reason } form, and the reason carries the tracking issue (or the retire condition) and review-by: YYYY-MM-DD. The gate reads deny.toml with a TOML parser and fails an entry whose reason has no review-by date, an unparseable one, or one past today (a HARD failure: staleness is a stop rather than a judgment nobody re-runs); a bare-string entry fails, having no reason to carry the date. The longer reachability evidence sits in the comment above each entry; the gate never judges reachability.

The review-by extractor is proptested (totality over arbitrary text; a date written after the marker in any prose reads back). Implementation: xtask/src/cmd/lints.rs::run_advisory_ignore_audit + advisory_ignore_audit_tests; xtask/src/pipeline_tests.rs pins that no CI job runs cargo-audit, that cargo-deny runs on every schedule, and that unused-ignored-advisory is deny.

Partner parse-prop coverage gate (#870)

Wired at the cargo xtask validate parse-prop-coverage step (blocking, phase_code_security_lints). Three layers, each closing a gaming vector the wave-1 review proved against weaker designs:

  1. Census — every crates/craig-partner-* workspace member must expose an adapter type Inbound = X; (located by syn inside the impl; src/adapter.rs or src/adapter/mod.rs). A crate under the prefix that is not a partner at all (PARSE_PROP_NON_PARTNER_CRATES; today: craig-partner-test-harness, the shared adapter test harness, #836) sits outside the census by declaration — and goes STALE if it ever grows an adapter. Deleting an adapter cannot silently deschedule a crate; the adapter floor catches census collapse (one since ADR-090: the reference partner’s, the only partner crate left in the tree; a jurisdiction’s adapters are held to the same rule in its layer by cargo xtask partners check); a listed crate that gains an adapter goes stale.

  2. Property presence — some test file must contain a proptest! invocation whose TOKEN STREAM carries both from_slice and X as identifier tokens (lint_tokens::has_ident, #2552). Tokens, not text: a comment is no token, and a /// doc comment or a string literal inside the macro is one literal, so none of them can satisfy it; deleting the property body removes the macro. (Presence-tier honesty: this proves a property exercises the decode, not its assertion semantics — the authz-coverage tier.)

  3. Compilation reachability — the file must be a top-level tests/*.rs target or reachable via a mod x; / #[path] chain (caps' nested tests/properties/ layout is the seed case). Orphaned files Cargo never compiles do not count.

#1575’s second census layer, over the erased audit-decode seam (audit_payload_from_value, PartnerAuditEvent::decode_jsonb), went with that seam (#2295): no audit decode remains to census, and the non-adapter exception list that held craig-partner-audit went with it.

Escape hatch: // allow-no-parse-prop: <reason> on the line above the type Inbound declaration — the reason MUST cite a #NNN issue. The properties execute in the pre-push full battery — the sole functional-correctness gate; the unit lane (test --unit) runs the --lib subset, which never compiles tests/ targets (#1577 corrected the claim; the selection deliberately stays), and the battery lane runs them. Implementation: xtask/src/cmd/lints.rs::run_parse_prop_coverage + parse_prop_coverage_tests.

Workspace dependency-inheritance gate (#869)

Wired at the cargo xtask validate workspace-dep-inheritance step (blocking, phase_doc_lints — pure TOML, no compile). Membership authority is the workspace itself: [workspace].members minus .exclude, expanded from the root manifest (never fixed directory lists), with a 66-member seed floor. Two checks, neither with an exception channel:

  1. [package] version/edition/license must each be PRESENT and .workspace = true — omission is a violation, not a pass. rust-version is recorded out of scope (most members omit it). Since #2596 the manifest also carries [lints] workspace = true: a member without it leaves [workspace.lints], the rustdoc policy of § Rustdoc gate included.

  2. Over dependencies/dev-dependencies/build-dependencies and every [target.] variant: default-features = true anywhere fails, and so does a hardcoded twin of a default-features = false workspace dep that drops the false (the twin is matched by its *resolved package name, package = rename honored; dotted/inline/expanded spellings are normalized by the parser — proptested).

Implementation: xtask/src/cmd/lints.rs::run_workspace_dep_inheritance + workspace_dep_inheritance_tests.

That a shared dependency is inherited at all is cargo-deny’s check (#2660). deny.toml [bans.workspace-dependencies] sets duplicates = "deny" and unused = "deny", so cargo deny check bans fails when two or more members declare the same crate and any of them does not take it from [workspace.dependencies] (whether or not the workspace declares it), and when a workspace entry has no user. It reads the resolved graph, so it also sees a dependency nobody hoisted. There is no exception list. A member that needs fewer features than its siblings is served by the workspace entry carrying only the features every consumer needs, with each member adding its own: reqwest is json + rustls-tls (members that send multipart bodies add multipart, xtask adds blocking) and tokio is time alone, because the standalone craig-intake-sdk takes nothing else.

Rust-built HTML gate (#2493)

A blocking cargo xtask validate step in the web-surface phase, after the template-safety and query-string guards (cargo xtask validate-rust-html, xtask/src/cmd/validate_rust_html.rs). The template gate refuses escape bypasses in templates; this one covers HTML a handler builds itself, the 2291 shape: in the production Rust of every service (services/*/src) and of craig-bff, a string literal inside format!, write!, writeln!, format_args! or concat! that holds an HTML tag (< then a letter, / or !) and a {…} placeable fails it (Html(format!(…)) and push_str(&format!(…)) are format! sites). Render a template instead. An audited builder whose every placeable is constant or escaped carries // html-audited: <reason> in the comment block directly above it; a marker with no reason fails. Test code ([test] fns, inline #[cfg(test)] modules, and the files a test-only mod x; loads) is skipped, and an unreadable or unparsable file fails the gate.

Nextest filter-term gate (#2402)

A blocking cargo xtask validate step, right after the contested-surface census: every exact test(=…) term in .config/nextest.toml (each profile’s override filter and default-filter) must name a test in the inventory the census builds (cargo nextest list --run-ignored all), so the inventory is built once. A term naming a helper, a renamed test or a typo matches nothing: nextest accepts it and the override it carries (a serial group, an envelope) silently applies to nothing, as #1832’s helper-named term left #2285’s race live. An empty inventory or a config with no exact term fails the step rather than passing vacuously (xtask/src/cmd/nextest_filter_terms.rs).

Changelog fragment check (#2973)

cargo xtask changelog check (xtask/src/cmd/changelog.rs, plan release-v0-2-0-changelog-fragments U1) holds every file in changelog.d/ to the fragment grammar in changelog.d/README.adoc: the name <issue>[.<slug>].<type>.adoc with one of Keep a Changelog’s six types, and a body that is one * #<issue> … bullet (the filename’s issue first, indented continuation lines, no heading or attribute entry) carrying exactly one Ops: clause. It also requires CHANGELOG.adoc == Unreleased to hold only the fixed pointer paragraph, and the four SDK version fields to equal [workspace.package] version (#3077): [project] version in sdks/python/pyproject.toml, version in sdks/typescript/package.json, and version and packages[""].version in sdks/typescript/package-lock.json. A differing field fails naming the file and both versions; a missing file or field fails too. All are state checks on the tree, so they are as correct on a merge-train result as on a branch. Since the v0.2.0 cut (#2975) it is a fast row of the gate table (Changelog state check, § Precompilation gates), so the pre-push hook and the train’s car run it: a stale branch’s bullet under == Unreleased fails its car.

cargo xtask changelog release --version X.Y.Z [--date D] folds the fragments into == vX.Y.Z (D): derived === Ops notes (* #N: <clause> for every clause that is not none.), then the six groups in order, each by issue descending then slug, every body byte for byte. It refuses, writing nothing, on an invalid fragment, no fragments, a stray Unreleased entry, a version that already has a section or an archive, or an SDK manifest that is missing or has no version field. The previous release section moves to changelog/v<prev>.adoc; when that file already exists it is never overwritten and the section stays in CHANGELOG.adoc. It sets [workspace.package] version through toml_edit (comments kept), sets the four SDK version fields to the same version (pyproject.toml through toml_edit; in the two JSON files only the version values' bytes are replaced, so a dependency’s version, the key order and the indentation stay as npm wrote them) and deletes the fragments, and neither commits nor tags. cargo xtask changelog notes --version vX.Y.Z [--images <image path>] --out <file> writes that section as Markdown, links absolute at the tag; with --images (the tag pipeline passes $CI_REGISTRY_IMAGE) it adds a Container images list, <image path>/<service>:vX.Y.Z for every promoted service, and refuses an empty path (#3012).

Custom lint inventory (#2299)

One row per cargo xtask lints subcommand (LintsAction). Each guards a fact clippy cannot express: a marker or a ratcheted baseline, a cross-file or cross-target count, an argument value rather than a callee, or a non-Rust surface. "Blocking" means a cargo xtask validate step that fails the run. The four rows marked (&110) stay by maintainer ruling on #2299 and are hardened under epic &110 (read tokens, walk every root, fail closed). The "xtask walked" column records where the dev-tooling member (in_dev_tooling) sits since #2299: the production-code lints skip it, and a lint over a non-Rust surface never reaches it. Since #2553, no-silent-skips, test-env-reads, db-error-construction, struct-method-count, dto-length, fn-name-and, jurisdiction-literals, untyped-list-envelope, tracing-pii-fields, serialize-credentials, fn-shape-report, secrets-yaml and parse-prop-coverage (with the authz-coverage and template-safety gates) read each walked file through lint_scan::read_lint_file (or read_lint_source where they need only the text): an unreadable file fails the lint, naming the file, and a walk error is never dropped. An unparsable file fails the lints that parse in order to scan, naming it (lint-regime too: its suppression walk parses every file under the lint roots, #2715), but not the others: db-error-construction scans every line of a file syn cannot parse, test-env-reads and secrets-yaml never parse, and parse-prop-coverage reads an unparsable file as holding nothing, which can only fail its census (fail-closed by direction). Since #2595, every lint walk (lint_scan::walk_dir) follows no link: a symlinked directory below a root fails the lint, naming it, a symlinked file is read through, and target/, .cargo/, node_modules/ and .git/ are never entered. Since #2559, the walkers derive their roots from the workspace: lint_scan::lint_roots is the top-level tree of every [workspace].members entry (crates/, plugins/, services/, tools/ and xtask/ today), and lint_scan::production_roots drops the dev-tooling member’s, so a member added under a new tree is walked with no lint edit and a declared tree that is missing fails the lint. Since #2618, every other lint walker (quality-budgets, the web query-string guard, scenarios, the fn-shape-report command, the validate SPDX and migration-apply steps, the evil-corpus and contention scans, contested-census, the OpenAPI registration scan, the authz key census, four-state-contract and validate-migration-constraints) walks through the shared walker (walk_lint_root; four-state-contract through walk_dir, after refusing a missing or non-directory plugins/ with WalkRefusal::BadRoot and before refusing a tree that holds no plugin template (require_files_floor, #2624), and the scenarios and contested spec listings through list_lint_dir) and reads through the shared fail-closed reader (lint_scan::lint_sources / read_lint_file), so a walk error or an unreadable file fails it, naming the file; the whole-checkout walks walk the lint roots instead of . (a test pins that every tracked .rs lies under them). Since #2298, a scan that parses or lexes every walked file runs that per-file work on the host’s threads (lint_scan::map_in_path_order, std::thread::scope) and takes the results, and the first failure, in path order, so each report is byte for byte what the file-by-file loop printed; no-sleep-polls and evil-body-probe lex a file for its marker comments only when its text spells the marker.

Lint Validate Class Why (the invariant) xtask walked

db-error-construction

blocking

wire

DB errors reach the wire through the craig-common classifier (ADR-068): no direct ApiError::Db(..) and no unmarked flatten to the redacted 500, so the typed 503/504 degradation classes hold. Every needle reads the file’s code view (lint_tokens::lex_view, #2552): a comment or a string never sanctions a flatten, and the DB-FLATTEN-OK: marker counts only as a // comment line.

no: the production roots

dto-length

blocking

wire

Every deserialized String-shaped field of a struct or enum variant in the cap-policy crates, or in any type a non-BFF Json / Query / Form / Path extractor reaches, carries a garde cap or #[garde(skip)] (a sequence both an entry-count and an item cap), with a matching OpenAPI max_length mirror. A string-shaped extractor parameter or an unresolvable payload type is a finding (§ DTO field-length validation). The ledger’s uncapped rows are seeded only when the lint’s reach widens, each with a reason; otherwise the baseline only shrinks.

no: the cap-policy crates and the non-BFF production sources

untyped-list-envelope

blocking

wire

API handlers return typed DTOs or PageResponse<T>, never Json<Value> or a hand-built json! envelope; the ledger xtask/baselines/untyped-envelope.toml only shrinks.

no: services//src/api.rs and services//src/api/**

undocumented-403

blocking

wire

A #[utoipa::path] handler whose body can refuse a caller lists a 403 in its responses(…​) (#2819), so a generated client meets no undocumented status. "Can refuse" is read off the body’s tokens: .check( / .check_typed( / .auto_scope_list_typed( on an engine receiver, a craig-auth require_* or worker_subject guard, deny_pure_service, require_direct_service_caller, list_scope_verdict, forbidden_policy, a naming of Forbidden / FORBIDDEN, or a call to a helper of xtask/baselines/authz-helpers.toml one of whose definitions holds such a signal. .auto_scope_list( alone is none: its deny is the Denied value, which a list may answer with an empty page. Not seen: a 403 from a callee outside the helper registry (a service-layer fn, a relayed upstream 403), from an extractor or from a middleware (the portal guard), and an engine call written as UFCS or with a turbofish. The ledger xtask/baselines/undocumented-403.toml is empty; it takes only a handler that provably cannot answer 403, with the reason, and a stale row fails.

no: services/*/src

problem-type-status

blocking

wire

A call to a typed ApiError constructor (bad_request_typed, forbidden_policy, conflict_typed, unprocessable_typed, internal_typed, service_unavailable_typed) that names a problem_types constant answers a status the constant’s doc comment opens with (#2411), so a client that branches on a problem type meets it under one status. A constant whose doc opens with no status fails; a call whose type argument is not a path to a constant is counted, not judged. The ledger xtask/baselines/problem-type-status.toml is empty (#3073) and takes no row; a row that does not match the tree fails. See § Problem-type status gate.

yes

store-model-baseline

blocking

wire

A Json<…store::models::…> response (a storage row on the wire) never grows per file; a bless (cargo xtask baselines bless --only store-model-responses) only shrinks.

no: services/*/src

four-state-contract

blocking

wire

Plugin templates that dispatch on state cover data / empty / error, the plugin half of the host contract (ADR-033).

n/a: templates

tracing-pii-fields

blocking

security

No PII-shaped tracing field outside a // pii-field-ok: marker; a site-census floor proves the macro detection still sees the sites (#896).

no: production code only (walk_workspace_member_sources)

serialize-credentials

blocking

security

A credential-shaped field on a Serialize type skips serialization or carries a // serialize-credential: marker, the auditable inventory of intended credential serialization.

no: production code only (walk_workspace_member_sources)

parse-prop-coverage

blocking

security

Every partner adapter’s inbound type has a compiled from_slice proptest: partner input never panics a parser (#870).

no: crates/craig-partner-*

sops-policy

blocking

security

The committed secrets store holds only ciphertext, under a strict .sops.yaml policy with recipient parity (ADR-064); no link or special file under secrets/ (#2623).

n/a: secrets/

secrets-yaml (&110)

blocking

security

No plaintext secret in any tracked YAML file except the sops-policy surface (.sops.yaml, secrets/) without an # allow-secret: reason. Since 2649 it matches env-style keys (DB_PASSWORD:, PGPASSWORD:, CRAIG_PARTNER_SECRET_<REF>:) and scheme://user:password@ URLs. Of plain scalar values only a bare boolean or null is exempt (a number is not), while placeholders, !tags and empty values are skipped as before; a credential-free URL is judged one path segment at a time. Since #2708 a block scalar (|, >, with chomping or indentation) under a secret-shaped key is judged on its content lines: one that is not a placeholder flags the key line unless it carries allow-secret:; an empty value opening a mapping is not a block scalar.

n/a: YAML

dockerfile-hygiene

blocking

security

In every tracked Dockerfile, every runtime stage runs non-root with a HEALTHCHECK, and no stage installs openssl to link against (apk openssl*, apt libssl-dev; container-ops). A file that cannot is a reasoned row of the lint’s carve-out table, printed on every run (#2675).

n/a: Dockerfiles

advisory-ignore-audit

blocking

security

Every deny.toml advisory ignore is a { id, reason } entry whose reason carries an unexpired review-by: date.

n/a: TOML

workspace-dep-inheritance

blocking

security

Supply chain: [package] metadata and [lints] are inherited, and default-features never drifts (cargo-deny checks that a shared dependency is inherited).

yes: xtask is a workspace member with its own manifest

jurisdiction-literals

blocking

data

No production source names a jurisdiction; the partner-adapter crates do (ADR-072). In services/craig-exchange/src/ no production literal equals a partner’s kind token either (ADR-089): the tokens are the interfaces each fetched layer’s partners/manifest.toml lists (ADR-090) and the crates/craig-partner-<name> directory names (the reference partner), so a new partner arms the check with no edit; the layers must have been fetched.

no: never walked

product-copy-jurisdictions

blocking

data

Product-default copy (Fluent catalogs, theme TOML) names no jurisdiction (ADR-072, ADR-034).

n/a: catalogs and TOML

test-env-reads

blocking

test-integrity

No raw CRAIG_TEST__* read outside the TestConfig resolver, so the env → .ports.env → default chain always applies (#1035).

no: xtask writes the variables and reads them only through TestConfig::from_env; it has no raw read

no-silent-skips (&110)

blocking

test-integrity

A test fn’s skip-return reports a vacuous pass, with or without a printed reason; the test takes #[ignore] and fails loud (Plan D F-024, #2368, #2567).

yes: its tests are tests like any other

evil-body-probe

blocking

test-integrity

Every parametric_evil_test! endpoint calls the body-limit probe, itself or through a same-file fn, or carries a reasoned // no body-limit probe: marker, so the corpus’s 4 MiB case cannot lose its 413 to a connection reset (#3024; testing-reference § body limit probe).

yes: every lint root is walked

lint-regime

blocking

hygiene

Every crate root carries the one canonical test-regime attribute xtask/lint-policy.toml defines (R1 at a test root, R2 at a production root) and no other test-scope crate-root suppression names a set lint (R3); every other suppression is an outer single-lint #[expect] on a non-container item or matches one [[suppression]] entry, one to one, with no group or lowered meta-lint and no correctness-class suppression outside test code (R4–R6). --fix writes the R1/R2 shape; the registry is edited by hand (§ Lint regimes). It retired no-transitional-allows (#2715).

yes: every file under the lint roots, xtask’s included

struct-method-count (&110)

blocking

hygiene

No impl block over 16 methods, getters, setters and builders excluded (coding conventions). The ledger xtask/baselines/struct-method-count.toml pins each reviewed over-cap impl with its method count and only shrinks (empty today).

no: the production roots

fn-name-and (&110)

blocking

hygiene

No production fn name joins two jobs with and; the opt-out file only shrinks (§ Function cohesion enforcement gate).

no: dev tooling

doc-pointer-integrity

blocking

docs

AGENTS.md exists and every link and repo path in it resolves.

n/a: Markdown

mandatory-docs

blocking

docs

Every mandatory project ROOT page exists with its placeholder sentinel removed.

n/a: Antora

doc-attr-refs

blocking

docs

No Antora page carries an undefined {name} attribute reference (§ Docs attribute-reference gate).

n/a: Antora

spdx

blocking

hygiene

Every .rs file under the lint roots starts with the SPDX line, a generated file excepted (#3043: the validate gate as its own verb).

yes: every lint root

migration-apply-isolation

blocking (full)

data

No production source outside craig-db’s internals and craig-api’s migrate-mode helper applies DDL: serving boot only verifies (ADR-063 M3b; #3043: the validate gate as its own verb).

no: the production roots

source-ownership

blocking (full)

hygiene

Every source a workspace unit compiled, read from rustc’s dep-info after a clippy replay, is a walked .rs file of that unit’s package (§ Lint regimes, M7; #3043: the validate gate as its own verb).

yes: every workspace unit

dockerignore-canary

blocking (a car gate)

security

A Docker build against the real context proves .dockerignore keeps the generated secrets, the encrypted store and the planted config probes out of it (#1003, #2648; #3043: the images gate as its own verb).

n/a: the build context

Why test-env-reads stays custom. The 2299 issue proposed a clippy entry; the maintainer kept the custom lint (ruling 2026-10-21). Clippy’s disallowed-methods matches a callee, never its argument. The clippy form would ban std::env::var itself: at least 113 legitimate non-test reads (45 in xtask, the rest production settings and bundle reads plus craig-test-lib) would each need an [expect], and the test scopes, where raw CRAIG_TEST__* reads live, would still allow it. Retiring the lint instead would leave the #1033 class (a raw read passes validate’s injected env and breaks a direct nextest or IDE run) with no tripwire. The only raw reader is craig_test_lib’s `config.rs resolver; xtask writes the variables (docker::build_env_for_ports) and is not walked.

Retired by #2299:

  • mq-topology and reqwest-client-new became clippy.toml disallowed-methods entries (§ Disallowed methods). Six sanctioned chokepoints each carry one #[expect(clippy::disallowed_methods, reason = …)]: craig_mq::subscriber::declare_queue, craig_common::http::base_builder, craig_auth::oidc_discovery::pinned_fetch_client, craig_intake_sdk::client::transport_client, craig_exchange_transport::egress::pinned_client and craig-intake’s BotVerifier::from_settings. The dependency layer under them is cargo-deny’s (§ Disallowed methods, #2603).

  • The unused_crate_dependencies deny at 62 crate roots, with its 30 use x as _; acknowledgements: cargo machete is the one dependency gate. Consequence: a dependency used only by a sibling target, or only by tests, no longer fails the build, and nothing re-verifies a partner crate’s ignored = ["thiserror"] entry (here the reference partner’s): removing one breaks the build while the partner_error! expansion names ::thiserror, but if the macro stops naming it the ignore hides an unused dependency.

Disallowed methods (#2299; was #771/#866 and #1198)

Two layers hold raw broker-topology and HTTP-client construction to their chokepoints. The call-site layer is clippy’s disallowed-methods list: it fails a named call in any crate that can reach the library. The dependency layer is cargo-deny’s [bans] deny entry with wrappers (#2603): it fails a direct dependency on the library outside the named wrapper crates, so no other crate can name an item of it, however a call is spelled. lapin has both layers; reqwest has the call-site layer only (see The dependency layer below).

clippy.toml carries a project disallowed-methods list (clippy reads exactly one config per crate, so the list lives in the workspace file). Clippy’s disallowed_methods lint is in clippy::style; the clippy passes' -D warnings (§ The clippy passes) makes every hit blocking. The list replaced two xtask scanners: the #771/#866 reqwest construction gate and the #1198 queue-declaration gate.

  • The entries: lapin::Channel::queue_declare (declare through craig_mq::Subscriber so the classic queue-type pin applies, ADR-003 § Amendment #1198); lapin::Channel::exchange_declare (exchanges are operator-owned topology, § Amendment #1202); reqwest::Client::new (hold the service-wide craig_common::build_shared_client client, ADR-014); reqwest::Client::builder and reqwest::ClientBuilder::new (a bespoke client is a recorded decision).

  • Six sanctioned chokepoints. Each carries #[expect(clippy::disallowed_methods, reason = "…")], which self-retires: once the call goes, the unfulfilled expectation fails -D warnings. Every other production call routes through one of them:

    • craig_mq::subscriber::declare_queue, the one raw queue_declare. prepare_queue, prepare_dlq_companions, build_replayer_session_inner and the depth gauge’s sample_queue call it. Every declaration carries queue_args (the classic pin) except the gauge’s, which is passive and creates nothing.

    • craig_common::http::base_builder, the shared builder: connect timeout, idle pool, User-Agent and the #771 no-redirect policy every service client inherits.

    • craig_auth::oidc_discovery::pinned_fetch_client, the IdP discovery and JWKS fetch client that OidcDiscovery::with_fetch_url, JwksProvider::with_fetch_url and JwksProvider::from_discovery hold, with a pinned 10 s total timeout.

    • craig_intake_sdk::client::transport_client, the standalone SDK transport behind IntakeClient::new and IntakeClient::new_signed: the SDK takes no craig-common dependency and pins its own 30 s timeout.

    • craig_exchange_transport::egress::pinned_client, the per-send egress client: redirects off, HTTPS enforced outside the loopback dev class, the connection bound to the vetted address.

    • BotVerifier::from_settings (craig-intake api/captcha.rs), the bot-protection verifier’s dedicated client: redirects denied, https_only, a fixed timeout (ADR-069).

  • Test code allows the lint through the test regime. The lint has no test scope: it fires in [cfg(test)] code and in tests/ targets alike, so clippy::disallowed_methods is in the test-regime set (§ Lint regimes). Every test root’s R1 attribute allows it (the two test-support crates, craig-test-lib and craig-partner-test-harness, are test roots and in no release graph), and every production root’s R2 ![cfg_attr(test, allow(…))] allows it in that root’s test build, xtask’s included. Production code stays held: xtask builds only reqwest::blocking clients and declares queues through craig_test_lib::declare_scratch_classic_queue, and a future production need takes a fn-level #[expect].

  • Recorded residuals, which the list does not catch:

    • Client::default(), ClientBuilder::default() and Default::default() typed as a reqwest client: clippy resolves inherent methods only, and a trait-impl path "does not refer to a reachable function";

    • reqwest::blocking;

    • declarations made through the RabbitMQ management HTTP API, and another AMQP client crate’s declare methods;

    • a second builder inside an already-`#[expect]`ed fn (per-fn granularity replaced the retired per-file builder count);

    • cfg(not(feature = …)) arms of a feature that another workspace member’s ordinary dependency turns on, which no clippy pass has off (§ The clippy passes); cargo xtask feature-matrix only cargo check`s its sets: the plugin axis (craig-web and craig-composition, each with `plugin-example,plugin-ssa-screening) and the workspace on its defaults. No feature links a jurisdiction’s partner code any more (ADR-090), so the matrix has no jurisdiction axis, and no_manifest_links_a_partner_crate holds every manifest to that. An arm behind a feature only a dev-dependency names is linted by the production pass (craig-mq’s fault-injection arms, #3057), and the battery-feature pass lints craig-intake’s self-signed-tls, the plugin-* features of craig-web and craig-composition, and authz-witness (#2598);

    • non-Rust code;

    • inline #[cfg(test)] modules, which may now declare topology directly (the retired path-classifying scanner flagged them); craig_test_lib::declare_scratch_classic_queue stays the classic-pinned path.

  • The dependency layer (#2603). deny.toml [bans] deny carries { crate = "lapin", wrappers = ["craig-mq", "craig-test-lib"] }: cargo deny check bans fails with error[banned]: crate 'lapin = …' is explicitly banned when any other workspace member, or a third-party crate, depends on lapin directly, and names the offending parent (unmatched-wrapper). It runs where every cargo deny check runs (the pre-push hook and CI’s cargo-deny job, § Advisory-ignore audit gate).

    • What it catches that the list does not: any lapin item outside the wrappers, whatever the method, and a new direct dependency in a manifest, test-only ones included: the ban reads the resolved graph, where a [dev-dependencies] edge counts.

    • What it does not catch: a call inside a wrapper crate (the call-site layer still holds those: craig-mq’s one #[expect], craig-test-lib’s test regime); a call made on a re-exported type (a crate holding craig_mq::amqp::Channel can still call queue_declare on it, which the call-site layer catches because clippy resolves the method to lapin::Channel::queue_declare); another AMQP client crate; and the management HTTP API.

    • The wrappers. craig-mq is the transport. craig-test-lib is the recorded exception: its scratch-queue and event-capture helpers (events.rs, case_assignments.rs) declare scratch exchanges and classic-pinned queues and consume from them, calls craig_mq::amqp leaves out on purpose, and its craig-mq dependency is optional (on only under fault-injection). Every other crate, craig-manage’s quarantine-drain included, names the item-by-item re-exports in craig_mq::amqp (shared crates § craig-mq). The module is never a wholesale pub use lapin, which would empty the ban.

    • reqwest stays on the call-site layer alone (analysis recorded 2026-11-12, #2603). No wrappers rule is written for it, for three reasons of size and shape, none of them a judgement that the layer is unwanted:

      • There is no single wrapper. Five crates construct clients on purpose (craig-common, craig-auth, craig-intake-sdk, craig-exchange-transport, craig-intake’s captcha verifier), and craig-intake-sdk is standalone by design (it takes no craig-common dependency), so its consumers cannot be routed through craig-common’s re-exports.

      • The types are the working vocabulary, not a few handles. reqwest is a direct dependency of 25 workspace members (21 normal, 4 dev-only). About 385 .rs files name a reqwest:: path, about 160 of them production sources: Client in signatures and struct fields (about 110 production files), StatusCode (about 50), Error inside typed errors (about 35), Response, RequestBuilder, header, multipart, Url, and xtask’s blocking client (14 files). A ban would mean re-exporting each of those from a wrapper and rewriting every one of those files, the ten partner adapters' error types included.

      • The risk the ban removes is construction, and tests construct freely. About 560 reqwest::Client::new() calls in about 165 files are test code under the test regime; a dependency ban would not change them unless test clients were also moved behind a helper.

        A wrappers rule becomes feasible once a wrapper crate re-exports that vocabulary and the roughly 385 files move to it. The pending TLS-backend decision (#2693) changes `reqwest’s feature set.

Remedy when it fires: hold the shared client or declare through the Subscriber. A genuinely new bespoke client is a new chokepoint fn with its own #[expect] and reason, listed here.

The ADR-068 db-error-construction line scanner (scan_db_error_construction) shared the retired reqwest scanner’s old truncation blind spot until #1576 and #2073 fixed it. A mod x; declaration never truncates it. A test-only inline module (cfg(test) / all(test, …), found by syn) skips only its own body. An any(test, …) module is scanned, and so is every line of a file syn cannot parse.

Jurisdiction-literal gate (#2207)

Wired into cargo xtask validate (blocking, right after the ADR-068 db-error classifier-bypass lint; standalone: cargo xtask lints jurisdiction-literals). The doctrine (maintainer, 2026-10-06, applying the ADR-072 tiers): no production source names a jurisdiction — a jurisdiction’s behaviour lives in its rulesets (tier 1) and its state bundle (tier 2). ADR-053 § Amendment #2207 moved the last eight production literals (the business-clock arms, the subsidy gates and two per-diem repair clocks) into bundle data. The gate is a syn visitor:

  • The token set is derived, never listed: every layer config-sources.lock pins and every fixture layer under fixtures/config/, except federal (the ADR-072 § Amendment #949 jurisdiction-invariant class), lowercased — today georgia, testonia and texas (until U4, #2955, the subdirectory names of rulesets/). A new jurisdiction’s layer joins the gate with no code change. An unreadable lock or fixture directory, or fewer names than the recorded jurisdiction.layers floor allows, fails the gate loudly rather than passing vacuously (the census-collapse precedent of the workspace-member seed floor).

  • What is flagged: a string literal whose value equals a token, ignoring ASCII case — in a comparison, a match arm, a "Georgia" case variant — including literals inside the token streams syn leaves opaque: macro arguments (format!, assert!) and list-attribute arguments ([serde(rename = "…")], [schema(example = "…")]), each walked recursively and counted once. Only a bare token matches: "georgia-authz-case" and other longer literals pass, and doc attributes (///, [doc = …] or [doc(…)]) are skipped as prose.

  • The scanned files: the workspace-member source surface (walk_workspace_member_sources, which skips the dev-tooling member), minus crates/craig-partner-* (the reference partner, the conformance kit, the SDK and the module host; the contract crate crates/craig-state-bundle/ is scanned, and clean), crates/craig-reference/ (reference data), crates/craig-test-lib/, tools/craig-seed/, every _tests.rs / tests.rs file and every path containing test_support (xtask is never walked, #2299).

  • Test exclusion is by cfg PREDICATE (attrs_are_test_cfg_only): an item, impl item, trait item or let statement whose attributes are test-only is skipped, while [cfg(any(test, …))] stays production. A [cfg(test)] mod x; declaration — at file scope or inside an inline module, with or without #[path = "…"] — excludes the file it resolves to and every file under that module’s directory. Tests that verify shipped rulesets may name jurisdictions.

  • Zero baseline, no allowlist: any hit fails the gate, reported by file, line and literal. The remedy is a bundle declaration or a ruleset, never an exception. Prose that names a jurisdiction without being a bare-token literal (OpenAPI descriptions, Fluent catalogs, theme metadata) is outside this gate; the product-copy gate owns it.

Implementation: xtask/src/cmd/lints.rs::run_jurisdiction_literals + the jurisdiction_literal_tests module.

Product-copy jurisdiction gate (#2213)

Product-default copy is jurisdiction-neutral (ADR-072; ADR-034 §3 calls the product catalogs the jurisdiction-neutral baseline). Jurisdiction wording lives in the bundle’s terminology overlay as a term-* message (ADR-034 §5/§6) or, for a policy input, in the ruleset that declares it: since #1719 the IV-E inputs' titles, descriptions and option labels are the {j}-ive-eligibility ruleset’s own (metadata.ive), which retired Georgia’s term-ive-ctw-first-order overlay and its product-default baseline. Two halves, one vocabulary: the #2207 token set (the config layer names except federal), matched as whole words ignoring case, so georgia-authz- is flagged and Georgian is not.

  • Catalogs and theme metadata — cargo xtask lints product-copy-jurisdictions, blocking in validate right after the jurisdiction-literal gate: every non-comment line (a comment is a # in column 0) of every tracked .ftl except tests/ fixtures (a jurisdiction’s terminology overlay lives in its configuration repository, outside this tree), and every string value of crates/craig-state-bundle/theme/.toml (the contract crate’s palettes carry CRAIG branding; a jurisdiction’s bundle/theme.toml overrides it).

  • The API reference — cargo xtask api-docs (and its --check validate step) scans every string of every served OpenAPI document — descriptions, summaries, `example`s, enum values — before rendering, in both modes. A doc comment utoipa serves is OpenAPI text, so it is scanned too; object keys are wire identifiers and are not.

  • Not machine-guarded (review): abbreviations (GA, TX — tx is also a database transaction), agency acronyms (DFCS) and places that are not CRAIG jurisdictions; template literals in services/*/templates/; Rust error and log strings that are not served OpenAPI text (for example the craig-config-bundle BundleError messages). The federal race category "American Indian or Alaska Native" is not a jurisdiction. Rust and TOML comments that are not served stay out of scope, as do identifiers.

  • Zero baseline, no allowlist: rows name the file and line (catalogs), the JSON pointer (theme, spec) and the word.

Implementation: xtask/src/cmd/lints.rs::{JurisdictionWords, scan_product_copy} and xtask/src/cmd/api_docs.rs::{refuse_jurisdiction_names, json_string_leaves} + the product_copy_jurisdiction_tests module.

OpenAPI registration gate (#2247)

Runs inside cargo xtask api-docs, in both modes, before rendering, so the validate api-docs drift step enforces it (blocking). utoipa serves a handler only when the service’s [derive(OpenApi)] names it in paths(…​); routing it does not. A routed, annotated handler the list omits is missing from the API reference, and the page diff cannot see it, because the page renders the document faithfully (#2247: GET /v1/security/workers; the same gap hid craig-cases' POST /v1/cases/_internal/jws-replay-check, #2331). For each rendered service, the (METHOD, path) set of the served document must equal the set the [utoipa::path] fns under services/<svc>/src/ declare:

  • An annotated handler the document does not serve is a row naming its file, line and fn. The remedy is a paths(…​) row, with its schemas and tag.

  • A served operation no scanned handler declares is a row too. This is the scan’s floor: a handler outside the scan (an impl method, a handler in a tests.rs / *_tests.rs file or in another crate) fails loudly instead of shrinking the check.

  • An attribute that does not open with <method>, path = "<literal>" fails closed.

  • A routed handler with no #[utoipa::path] is a row naming its line (#2577: craig-api’s POST /v1/admin/events/replay was in no document, because the scan saw only annotated fns). The gate reads every production method router — a one-argument call of an axum routing fn, get(h) or axum::routing::get(h), and each .post(h) chained onto one, through any .layer(..) — wherever it is built, so a router builder that takes MethodRouter arguments hides no handler. Each handler must be an annotated fn of the scanned trees, matched by fn name (syn cannot resolve the path across files, so an unannotated namesake of an annotated fn passes; review catches it). A handler that is not a fn path (a closure) fails closed.

  • A handler routed off its documented path is a row naming the line and both paths (2664). The two halves above hold the handler sets equal and read no path, so .route("/a/{id}", get(h)) beside path = "/v1/b/{id}" passed them, and the reference described a path the service does not serve. For each handler a production .route(<path>, <method router>) names, a [utoipa::path] of that name must carry the same method and a path that ends with the routed one. It is "ends with" because the router that mounts a service’s routes nests them under a prefix (/v1; the intake edge’s /public/v1, /partner/v1, /signed/v1) and the scan does not follow the nest: a wrong prefix is outside this check. The routed path is read from a string literal, a const or let of one (constants of the scanned tree and of every crates/*/src/, matched by name), or a format! whose arguments are inline captures of those. A fn that routes its own parameters (craig-cases' ledger_routes and event_routes, which build the ledger routes) is expanded at each call with the caller’s arguments, and a call wrapping one method router (craig-placement’s enrollment limiter) is read through. A path the scan cannot read fails closed, as does a builder called with an argument that is not a method router, and so does an annotated handler whose method router the scan cannot tie to a .route(..) at all (one held in a let, or passed to a builder whose name another fn of the tree shares). A constant name declared with two values, or once with a value that is not a string literal, is unreadable, not guessed, and a fn’s own name is read only when the fn binds it once, immutably, by a plain let or as a parameter. An annotated handler that no router names is not this check’s concern. A handler with no #[utoipa::path] is the previous bullet’s row, and the waiver below covers this check too.

  • The shared routes: crates/craig-api/src/ is scanned too. craig_api::ApiServer::router mounts its routes on every service built on it, and craig_api::served_document merges their documents into the document such a service serves and prints, so each shared handler must be served by every rendered service whose Cargo.toml lists craig-api under [dependencies] (the intake edge does not).

  • Waiver: a method router kept out of the reference on purpose (the /livez, /readyz, /healthz and /metrics probes, the intake UI’s pages and assets) carries // openapi: skip — <reason> in the // comment block directly above its line, or above the fn that builds it, which covers every method router in that fn. An empty reason is not a waiver. /version is built by craig_common::version::version_route, outside the scanned trees.

  • Test code is excluded by cfg predicate (cfg(test), cfg(all(test, …)); cfg(any(test, …)) stays production), by the tests.rs / *_tests.rs file names, and by the #2207 resolver (a file a test-only mod x; loads). Zero baseline; the only exclusion is a reasoned waiver.

Implementation: xtask/src/cmd/openapi_registration.rs (the router half in openapi_registration/routes.rs, the path half in openapi_registration/paths.rs), called from xtask/src/cmd/api_docs.rs::refuse_unregistered_handlers (the served set is coverage_matrix::spec_routes::extract_routes).

Unique operation-id gate (#2766)

Runs inside cargo xtask api-docs in both modes, right after the registration gate, so the validate api-docs drift step enforces it (blocking). OpenAPI requires each operationId to be unique within a document. utoipa derives an id from the handler’s function name, so two modules' same-named handlers in one service collide; craig-placement’s portal and home document handlers did, and the authenticated ZAP scan’s import refused the spec. The gate fails naming each repeated id with every METHOD path that carries it. The remedy is an explicit operation_id = "…​" in the colliding handler’s #[utoipa::path]. Zero baseline. Implementation: xtask/src/cmd/api_docs.rs::refuse_repeated_operation_ids.

OpenAPI version gate (#2975)

Runs inside cargo xtask api-docs in both modes, after the operation-id gate, so the validate api-docs drift step enforces it (blocking). Every served document’s info.version must equal Cargo.toml [workspace.package] version. A hand-written #[openapi(info(version = "…"))] drifts from Cargo: by v0.2.0 eight services and the identity issuer said 0.1.0 and craig-intake 0.2.0. With no version, utoipa uses the crate’s CARGO_PKG_VERSION, which every service inherits from the workspace, so the remedy is to delete the literal. The gate names each document and the version it reports. Implementation: xtask/src/cmd/api_docs.rs::{workspace_version, refuse_version_drift}.

Untyped list-envelope gate (#865)

Wired at the cargo xtask validate untyped-list-envelope step (blocking; standalone: cargo xtask lints untyped-list-envelope). A syn visitor over the service API sources, services//src/api.rs and services//src/api/* (lint_scan::is_service_api_source, #2604: the fleet’s HTTP boundary — store/worker code has no envelope to leak) flags two shapes in production code: a handler whose return type is, or wraps (Result<Json<…>, E>, (StatusCode, Json<…>), ApiResult<Json<…>>), a Json<T> whose T is or contains serde_json’s Value (Json<Value>, Json<Vec<Value>>, Json<Option<Value>>, Json<Map<String, Value>>) — spelled bare through a use alias (Value, an as rename, a glob), crate-qualified (serde_json::Value, sj::Value after use serde_json as sj;) or via the value module path; and a json!({ … }) invocation with a *top-level "data" key (a nested {"meta": {"data": …}} does not match). Recorded gaps: an in-file type alias of the return type and trait-fn signatures are not seen. Test-only containers are excluded by cfg predicate, never by line position. The charter: the {data: []}-vs-bare-array divergence (#769, #843) and per-site pagination math (#822) become type errors once a handler returns Json<Dto> / Json<PageResponse<Dto>> — the craig_common::pagination envelope #1083 already provides — and utoipa then emits a real response schema for the OpenAPI snapshot gate.

The ledger xtask/baselines/untyped-envelope.toml is the per-file COUNT ratchet, seeded green at the 2026-09-03 census (57 sites — 29 Json<Value> returns + 28 hand-built envelopes — across 20 handler modules) and reconciled bidirectionally through the shared reconcile_site_allowlist ratchet: a file outside the list, or a count above its entry, is a violation (a NEW untyped handler is a fresh decision the gate refuses); a count below is a STALE entry that must be blessed DOWN in the MR that typed the site; a listed file that reaches zero sites LEAVES the list (an entry of 0 never reconciles). The const shrinks by convention — like the quality-budget locks it is the reviewed baseline, and the gate itself refuses a new file or a count mismatch in either direction; migrating the listed sites is ordinary burn-down, one wave at a time. Argument-position Json<Value> extractors are deliberately out of scope (request bodies are the input-validation gates' concern, not the response-envelope class).

Problem-type status gate (#2411)

Wired at the cargo xtask validate problem-type status step (blocking, both profiles and the car; standalone: cargo xtask lints problem-type-status). ApiError’s typed constructors take any `&'static str as the problem-type URL, so nothing in the type system ties a problem_types constant to one HTTP status. The lint does: a constant is answered only under a status its doc comment states.

The registry is pub mod problem_types in crates/craig-common/src/error.rs, read through syn. The first line of each constant’s doc comment opens with its status (/// 409 — …, /// 400 sub-type — …). A constant that is deliberately answered under more than one status lists each, joined by commas and a final or (/// 400 or 422 — …), and the doc says where each applies; REQUIRED_FIELD_MISSING is the one such constant. A constant whose doc opens with anything else fails the lint, naming it, so the registry is always complete.

The call sites are the calls to bad_request_typed (400), forbidden_policy (403), conflict_typed (409), unprocessable_typed (422), internal_typed (500) and service_unavailable_typed (503) in every .rs file under the lint roots, test code and xtask included, read off tokens at any depth (macro arguments too; a comment or a string spells no call). A site is judged when its type argument is a path naming a registry constant: problem_types::NAME, alias::NAME under a use … problem_types as alias, or a bare NAME the file imports from problem_types (by name, by as rename or by glob). A finding reads file:line: CONST is documented <n>, used with <m> via <constructor>.

Not judged, and printed as the unjudged count rather than failed: a type argument that is a forwarded parameter, a local const or let, or an if / match that picks the URL, and a call whose arguments do not parse as expressions. Not seen at all: a problem type set without a typed constructor (an ApiError variant written as a struct literal, craig-common’s own From and IntoResponse mappings) and an import written inside a macro; imports are read per file, not per scope.

It fails closed: an unreadable or unparsable file (the registry included) is an error, and so is a scan below its recorded floors (files walked, constants read, sites judged; xtask/baselines/scan-floors.toml), so a reader that stopped recognising the registry or the constructors cannot pass on nothing.

The ledger xtask/baselines/problem-type-status.toml is empty: the ten sites that answered VALIDATION_FAILED (documented 422) with a 400 when the lint landed now answer a 400 type of their own (#3073; body-shape validation is 422 validation-failed, a semantic refusal a handler makes is a 400 under its specific type). A row is (file, constant, status, sites) with the reason, and each is a wire defect with its own issue, since fixing one changes a response’s status or type. The list only shrinks: a row admits its sites only while the tree holds exactly the count it states, so a second mismatch in a baselined file is reported, a row whose sites were fixed is stale and fails until it is deleted, and a new mismatch is fixed, never added.

Authz coverage gate (Plan A D17; the #1898 exhaustive-scope rule; the #1902 unit-attr rule)

Wired at the cargo xtask validate authz-coverage step (blocking; standalone: cargo xtask validate-authz-coverage, report-only unless --bail-on-bypass). A syn visitor over every [utoipa::path] fn under services//src/ — the OpenAPI registration gate’s universe (#2554; before it only src/api/ and flat src/api.rs, #1292, were read) — minus test code (a test-only-cfg module, a file mounted under one by B36’s #2207 resolver, a ![cfg(test)] file) requires the body to call the engine (one of its four entry points, check, auto_scope_list and their _typed twins, #2666) or a registered authorizing helper (below) — a CALL read off the body’s token tree (., the method name, a parenthesised argument list; macro arguments included) on an ENGINE receiver (#2555, is_engine_receiver): a path ending in authz (authz, ctx.authz, state.authz) or in <authz>.engine (authz.engine, authz_ctx.engine). A rate limiter’s or a replay guard’s .check(, a bare engine (craig-rules binds its rules engine so), a call result or a ? before the . does not wire, and the handler reports bypassed. The rule is a name rule, chosen over a typed seam (a handler parameter or state field of dyn AuthzEngine) that needs cross-file type resolution syn cannot give; a non-engine value named authz passes it, which review must catch. So a // or /* … */ comment, a doc comment or a string literal that spells it never counts, nor does a range into a free fn named check (#2332); a UFCS call (AuthzEngine::check(&*authz, …)) or a turbofish call (authz.check::<…>(…)) is not recognised and reports the handler bypassed (fail-closed) — or to carry // authz: skip — <reason> on any line of the contiguous // comment block directly above the handler’s first attribute (a reason is required — an empty one is a bypass; a blank or code line ends the block). The block is shared with the // evil-corpus: skip / // contention: skip waivers of the coverage ratchets (§ Coverage ratchets), one marker per line in any order, all read by lint_scan::skip_marker_reason (#2039). Bypassed (FAIL) is the blocking count; the module doc in xtask/src/cmd/validate_authz_coverage.rs shows the report shape. The scan walks services/ through lint_scan::walk_lint_root and reads and parses each file through lint_scan::read_lint_source and parse_lint_source, so a missing root, a walk error, or an unreadable or unparsable service file fails the gate, naming it — every handler in a skipped file would escape all three blocking classes (#2553). The report prints Files scanned first, and bail_on_thin_scan (called by the command and by the validate gate) refuses fewer files than the recorded floor allows (authz-coverage.files in xtask/baselines/scan-floors.toml, less one fifth). The report carries the engine-wired handlers by name (WiredHandler; CRAIG_AUTHZ_COVERAGE_FULL=1 lists them with the helpers they are wired through), and the ledger xtask/baselines/authz-engine-wired.toml pins the set as <file>::<fn> (#2556). Since #2666 the gate enforces the pin itself, in validate and under --bail-on-bypass, failing on any handler that leaves or joins the set and naming it; cargo xtask baselines bless --only authz-engine-wired rewrites the pin for review.

Registered helpers (#2666; plan authz-verification-integrity). A handler that delegates its check to a shared helper — the ledger cores record::<L> and friends, a route path’s authorize, the craig-rules bootstrap gates, craig_api::jobs::get_job — is engine-wired through it when the helper is a row of xtask/baselines/authz-helpers.toml (name, kind = "fn" | "method", defined_in, reason). A fn row matches a path call (name(…), a::name(…), name::<T>(…)) and verifies the free fns of that name in its defined_in files; a method row matches a method call (.name(…)) and verifies the impl and trait-default methods. The registry is verified, not trusted: every such definition must reach the engine — a call to one of the four entry points on an engine receiver (in a helper, also a parameter whose type names AuthzEngine) or a call to another row that reaches — and reach is a least fixed point, so a cycle of helpers with no engine call never reaches (a route path’s authorize that delegates to another path’s authorize reaches when some authorize reaches without the self-call). A row that does not reach is BLOCKING (Helpers not reaching (FAIL)) and names the helper, each definition and every handler wired through it. A // authz: skip comment above a handler the gate finds wired is BLOCKING too (Redundant skips (FAIL)): the comments left are exactly the exemptions — service-only bearer gates, partner-key and JWS edges, public endpoints, and human-admin operator acts gated on claims. Name matching is coarse: a handler that calls a same-named fn outside the row’s files counts as wired through the row, so a row lists every API-level file whose fn of that name a handler calls, and the wired pin shows any new wiring for review.

The runtime witness (#2667; plan authz-verification-integrity U2a). The static gate proves only what syn can see. In test and devstack builds, the authz-witness feature (craig-api, craig-bootstrap, craig-authz’s witness, and each of the eight ApiServer services) proves the wiring for every route a test reaches. craig-bootstrap wraps the installed engine in craig_authz::witness::RecordingEngine, which counts each decision (the four entry points) into a per-request task-local. A middleware on ApiServer’s protected routes runs each request inside a fresh count and stamps `authz-decisions: <n> on every response. A 2xx made with zero decisions on a route that is not a declared exemption becomes the typed 500 authz-unwired and increments craig_authz_unwired_total. Exemptions are matched by service, method and the mounted pattern against xtask/baselines/authz-exempt-routes.toml (embedded in craig-api), which the gate generates from the handlers' // authz: skip comments (the one declaration of an exemption), plus the shared admin event-replay route ApiServer mounts for every service. The gate fails on drift between the comments and the table; cargo xtask baselines bless --only authz-exempt-routes regenerates it. The feature is classified test-only on every crate that defines it, so the release-artifact gate refuses it in any release graph. The runtime-coverage recorder reads the header into HttpRecord::authz_decisions (record format v2). craig-intake, which has its own router and no engine-checked route, is not witnessed. Since U2b the devstack images carry the witness (the CRAIG_DEVSTACK_FEATURES build-arg; testing-reference § The authz witness in the devstack), so the battery and e2e verify every route they reach. A per-row filter (an unreadable row is omitted, never refused) over no rows reaches no entry point. It calls AuthzEngine::filtered_empty(<rows it would check>) first: the witness counts that as one decision only when the count is 0, so it can never vouch for a response with rows in it.

Unit-bearing check refs (#1902; plan admin-unit-scoping Decision 5, ADR-077 D5). Every ResourceRef { … } literal in the scanned files whose resource_type is [craig_authz::]ResourceType:: one of the fifteen unit-bearing variants (UNIT_BEARING_TYPES) — Case, Referral, Report, Investigation, Placement, KinshipOption, FosterHome, FosterHomeCaregiver (the caregiving unit’s admin_unit, #1928), HomeDocument (the parent home’s, #1909), EducationRecord and HealthRecord (the record’s creation-time stamp from the child’s latest live removal episode, #1909 b), Payment, PaymentAdjustment, SubsidyAgreement, SubsidyBackpay (#2225) — must carry attrs.admin_unit: the enclosing fn (handler, builder or impl method) inserts the key — attrs.insert(ATTR_ADMIN_UNIT, …) under any path to the craig-authz const, or the bare "admin_unit" literal, a conversion after it (.to_owned(), .into()) allowed; the insert is read off the fn body’s tokens (inserts_unit_key, #2552), so a comment, a doc comment or a string quoting it is none — and the literal’s own attrs is not an empty HashMap::new() / default() (a second literal in the same fn cannot lend its insert to an empty one). The ONLY escape is a nil-id literal (resource_id: Uuid::nil() — a collection / sweep / create check with no row to read) under // authz-unit: nil-id exception — <reason> on the non-empty line immediately above the literal, the enclosing fn’s first line (doc comments included) or its fn line; the reason is required. The class is BLOCKING (Unit attr missing (FAIL)), // authz: skip — <reason> does NOT exempt it, and the marker over a real-id literal or over one that already carries the unit is itself a failure — the marker names a nil-id exception, nothing else. The accepted exceptions print under Nil-id unit exceptions, and the ledger xtask/baselines/authz-nil-id-exceptions.toml pins that list as <file>::<fn>::<ResourceType>, enforced by the gate itself since #2666: adding or removing a marker means editing the pin in the same change. Why: D5 rules that an absent attrs.admin_unit evaluates false at the i_unit_match input, so a builder that forgot the insert would refuse every unit-scoped worker on that route once the U4 rows land; the rule makes the omission a gate failure at the literal, before any ruleset reads it. A literal whose resource_type is a variable (the security and rules builders) is not classifiable statically and is not scanned.

Exhaustive list scope (1898; plan admin-unit-scoping Decision 5, ADR-077 D5). In any handler whose body calls .auto_scope_list( (a call by the same token test, on ANY receiver — the wider precondition is the fail-closed direction here; a comment naming it does not make a list handler, #2332), the gate REFUSES a refutable test of ListScope — if let … ListScope::…, let ListScope::… else, or matches!(<scrutinee>, [craig_authz::]ListScope::…), or an equality test scope == [craig_authz::]ListScope::… / != in either orientation, a tuple variant’s payload (nesting at most one paren level) included — ListScope::AssignedWorker(id) == scope (#1915) (the scan reads each file’s code-only token view, lint_tokens::lex_view (#2620): comments, doc comments and literal contents are not code, so a raw string or a comment ahead of a test can no longer hide it and a string can never fake one (a comment glued between a test’s own tokens, as in if /* c */ let, can still break the pattern match, as it could before), and a scanned file that does not lex fails the gate, naming it; the matches! form is matched across rustfmt’s line wrap and any scrutinee spelling — scope, &scope, scope.clone()). The class is BLOCKING (Non-exhaustive scope (FAIL)) and // authz: skip — <reason> does NOT exempt it: the allowlist clears a handler of engine wiring, not of how it treats the scope the engine returned. Why: a refutable test names the variants it handles and lets every other variant fall through to whatever follows — at the thirteen pre-#1898 sites, the UNFILTERED query. A list handler instead matches scope.filter() (craig_authz::ScopeFilter { All, Worker, Supervisor, Units, Denied, Refused }) exhaustively under the workspace wildcard_enum_match_arm = deny, so ListScope::AdminUnits (U2, #1903) — and any variant after it — is a compile error at every list handler until that handler names the arm, never a silent widening of the list. Routing the scope through list_scope_verdict (itself exhaustive over filter(); since #2210 it admits only All, for lists whose rows carry no scope column) passes. Since #1915 the same refutable set is applied to every other fn in the scanned files — free fns, impl methods and trait default methods, a helper the scope is handed to — and reported under the helper’s name. Test code (a [test] / [cfg(test)] fn or module) is skipped. Since #2554 a file mounted under a test-only cfg (B36’s #2207 resolver, cfg_test_module_files) or a ![cfg(test)] file is test code too. The workspace wildcard_enum_match_arm = deny alone would catch only a helper’s _ ⇒ arm. A .check(-only handler is not scanned for this class.

Route role coverage (#490)

Every route inside the protected_routes fn in services/craig-web/src/main.rs declares its role tier in the type system. No lint reads the source for it (#2665).

protected_routes builds its table through ProtectedRouter (services/craig-web/src/role_gate.rs), an alias of craig_bff::gated::GatedRouter<AppState, RoleGate>. The builder wraps the axum router and has one way to add a route, route(path, gate, method_router). It has no Deref to the router and no public field, so a route written without a gate is a compile error: the compile_fail,E0061 doctest in crates/craig-bff/src/gated.rs pins that, beside a passing twin of the same snippet with the gate supplied. into_router() ends the table; protected_routes adds only the fallback and the table-wide layers (require_write_access, require_auth, verify_csrf) after it.

RoleGate is an enum with one variant per tier:

Variant Middleware Admits

CaseworkerDefault

none

every worker session require_auth admits; the backend or the handler decides

AdminOnly

middleware::require_admin_only

admin

AdminOrSupervisor

middleware::require_admin_or_supervisor

admin, supervisor

AdminOrCountyDirector

middleware::require_admin_or_county_director

admin, county_director

FieldApprover

middleware::require_field_approver

admin, supervisor (FIELD_APPROVER_ROLES)

The variant-to-middleware mapping is one match with no wildcard arm (RoleGate::apply), so a new variant does not build until it is mapped. The gate is layered over every method the route serves and outside any layer already on the method router, such as an upload route’s DefaultBodyLimit. The test each_tier_serves_its_roles_and_refuses_every_other in role_gate.rs drives a route declared with each variant as each role and asserts the status.

Use CaseworkerDefault for read-only views, list pages and write paths any worker can use, and a higher tier where the page or act needs it (for example AdminOrSupervisor for security/audit and the NCANDS approve, AdminOnly for partner administration). A route whose methods need different tiers takes the lower tier and enforces the higher one in the handler, as /financial/subsidy-agreements does for its POST.

These gates are defence in depth: the backends' rulesets stay the authority. See ADR-027 for the underlying role model.

sops-policy gate (#1382, ADR-064)

Blocking gate-table row (cargo xtask lints sops-policy, a car line; the car’s MR rule includes .sops.yaml + secrets/**/* so a store-only rotation MR still runs it; the secrets-policy job runs cargo xtask secrets policy, the parity, needle and keyed-decrypt checks): the repo-committed encrypted secrets store must stay structurally sound. Enforced: strict .sops.yaml grammar (exactly creation_rules with compiling path_regex + canonical-bech32 age recipients, plus a parser-differential tripwire — the lint’s YAML view and the store tooling’s own recipient parser must agree or the gate fails closed); encrypted-only ciphertext (every leaf ENC[AES256_GCM,…], diagnostics name keys only — never values); .sops.yaml↔ciphertext recipient parity; a split-form age secret-key needle over both surfaces; and NO non-YAML artifacts under secrets/ (the walk is filesystem-side, so untracked decrypt residue fails); no link and no special file anywhere under secrets/, secrets/ and .sops.yaml included: the walk (lint_scan::walk_regular_files) follows no link, and a symlink (file, directory or dangling) or a socket, FIFO or device fails the gate, naming it, judged from the entry’s own type before anything opens it — git commits the link, not its target, so the gate cannot vouch for one (#2623). Armed from day one — a missing store is itself a violation (partial-revert guard).

Remedy when it fires: recipient changes go through cargo xtask secrets add-recipient / remove-recipient, store edits through cargo xtask secrets edit; never hand-edit either surface. Run cargo xtask lints sops-policy for the full list, cargo xtask secrets check for the non-disclosing store verification.

release-artifact test-only-feature gate (#1502, #2646, ADR-067 §D4)

Blocking xtask validate step (cargo xtask release-artifact-gate, folded into the pre-push battery): no test-only feature may reach a promoted image. That covers the contested-environment fault-injection seams (craig-mq/fault-injection, craig-crypto/fault-injection, craig-store/test-util), the test-util / test-fixtures constructors, the contract-stub send authority and the module host’s stand-in-sources, every partner mock route, and the devstack-only plugin-example and self-signed-tls. They ship default-off and activate only through dev-dependencies, a devstack build-arg, or the devstack’s one compile and the clippy lane’s second pass (lanes::BATTERY_FEATURES).

Since #2646 the gate hand-lists neither side:

  • The forbidden set is every member’s [package.metadata.craig] test-only-features, read from cargo metadata. Each feature except default sits in exactly one of release-features / test-only-features. The gate fails on an unclassified feature, a feature in both lists, or a listed name missing from [features], so a new crate’s mock cannot pass unseen.

  • The release build units are the Dockerfile cargo build invocations whose binaries a promoted target’s stage copies (COPY --from=<stage> /out/<bin>), the promoted targets being the stages docker-bake.hcl’s `release group builds. The gate also reads the bake file itself (#3045): every target it groups must ship only builder / tools-builder units (never a copy-only *-devstack stage), and no release target may set a build arg a unit expands as features or name a declared test-only feature in a value. The gate never infers them from stage names. A unit’s whole -p set is one feature-unification graph, so a tool built beside a service is seen. The parser fails on --package, -pX, --workspace and a literal feature flag. The build args a unit expands into --features (${VAR:+--features "$VAR"}) are searched for by literal name, over-approximately: quotes, backslashes and whitespace are removed first, so no quoting, escape or continuation splits a literal name. The search covers the Dockerfile and the in-repo CI configuration, .gitlab-ci.yml and every local file any of its YAML documents includes, each CI file read as raw text and as its YAML-decoded string values. CI configuration that names a features variable fails, wherever the name sits (a variable, a script line, a comment); the error gives the file’s line, or on the decoded path the decoded value’s line. In CI text, the word that directly follows a literal --build-arg also fails when $ or a backtick builds its name. A remote:, project: or component: include fails closed, and a GitLab template: include is not followed. A Dockerfile instruction naming one, in any stage (comments are inert and skipped), passes only as an empty ARG declaration (ARG VAR, ARG VAR=, ARG VAR="" or ARG VAR='', nothing else on the line) or as the canonical ${VAR:+--features "$VAR"} expansion inside a RUN. Any other mention fails (an ENV, a RUN VAR=… or export, a ${VAR} used elsewhere), and so does a key that $ or a backtick builds (any ARG / ENV word, an assignment-shaped word elsewhere).

A text check cannot see what the text does not literally say. Outside it: a flag or name assembled through shell variables (F=--build-arg; K=CRAIG_WEB_; … $F ${K}FEATURES=x), shell brace expansion, a !!binary or otherwise encoded scalar, the GitLab templates the gate does not follow, a CI/CD settings variable (defined in GitLab’s project or group settings, outside the repo; promotion’s settings variables are operator configuration, reviewed there), and a features value computed at build time (a RUN that sources a context file, printf -v, an opaque $X in the cargo arguments, a # escape= parser directive). The complete check is #2709.

The gate walks cargo tree -e normal,build (normal + build deps only, dev-deps excluded) over each release unit and over xtask. It fails if a test-only pair is active, and fails if the parsed output omits any unit package (an empty tree never passes). Before #2646 the Dockerfile built craig-seed and craig-mock-server in the services' cargo build, so resolver 2 unified a state crate’s mock feature and all ten partner mock features into every service binary, unseen by the old hand list. The tools now build in their own tools-builder stage, and no build compiles a partner mock in: a devstack’s are the simulators of its configuration layer, loaded by the mock server (ADR-090). Honest claim (ADR-067 §D4): "absent from release artifacts and every normal-dependency graph, machine-enforced" — NOT "impossible" (the seams compile under --all-features, by design).

craig-auth/test-fixtures (#2647) compiles ClaimsBuilder and JwksProvider::inject_keys, and craig-common/test-zones (#2956) makes BusinessClock answer the shipped zones for a jurisdiction nothing installed. xtask’s graph carries both through craig-test-lib, as the gate’s two named exceptions (XTASK_GRAPH_EXCEPTIONS). The operator tools left xtask under ADR-088 (#2671), so what needs the dependency now is developer and CI tooling, listed on #3135. Both exceptions are an accepted risk (ruled 2026-11-18, #3135): xtask is the developer task runner and is built into no released image, and a release unit that built it would carry these pairs with no exception and fail. The gate prints each exception on every run and fails once xtask’s graph no longer carries it, so a stale exception cannot linger; the release units take no exception.

Remedy when it fires: a normal (non-dev) dependency, or a tool built in the same cargo build, enabled a test-only feature. Make that edge a dev-dependency, drop the feature from it, or build the tool in its own unit. A new feature needs a line in its crate’s [package.metadata.craig]. Run cargo xtask release-artifact-gate for the detail.

Program-verification gate (C24, #1519, ADR-067 §D9)

Two blocking xtask validate steps that BRACKET the integration battery, plus the standalone cargo xtask program-gate:

  • before nextest — program_gate::reset purges every executed-fault record (every test-results/fault directory, discovered by walking the checkout) and writes the run stamp test-results/fault/.gate-stamp;

  • after nextest — program_gate::verify checks that every record postdates the stamp, that no record file was unreadable (the aggregation counts read/parse failures), that every armed fault fired, that the run executed faults AT ALL, that every recording class fired, and that the program’s two self-tests still exist in the nextest inventory; then retains test-results/fault/fault-report.json and consumes the stamp (single-use — only on success, and never from the standalone command).

The fault layer is REQUIRED for the same battery (fault-preflight --required), so a run cannot go green with the fault sidecar absent. validate --skip-devstack never reaches either step (its substitute battery is --lib --bins) and is the one sanctioned fault-optional mode.

Remedy when it fires:

  • "no run stamp" — this verification already passed once (the stamp is consumed on success), or the reset/verify pairing broke mid-run. Either way the accounting cannot be attributed to a run again; re-run the battery.

  • "record(s) predate this run’s reset" — two batteries' evidence is mixed, or the record filesystem’s clock lags this host’s. Delete the test-results/fault directories and re-run.

  • "record file(s) could not be read or parsed" — a test was killed mid-write. The missing record could be the armed-but-unfired fault the gate exists to catch; re-run rather than deleting it.

  • "armed but NEVER fired" — a real finding: the test armed an injection its codepath never reached, so it passed for the wrong reason. Fix the leg, not the gate.

  • "ZERO executed faults" — the fault-gated legs did not run (--run-ignored all missing, or a filter excluded them).

  • "class(es) … reported ZERO this run" — a recording class lost its legs or its recorder.

  • "the gate’s self-test(s) are gone" — a rename updates SELF_TESTS in the same diff; a delete retires a guarantee and needs saying out loud.

Honest limits, recorded in the module doc and the runbook rather than implied away: the per-class floor is enforced only for the classes that emit records today (#1546), the armed⇒fired check is only as sharp as the recorders that observe firing (#1547), and the self-test check pins EXISTENCE, not behavior.

Coverage-signature gate (#2704, plan runtime-coverage-matrix D6)

cargo xtask coverage-matrix --check is a blocking step of every full devstack battery: cargo xtask test --integration (local validate and the car’s battery lane). It runs in the battery’s last step, right after the coverage matrix is computed from the run’s HTTP recordings (Coverage Matrix). The scoped run (cargo xtask test --package <crate> --integration) never checks: a partial battery cannot judge what it did not observe.

What is required. Every operation of the nine api_docs::SERVICES specs requires these signatures, each earned by a credited record (a passed test’s final attempt) on the route:

  • S1 success: a happy credit, a 2xx.

  • S2 refusal: a sad or evil credit, a 400, 404, 409, 422, 401 or 403.

  • S3 replay, only on an idempotent route: a replay credit, a 2xx carrying Idempotent-Replayed: true. A route is idempotent when it is a POST, PUT, PATCH or DELETE whose application/json or multipart/form-data body schema has a client_request_id property in any $ref, allOf, oneOf or anyOf branch (Coverage Matrix § Idempotent routes).

A required pair is a route and one signature; it is missing when the run credits it nothing.

Provenance first. The check and the bless both refuse, each with its own message, unless the run manifest test-results/http/run.json, which the full battery writes once nextest and its gates pass, proves the recordings are a full battery of the current, committed tree:

Refusal Cause, and the remedy

no run manifest

No run.json: run the full battery.

unreadable

run.json does not read or does not decode.

scoped

It says kind: scoped; a scoped run’s records are never gated.

foreign run

Its run_id is not the records' NEXTEST_RUN_ID: the two come from different batteries.

tree mismatch

Its tree hash is not git rev-parse HEAD^{tree} now: re-run the battery on this tree.

dirty

The battery ran on a dirty tree, or the working tree is dirty now: commit or stash, then re-run the battery.

spec mismatch

Its spec digest is not the from-source specs' digest now: re-run the battery.

The check. --check compares the missing pairs with the baseline and fails on drift either way:

  • a new pair is missing and not in the baseline. Its line names the tests that call its route (every credited record on it, whatever its status), or says (no test calls this operation); a replay line also prints the route’s replay attempts, which tell a replay never sent (0) from one sent but never confirmed.

  • a stale line is in the baseline but no longer missing. It is unserved (the route is no longer an operation of the specs), no-longer-idempotent (a replay line for a route the predicate no longer marks, whatever its credit) or observed (the run credits it now; its line names the observing tests).

A clean check prints one line with the counts of required pairs and missing ones.

The baseline, the ledger xtask/baselines/coverage-signatures.toml, records the gaps the gate accepts: one <service> <METHOD> <template> <signature> entry each in its pairs list, sorted in byte order, under a header comment. The file has no default: a missing one refuses. An entry that is not exactly four tokens, or has an unknown method or signature word, refuses the load; an unsorted or a duplicate entry refuses, naming its position. The baseline is shrink-only:

  • cargo xtask baselines bless --only coverage-signatures rewrites it from the last full battery’s recordings, keeping only the entries still missing and dropping (and printing) the stale ones. It adds a missing pair only with --allow-growth "<why>"; the reason is written into the file. Without one, a missing pair the file lacks refuses, named.

  • Bless only after a full battery of the committed tree; provenance refuses anything else, before the bless writes. Writing the baseline dirties the tree, so a second check or bless before the baseline is committed refuses as dirty: commit it, and the next battery checks it.

  • Closing a gap deletes its entry in the same commit as the test that earns it; an entry left behind is stale and fails the next battery.

  • An added entry, a gap accepted without a test, needs justification in its MR.

  • cargo xtask baselines check only proves this ledger loads and is in order; the gate itself needs a battery’s records and runs in the battery.

Flapping. A signature seen only on a racy path flips between missing and stale from one battery to the next. A required signature comes from a deterministic test: a flapping route is a test defect, fixed under its own fix: issue, never baseline churn.

Scenario-inventory audit gate (#665, ADR-071)

cargo xtask scenarios audit over the two-corpus scenario inventory (compliance/scenario-inventory/ core + each config layer’s scenarios/ pack). The doctrine is Canopy ADR-032’s, verbatim: uncovered scenarios never fail; lies in the inventory always do. Checks: id grammar + closed vocabularies (stage list, entity registry) + corpus/file placement; global id uniqueness; declaration-anchored binding resolution (a describe title in a comment, a .skip/.fixme suite, or an attribute-less fn does NOT resolve; a devstack-gated #[ignore] test DOES — the battery runs --run-ignored=all); policy_refs resolution (ruleset file#json-path via ADR-070’s resolver, adr: existence); the BIDIRECTIONAL oracle↔invariant-catalog join (invariant classes must name a real stem with matching blocking-ness; a cataloged key may not hide under a non-invariant class; stem == header-name asserted catalog-wide); knob/blocked_by formats; the reverse audit over journey-*.spec.ts. Coverage status is DERIVED from path-derived binding altitude vs the row’s level — rows never self-grade. A pack is active because its layer carries one (the rulesets/scenario-packs.toml registry, set-equal in BOTH directions since #1618, retired with U4, #2955); a missing layer view, or a view with no pack at all, fails the audit; duplicate invariant-catalog stems across service buckets are findings (the scenarios join and the runtime gate key on the bare stem).

Enforcement (since 669, B5): the standalone command AND the validate step are BLOCKING — any finding fails pre-push and CI; the committed corpus is additionally audited by a battery [test] in xtask::cmd::scenarios. The ratchet is the committed per-ID ledger compliance/scenario-coverage.lock (status/level/oracle-set monotone per row, per-corpus covered floors over the denominator, human tombstones; ADR-071 § Amendment — #669): coverage regressions are findings too, and an absent lock is itself a finding. Record honest forward moves with cargo xtask scenarios audit --bless (refused on findings or regressions; a reviewed, CODEOWNERS-owned diff — never edit the rows by hand). Knob-capped and blocked rows are reported in their own buckets outside the denominator.

When the gate fires

  • "ledger — …" — a coverage regression against the lock (id vanished without a tombstone, level lowered, oracle set shrank or an oracle was demoted into a weak class, status regressed, floor broken); restore the coverage or add a reasoned .

  • "binding asserts sweep stem … but the spec tracks no … footprint" — a journey binding claims a sweep-run oracle its spec never records ids for; ledger.track the entity kind in the spec (or drop the assert).

  • "dangling binding" — the bound file/describe/test fn no longer exists, went .skip/.fixme, or lost its test attribute; fix the binding or the test, never by deleting the row.

  • "enforcement — declared … but the catalog says …" — an invariant was promoted or demoted; update the oracle’s enforcement to match reality.

  • "key matches catalog stem" — an oracle understates a cataloged invariant; declare the invariant class.

  • "corpus/stage segment" — a row is filed in the wrong corpus dir or stage file; move it.

  • "orphan journey spec" — a journey-*.spec.ts exists that no scenario binds; add the binding (with its asserts) or rename the spec.

  • "knob-evidence registry … unreadable / does not parse / unsupported glob" (#668) — tests/e2e/knob-projects.toml is the declared evidence for which Playwright project runs with which knobs ON; without it knob-gated rows cap at Partial (knob-capped).

  • "no config layer carries a scenarios/ pack" — the layer view holds no pack (run cargo xtask config fetch); never delete a pack to green the gate. Until U4 (#2955) the "scenario-pack registry drift" finding held the packs to rulesets/scenario-packs.toml (#1618).

  • "duplicate stem" — two invariant-catalog buckets carry the same filename stem; rename one file — stems are the gate’s join identity (#1618).

Known Agent Biases

AI agents trend toward recommending older, heavily-documented tools over newer, better alternatives. When making architectural recommendations, always perform web research for current state of the art (see the delivery-protocol standard). Known stale defaults to watch for:

  • OpenSSL over rustls (rustls is mandated — see deny.toml)

  • Selenium/Cypress over Playwright (Playwright is mandated for E2E)

  • reqwest with openssl-sys over reqwest with its rustls feature

  • chrono over jiff or time (evaluate current state before choosing)

  • Heavyweight ORMs over lightweight query builders

  • Class-based or inheritance-heavy patterns over composition and traits

  • Older serialization formats over modern alternatives

  • Assuming library APIs from training data instead of reading current docs — methods get renamed, removed, or change signatures between major versions. Always verify against the actual version in Cargo.toml (see the delivery-protocol standard § Library usage)

  • Using deprecated config file formats (e.g., cargo-deny v1 format when v2 is current)

  • Jumping to workarounds instead of diagnosing root causes — when something breaks, agents tend to try alternative approaches rather than reading the source to understand WHY it broke (see the delivery-protocol standard § Debugging)

  • Defending wrong mental models against contradicting evidence — rationalizing instead of re-examining

  • Manufacturing borderline findings to make an audit step "feel productive" — an audit is a measurement, not a mandate. When the discovery honestly surfaces zero action items, the audit documentation itself (clean baseline + evidence the discipline holds) IS the deliverable; forcing a false positive ratchets discipline down

  • Leaving stale placeholders in a plan/close-out Status table — the author knows each step’s real MR + SHA but stays in working memory while the "this MR"/"TBD" cells accumulate. Dispatch a fresh Explore subagent that reads the FILED plan body cold at every archive/close-out MR; it reliably catches the gaps the primary agent’s working memory papers over

  • Charging into a /loop or resumed prompt without verifying the work is still open — sessions accumulate stale queued prompts that may reference already-shipped work. Run a quick 2–3 command state check (git log for the touched file + nav entry + issue-tracker view) BEFORE doing the work; discovering the task is already done is a valid, correct outcome

  • Trusting an audit subagent’s verdict TAG over its own body evidence — the tag and the evidence are generated in different passes and can disagree (a FAIL tag over a body that clearly demonstrates PASS). The body evidence is ground truth; re-read the cited file:line before reacting, and don’t reflexively block on a tag mismatch

  • Blindly implementing an aged backlog item from its original framing — old issues are frequently already resolved by later work, or rest on a premise the implemented design has since contradicted. Verify each against current main FIRST (grep/read the cited files, run the relevant test); closing-as-verified-resolved with a criterion-by-criterion comment is a valid deliverable, and a since-contradicted premise is a domain decision, not a blind implement

  • Building a work master-list from all-state (or unverified) issue inventory — query OPEN-only state (not --all), and before recommending any item sample its body for external-CR / other-team / gateway / stakeholder-filed signals; a top-ranked recommendation drawn from a closed or externally-owned issue is worse than none

  • Recommending a new tool, dep, script, or pattern without first checking whether the project ALREADY has infrastructure for it — the reflex defaults to the lowest common denominator ("add an ad-hoc bash script", "pull in a new crate") instead of the established CRAIG pattern, and quietly builds parallel machinery beside an existing tool. Before proposing anything new, grep cargo xtask --help, scan tools/ and tests/, check Cargo.lock / cargo tree, and skim the plans archive for prior work on the same need. If the existing infrastructure is genuinely wrong-shaped for the new use, say so explicitly with reasoning — never silently pretend it doesn’t exist

This list is a living document. When you catch an outdated recommendation, add it here.

Citation audit gate (#661, ADR-070)

cargo xtask policy audit over every config layer: the two-granularity universe (per-rule keys for program JDMs; per-file for authz
composition config TOMLs; the screening-policy files retired with #1672) vs citations.toml coverage and the expiring citation-exceptions.toml. Same polarity as the scenario gate: uncovered keys never fail in advisory jurisdictions; manifest lies always do (schema violations, broken content tethers, orphaned or expired exceptions, unresolvable keys). blocking_jurisdictions is code-side; since A5 (#663) and the texas population (#1622, both 2026-09-03) it names georgia and texas — their uncovered keys and (georgia’s) unpinned pamms rows are findings. Both landed at full-universe coverage: every rule key of every program ruleset either cites its source (evidence quote in notes, so a row is checkable from the file alone) or sits on the expiring citation-exceptions.toml ledger under one of three recorded row classes — plumbing (mechanical table rows: catch-all defaults, "not screened in → none", the timeliness overdue/critical/warning/on-track status rows), operational (CRAIG design with no external policy source: routing methods, caseload tiers, county→region maps, person-match thresholds, proximity tiers) and source-not-located (a real policy claim no source was found for — the shortest review_by) — plus file-level entries for the authz matrices and the composition config TOMLs. Texas has no git-backed source (policy-source.toml type = "manual": the DFPS handbooks are web pages, the Family Code is statute), so its rows carry URLs and no pins; its drift control is the staleness warning’s re-read cadence. The battery pin is the committed-corpus finding-free test in cmd::policy (+ the per-jurisdiction manifest tether tests in crates/craig-policy/tests/); validate prints the per-jurisdiction coverage summary report-only.

Its sibling, cargo xtask policy drift (#662), compares the manifest’s pamms pins against a fresh cache sync — CHANGED/MISSING-UPSTREAM/UNPINNED raise, an unexpired drift-acks.toml entry on the CURRENT hash suppresses to ACKED (expiry or a further change re-raises; entries cap at 90 days). It runs as the weekly discriminated-schedule CI job policy-drift (POLICY_DRIFT=true on the Monday schedule), allow_failure FOREVER — it compares a live upstream and can go red with zero repo change; the ack ledger is what stops known drift shipping forever.

The url source kind (#1970 — the federal layer, the class rulesets § "The federal ruleset class" describes) runs the same classes per AUTHORITY over sources.toml’s `[source.*] rows, never the generated manifest: a cfr / federal_register row’s source_ref is fetched through the injected PolicyFetcher (10 s connect / 30 s total, fixed constants — not knobs) into .policy-cache/<sha256 of the URL string>.<ext> and hashed; an acf_technical_bulletin row hashes the COMMITTED file at source_ref (the federal layer’s sources/acf/<bulletin>-<bulletin_version>.<ext>) with no network; every other authority is skipped (no pin doctrine). A non-2xx, timeout or transport failure is MISSING-UPSTREAM (pinned) or UNPINNED (not) with the status after the class token — never CHANGED, and the bytes are cached ONLY on a 2xx. --jurisdiction is repeatable (policy drift --jurisdiction georgia --jurisdiction federal --jurisdiction texas is the scheduled job’s line): every dir renders its own section, in the order given, into ONE policy-drift-report.txt; a dir that fails BEFORE classification (a missing policy-source.toml, an unreadable manifest) renders a FAILED before classification section and counts as one raise without skipping the others; the command bails ONCE with the total. What drift does NOT detect: it watches the PINNED artefact at the pinned URL / path only. A new annual CFR edition (a new govinfo volume URL each October), a Federal Register amendment published elsewhere, or a new bulletin version is NOT discovered — that is a maintainer task (the October annual-edition check + the FR amendment watch; the automation follow-up is #1975). Since #1974 the url-class rows (cfr / federal_register) of a pamms-git or manual dir’s citations.toml drift the same way, in that dir’s own section, with their pins in that citations.toml (the #1619 --pin / --repin doctrine). Georgia’s FMAP and crosswalk rows and Texas’s 45 CFR 1356.21 rows are among them, which is why texas is in the scheduled line. A dir with no such row never builds an HTTP client (rulesets § "Url-class rows outside the url dir").

Dockerfile hygiene gate (#868)

cargo xtask lints dockerfile-hygiene (blocking in validate’s doc-lint phase — a line scanner over LOGICAL lines — backslash continuations joined — no compile) is the container-ops mandate as a machine floor over every tracked Dockerfile: each file `git ls-files lists whose name is Dockerfile or Dockerfile.<suffix> (2675; see "Scan set and carve-outs" below). The rules are the same for every file: every RUNTIME stage — a LEAF, non-build stage (not chef/planner/builder, and not used as another stage’s base; the shared runtime base is therefore exempt while every service stage derived from it is checked) — must end as a non-root user (its own USER, or one inherited through its FROM <local stage> chain; root, 0 and root:/0: forms count as root, and a stage that switched to USER root for a package install must switch back), must carry an ENTRYPOINT/CMD (a serving stage that runs nothing is a finding, never a silent exemption), and must carry an image HEALTHCHECK other than NONE unless a dockerfile-hygiene: no-healthcheck <reason> line INSIDE the stage carves a one-shot job out (the seed; a reason is required, and a marker placed above a FROM is itself a finding). Independently, NO stage may apk add an openssl* package or apt-install libssl-dev (deny.toml bans the crate; rustls-only). The ban is on what lets a build link openssl: apt’s openssl package is the command-line tool alone and is outside the rule (the CI job image installs it, #3060). Findings anchor to the stage’s FROM line (or the offending instruction). The committed Dockerfile is pinned clean — with exactly twenty-nine runtime stages — by a unit test, so the floor can only ratchet.

Scan set and carve-outs (#2675). The scan set comes from git’s index, not from a list or a directory walk, so a Dockerfile added anywhere in the tree is scanned from the commit that adds it, and untracked work is not. The workspace Dockerfile is reported first and the rest in path order. A Dockerfile.dockerignore (or Dockerfile.<x>.dockerignore) is an ignore list, not a Dockerfile, and is skipped. A final stage written as an unaliased FROM <earlier stage> is a stage of its own and is checked as a runtime leaf.

A file meets the floor by a fix or an in-stage marker where it can. A file that cannot is a row of the CARVE_OUTS table in xtask/src/cmd/lints.rs: its path, the rules waived for it, and the reason. The waivable rules are user, entrypoint, healthcheck and marker-placement (a marker above a FROM); the openssl ban and the validity of an inherits-user or root-residue marker are not waivable. Every run prints each row as a CARVE-OUT <path>: waives <rules> — <reason> line. A row that waives a rule its file does not break, or that names a path that is not a tracked Dockerfile, is a finding, so a row is removed when its file is fixed or deleted. A unit test pins the committed rows, so adding or widening one is an edit of that pin. The rows today:

File Rules waived Reason

ci/Dockerfile.ci

user, entrypoint, healthcheck, marker-placement

A CI job image, not a shipped one: jobs run as root to write the checkout GitLab mounts and to drive Docker through its socket, the job supplies the command, and nothing is served. Its no-healthcheck marker sits above the FROM.

tools/craig-devtools/Dockerfile, tools/craig-gitleaks/Dockerfile

user, entrypoint, healthcheck

One-shot tool images with one invoker, xtask/src/devtools.rs, which names the command and passes --user UID:GID on every run. They serve nothing.

These three are rows rather than in-file markers because each file’s bytes are hashed into the tag of the image it builds: a comment added for the lint would make every box and CI rebuild an unchanged image. tests/e2e/Dockerfile needs no row: it sets USER pwuser and an ENTRYPOINT, and carries the one-shot no-healthcheck marker.

Devstack overlays (1646). The devstack//Dockerfile overlays are single leaves FROM an *external image whose USER the scanner cannot see across the image boundary, so the file carries an attestation with its source: dockerfile-hygiene: inherits-user <user> <source URL> INSIDE the stage. What the lint checks is the marker’s PRESENCE, that a source URL is given, and that the declared user is not root (root / 0 / root:… are findings); the fact itself is the cited vendor source, sourced row-by-row in local-dev § Devstack image run-as users. Marker validity is checked on EVERY runtime stage, whether or not it sets a USER (an invalid marker beside a real USER is still a finding); on a stage based on a LOCAL stage a marker is a finding, because local chains are followed for real and a marker must not paper over one. A root-running leaf on an upstream base may carry # dockerfile-hygiene: root-residue <reason> instead: a REASONED residue on an upstream base is a WARN line on every run, never a finding (the residue set is pinned by a unit test — EMPTY since #1653 made garage non-root, the last residue — so adding one is a conscious edit of that pin); a reasonless one, or one on a locally-based stage, IS a finding. Only a VALID marker also vouches for the inherited ENTRYPOINT/CMD (it comes from the same upstream image the marker names); the HEALTHCHECK rule still applies — the overlays name their compose-defined probe through no-healthcheck <reason>. The CRAIG-authored garage-init one-shot is a real leaf: its own USER craig (uid 10001) plus the one-shot carve-out. --path <file> narrows the scan to a single file.

Edit this page · latest