Coding Conventions (Canopy)
- Askama 0.16 templating quirks
- CI/CD runners (DHS self-hosted)
- HTTP / API: 201-Created create-endpoint override
- Secure-by-default environment behavior
- Framework patterns (Axum 0.8)
- Design principles (binding)
- Canopy-specific conventions (cheat-sheet)
- Commit review and the pre-commit hook
- Quality-budgets gate (ADR-030)
- Legal days in production code
- Decision clocks in program services
- Documentation (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 "expectedendcallto terminatecallnode", reported at thecall. -
{% 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
.htmlescaper 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 xis rejected ("cannot userefas 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'sdefault:sets it and no job sets its own, so the SAST / secret-detection / dependency-scanning templates' jobs andpagesinherit it too. canopy pins the literal tag rather than theRUNNER_*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(invalidateand CI'slintjob) refuses adefault:off the 4xlarge, any job tagged for another runner, and a gating job withallow_failure,services:orretry:(the docs template's diagram renderer is the one service allowed, #2630).
HTTP / API: 201-Created create-endpoint override
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 |
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): extractState(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>_runfunction with the same parameters. -
Errors:
canopy_common::error::ApiErroris 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 9457ProblemDetails. 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'sResponseis 80 bytes sincehttp1.6, under the 128 at which clippy'sresult_large_errrefuses aResult; the lint checks async functions too since Rust 1.98 (#2911).?carries aResponsethrough, a refusal type converts withFrom<It> for Response, and an extractor may useResponseas itsRejection. -
State:
AppState { db, auth }viaState<AppState>; service-specific state viaExtension<T>layers (services/canopy-rules/src/main.rsis the referencemain). -
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 thecanopy_signing::DeterminationSignertrait to emit detached JWS (ADR-002); the redact endpoints stage their audit event withcanopy_api::determination_redaction::publish_determination_redacted. -
Rules-as-data (ADR-003): eligibility logic lives in the packs' JDM
.jsonfiles, never in Rust; Rust assembles the input, callscanopy_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 incitations.tomlbeside 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 — aconstis 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. Theaudit-literals,jurisdiction-literalsandneutralitystages ofcargo xtask validatecatch 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 filterWHERE active = true. -
SQL text is static. sqlx takes a
&'static strand refuses any other string. A statement is a literal or a constant; one assembled from constants is a function-localstatic NAME: LazyLock<String>, read withNAME.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 orSETtakes no parameter, the call wraps it insqlx::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 forunsafe. -
Primary keys are UUID v7 (
Uuid::now_v7()) behind the typed newtypes fromcanopy_types::id(define_id!); rawUuidonly for polymorphic references such as the rulescontext_id. -
Pagination is
canopy_types::pagination::PageRequest(MAX_PER_PAGE= 500). The pool is shared per service — neverPgPool::connect()per request; size and idle timeout come from the baselinedb_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_namerefuses 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=truehands the schema to the deploy-time jobcanopy-manage migrate apply --service <svc>(crates/canopy-api/src/bootstrap.rs). Devstack rollback iscargo 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>_ownerplus 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(takeProgramScope<Tag>),RequireAuthorizedWrite(build anAuthorizedResourcefrom the fetched row, never a form field) orNotProgramScoped(reason)— and obtains write-capable clients throughclients.authorized(&authz); theInternalClientwrite verbs are module-private. Empty authoritative sets fail closed (422); an unlisted mutation failscargo 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 contextdatabase 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 reachApiError::fromthrough?, 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 |
|---|---|---|
|
409 |
|
|
409 |
|
|
422 |
|
|
422 |
|
-
Under
internal_databaseevery 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
codewins over one a handler attached:Failure Status Answer sqlx::Error::PoolTimedOut: the pool lent no connection within its bound503
ApiError::PoolExhausted, codedb_pool_exhausted, headerRetry-After: 1SQLSTATE
57014: the server cancelled the statement, at its budget or by an explicit cancel504
ApiError::StatementTimeout, codedb_statement_timeout, noRetry-AfterA commit returned without the server's answer having been read (I/O, protocol, a closed connection)
500
ApiError::CommitOutcomeUnknown, codedb_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,
xtasksubcommand 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
xtaskchecks 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 |
FTI audit logging (canopy-tanf, canopy-medicaid) |
FTI access writes |
Determination objects |
Append-only: a signed, accepted determination is superseded by a new evaluation, never edited (ADR-002). |
Session storage |
|
Secrets |
SOPS + age ( |
Service config loading (ADR-012, #1773) |
One load per prefix: |
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 |
Infrastructure tests |
Every |
Iterator first-match footgun |
|
Adding a new service
-
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 rootCargo.toml. -
Take the next container port from the topology in the Service Catalog and add the
PORT_MAPPINGSentry inxtask/src/docker.rs; host ports stay ephemeral (.ports.env). -
Database: add
CREATE DATABASE canopy_<name>;todevstack/postgres/init.sql(infrastructure service) or a dedicatedpostgres-<name>container (program service, ADR-001); createservices/canopy-<name>/migrations/. -
Compose: a service entry with the
wget -qO- http://127.0.0.1:<port>/livezhealthcheck,CANOPY_<NAME>__*env,read_only: true, the config bind mount anddepends_on(copycanopy-rulesindocker-compose.yml). -
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-uiand the public routes of the third argument, none here (crates/canopy-api/src/lib.rs);#[derive(OpenApi)]onApiDocwith utoipa annotations, thencargo xtask api-docssnapshots it. -
Events:
src/events.rswith ids-only payloads; a per-service RabbitMQ user and topic permission indevstack/rabbitmq/definitions.json(cargo xtask mq-topologychecks it). -
Every
.rsstarts with// SPDX-License-Identifier: AGPL-3.0-or-later;unsafe_codeis already denied workspace-wide by[workspace.lints.rust]in the rootCargo.toml— no per-crate attribute. -
Tests:
tests/<name>_test.rsthat probes/livezfirst (services/canopy-rules/tests/rules_test.rs). -
Docs:
api/canopy-<name>.adoc,data-models/canopy-<name>.adoc, a capability block and topology row in Canopy Service Catalog, andcompliance/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:
-
The pack’s
canopy-config.toml(the layer manifest:schema = 1,layer = "jurisdiction",jurisdiction = "<slug>"),jurisdiction.toml(every value cited incitations.toml, ADR-011),idp.toml,theme.toml,composition/,workflows/. -
JDM rulesets: the files Georgia ships (
snap-eligibility.json,snap-benefit-calculation.json,snap-self-employment-deduction.json, thetanf-,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. -
Notices:
notices/manifest.toml,notices/snap/*.typ,notices/components/,notices/shared/,notices/fonts/. -
Signing keys: the devstack generates its own under
.keys/(gitignored) oncargo xtask dev start; a production pair comes fromcanopy-manage gen-signing-keys(canopy-manage Reference). -
The deployment’s layers are configuration with no shipped default (#2627):
CANOPY_CONFIG_SOURCE(federal, then the pack, eachname=path:<dir>or a git source) sets the whole stack,CANOPY_<SVC>__CONFIG_SOURCEpins 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). -
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 shipsstyle-src 'self'(services/canopy-web/src/csp.rs);primitives_test.rs::smoke_emits_no_inline_style_attributespins it. -
Every panel renders all four states (
empty,loading,populated,error) and itsPlugin.tomldeclaresrequired_statesfrom that set (validate_required_statesincrates/canopy-composition/src/manifest.rsrejects 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].slugand emits apub static REGISTRATIONbeside it). Add the module’sREGISTRATIONtoPLUGINSinservices/canopy-web/src/plugins.rs: that list is the registry, and its test fails on anyPlugin.tomlundersrc/it does not list (#855). -
/v1/composition(api::composition::CompositionStateas anExtension) relies on the session cookie’sSameSite=Strictfor CSRF — the load-bearing comment inweb_session/cookie.rs; never downgrade it. Composition mutations publish throughpublisher.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 |
B2 |
production functions over 100 lines ( |
B3a / B3b |
|
B4 |
|
B5 |
|
B6 |
duplicate dependency versions ( |
B7 |
|
B8 |
ambient decision-clock reads: |
B9 |
lint-expectation attributes: |
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.rskeeps its file and gains children underx/; anapi/mod.rsgains siblings underapi/. 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 namescase_detail::page::get_case_detail. Nopub useis 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), thenpub(in crate::api), thenpub(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.rsin 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.
Legal days in production code
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:
-
Never edit the numbers by hand.
cargo xtask quality-budgets --write-lockre-baselines every counter at the current tree and is the one mode that exits 0 on anOVERrow (#1617). -
Lowering is routine: after a cleanup run
--write-lockand commit the lock with the change. -
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. -
--write-lockregenerates 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 |
|
Lanes, |
|
Env keys, secrets workflow, |
|
Health, profiles, database inventory, images |
|
Ports |
Canopy Service Catalog (topology tables) |
Procedures (rotation, incident, rolling deploy) |
the runbook; Security Operations & Runbooks points |
Outbox / inbox schema |
|
Security invariants, receiver contract, CSP |
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 |
Duplication |
no paragraph restates a canonical page; it xrefs instead |
Links |
every |
Status |
plan and ADR Status in the canonical form; dates ISO |
Gates |
|
Scope |
docs-only diff; a defect found in code became an issue, not a fix in the docs MR |
CHANGELOG |
the |