Coding Conventions (Canopy)

For a contributor or coding agent about to change canopy code: this page carries only what is canopy-specific. The universal Rust conventions — style, errors, concurrency, formatting, the [workspace.lints] table, SPDX headers, plan authoring, ADR format, dependency management — live in the standard and are not repeated here. Where an ADR or a plan owns the detail, this page points at it.

Askama 0.16 templating quirks

canopy-web uses askama = "0.16" (the workspace Cargo.toml). Each point below was checked on 0.16.1; examples written for an older release mislead on some of them.

  • {% call macro() %} is a block and needs {% endcall %}. A missing one is the error "expected endcall to terminate call node", reported at the call.

  • {% let x %} without a value no longer declares a variable: it opens a block that ends at {% endlet %}, whose text becomes the value (0.16). To declare a variable and assign it later, write {% decl x %}.

  • A block defined twice in one template is an error (0.16; a warning before).

  • The .html escaper emits numeric entities (<, >, ", ', &); escaping tests assert the numeric form. Escaping applies in attribute position too.

  • Option<String> binds via {% if let Some(x) = field.as_ref() %}; ref x is rejected ("cannot use ref as a name": a Rust keyword).

  • A method call works in an expression ({% if rows.is_empty() %}), and so does {% match %} (services/canopy-web/templates/cases/medicaid_worker_facts.html).

  • A template brought in by {% include %} reads the including template's fields and may call methods on them.

CI/CD runners (DHS self-hosted)

  • Every job runs on the DHS self-hosted pool; GitLab shared runners (saas-linux-*) are never used.

  • Every job runs on dhs-aws-autoscaler-docker-4xlarge, the one tag in use (maintainer, 2026-11-06: the fleet is dedicated to this work, and wall time matters more than a smaller runner's queue). .gitlab-ci.yml's default: sets it and no job sets its own, so the SAST / secret-detection / dependency-scanning templates' jobs and pages inherit it too. canopy pins the literal tag rather than the RUNNER_* variables the coding standard's CI/CD Runners section describes.

  • A new gating job extends .gate (or .stack, for one that drives the daemon) and runs the commands a developer types (#3354); cargo xtask ci-config-lint (in validate and CI's lint job) refuses a default: off the 4xlarge, any job tagged for another runner, and a gating job with allow_failure, services: or retry: (the docs template's diagram renderer is the one service allowed, #2630).

HTTP / API: 201-Created create-endpoint override

IMPORTANT
Every create endpoint returns 201 Created, not 200 — a canopy override of the universal default, required for correct HTTP semantics in FFE account-transfer integrations. Return Result<(StatusCode, Json<T>), ApiError> from the handler. The other HTTP/API rules (idempotency, one shared reqwest::Client, RFC 9457, contract stability) are universal.

Pre-1.0 means no backward compatibility — delete and replace. Canopy has no production deployments; "canopy has no pre-1.0 backward-compatibility obligation" (ADR-014; the same cut in ADR-036 and ADR-039). A change to an internal contract — a Rust type, an inter-service wire shape, a column, a config key, a ruleset field — replaces the old shape and updates every consumer in the same MR. Do not keep the old shape alive: no Option<> / #[serde(default)] added only so old callers or rows still parse, no deprecated fields or legacy variants retained, no dual code paths / shims / transitional helpers / feature flags preserving old behaviour, and no "additive, so existing consumers are unaffected" justification — that is the _post-1.0 API-response rule, not an internal-contract rule. Forward-only migrations (ADR-016) constrain how the schema moves; they are not a licence to keep old shapes alive in code — pre-1.0 the expand–contract dual-write window is skipped and the devstack re-seeds. Accepted ADRs that model compatibility scaffolding — ADR-016’s "writes the old shape too", ADR-037’s Option<Revalidation> legacy path, ADR-038’s NULL-defaulted columns and feature flag, ADR-027’s dual-write window — record what was decided then; they are not precedent for new work. Record the break under == Unreleased Changed/Removed.

Secure-by-default environment behavior

With CANOPY_ENV unset every service behaves as production. Permissive behaviour needs CANOPY_ENV=development — case-insensitive, and the only recognised value (canopy_common::env::is_development; test is not recognised). Each guard keyed on it, with its accountable override, is inventoried at the startup-guard inventory. CANOPY_ENV also names the YAML overlay tier config/<svc>/<tier>.yaml — a file-naming axis that agrees with the recognizer: only a development value names dev.yaml, and unset or empty names no overlay (overlay_env_name in crates/canopy-common/src/settings.rs, #2632).

Framework patterns (Axum 0.8)

  • Handlers return Result<Json<T>, ApiError> (Result<(StatusCode, Json<T>), ApiError> for creates): extract State(state): State<AppState> and typed ids, ? on store calls, ok_or_else(|| ApiError::NotFound(..)) on a miss.

  • Run to completion (#3202, #3242): a handler whose work spans several writes or calls (a saga, a claim then its effects, a write then a publish) awaits that work through canopy_api::run_to_completion (crates/canopy-api/src/completion.rs), which runs it on its own task. hyper drops a request's future when its client disconnects, and an inline await stops wherever it had reached: a claim held until its lease expires, a saga stranded part-way, a determination signed but unrecorded. A handler with a single transaction needs none of this; the transaction rolls back. The wrapping keeps the handler's signature and OpenAPI annotation and moves its body into a <handler>_run function with the same parameters.

  • Errors: canopy_common::error::ApiError is the one error type; its variants carry their status codes (NotFound, BadRequest, Unauthorized, Forbidden, Conflict, Gone, UnprocessableEntity, NotImplemented, PayloadTooLarge, ServiceUnavailable, BadGateway, Internal { context, source }, Coded { .. }) and every response serializes as the RFC 9457 ProblemDetails. Use ? on queries: From<sqlx::Error> classifies the failure as in Database errors.

  • Rendered refusals: a handler or helper whose error arm is a whole response (a rendered page, a redirect, a marked fragment) returns Result<T, Response>. axum's Response is 80 bytes since http 1.6, under the 128 at which clippy's result_large_err refuses a Result; the lint checks async functions too since Rust 1.98 (#2911). ? carries a Response through, a refusal type converts with From<It> for Response, and an extractor may use Response as its Rejection.

  • State: AppState { db, auth } via State<AppState>; service-specific state via Extension<T> layers (services/canopy-rules/src/main.rs is the reference main).

  • Signing: a program service builds its signer at boot with canopy_signing::load_program_signer (crates/canopy-signing/src/program_signer.rs) and signs through the canopy_signing::DeterminationSigner trait to emit detached JWS (ADR-002); the redact endpoints stage their audit event with canopy_api::determination_redaction::publish_determination_redacted.

  • Rules-as-data (ADR-003): eligibility logic lives in the packs' JDM .json files, never in Rust; Rust assembles the input, calls canopy_rules_client::RulesClient::evaluate(), parses the output. Federal parameter sets load from the federal layer’s .json.

  • Jurisdiction-neutral mechanism, ruleset-owned policy (ADR-006, ADR-031): Canopy must be correct in any US jurisdiction; Georgia is the reference dataset, not the design. Rust holds the mechanism; every knob a jurisdiction could conceivably tune is policy and lives in the jurisdiction’s pack (jurisdiction.toml, JDM, notice templates) — not only dollar thresholds but dates and deadline offsets ("deadline minus one day"), gauge/reporting windows ("30 days"), schedules, calendar and issuance-cycle semantics, notice routing and wording, and which arm of a rule a case falls under (e.g. which timely-filing arm a short certification gets). A literal or a fixed branch justified as "PAMMS 3105:599", "Chart B1’s reading" or "Georgia’s reading" is the tell, not the licence: PAMMS supplies one jurisdiction’s values; the citation belongs in citations.toml beside the ruleset value (ADR-011) and the code reads the value. The agency standard’s "define constants at file top" rule (Coding Conventions) does not satisfy this — a const is still a hardcode. Ask: could another state want this different? If yes, it is ruleset data, and the MR that introduces it as code is a defect. The audit-literals, jurisdiction-literals and neutrality stages of cargo xtask validate catch the grep-able cases (the neutrality gate); a tunable mechanism or arm no detector matches is still a defect.

Database patterns

  • PostgreSQL via sqlx 0.9. Soft delete is active BOOLEAN NOT NULL DEFAULT true; list queries filter WHERE active = true.

  • SQL text is static. sqlx takes a &'static str and refuses any other string. A statement is a literal or a constant; one assembled from constants is a function-local static NAME: LazyLock<String>, read with NAME.as_str(), which the compiler holds to values known before the function runs. Every value goes in as a bind parameter. Where the text must be built at run time, because a table name is chosen by a closed enum or SET takes no parameter, the call wraps it in sqlx::AssertSqlSafe(…) under a // SQL-SAFE: comment that names what is written in and why nothing a caller supplies can reach it. A name passed down for that purpose is a &'static str. A reviewer checks that comment against the code, as for unsafe.

  • Primary keys are UUID v7 (Uuid::now_v7()) behind the typed newtypes from canopy_types::id (define_id!); raw Uuid only for polymorphic references such as the rules context_id.

  • Pagination is canopy_types::pagination::PageRequest (MAX_PER_PAGE = 500). The pool is shared per service — never PgPool::connect() per request; size and idle timeout come from the baseline db_max_connections / db_idle_timeout_secs.

  • Program isolation (ADR-001): each program service owns its own PostgreSQL instance; no cross-database queries; a migration lives under its own services/canopy-<svc>/migrations/. canopy_db::validate_database_name refuses a mismatch outside development.

  • Forward-only migrations (ADR-016): a wrong migration is fixed by a new forward migration; destructive changes are expand–contract. Pre-1.0 the expand–contract dual-write window and the standard’s "deprecate-then-remove" step are skipped: the old column or shape is dropped in the same MR that introduces the new one and the devstack re-seeds (pre-1.0 means no backward compatibility). Expand–contract becomes mandatory only once a production database exists. Bootstrap runs sqlx::migrate!("./migrations") over a dedicated connection closed before the app pool exists; CANOPY_<SVC>__SKIP_MIGRATIONS=true hands the schema to the deploy-time job canopy-manage migrate apply --service <svc> (crates/canopy-api/src/bootstrap.rs). Devstack rollback is cargo xtask migrate snapshot + migrate rollback; production rollback is PITR (Database Backup & Restore).

  • Owner/app role split (ADR-004, #1456; canopy-reporting today): every new migration that creates a table or function ends with ALTER … OWNER TO canopy_<svc>_owner plus the app-role grants its runtime SQL needs — a missed transfer fails loud in the devstack battery, but only after the migration merges. Procedure: the credential-cutover runbook.

  • canopy-web mutations (ADR-044, #1516): a new BFF mutation handler classifies itself in SCOPE_POLICY (xtask/src/cmd/route_authz.rs) — RequireExtractor (take ProgramScope<Tag>), RequireAuthorizedWrite (build an AuthorizedResource from the fetched row, never a form field) or NotProgramScoped(reason) — and obtains write-capable clients through clients.authorized(&authz); the InternalClient write verbs are module-private. Empty authoritative sets fail closed (422); an unlisted mutation fails cargo xtask validate (route-authz).

Database errors

Two constructors in crates/canopy-common/src/error.rs map a database failure, and the call site picks one by who can trip the write’s constraints:

  • ApiError::database(context, err) — the client’s input can trip the constraint. From<sqlx::Error> calls it with the context database error, so ? on a query lands there.

  • ApiError::internal_database(context, err) — only a server defect can: every constrained value is server-computed, or the handler has already refused the client values the constraint covers. Where such a write’s error would otherwise reach ApiError::from through ?, the call site names this constructor so the choice is visible.

Under database, a PostgreSQL integrity-constraint refusal is a ConstraintViolation and answers with a coded 4xx and a fixed per-class detail:

SQLSTATE Status code

23505 unique

409

unique_violation

23P01 exclusion

409

exclusion_violation

23503 foreign key

422

foreign_key_violation

23514 check

422

check_violation

  • Under internal_database every class above is the uncoded, redacted 500 — a 4xx would tell the client it erred.

  • Under both, a degraded database gets its own typed answer (ADR-053), whose code wins over one a handler attached:

    Failure Status Answer

    sqlx::Error::PoolTimedOut: the pool lent no connection within its bound

    503

    ApiError::PoolExhausted, code db_pool_exhausted, header Retry-After: 1

    SQLSTATE 57014: the server cancelled the statement, at its budget or by an explicit cancel

    504

    ApiError::StatementTimeout, code db_statement_timeout, no Retry-After

    A commit returned without the server's answer having been read (I/O, protocol, a closed connection)

    500

    ApiError::CommitOutcomeUnknown, code db_commit_outcome_unknown. The transaction may have been committed: re-read, or retry only under an idempotency key

A transaction is committed with canopy_db::commit(tx), never a bare .commit(): the helper tells a commit the server refused (CommitError::Refused, nothing was committed) from one whose answer was never read (CommitError::OutcomeUnknown). ? maps it for a handler; .map_err(|e| e.internal("…")) is for a commit of server-computed values; a function that returns sqlx::Error uses .map_err(sqlx::Error::from), which keeps the unknown case readable by ApiError::database, internal_database and internal. An error type that keeps only the error's text loses it: carry the sqlx::Error as a #[source]. The db-pools gate refuses a bare commit in production code. * Every other failure, 23502 NOT NULL included, is the redacted 500. * The body never carries database text: the database message names the constraint and table, and its DETAIL field holds row values. A constraint refusal logs the context, code, constraint and table at warn! under both constructors, and internal_database's 500 logs those names as its source, never the message. * ApiError::internal(context, err) never reclassifies its source — every failure, pool exhaustion and a cancelled statement included, is a 500. For a database error prefer internal_database, which keeps the typed 503 and 504. * A handler that owns a specific constraint maps its name to a domain code first and hands every other refusal to the constructor the write’s remaining constraints call for: the create_application handler in services/canopy-applications/src/api/filing.rs maps uq_applications_one_renewal_per_certification to renewal_already_filed and sends the rest to internal_database.

Design principles (binding)

YAGNI, KISS, DRY and SOLID are review blockers in canopy, not advice. Until the agency standard carries them, this is their home:

  • Build what the issue needs and no more. The acceptance criteria bound the change. A knob, enum arm, trait, generic parameter or config surface with no current caller is scope growth inside the deliverable and is cut (file an issue if it is genuinely wanted). The delivery protocol’s scope rule already forbids side-quests; this forbids over-building the requested thing itself.

  • The simplest correct design ships. When two designs both satisfy the criteria, take the one with fewer moving parts; the plan says in one line why the alternative lost.

  • Reuse the existing primitive; never add a parallel one. Before writing a helper, client, middleware, xtask subcommand or test fixture, look for the one that already exists — the shared crates, crates/canopy-test-lib/, xtask/src/cmd/, services/canopy-web/templates/_primitives/ — and extend it. A second implementation of an existing capability is a defect (ADR-039 is the pattern: one canonical home plus a parity gate). gadhs/pi’s judgment rule — "pick, and say why in one line" for an in-repo helper — applies only once this search comes up empty.

  • Policy lives with its owner. A rule or override belongs in the service or module that already owns the attribute it governs; a second knob elsewhere is a second source of truth (ADR-044 § Why no canopy-side override is the worked example, generalized here as authority).

  • No new gate, rule or doc page unless asked — the delivery protocol scope rule, restated because it applies to xtask checks and hooks too.

"No fig leaves" (contributor workflow) means the issue’s defect is closed completely; it does not license building beyond the issue.

Canopy-specific conventions (cheat-sheet)

Convention Rule (authoritative detail → ADR or file)

Event-bus data restrictions

Events carry ids, status codes, timestamps, program codes and non-restricted metadata only; FTI, SSA SOLQ/BENDEX, IEVS and HIPAA fields never. The publisher refuses RESTRICTED_FIELDS (crates/canopy-mq/src/publisher.rs); canopy-security’s wildcard # subscriber is intentional. (ADR-004)

FTI audit logging (canopy-tanf, canopy-medicaid)

FTI access writes fti_audit_log directly — not via the bus — for independent Pub 1075 audit (services/canopy-tanf/src/fti_audit.rs). The SHA-256 hash chain is transitional: ADR-041 is authoritative and retires the chain behind #1304; ADR-014 describes the mechanism still live.

Determination objects

Append-only: a signed, accepted determination is superseded by a new evaluation, never edited (ADR-002).

Session storage

MemoryStore is banned, and there is no in-memory session store in tests either. canopy-web’s worker sessions are its own store (services/canopy-web/src/web_session/, #2518): read the request’s one SessionState (web_session::layer), never the store, in a handler; write only through a named statement in web_session/sql.rs — no upsert, no whole-record write, nothing after the response, and every end through the logging CTE. A routed test that touches the store runs on an ephemeral schema in an infra_tests module; a hermetic authorization harness injects SessionState::Live through web_session::test_support::InjectedSessions. canopy-portal is Postgres-free with Redis-primary opaque sessions (ADR-009, ADR-026).

Secrets

SOPS + age (secrets/dev.yaml, dev values only) through cargo xtask secrets …; runtime reads go through canopy_secrets::EnvSecretProvider; no plaintext secret in checked-in YAML (cargo xtask secrets-yaml-lint). (ADR-017; workflow in Configuration Reference)

Service config loading (ADR-012, #1773)

One load per prefix: canopy_api::load_config(prefix, config::RESERVED_KEYS, config::MIRRORED_KEYS)? returns (ServiceSettings, <Svc>Config), then canopy_api::bootstrap_with(prefix, settings, name, sqlx::migrate!("./migrations")). Both structs are deny_unknown_fields, so a misspelled CANOPY_<SVC>__* key fails boot by name. RESERVED_KEYS lists keys read out-of-band (secrets, the strict true-literal overrides); MIRRORED_KEYS lists baseline keys the service struct also declares (jurisdiction). Each src/config.rs pins them with a config_gate_tests module over the checked-in config/<service>/default.yaml under its dev overlay (dev.yaml, the tier a development boot reads, which carries the devstack’s jurisdiction).

Peer service URLs (ADR-049 Amendment 4, #2642)

A service holds the base URL of each peer it calls in the service’s own crate, in a field named <peer>_url (persons_url for canopy-persons; <peer>_base_url also counts, and self_base_url is the service’s own), read from CANOPY_<SVC><PEER>_URL; canopy-eligibility’s program services are CANOPY_PROGRAM_URL_<PROGRAM>. cargo xtask call-graph census derives the call graph from these names in every non-test source file under services//src/ and tools/canopy-cli/src/, and fails on any other url field or CANOPY*URL variable until it is classified: as a peer, or in NOT_PEERS (xtask/src/cmd/call_graph/observed.rs) with the reason it is not one. An entry for a value built at run time rather than a setting, such as an HTTP client’s base_url, covers only a field of an item that does not derive Deserialize, never the name read from configuration. A peer URL escapes the census when it is held under any other name, in a field of a shared crate (crates/ is not scanned, yet canopy-common’s ServiceSettings is deserialized from every service’s CANOPY<SVC>), in a field declared inside a macro body, or in a variable name assembled from fragments; the convention is the limit of its guarantee.

Infrastructure tests

Every cargo xtask lane arms CANOPY_TEST_INFRA=required: an unavailable stack panics, never skips (crates/canopy-test-lib/src/infrastructure.rs). Thread counts are fixed per profile in .config/nextest.toml. Lanes and gates: Testing (Canopy).

Iterator first-match footgun

find / find_map act on the first element only; when the target is positional in a homogeneous collection (JDM decision-table nodes, repeated record types) use an explicit counter or filter(..).nth(k).

Adding a new service

  1. Create services/canopy-<name>/ (Cargo.toml, src/main.rs, src/config.rs, src/api/mod.rs) and add it to the workspace members in the root Cargo.toml.

  2. Take the next container port from the topology in the Service Catalog and add the PORT_MAPPINGS entry in xtask/src/docker.rs; host ports stay ephemeral (.ports.env).

  3. Database: add CREATE DATABASE canopy_<name>; to devstack/postgres/init.sql (infrastructure service) or a dedicated postgres-<name> container (program service, ADR-001); create services/canopy-<name>/migrations/.

  4. Compose: a service entry with the wget -qO- http://127.0.0.1:<port>/livez healthcheck, CANOPY_<NAME>__* env, read_only: true, the config bind mount and depends_on (copy canopy-rules in docker-compose.yml).

  5. Boot: canopy_api::load_config + bootstrap_with + ApiServer::router(state, api::routes(), Router::new(), ServerOptions::new("canopy-<name>", boot.config.clone()), Some(api::ApiDoc::openapi())) — the router mounts /v1 (protected), /livez, /readyz, /version, /swagger-ui and the public routes of the third argument, none here (crates/canopy-api/src/lib.rs); #[derive(OpenApi)] on ApiDoc with utoipa annotations, then cargo xtask api-docs snapshots it.

  6. Events: src/events.rs with ids-only payloads; a per-service RabbitMQ user and topic permission in devstack/rabbitmq/definitions.json (cargo xtask mq-topology checks it).

  7. Every .rs starts with // SPDX-License-Identifier: AGPL-3.0-or-later; unsafe_code is already denied workspace-wide by [workspace.lints.rust] in the root Cargo.toml — no per-crate attribute.

  8. Tests: tests/<name>_test.rs that probes /livez first (services/canopy-rules/tests/rules_test.rs).

  9. Docs: api/canopy-<name>.adoc, data-models/canopy-<name>.adoc, a capability block and topology row in Canopy Service Catalog, and compliance/deployment-profile-capabilities.toml (cargo xtask compliance capabilities).

Adding a new jurisdiction

Detail: Jurisdiction Onboarding Runbook. The shape, using the georgia pack as the reference:

  1. The pack’s canopy-config.toml (the layer manifest: schema = 1, layer = "jurisdiction", jurisdiction = "<slug>"), jurisdiction.toml (every value cited in citations.toml, ADR-011), idp.toml, theme.toml, composition/, workflows/.

  2. JDM rulesets: the files Georgia ships (snap-eligibility.json, snap-benefit-calculation.json, snap-self-employment-deduction.json, the tanf-, medicaid-, caps-, chip-, wic-eligibility.json); federal parameter sets (snap-deductions-<FY>.json, allotments, income limits, FPL) stay in the federal layer and are shared.

  3. Notices: notices/manifest.toml, notices/snap/*.typ, notices/components/, notices/shared/, notices/fonts/.

  4. Signing keys: the devstack generates its own under .keys/ (gitignored) on cargo xtask dev start; a production pair comes from canopy-manage gen-signing-keys (canopy-manage Reference).

  5. The deployment’s layers are configuration with no shipped default (#2627): CANOPY_CONFIG_SOURCE (federal, then the pack, each name=path:<dir> or a git source) sets the whole stack, CANOPY_<SVC>__CONFIG_SOURCE pins one service over it, and a boot without one is refused; the jurisdiction is the pack manifest’s. Only the development overlay, config/<service>/dev.yaml, names the devstack’s (Configuration Reference).

  6. Verify: cargo xtask dev start, cargo xtask seed --jurisdiction <slug>, then a determination and a notice PDF end to end.

Worker-portal & composition patterns

The composability runtime (ADR-021, ADR-022; the case-detail shell decision in Worker portal redesign — composability runtime + design-system extraction). The load-bearing rules:

  • Reach for an Orchard primitive (templates/_primitives/orchard.html: {% call o::panel_frame(…​) %}…{% endcall %} for body-slot macros, {{ o::big_number(…​) }} for inline ones) when you need structure; a utility class for stateless layout only.

  • Never emit inline style=: canopy-web ships style-src 'self' (services/canopy-web/src/csp.rs); primitives_test.rs::smoke_emits_no_inline_style_attributes pins it.

  • Every panel renders all four states (empty, loading, populated, error) and its Plugin.toml declares required_states from that set (validate_required_states in crates/canopy-composition/src/manifest.rs rejects any other state).

  • A plugin is #[canopy_plugin(manifest = "…​")] with a crate-relative manifest path, one per module (the macro reads the slug from the manifest's [plugin].slug and emits a pub static REGISTRATION beside it). Add the module’s REGISTRATION to PLUGINS in services/canopy-web/src/plugins.rs: that list is the registry, and its test fails on any Plugin.toml under src/ it does not list (#855).

  • /v1/composition (api::composition::CompositionState as an Extension) relies on the session cookie’s SameSite=Strict for CSRF — the load-bearing comment in web_session/cookie.rs; never downgrade it. Composition mutations publish through publisher.publish_tx(&mut tx, ..) so the outbox row commits with the mutation.

Commit review and the pre-commit hook

gadhs/pi reviews every agent commit before git runs. It answers its J1–J8, plus one question per rule in the ## Code Review Rules section of the committed AGENTS.md, which is the only list of those rules. They reach the reviewer only in a project pi trusts. pi counts canopy as trusted by default while the checkout has no trust-requiring .pi/ resource (.pi/settings.json, .pi/extensions/, …), and /trust records the decision explicitly. After a FLAGS verdict, fix the diff (the changed diff is reviewed afresh), or retry the identical diff with one Review-Response: J<n> accepted|disputed - <why> line in the message per flagged question. Only that retry needs the line (#2989). Fix every finding this diff introduced in the same change. A pre-existing defect gets its own fix: issue.

.githooks/pre-commit runs the mechanical checks on every commit: the staged-blob SPDX check, the untracked-debt-marker block and the CHANGELOG.adoc soft reminder. Never --no-verify. .githooks/pre-push adds cargo xtask test --unit and git-lfs (What git push runs); GitLab's push rule refuses an unsigned commit, and everything else is the merge train's pipeline.

Two canopy-local classes are defects whatever a review answers: a fig leaf — a cosmetic or partial fix, a sleep/retry/timeout widening that masks a race or contention, a warn-and-continue where a refusal is right, an "interim" posture, a test excused as a documented gap (no fig leaves) — and a jurisdiction-tunable value or arm fixed in code (jurisdiction-neutral mechanism). The commit review checks the fig-leaf class as the fifth of AGENTS.md's Code Review Rules (R5), and its race-masking part as the fourth (R4). It does not check jurisdiction literals: the audit-literals, jurisdiction-literals and neutrality stages of cargo xtask validate catch the grep-able ones, and the rest binds authors and reviewers.

GitLab CI on the dhs-aws-autoscaler-docker-4xlarge runner, through merge trains, runs the whole battery and owns correctness (CI is the gate). Locally, git push runs only cargo xtask test --unit and git-lfs.

Quality-budgets gate (ADR-030)

cargo xtask quality-budgets (ADR-030) counts ten debt metrics against xtask/quality-budgets.lock. The ceiling is the lock value whenever the lock file names the metric, a lock of 0 included, else the metric’s threshold; any OVER row fails the run, and the identical check runs as a blocking cargo xtask validate stage and the quality-budgets CI job. Scanners prune target, .git, node_modules, .cargo, local agent state (.pi and its retired predecessor), any nested checkout (#1716) and the root design/ tree of vendored prototypes that no workspace crate builds (#2290); a design directory below the root is scanned. Definitions (xtask/src/cmd/quality_budgets.rs):

Id Counts

B1

route modules over 500 lines: the production .rs files under services/*/src/api/, at any depth. A file is counted whole, its inline test modules included. A test-only file as xtask/src/test_scope.rs names it — one a [cfg(test)] mod loads, one gated by ![cfg(test)], and the files those load — is not counted (#3406)

B2

production functions over 100 lines (syn-parsed); every fn in test-only code as xtask/src/test_scope.rs names it — test-only files and the test-only regions of the rest, helpers in a test module included — is skipped (#2474)

B3a / B3b

serde_json::Value occurrences in /src/ outside canopy-contracts-* / in the integration-test targets (tests/ outside src/): a path partition, so a test module’s Value under src/ counts in B3a

B4

[allow(…​)] and inner ![allow(…​)] attributes; cfg_attr(…​, allow(…​)) is not counted

B5

.unwrap_or_default() calls in /src/ outside test-only code (#2474)

B6

duplicate dependency versions (cargo tree -d)

B7

crates/canopy-test-lib/src/clients/*.rs methods returning serde_json::Value

B8

ambient decision-clock reads: clock::now( / clock::today( calls plus DecisionClock::shared( constructions in /src/ outside test-only code (#2474)

B9

lint-expectation attributes: [expect(…​)], inner ![expect(…​)] and each expect(…​) inside a cfg_attr(<pred>, …​), one-line or multi-line (#2290)

Skip markers sit on the line above the site: // SILENT-OK: <reason> (B5), // PARTNER-EDGE-UNTYPED: <ticket> and // STRUCTURAL-VALUE: <reason> (B3).

Splitting a route module (B1). A route module that nears 500 lines is split by route group, and the split follows three rules (#3406):

  • Layout. x.rs keeps its file and gains children under x/; an api/mod.rs gains siblings under api/. A child is named for the route group it holds. The route table stays in the parent and names each handler by its child's path, as canopy-web's names case_detail::page::get_case_detail. No pub use is added only to keep an old path compiling: callers are updated in the same merge request.

  • Visibility. A moved item keeps its visibility. Where the move puts a caller outside its new module, it is widened by the least that compiles: pub(super), then pub(in crate::api), then pub(crate).

  • Tests travel with their code. An inline [cfg(test)] mod tests { … } becomes a file declared [cfg(test)] mod tests;, in the child whose private items it uses. A helper several test files share goes to a [cfg(test)] test_support.rs in the parent. A test file declared without the [cfg(test)] gate is production code to B1, and counts.

A handler that moves names its OpenAPI tag (tag = "…" in #[utoipa::path]): utoipa otherwise takes the tag from the module's path, and the published document would change.

A legal date (a claim’s discovery date, a payment’s effective date, a closure date, the day a due or overdue feed classifies on) is the jurisdiction’s calendar day: DecisionClock::legal_today(tz) on the service’s injected handle, canopy_common::clock::date_in(instant, tz) on an instant the request already holds, or canopy_common::clock::legal_today(tz), with tz the loaded pack’s [jurisdiction].timezone. In SQL, bind that date; never CURRENT_DATE, the database session’s UTC date.

cargo xtask test-lanes-lint (check 5, #2526; xtask/src/cmd/test_lanes_lint/prod_today.rs) refuses a UTC "today" in services//src/* outside test-only code: now().date_naive() on any receiver, now().naive_utc().date(), now().format(…), the paths clock::today and Utc::today, and a string literal holding CURRENT_DATE or a SQL clock cast ::date. It cannot see types, so .date_naive() on a named DateTime<Utc> value is review’s to catch. A genuine UTC use takes an entry with a written reason and its site count in compliance/prod-utc-today-allowlist.toml. A regression test pins the decision clock at canopy_test_lib::day_split_instant(day, tz), where the two calendars disagree.

Decision clocks in program services

A service stamps a decision from its one injected DecisionClock (ADR-033 §5): the request, delivery or pass reads now() once and binds that instant to every row, event and date it writes. cargo xtask test-lanes-lint (check 6, #2588, widened by #3000; xtask/src/cmd/test_lanes_lint/ambient_clock.rs) refuses, in the production code of the scanned services (SCANNED_SERVICES: canopy-snap, -tanf, -medicaid, -caps, -wic, -renewals, -appeals, -persons, -eligibility and -applications), canopy-overpayments and canopy-db’s redaction store: the paths Utc::now, Local::now and SystemTime::now; the module-level accessors clock::now, clock::today and clock::legal_today, since the injected handle is the only sanctioned read there; each as a call or a function pointer; DecisionClock::fixed outside test code; and a string literal calling a SQL clock (now(), CURRENT_TIMESTAMP, CURRENT_DATE, LOCALTIMESTAMP, clock_timestamp(), statement_timestamp(), transaction_timestamp()). The B8 ratchet counts the accessor calls workspace-wide but not a function pointer, legal_today, Utc::now or SQL. The scan reads tokens with no import resolution, so an aliased import, a bare-imported accessor, a wrapper fn outside the scanned trees, a column default (#2589) and SQL built at run time stay unseen. An operational instant — the time FTI was actually read (ADR-014), a hash chain’s order key, a lease or retry gate, a metric, updated_at bookkeeping, a read-only query window — takes an entry with a written reason and its site count in compliance/prod-ambient-clock-allowlist.toml; a decision-bearing stamp is fixed, with a test that pins it.

Moving the lock — the only rules:

  1. Never edit the numbers by hand. cargo xtask quality-budgets --write-lock re-baselines every counter at the current tree and is the one mode that exits 0 on an OVER row (#1617).

  2. Lowering is routine: after a cleanup run --write-lock and commit the lock with the change.

  3. Raising is the exception and the MR must justify each raised counter: the issue, and whether it is new debt or a ruler correction (the B8 8 → 9 (#1684) precedent). ADR-030: any change to the lock, up or down, is justified in the MR.

  4. --write-lock regenerates the file without prose; re-add the movement note above the moved key in the same commit (the lock’s convention: # B8: 8 → 9 (#1684). …) so the history survives.

Documentation (Canopy)

The standard fixes the format (AsciiDoc under Antora, CHANGELOG.adoc, plans as .adoc); these are the canopy rules for every page under docs/modules/ROOT/pages/.

Page shape. First line // SPDX-License-Identifier: AGPL-3.0-or-later (new pages), then = Title, a one-sentence :description:, :toc: left / :toclevels: 2 on long pages. The first body sentence names the reader and the job ("For an operator rotating a signing key: …"); one audience per page — a second audience gets an xref, not a section. One idea per sentence; issue archaeology goes to the CHANGELOG or the ADR. At most ten == headings per guide; [#kebab-id] on any heading another page links to; never rename an anchor — [#fixture-design] is cited from crates/canopy-policy/src/citation.rs. One fact per table cell; a cell over two sentences becomes bullets (a|) or a sub-section.

Length targets by kind. Guide ≤ 250 lines (prerequisites → do it → verify → next page). Runbook ≤ 150 (Symptom / Preconditions → numbered Steps, one command each → Verify → Rollback → a History NOTE of ≤ 3 lines). ADR: template kept, body immutable once Accepted — changes are the Status value, a dated [NOTE] banner under the title (Amendment N (YYYY-MM-DD) — as built) and link repairs. API page: Base URL:: as container port plus CANOPY_PORT_<SVC>_<PORT> in .ports.env, Access:: from the handler guard, one row per route (method, path, guard, 2xx, coded 4xx), shapes by xref to the contracts crate and openapi/*.json. Data-model page: one row per table (purpose, policy columns, CHECKs), a relationship-only ERD, no "N tables across M files" counts, outbox/inbox as one pointer to data-models/index.adoc. Walkthrough: the # | Screen | Action | Expected | Screenshot table, Expected describing the captured PNG, bring-up as the one prefixed command. Plan: Design + Scope, ≤ ~300 lines.

Commands. [source,bash] blocks; spelling copied from cargo xtask <cmd> --help, never memory (cargo xtask seed [--seed <u64>] [--households <n>] [--jurisdiction <name>] — no --reset). Compose service names (cargo xtask dev logs canopy-medicaid). Host ports are ephemeral: write "the URL cargo xtask dev status prints" or CANOPY_PORT_<SVC>_<PORT> from .ports.env, never a number. Never raw docker compose for the devstack lifecycle — cargo xtask dev reload keeps data, dev restart wipes it. The journey lane needs CANOPY_CARGO_FEATURES=canopy-api/test-clock. Env keys are CANOPY_<SVC>__<KEY>; unprefixed only for the process-wide set in Configuration Reference.

Never duplicate — link. Before writing a paragraph, rg its key phrase; if it exists, xref it. Same-module links use the module-root form Local Development (never a ../-relative path); standards pages Git Workflow; a section is addressed as <page>.adoc#<kebab-id>.

Surface Canonical home (every other page points)

First run, devstack lifecycle

Local Development

Lanes, CANOPY_TEST_INFRA, what git push runs, e2e

Testing (Canopy)

Env keys, secrets workflow, CANOPY_ENV

Configuration Reference

Health, profiles, database inventory, images

Deployment Guide

Ports

Canopy Service Catalog (topology tables)

Procedures (rotation, incident, rolling deploy)

the runbook; Security Operations & Runbooks points

Outbox / inbox schema

Data Models

Security invariants, receiver contract, CSP

Security

Status and dates. ISO YYYY-MM-DD; no "recently" or "currently" without a date. Plan Status is one of Not started, In progress, Done (YYYY-MM-DD) — !N, Deferred (reason, #N), Blocked (reason, #N), N/A (cargo xtask docs plan-lint checks the cells; cargo xtask plan-lint --done <plan> is the completion gate, then git mv into plans/archive/ with the nav path gaining archive/); the Done date is the maintainer’s local calendar day at merge (America/New_York), not the UTC day of the merge commit. A deviation is one line, Erratum (YYYY-MM-DD): …; reviews log round | vendor | resolved model | verdict under == Review log. ADR status is Accepted, Accepted — amended by xref:…[ADR-0NN] or Superseded by … with the banner; superseded ADRs stay in the nav. Issues #N, MRs !N, epics &N; no SHAs in reader-facing prose; no volatile counts — say "every …" or name the command that owns the number.

No claim without a source. Every factual sentence about behaviour, config, schema or process cites a symbol, migration filename, struct field, compose key or anchor the reader can open — not a raw line number, which drifts. If one rg cannot find the source, do not write the sentence; nothing is published as "unverified" or "TBD". Prefer the code’s own words: route paths from crates/canopy-contracts-*/src/paths.rs, guards from the handler, defaults from config/<svc>/default.yaml or the serde default, UI labels from the template. Screenshots are evidence: an Expected cell describes the PNG, not the intended end state. Regulatory figures cite the eCFR section, the federal publication or the PAMMS section and the date checked.

AsciiDoc. One-liner NOTE:; multi-line [NOTE] + ====; [IMPORTANT] for must-not-skip; WARNING: for data loss; avoid TIP. Every source block names a language. Backticks for commands, paths, keys, routes and labels as rendered. Images inline (image:walkthroughs/<journey>/step-NN-<slug>.png[alt]) inside table cells. Generated pages (the gateway catalog) are edited through docs/tools/gen-gateway-catalog.py, regenerated, hash pin kept.

What a reviewer checks per changed page.

Check Pass when

J5 on every changed claim

each new or edited assertion cites a source in the diff or is verifiable in one command; security words (encrypted, authenticated, atomic, exactly-once, bounded, times-out) carry a code citation

Audience line

the first sentence names reader and job

Length

within the kind target or the per-page cap the plan set

Commands

copy-paste runnable; every flag exists in --help

Duplication

no paragraph restates a canonical page; it xrefs instead

Links

every xref: target exists (test -f); module-root form; no new ../-relative link

Status

plan and ADR Status in the canonical form; dates ISO

Gates

asciidoctor --failure-level WARN -o /dev/null <page> clean; plans plan-lint; walkthroughs cargo xtask scenarios audit

Scope

docs-only diff; a defect found in code became an issue, not a fix in the docs MR

CHANGELOG

the == Unreleased line names the pages and the reason

Edit this page · default