Shared Crates — Public API Surface

This is the canonical reference for the shared crates' public APIs. Per-service endpoint/table/event detail lives in the API reference + the data-model-* pages; this page covers the reusable library crates under crates/.

craig-common

  • ApiError enum — RFC 9457 Problem Details: NotFound, BadRequest, Unauthorized, Forbidden, Conflict, Internal, Validation, plus typed-source variants (Db / ObjectStore / Http / Csv / Uuid / Header). See Architecture § RFC 9457 Problem Details for the catalogue rationale + coding-conventions.md § RFC 9457 problem-type URLs (#311) for call-site discipline.

    • Implements IntoResponse (Axum) and From<anyhow::Error> (internal anyhow paths). New code should prefer typed thiserror errors + a From<TypedError> for ApiError impl over routing through anyhow.

    • BadRequest + Conflict carry a type_url: Option<&'static str> populated by bad_request_typed(url, detail, field) / conflict_typed(entity, detail, url); problem_type_url(&self) returns the variant’s URL. Catalogue: craig_common::error::problem_types (the module is the source of truth; counts drift as endpoints add typed refusals).

  • Value-free error text (#2523): json_detail is the one renderer for a deserialize failure’s client detail or log text — the path plus serde’s missing / unknown / duplicate field template or INVALID_VALUE, never the value (RedactedJsonError, deserialize_redacted, from_slice_redacted). from_slice_redacted_keeping also keeps a caller’s own fixed refusal text verbatim, on an exact match only (#2335: craig-intake keeps UnsanitizableText’s, so a refused free-text field names its cause). `problem reads an upstream refusal bounded (read_bounded → BoundedBody, BODY_CAP 64 KiB) and lifts a detail only from a validated RFC 9457 document (UpstreamProblem, lift / lift_str, bounded to DETAIL_CHARS); log_dropped logs a dropped body’s shape only. extract::{Path, Query, Form} join extract::{Json, Multipart} as drop-in wrappers whose rejection is a value-free problem document; their path_rejection_detail / query_rejection_detail / form_rejection_detail also back craig-bff’s extract::{Path, Query, Form} family, which keeps the BFFs' plain-text shape (PlainRejection; Query::try_from_uri for a handler that parses its own URI).

  • validation::MULTIPART_TEXT_PART_MAX_BYTES (8 KiB, #2632): the one byte cap on a multipart text part, read by every multipart reader — craig-api’s parse_upload_multipart, craig-intake’s attachment proxy and craig-bff’s upload relay — each streaming the part and refusing it the moment it passes the cap, naming the part and never its value. One number for every tier, so a part a relay accepts is never refused for length by the service it relays to.

  • Concurrency primitives (canonical per coding-conventions.md § Style): parking_lot::Mutex for short sync critical sections (no poisoning); tokio::sync::Mutex when the lock crosses .await; std::sync::Mutex/RwLock are forbidden in CRAIG-authored code (prefer parking_lot).

  • write_idle (#1951) — the server-side write-progress bound: bounded(TcpListener) → BoundedListener (production budget; bounded_with(listener, budget) is the test seam) for axum::serve, and WriteIdleIo::new(stream, budget) for axum-server acceptors (intake’s TLS path). A connection whose writes make no progress for ceiling::RESPONSE_WRITE_IDLE_BUDGET (120 s) ends with TimedOut; BoundedListener keeps ConnectInfo<SocketAddr>.

  • roles_claim::RolesClaimPath (#2684): the validated roles-claim path (CRAIG_IDENTITY_ROLES_CLAIM_PATH, default realm_access.roles) and the one reader the JWS, introspection and BFF paths share; settings::IdentitySettings loads it, failing boot on a malformed path.

  • owner_only (#2761): owner-only, durable file writes (ADR-085 D12’s writer). write_durable(target, bytes) stages bytes in a fresh sibling .<file name, at most 64 bytes>.<uuid v7>.tmp in target’s directory, created exclusively (`0600 on Unix), sync_all`s it, renames it over `target and fsyncs the directory (Unix), so a concurrent reader sees the whole old file or the whole new one. StagedFile::create(target, bytes) / publish(self) are its two halves; a StagedFile dropped unpublished removes its sibling (best-effort), and one left by a crash stays (no sweeper). ensure_private_dir(dir) creates dir 0700, fsyncs the parent of each directory it creates (Unix), and tightens a looser existing one. Errors: OwnerOnlyError::{Io { op, path, source }, NoParent, NoFileName}. The CLI token store writes through it.

  • middleware::security_headers: hsts_layer(), the shared HSTS header a service lays on its top-level router (craig-api’s ApiServer, craig-intake, craig-web and craig-portal); and Swagger UI’s route-scoped CSP (#2790), shared by craig-api and craig-intake: SWAGGER_UI_PATH (/swagger-ui, which both hand to SwaggerUi::new), SWAGGER_UI_CSP, and the swagger_ui_csp middleware, which sets that policy on a response to /swagger-ui or a path under it and leaves every other response alone. Lay it outside the service’s overriding global CSP layer.

  • Id = uuid::Uuid; new_id() generates UUID v7.

  • PageRequest { page: u32, per_page: u32 } — offset() / limit() (clamped to MAX_PER_PAGE = 500); derives Deserialize + IntoParams. PageResponse<T> { data: Vec<T>, page, per_page, total: i64 } — derives Serialize + ToSchema.

  • ServiceSettings — loaded from CRAIG_<PREFIX>__* env vars. Fields: port, database_url, rabbitmq_url, oidc_issuer, oidc_internal_url (opt), log_level, jurisdiction, cors_origins, body_limit, attachment_body_limit (Option<usize>, #974 — the per-route attachment cap for cases/placement/exchange; None = derived at boot), db_max_connections, db_idle_timeout_secs, cases_base_url (#1776 — a SHARED core leaf, not an extension field: exchange, placement and reporting read settings.cases_base_url; a per-service twin would be handed to the first flattened struct and silently keep its default), placement_base_url (#2118 — a SHARED core leaf lifted from FinancialSettings; craig-financial reads it, and craig-reporting’s AFCARS export client will once the generate job #2143 wires it), financial_base_url (#2140 — a SHARED core leaf; craig-reporting’s AFCARS facts client, wired by the generate job #2143). load(prefix); Debug redacts database_url + rabbitmq_url. Defaults: log_level=info, jurisdiction=georgia, cors_origins="" (same-origin), body_limit=2 MiB, max_connections=10, idle_timeout=600 s, cases_base_url=http://localhost:8002, placement_base_url=http://localhost:8003, financial_base_url=http://localhost:8005.

  • CasesSettings / ExchangeSettings / FinancialSettings / SecuritySettings (998) — the per-service extension structs [serde(flatten)]-ed into ServiceSettings as settings.cases / .exchange / .financial / .security; env names are unchanged (CRAIG_<SVC><FIELD>, nested groups still on ). cases: encryption_mode, jws_replay_ttl_hours, jws_replay_cleanup_interval_seconds, exchange_base_url; exchange: icpc_deadline_days, ssa_screening; financial: payment_period, subsidy_generator_interval_seconds, subsidy_review_sweep, subsidy_err, subsidy_sg, subsidy_import, subsidy_backpay; security: admin_unit_label (still required, no Default). The first three implement Default mirroring their serde defaults; retention_archive stays on the core (security + rules + exchange consume it).

  • supervisor module (#1229 — moved from craig-api, which re-exports every name): the ADR-061 worker supervision + liveness registry (Supervisor, WorkerHealth, shutdown_signal, the WorkerCheckEntry healthz wire mapper). Lives HERE so the DB/MQ-less craig-web BFF can supervise its workers without sqlx/lapin; panic text comes from craig_mq_error::panic_message_bounded (same layering rationale). See the craig-api section for the full API sketch.

  • telemetry::init(default_level) — structured JSON logging via tracing-subscriber.

  • rate_limit::RetainingIpLimiter (#1136) — per-IP keyed governor limiter with amortized key retention: every 4096th allow() sweeps buckets indistinguishable from fresh (retain_recent), bounding the key map by distinct IPs per bucket-drain horizon instead of process lifetime. new(Quota) / with_retain_every(Quota, NonZeroU64) (test seam) / allow(&IpAddr) → bool / key_count(); re-exports governor::Quota. Consumed by craig-api’s per-minute limiter and craig-intake’s per-hour public/signed limiters (their quota construction + 429 middleware stay crate-local).

  • SubsidyReviewSweepSettings (#1096) — the sweep scheduler’s consent-knob group on FinancialSettings (settings.financial.subsidy_review_sweep since #998, nests as CRAIG_FINANCIALSUBSIDY_REVIEW_SWEEP*; all default off). metrics::subsidy_review_sweep — run/leg counters, backlog gauges, duration histogram, last-success timestamp, lease skips. problem_types gains SWEEP_RUN_STATE (+ SWEEP_PREVIEW_EXPIRED / SWEEP_TOKEN_ISSUED since #1939; SWEEP_ALREADY_RUNNING was RETIRED by #1939 — a held lease is the sweep_execute job’s waiting_for_lease, never an HTTP 409).

  • SubsidyErrSettings (#1069 M2) / SubsidySgSettings (#1070, ADR-056) — the enrollment consent knobs on FinancialSettings (settings.financial.subsidy_err / .subsidy_sg since #998, nesting as CRAIG_FINANCIALSUBSIDY_ERR* / CRAIG_FINANCIALSUBSIDY_SG*; both { enabled: bool }, default OFF — enabling is the operator’s recorded consent to the ⁂ #1073 money-policy readings). ONE subsidy_sg knob covers the sg AND nrsg family and gates the create arms
    the witnessed activation ONLY — existing agreements' lifecycle (generator, ALL transitions incl. the corrective guardianship_finalized, reviews, sweep) is deliberately grandfathered. problem_types gains CLOSED_PROGRAM (#1070 — closed-cohort creation refusals naming the closure date + the #1071 import path).

  • problem_types gains SUBSIDY_AUTHORITY_NOT_READY (503 — the detail is ONE closed reason token), SUBSIDY_AUTHORITY_UNCONFIGURED (403), SUBSIDY_AUTHORITY_EVALUATION_FAILED (500) and SUBSIDY_APPROVAL_CONTEXT_STALE (409) — the administrative-authority fail-closed map (#1787, ADR-074 decision 11). ApiError::internal_typed is the FIRST typed 500: a NAMED invariant breach with a client-safe detail rendered verbatim (the redacted catch-all internal stays the default). metrics::authority_surface::record_verified — the authority_surface_verified{jurisdiction} gauge, the operator alert for the human approval acts' 503.

  • problem_types gains ADMIN_UNITS_UNAVAILABLE (503 — the detail is ONE closed reason token: pending / stale / unreachable / forbidden / malformed / unconfigured), the engine’s refusal when a ruleset consults claims.admin_units and the worker’s units are not ready (#1903, ADR-077 D3); metrics::admin_units_snapshot::record_verified — the admin_units_snapshot_verified{jurisdiction} gauge (the authority_surface_verified shape; both ride ONE gauge helper). ServiceSettings gains the shared security_base_url leaf (lifted from PlacementSettings, env names unchanged) and admin_units: AdminUnitsSettings { max_age_secs: 300 } (CRAIG_<SVC>ADMIN_UNITSMAX_AGE_SECS; boot refuses 0).

  • problem_types gains INVALID_KINSHIP_HOUSEHOLD (409 — a kinship_household.existing choice names no household) and CAREGIVER_BINDING_OVERLAP (409 — one person’s bindings on one caregiving unit never overlap), and loses ARRANGEMENT_HAS_BINDINGS (a binding keys the kinship household, not the arrangement, so no binding blocks a retract) (P-B2 U5, #2058).

  • problem_types gains five 400 types for refusals a handler makes on a well-formed body (#3073; VALIDATION_FAILED stays the 422 of body-shape validation): DUPLICATE_ENTRY (a list names one identity twice), SCREENING_COHORT_HASH_MISMATCH (a screening stage’s cohort_hash is not the hash of the members sent), TRIGGER_INTERFACE_UNDECLARED (a trigger backlog act names an interface the deployment declares no leg for), AFCARS_SUBMISSION_INVALID (the ready-for-transmission act on a submission without records or with validation errors) and INVALID_SIGNER_JWK (a partner signer key that is not exactly a P-256 public key).

  • problem_types carries the collection run’s two (#3188): COLLECTION_UNDECLARED (400, field leg: the deployment holds no collection for that interface and leg) and COLLECTION_DISABLED (409: the interface’s collection consent is off). They are what the run route answers before it enqueues a job. The four it also answered while the run was inside the request (COLLECTION_RUNNING, COLLECTION_PARTNER_UNRESOLVED, AGREEMENT_DOES_NOT_ADMIT, PARTNER_UNREACHABLE) are removed with #3190: a held lease is the job’s wait, an unreadable document is a recorded run in the job’s result, and the other two fail the job refused_at_start, a token whose meaning #3190 widens from a consent knob read off to any precondition an attempt reads at its start. ExchangeSettings gains collections, the twin of triggers. Since #3196 both are an InterfaceConsents: a map from interface token to its enabled knob, with no field per partner, loaded from the same variables (CRAIG_EXCHANGETRIGGERS<INTERFACE>ENABLED and the COLLECTIONS twin). enabled(interface) → bool is false for an interface with no variable; interfaces() lists the ones a variable names, which craig-exchange checks against its build at boot. Since #3190 ExchangeSettings also carries collection_schedule (CollectionScheduleSettings { interval_seconds }, CRAIG_EXCHANGECOLLECTION_SCHEDULE__INTERVAL_SECONDS, default 0 = no schedule): a group of its own, because the COLLECTIONS group’s keys are interface tokens.

  • problem_types gains IVE_SURFACE_NOT_READY (503 — the IV-E surface is unverified or unreachable), IVE_POLICY_MOVED (409 — the act’s rendered surface identity is not the active one, or the ruleset moved during the fan-out) and IVE_INPUT_NOT_DECLARED (400 — an answer the surface does not declare at that scope, or one its declared property refuses; the detail names the key) (#1719, plan ive-determination-inputs U2).

  • problem_types gains SAFETY_SURFACE_NOT_READY (503 — the safety surface is unverified or unreachable; the detail is one closed reason token), SAFETY_POLICY_MOVED (409 — the surface identity an assessment names is not the active ruleset), SAFETY_FACT_NOT_DECLARED (400 — an answer the surface does not declare, or one its declared property refuses; the detail names the key and the expected kind) and SAFETY_FACT_UNANSWERED (422 — a declared fact has no answer; the detail lists the missing keys) (#3104).

  • problem_types gains RULESET_MOVED (409 — an evaluate’s expect names a (rule_set_id, revision) other than the active one; the detail names the active identity, no zen run, no audit row) (#2325, plan ive-determination-inputs U1b).

  • SubsidyImportSettings (#1071, ADR-057 D12) — the conversion-import gate on FinancialSettings (settings.financial.subsidy_import since #998, nesting as CRAIG_FINANCIALSUBSIDY_IMPORTENABLED; { enabled: bool }, default OFF — flipped only for the conversion window). Gates every import WRITE (create-batch, stage, abort, finalize); the GETs stay readable knob-off for post-conversion audit, and materialized agreements' lifecycle never consults it.

  • SubsidyBackpaySettings (#2223, plan backpay-import-path G-B) — the below-floor backpay consent gate on FinancialSettings (settings.financial.subsidy_backpay, nesting as CRAIG_FINANCIALSUBSIDY_BACKPAYENABLED; { enabled: bool }, default OFF; a standing capability, G-B ruling 2026-10-08 on #1115). Read first by every backpay write route and re-checked at backpay_finalize attempt start (#2225); the GETs stay readable knob-off.

  • BusinessClock (#1092, ADR-053 amendments) — jurisdiction → business calendar date. The zone is bundle data (#2207): a jurisdiction’s bundle/settings.toml declares an IANA name (StateBundle::business_timezone() — the Georgia layer America/New_York, the Texas layer America/Chicago), and the clock reads the zone installed at boot from the loaded bundle, keyed on the jurisdiction the configuration snapshot names (exact, case-sensitive). for_jurisdiction(&str) (total: an undeclared jurisdiction → UTC), try_for_jurisdiction(&str) (None when undeclared — the AFCARS surface’s jurisdiction-unregistered), from_iana(&str) (#2207 — a tzdb name → clock, None otherwise), today(), date_of(DateTime<Utc>), timezone_name(), tz() (#895 — the zone itself, for local wall-clock arithmetic). Copy; resolve today() ONCE per unit of work and thread the NaiveDate through domain logic (the financial store writers take it as a parameter).

    • Installation (#2207, #2956). The clock reads a set-once process registry in craig_common::clock. install_business_timezone(jurisdiction, iana_zone) installs one zone; install_business_timezones(pairs) installs every (jurisdiction_code, Option<iana_name>) pair that declares one. Every binary that resolves a business clock (the services, and craig-seed) installs its zone through ConfigBundle::boot (craig-config-bundle), before its router is built. Installing the zone a jurisdiction already has is a no-op; a different zone is refused (InstallTimezoneError::Conflict), and a name that is not a tzdb zone is refused (InstallTimezoneError::NotATzdbName); either refuses startup. A jurisdiction nothing installed is undeclared (UTC). craig-ledger installs nothing — it reads its host binary’s registry. business_timezone_installed(jurisdiction) reports real installs only.

    • Test binaries (#2956). A test binary boots no service. Under the test-only test-zones feature, which craig-test-lib enables, a jurisdiction nothing installed answers from a fixed table of the shipped zones (Georgia, Texas); an installed zone always wins. The release-artifact gate keeps the feature out of every release build unit (Quality Gates & Enforcement (CRAIG)).

    • craig-web templates (#2450). An Askama filter takes no state, so craig-web’s top-level business_clock::scope_layer scopes the active jurisdiction’s clock in a task-local per request, as with_locale does for |t. format_date, the episode removal and exit prefills and the historical arrangement days render an RFC 3339 instant as its date_of on that clock; a date-only YYYY-MM-DD is never projected. Outside the scope (a handler called from a unit test) the clock is the UTC fail-safe.

  • export_window (#2119, plan afcars-pipeline-sources D3) — the window rule every AFCARS source projection applies once: check_export_window(clock, from, to, as_of, now) admits from / to only as local midnights with from < to and an as_of at least EXTENDED_REQUEST_CEILING in the past, returning an ExportWindow (the instants plus from_d, to_d, period_end) or a WindowFault { field, detail } the handler maps to its own status (placement’s GET: 400; cases' POST: 422). is_local_midnight(clock, t).

  • deadline (#895 MR-B / #1744, plan investigation-response-deadlines §B) — the pure investigation response-deadline arithmetic. WindowSpec { count (1..=366), unit: WindowUnit (Hours | Weekdays | CalendarDays), receipt_day_is_day_one, skip_weekends, skip_holidays, end_of_day } is the {j}-response-window ruleset row as data; HolidayCalendar { dates, covered_from, covered_through } (empty(), new(..), covers(from, through)) is the bundle’s calendar with the range it vouches for; derive_deadline(received_at, &spec, clock, &holidays) → Result<DateTime<Utc>, DeadlineError>. HOURS = received_at + count h (checked); day units walk from clock.date_of(received_at) counting dates that are not a skipped weekend (the Weekdays unit never counts one) nor a skipped holiday, day one = the first counted date ≥ d0 (day-one) or > d0, to day count; the instant is the target’s local end of day (23:59:59.999999) or the receipt’s local wall time on the target; local → UTC is total (fold → earliest, gap → the first valid wall time reached by one-minute steps, ≤ 180). skip_holidays REQUIRES calendar coverage of d0 ..= target — an empty calendar refuses (HolidayCalendarUncovered), never a silent working day. Spec refusals: ZeroCount, CountTooLarge, HoursWithDayFlags (any day flag on HOURS), DayOneRequiresEndOfDay, WeekdaysRequireSkipWeekends (a WEEKDAYS row must carry the flag); DateOutOfRange for out-of-range arithmetic / the 2·count + 366 visited-date cap. Consumed by craig-cases (MR-E) with the bundle-supplied StateBundle::holiday_calendar() parsed fail-fast at boot (craig_cases::holidays).

craig-auth

  • Claims: every field is private (#2522), so the token is read through methods. The non-identity facts have same-named getters: aud(), azp(), iat(), scope(), typ(), nonce(), at_hash(). nonce/at_hash are OIDC id-token-only claims (#813); JwksProvider verifies typ against a configurable expected value (default "Bearer"; the craig-web id-token verifier sets "ID" via with_token_type). The token on the wire (under a BFF relay, the service principal) is read only through the bearer accessors bearer_sub, bearer_username, bearer_email, bearer_name, bearer_roles, bearer_has_role(role), bearer_is_service, bearer_is_portal_principal and bearer_require_service_caller. is_relayed() is true when a verified actor was lifted; is_direct_service() (a service bearer with nothing lifted) is the one "evaluates as a service" predicate. Also channel(), is_portal_channel(), service_id(), service_role_id(), has_scope(scope), require_scope(scope), and acting_worker(), which returns the view below.

  • ActingWorker<'_> (#2522): the Copy view of who acted, the lifted actor under a relay, else the bearer. Reads username(), email(), name(), roles(), has_role(role), is_service(), is_portal_principal(); the role gates require_role, require_any_role, require_caseworker_or_above, require_supervisor_or_above, require_admin, require_eligibility_worker_or_above, require_icpc_coordinator_or_above; and claims(), the acting token. Every role gate reads it, so a relay is judged on its worker, and so does every recorded actor (the acting-identity census pins no open owner site). log_id() (#2740) is the actor’s encoding for a log line, or the raw sub when the claims name no actor, so a log line never fails. ActingWorker::sub() is removed (#2740, ADR-085 D3): a raw use reads Claims::actor(), Claims::worker_subject() or log_id() instead.

  • The acting principal (actor module, #2740, ADR-085 D3), re-exported at the crate root. Actor is Worker(Subject) or Service(ServiceName); a service never has a subject.

    • Subject wraps a worker’s UUID (uuid(); Display and Serialize are the bare UUID’s).

    • ServiceName is any client’s name, ^[a-z0-9][a-z0-9-]{0,63}$ and never a string that parses as a UUID, so it holds no :; ServiceName::new(name) is None otherwise. It is not craig-reference’s enum of the core services: craig-intake, craig-web and craig-cli are names too.

    • Actor::encoding() is the one persisted encoding of every stored actor, intent digest and audit actor: the lowercase hyphenated UUID for a worker, service:<name> for a service, which never parses as a UUID. Serialize writes it as a JSON string; Actor::parse_encoding(s) inverts it and accepts only the canonical forms. subject() and service() project the two variants.

    • Claims::actor() reads the acting identity (the lifted actor under a relay, else the bearer, as acting_worker() does) by an ordered rule: its own service:<name> role (today’s IdP service token) is Actor::Service(name); else a UUID sub is Actor::Worker; else a sub equal to its azp that is a valid name is Actor::Service(sub) (the internal issuer’s bare service principal, whose sub is its client id); else a typed 500. The first rule never reads service_id()’s `azp fallback, since a worker token carries an azp too.

    • Claims::worker_subject() is the subject for an operation that acts for a worker. A service is a 403 with the problem type worker_required (problem_types::WORKER_REQUIRED), never a 500.

    • Claims::legacy_service_uuid() is Some only when the actor is a service and the acting sub parses as a UUID (today’s IdP service token). It exists only for D3’s comparison with digests stored before #2740 (see craig-api below) and is deleted at the switch (ITI U17), with the IdP tokens that carry such a sub.

    • Claims::test_service(name) (test-fixtures feature): a bare service principal in the internal issuer’s shape (plan ITI § C): sub = azp = name, no service: role, no user fields. Its actor() is Actor::Service(name).

  • ClaimsBuilder (test-fixtures feature only): the one way a test outside craig-auth builds a Claims; actor(..) lifts a second token as a verified actor would be. (craig_test_lib::jwt_mutation::ClaimsBuilder is unrelated: it builds JWT claim JSON.)

  • Construction rule: production Claims come only from craig-auth’s JWT, introspection and actor-token decoders. Claims has no public Deserialize (#2684), and the introspection body type IntrospectionResponse and its into_claims() are crate-private (#2526); crates/craig-auth/tests/decode_surface.rs pins their visibility. The test-fixtures feature is the one remaining way around the rule; no released image carries it (the release-artifact gate), and its last carrier, xtask’s graph, is an accepted exception of that gate (#3135).

  • Claims roles come from the configured roles-claim path (#2684), never a fixed realm_access field.

craig-authz (ADR-023 / ADR-024)

  • AuthzEngine trait (async) — check(claims, resource, action) → Result<(), ApiError>; auto_scope_list(claims, resource_type, action, jurisdiction) → Result<ListScope, ApiError>; check_typed / auto_scope_list_typed (#786) — provided typed seams surfacing AuthzError so craig-rules' bootstrap fallback can distinguish source-attested PolicyMissing (the ONLY admitting class) from a real deny or a runtime fault (incl. the #786 PolicyLoad refresh-fault variant → 500); the defaults report an opaque non-admitting deny (test doubles inherit unchanged), and the typed list seam surfaces a miss as Err(PolicyMissing) where the untyped path keeps Ok(ListScope::Denied); resolve_field_permission(claims, resource, field, field_owner) → Result<FieldPermission, ApiError> (ADR-037 §2/§3; default-deny default impl so test doubles / alternate engines compile unchanged) — the acting worker’s effective per-field permission, resolved through the SAME {jurisdiction}-authz-<resource> ruleset (ZenAuthzEngine builds the input via build_check_input(…, Action::Update) + injects field/field_owner into resource.attrs) read through a NEW disjoint field_permission output token, so check/auto_scope_list are untouched.

  • ZenAuthzEngine — concrete impl over zen_engine::Decision + a dedicated !Send-future eval thread (mirrors craig-rules). boot(source, jurisdiction, source_service, policy_ttl) → (engine, Option<CoverageWarning>) bulk-fetches {jurisdiction}-authz-* rulesets, compiles, primes the cache, computes ResourceType × Jurisdiction coverage. boot_degraded(…​) (#786) skips the bulk fetch — empty cache, the REAL source retained — so a degraded boot genuinely self-heals (per-request lazy loads + invalidation events + the bounded post-boot warmup; the TTL task only re-fetches names already cached). refresh_entry(name) / refresh_stale_entries().

  • WorkerUnitsSource (#1903, ADR-077 D3) — units(worker_sub: &str, jurisdiction: &str) → UnitsAnswer::{Ready(Vec<String>), NotReady(UnitsReason)}; UnitsReason::{Pending, Stale, Unreachable, Forbidden, Malformed, Unconfigured}::token() (six closed kebab-case words — the ONLY source-side text that reaches a response); StaticUnitsSource::{ready(map), not_ready(reason)} + calls() — the ONE test double (not cfg(test)). ZenAuthzEngine::set_units_source installs the production source (craig_bootstrap::admin_units::SecurityUnitsSource); the engine DEFAULTS to StaticUnitsSource::not_ready(Unconfigured). CachedRuleset.consults_units is recorded once at compile from the JDM census; units_for answers [] without a consult for a non-consulting ruleset or a bare service principal, otherwise the ACTING worker’s units, on all three entrypoints; AuthzError::UnitsUnavailable { reason } → typed 503 ADMIN_UNITS_UNAVAILABLE (never [], never FieldPermission::None, passed through by the untyped auto_scope_list). The evaluation input’s claims.admin_units is ALWAYS a JSON array.

  • calling_service(&Claims) → Result<Actor, ApiError> and audit_actor(&Actor) → AuditActor (#3116) — the audit actor a publisher states for the principal its handler holds. calling_service reads the bearer’s service:<name> role only (never a relayed worker, never azp) and is a 403 for any other token; audit_actor names a worker by subject and a service by service:<name>, the text a denial of that service carries, and never the system.

  • ResourceRef<'a> { resource_type, resource_id, assigned_worker_sub, supervisor_sub, jurisdiction, attrs: HashMap<&str, Value> }.

  • Action enum — Read | List | Create | Update | Delete | Approve (snake_case).

  • ResourceType enum — one variant per protected resource across every service (snake_case, IntoEnumIterator for the boot coverage check; the enum in craig-authz/src/types.rs is the source of truth).

  • ListScope — All | AssignedWorker(Uuid) | AssignedSupervisor(Uuid) | AdminUnits(Vec<String>) | Custom(Value) | Denied; filter() → ScopeFilter { All, Worker(Uuid), Supervisor(Uuid), Units(Vec<String>), Denied, Refused } is the projection every list handler matches exhaustively (#1898 / #1903, ADR-077 D5). AdminUnits is resolved by the engine from the ONE marker cell {"custom": {"scope": "admin_units"}} over the SERVER’s units for the acting worker — never a list the ruleset emitted.

  • PortalScope (#1851 / ADR-076 D4) — CaregiverBinding; decode(&ListScope) → Option<PortalScope>, the STRICT decoder of the only custom scope any shipped ruleset emits: Some iff Custom carries exactly {"binding":"caregiver"}; every other scope or payload is None and the caller falls back to ApiError::custom_list_scope_unsupported() — Custom stays fail-closed at every boundary that does not call it.

  • FieldPermission — Read | Write | Propose | None (ADR-037 §3; the per-field analogue of ListScope; Propose = a non-owner’s effective permission on a shared field under Action::Update).

  • CoverageWarning::Missing { jurisdiction, missing } — boot signal; bails when CRAIG_<SVC>__AUTHZ_REQUIRE_FULL_COVERAGE=true.

  • RulesetSource trait + InMemoryRulesetSource (tests) + craig_rules_client::RulesClient (prod). RulesetCache = HashMap<name, CachedRuleset> behind tokio::sync::RwLock. compute_coverage(cache, jurisdiction); ruleset_name_for(jurisdiction, resource_type) = "{jurisdiction}-authz-{resource_type}".

  • audit::AuthzAuditSink — emission port the engine REQUIRES at construction (ADR-050 / #908); production adapter is craig_bootstrap::OutboxAuditSink (one-shot outbox tx, fire-and-forget, warn!-only failures). NoopAuditSink (explicit discard) + RecordingAuditSink (test assertions) ship alongside. The engine stages authz.cache_miss on every source-attested miss (attributed: sub/is_service/service_id; never on PolicyLoad faults) and authz.cache_refreshed on every refresh path (trigger-attributed, incl. boot/warmup/ lazy_load; eviction = new_version: null).

  • audit::build_*_event(…​) — authz.access_denied / authz.cache_miss / authz.cache_refreshed envelope builders. All three are engine-emitted through the injected sink; access_denied (since #1063) is volume-gated by the full-dimension deny aggregate — exact repeats per 60 s window suppress WITH reported counts (suppressed_prior / kind: "suppression-flush"), never silently (ADR-050 §Amendment #1063).

  • Fail-closed (#786 fault/absent split): a SOURCE-ATTESTED miss (the source itself returned None) → check Forbidden (PolicyMissing), auto_scope_list ListScope::Denied (untyped path; the typed seam surfaces Err(PolicyMissing)), resolve_field_permission FieldPermission::None; a refresh FAULT during a miss (fetch/compile failure) → PolicyLoad → Internal on every path — the engine never claims absence it cannot attest; malformed output → Internal.

  • invalidation::spawn_invalidation_subscriber(…​) — binds ruleset.changed.<prefix>* to an exclusive auto-delete queue. invalidation::spawn_ttl_refresh_task(engine) — TTL/10 sweep (floor 30 s) with ±25% jitter.

craig-rules-client (Plan A § D4)

  • RulesClient::new(http, base_url, bearer) — clone-friendly (Arc inner) HTTP client for craig-rules. list_by_prefix(prefix) → Vec<FetchedRuleset> (paginates internally, and asks the list for each row’s graph with include=content, which GET /v1/rules/sets leaves out by default since #3170); get_by_name(name) → Option<FetchedRuleset> (404 → None). Implements craig_authz::RulesetSource.

  • evaluate(&EvaluateRequest, &RelayedAuth, timeout) → Result<EvaluatedRuleset, EvaluateError> (hard-checks U2) — POST /v1/rules/evaluate under ACTOR-RELAY auth (the inbound Authorization + X-Craig-Actor pair forwarded verbatim), per-request hop-budget timeout, strict decode (output + rule_set_revision + evaluation_id all required — never a defaulted verdict; #1627 adds the tolerant rule_set_version: Option<String>, the rule set’s human version label the consumers freeze as provenance). #2281: a 2xx body that does not read in full (the hop budget elapsing, or the connection closing mid-body) is EvaluateError::Transport — the callers' fail-closed 503; only a body read in full that does not decode is Malformed, carrying the serde_json::Error. #1623: with_metrics_caller(caller) (builder-style) routes evaluate’s send through craig_common::telemetry::send_with_metrics — the epic-&35 outbound histogram + W3C traceparent — attributed to the consuming service (cases sets "craig-cases" since #1623; financial "craig-financial" since #1628). Consumers: financial’s subsidy age check (U2) and, since #1623, all three cases evaluate relays (safety, IV-E assembly, person-match).

  • JwksProvider — JWKS cache with auto-refresh: new(issuer) / with_fetch_url(issuer, fetch_url) (split URLs for Docker); refresh() / start_refresh_task() (hourly); validate_token(token) → Result<Claims>.

  • AuthLayer — Axum middleware (new(provider), inserts Claims into extensions); auth_middleware() Tower fn; require_role(claims, role) → Result<(), Response>. Every 401 the middleware answers is the RFC 9457 application/problem+json document with the shared unauthorized type and a fixed, value-free detail (#2920), the body each service’s OpenAPI documents for it.

craig-db

  • DbPool — wraps sqlx::PgPool, Deref<Target = PgPool>. connect(url) / connect_with(url, opts) / connect_for_gate(url, opts) (#1340 — the ADR-063 migration gate’s variant, 60 s acquire) — all three → Result<Self, DbConnectError> since #1399 U1 (Sqlx(sqlx::Error) transparent, or RewriteFenceHeld { holders: Vec<FenceHolder> } when the eager probe finds the field-scheme rewrite fence held — crates/craig-db/src/rewrite_fence.rs; connect_lazy_with keeps sqlx::Error, hook-only); inner() → &PgPool; begin() → Result<Transaction>; health_check(); run_migrations(migrator) (gate-plane only since ADR-063 — the validate isolation lint pins its callers to craig-db + the migrate-mode helper; serving boot verifies via verify_schema, below); snapshot() → PoolSnapshot; probe_acquire() → ProbeSample.

  • DbPoolOpts { max_connections: u32, idle_timeout: Duration, statement_timeout_ms: u64, rewrite_fence: RewriteFence } (RewriteFence::Participant by Default — every pool connection takes the shared session advisory lock SCHEME_REWRITE_LOCK_SQL_KEY in after_connect; Rewriter is reserved for the #1399 U2b tool).

  • Pool observability (#1160): PoolSnapshot { max, size, idle } (cheap atomic reads for the scrape-time db_pool_connections_* gauges) and ProbeSample { wait, error } from probe_acquire — one timed acquire-and-release; PoolTimedOut is the session-exhaustion signal, catching the server-ceiling case (size < max while Postgres refuses new sessions) the gauges alone cannot. The shared bootstrap (craig_api::connect_database) registers the gauge source and spawns the 15 s probe for every service. The serving pools' 5 s acquire_timeout remains a FIXED constant by recorded policy — the fail-fast cliff is intended; capacity and the instruments are the remedy (deployment guide § Database connection budget). ONE recorded exception (#1340): connect_for_gate gives the one-shot migration gate a 60 s bound — a deploy phase waits out a busy server instead of failing on the serving cliff.

  • Migration session isolation (#1153): run_migrations executes on a dedicated connection (detached from pool accounting, closed after the run) — never directly on the serving pool. sqlx performs no session reset on return-to-pool and the F-019 after_connect timeout hook fires only on new physical connections, so a migration’s plain session-scoped SET (e.g. SET statement_timeout = 0) would otherwise serve traffic for up to max_lifetime. Convention for migration authors: use SET LOCAL for per-migration overrides so one migration’s setting cannot bleed into later migrations in the same run (cargo xtask validate-migration-constraints reports plain SET statement_timeout sites).

  • Schema state machine (ADR-063, #1306, schema_state module): the ONE classifier both process modes consume. Pure core classify(&[AppliedRecord], &[EmbeddedMigration]) → SchemaState (Dirty | ChecksumMismatch | Diverged | Behind | Ahead | Exact, deterministic precedence; Behind ⇒ applied ⊊ embedded by construction)
    embedded_up_migrations(&Migrator) (down-files filtered, matching sqlx apply semantics). Consumers on DbPool: verify_schema(migrator, FloorCheck, gate_hint) → Result<SchemaVerified, SchemaVerifyError> (serving boot: plain-SELECT inspection, no DDL, no advisory lock, SELECT-only-role safe; Ahead tolerated only while the schema_compat_floor table’s min_required_version ≤ max(embedded)) and apply_by_verdict(migrator) → Result<ApplyOutcome, SchemaApplyError> (migration gate: Exact/Ahead no-op, Behind applies via run_migrations, everything else refuses). Only SQLSTATE 42P01 maps to Behind-from-zero; every other DB error passes through typed. The schema_compat_floor singleton table exists in all 8 service schemas; destructive contract migrations must bump it in the same file (lint from M2/#1307).

craig-mq

  • EVENTS_EXCHANGE = "craig.events" (topic exchange). connect(url) → Result<Connection>.

  • amqp (#2603) re-exports the AMQP client types other crates name, item by item: Channel, Connection, ConnectionProperties, ChannelStatus, ConnectionStatus, Error, ErrorKind, BasicProperties, Confirmation, Delivery, ChannelId, FieldTable, and the option structs of confirm-select, publish, get, ack, nack, queue bind, queue declare and queue delete. deny.toml bans a direct lapin dependency outside craig-mq and craig-test-lib, so these paths are the only way another crate names one (quality gates § Disallowed methods). Exchange-declaration and consumer types are not re-exported.

  • EventEnvelope { id: Uuid, timestamp, source_service, event_type, payload: Value, trace_context, audit: Option<AuditMeta> } — new(source_service, event_type, payload, audit) (UUID v7 + now, carrying the audit header its publisher states, #2314). Code outside craig-mq has no constructor that builds an envelope without a header; audit is None only on an envelope decoded from a message that carried none, or on a capture of such a delivery. audit is omitted from the wire when None, and its decode never fails the envelope: any JSON under audit is read field by field. craig-security files a headerless envelope as the system’s, with no record and the payload unread (data model § audit_log).

  • AuditMeta (#2314, audit_meta.rs) is the envelope’s audit header: what the event did (AuditAction, 43 tokens), to which kind of record (AuditResource, 85 tokens) and which one (Option<Uuid>), by whom (AuditActor: Sub(Uuid), System, or Named, built only by AuditActor::named(text), which classes a UUID in any spelling as Sub and empty text or system as System), and with what outcome (AuditOutcome). AuditMeta::new(action, resource, id, actor) states a completed act; .refused() and .with_roles(roles) state a denial and its roles. The header is bounded where it is built and decoded (256 bytes of named actor, 32 roles of 128 bytes; MAX_AUDIT_HEADER_BYTES). AuditMeta::from_wire decodes per field and marks a header whose field it replaced is_degraded(); each enum’s Unknown variant comes only from that decode, and staging refuses a header naming it (Unpublishable::UnknownAuditToken) and an envelope with no header (Unpublishable::MissingAuditHeader). craig-authz maps each ResourceType to the AuditResource of the same token (From). A DLX wrapper and a _park capture carry the original’s header unchanged; the capture’s size fit reserves the header’s length.

  • Publisher (Clone) — new(channel), publish(envelope) (routing key = event_type; persistent). Every publish and outbox send is judged on the exact bytes it frames (the trace context injected, serialized once, #2825): a routing key over 255 UTF-8 bytes (the AMQP short-string bound) or a body over 12 MiB is refused unframed as PublishError::Unpublishable(Unpublishable) (sizes only, never a value). 12 MiB is an application policy under RabbitMQ 4.2’s max_message_size (16,777,216 payload bytes, inclusive, framing not subtracted), which devstack/rabbitmq/rabbitmq.conf pins; a deployment’s broker limit must be at least 12 MiB, or an admitted body still closes the publisher channel. Each confirm is awaited for 10 s (#1142); one that times out is not dropped but awaited on a detached task until the broker answers or the channel fails (#2616). lapin 4.4 parks a confirm dropped unresolved on a per-channel list that only Channel::wait_for_confirms drains, which CRAIG never calls (it waits for the last pending confirm, so it would block under the very broker stall that causes the timeouts), so dropped confirms grew for the channel’s life. A publisher and its clones hold at most MAX_IN_FLIGHT_CONFIRMS (1024) unresolved confirms, awaited or timed out, and a send past that is refused unframed as PublishError::ConfirmBacklog, a failed publish the outbox retries like a timeout.

  • Subscriber — new(url); subscribe(queue, routing_keys, handler) (competing consumers, durable shared queue — actually durable since #1127/#1104); subscribe_exclusive(queue, routing_keys, handler) (fan-out, exclusive auto-delete). Every subscription runs under a supervisor owning its own connection: on stream loss it reconnects with capped backoff (0.5s→30s), redeclares exchanges/queue/bindings, and resumes — a broker restart no longer silently halts consumption until a process restart. Every session establishment is bounded by AMQP_LIVENESS_TIMEOUT (a compiled 15s constant, deliberately not a config knob — #1528): lapin has no connect/handshake/RPC timeout, so an unbounded rebuild against a broker path that accepts TCP and never answers used to pin the supervisor permanently and stop the backoff ladder dead (ADR-003 § Amendment — #1528, which also records the measured thread-strand cost). Channels set basic_qos prefetch 16. Redelivery: nack-requeue on 1st failure, requeue=false on 2nd (DLQ); the inbox retry re-runs immediately (#1127 — no in-loop sleep; pacing is the broker’s, ladder redesign is #1053). readyz’s MQ flag reflects the publisher connection; subscriber supervisors heal independently. Handler PANICS are contained on every path (#1203): a per-delivery task boundary converts unwind panics to the normal failure ladder (events → 2-strike nack; DLQ → immediate `TransientPark, never re-invoked in-session; inbox → error_count/last_error stamp
    InboxError::HandlerPanicked), counted by dlq_handler_panics_total{path}. Unwind-only — the panic hook still runs, panic = "abort" is not contained, and handler-owned shared state must remain valid after unwind (the caller’s contract). Fut: 'static on all subscribe/inbox handler bounds (pre-1.0 breaking, #1203). Every queue is declared x-queue-type=classic (#1198, ADR-003 §Amendment #1198 — the redelivery semantics above assume classic-no-delivery-limit): a conflicting pre-existing queue fails boot with 406; a mid-life type flip logs at error! ("operator action required") while the supervisor keeps retrying.

  • stage_event(tx, envelope) → Result<(), StageError> — transactional-outbox staging (ADR-022 §D3.1): serialize once with trace_context omitted, compute the effective post-JSONB byte length (accounting for scientific-notation integral f64 values that Postgres jsonb expands to plain decimals), verify the routing key (⇐ 255 UTF-8 bytes) and effective body (⇐ MAX_STAGE_BYTES, reserving 1130 bytes below the 12 MiB MAX_PUBLISH_BYTES application publish policy for drain-time W3C trace injection) via check_envelope_bounds (2827), and INSERT the envelope in the caller’s tx. Returns the typed craig_mq_error::StageError (re-exported as craig_mq::StageError, including StageError::Unpublishable when the envelope exceeds either bound so the caller’s transaction rolls back before anything is stored); see craig-mq-error. stage_json_event(tx, source, event_type, payload, audit) is the one-call form every per-service wrapper funnels through; audit is the event’s audit header (#2314). domain_event! takes the header as a required clause after the routing key, audit = (Create, Payment, Some(payment_id), Sub(user_id)): an AuditAction variant, an AuditResource variant, an Option<Uuid> expression and an AuditActor expression (AuditActor, Sub and System are in scope); an invocation without the clause does not compile. domain_event! (#993, [macro_export]) is the fleet’s ONE definition of such a wrapper: domain_event! { /// docs publish_x(a: T, b: U), "routing.key" | SOME_CONST, audit = (..), { "a": a, "b": b.field } | value = serde_json::to_value(typed)? } expands to a pub(crate) async fn publish_x(tx, a, b) → Result<(), StageError> staging through stage_json_event with the invoking module’s const SOURCE. The six converted events.rs modules (cases, exchange, financial, placement, reporting, security) are macro-generated except the recorded hand-written residue (runtime-computed routing keys, conditional key omission, a pub wrapper a bin needs); composition’s jurisdiction-suffixed invalidation and the other staging call sites (payment_events.rs, the upload_finalizers.rs trio, rules) stage through stage_json_event / stage_event directly — the call-site contract is on the macro’s rustdoc.

  • OutboxWorker (spawned by craig_bootstrap::spawn_outbox_worker) drains each pass pipelined (#2593, ADR-022 §Amendment #2593): claim, send the batch, await its confirms together, stamp the confirmed rows in one UPDATE; a pass of 2 s or more logs outbox drain pass slow naming its slowest phase. A row the publisher refuses as unpublishable is retired the way a malformed row is (#2825): published_at stamped, attempts untouched, last_error = unpublishable envelope: … with sizes only, one value-free ERROR line; it never reaches the broker, so its batch siblings still publish and it is never retried. A stored row between 12 MiB and the broker’s limit, which the broker would accept, is retired too. Operators find retired rows with last_error LIKE 'unpublishable envelope:%' until the published-row retention prunes them.

  • subscribe_dlq(queue, routing_keys, shutdown, config, handler) — DLQ subscription; the handler takes a typed DeadLetterDelivery (#1181): envelope + dlq.-stripped original_queue + the derived per-occurrence identity (valid _park capture first — carried verbatim through the parking hop, #1197 — then x-death, then the validated _dlx wrapper, else tokenless) behind occurrence_token()/occurred_at()/park_count() accessors, and returns Result<(), DlqError<E>> — the handler CLASSIFIES its failures (Disposition::{TransientRetry, TransientPark, Permanent}, ADR-059 §D2) and the session retries in-session, parks, or quarantines, acking only after a durable anchor (#1197; settlement failures tear the session down instead of leaking prefetch credit). config is a validated DlqRetryConfig { parking_ttl, park_cap, handler_attempts, depth_sample_interval } (typed refusal before any connection); the subscription also runs a read-only depth sampler feeding the #1199 dlq_queue_depth gauges for the family queues (metrics::dlq; craig-security records dlq_outcomes_total via the re-exported DeadLetterOutcome). OccurrenceToken is a bounded validated newtype; publish_dlx takes the caller-derived token (the inbox derives it deterministically from durable state — see ADR-022 §#1181).

  • handle_idempotently(db, publisher, consumer_queue, envelope, handler) — the ADR-062 single-transaction attempt machine (#1053, supersedes ADR-022 §D3.2): ONE domain transaction per attempt commits the identity claim, the handler’s effects, and the completion stamp atomically. The handler is for<'t> FnOnce(EventEnvelope, &'t mut Transaction<'static, Postgres>) → BoxFuture<'t, Result<(), E>> (craig_mq::BoxFuture is re-exported); every domain write goes through the transaction, and the handler must never commit/roll back — the substrate owns completion. Timeout hierarchy: claim lock-wait under the default 30 s statement timeout, SET LOCAL 5s only after the lock, a 15 s attempt deadline; after the handler’s Ok, SET CONSTRAINTS ALL IMMEDIATE runs the deferred constraint checks inside the savepoint under the same 5 s cap (#2775), so COMMIT has none left and a failing check is a counted attempt. Failure accounting rolls back TO a savepoint so the claim row survives as the accounting row and INBOX_MAX_RETRIES (5) is hard over counted attempts; panics are two-tier (construction/poll caught + counted; drop/Display-render escape to the #1203 task boundary, whole-tx rollback, uncounted). Envelope identity is the triple (source_service, event_type, payload_hash) (payload_identity_hash, hex SHA-256; NOT NULL since #1273 — the legacy NULL/backfill window is closed); a reused id with different content lands in event_inbox_collisions with a dlxcol: token and nacks without requeue — the canonical row is never touched. The terminal DLX surface is mandatory-published from durable row state (occurred_at := stored received_at — re-surfaces byte-identical); a failed/unroutable surface leaves failed_at NULL and nacks requeue-TRUE (the source-queue copy is the durable envelope). Callers propagate InboxError to subscribe unmapped — the subscriber’s settlement keys on its Display. consumer_queue (#1196, epic &75 C1) stays the subscription’s own queue name: the surface routes under dlq.<consumer_queue> and records it as _dlx.original_queue, matching the broker dead-letter path.

  • Delivery timings (#2699, metrics::delivery_timing). handle_idempotently keeps ONE stage clock per delivery across its re-claim passes and reports once, after them, on every Ok or Err return (a tier-2 panic or a dropped future reports nothing):

    • craig_mq_inbox_attempt_stage_seconds\{queue, stage} (f64 histogram, unit s; queue is the consumer_queue) records one sample per stage the delivery ran. acquire is PgPool::begin: the pool wait, then sqlx’s test_before_acquire ping of a reused connection or a new connection’s setup, then BEGIN (not split further: the split needs sqlx’s #[doc(hidden)] API). claim is the claim INSERT, plus the FOR UPDATE classification on the conflict path. handler runs from the SET LOCAL statement_timeout to the handler’s return. complete is, after a handler’s Ok, the deferred constraint checks (SET CONSTRAINTS ALL IMMEDIATE, #2775), then the savepoint release or rollback plus the processed_at stamp or the accounting UPDATE. commit is COMMIT alone (or a vanished-row pass’s ROLLBACK). surface is the terminal or collision path’s post-commit DLX work. total spans the whole call; its remainder over the others is client-side time (the payload hash, clones, scheduling).

    • craig_mq_consumer_settle_seconds\{queue, outcome} times each ack/nack await of a regular subscription (outcome = ack / nack_failed / nack_undecodable, and the batched subscription’s nack_requeue). queue is the consumer queue for subscribe, subscribe_idempotent and subscribe_idempotent_batched, and the literal exclusive for every subscribe_exclusive queue, whose per-instance names would mint a series per boot.

    • craig_mq_consumer_receive_seconds{queue} (same queue label) times a regular subscription’s wait for each delivery: from the end of the previous settlement (or the session’s start) until consumer.next yields the delivery. A liveness tick or a delivery error does not restart the clock, so the wait includes idle time when the queue is empty: it reads as broker delivery latency only under a backlog, e.g. in an instrumented battery.

    • All three histograms use explicit second-scale buckets (0.5 ms, 1, 2.5, 5, 10, 25, 50, 100, 250, 500 ms, 1, 2.5, 5, 10 s); the SDK defaults would put every millisecond sample in one bucket.

    • Two value-free DEBUG events carry the same numbers per envelope, never a payload field. inbox attempt timings (target craig_mq::inbox): envelope_id, queue, outcome (processed / deduplicated / failed / terminal / collision, or error when no branch classified the delivery, e.g. a BEGIN or COMMIT error), acquire_us … surface_us and total_us (integer µs, 0 for a stage not run), and pool_size / pool_idle read at entry. inbox delivery settled (target craig_mq::subscriber): queue, outcome, receive_us, settle_us, and envelope_id when the body decoded. To see them on a service (devstack or an instrumented battery), set RUST_LOG to include craig_mq=debug, e.g. RUST_LOG=info,craig_mq=debug; compose sets no RUST_LOG on a CRAIG service, so its default level hides them. The on-demand reproduction that reads the inbox attempt timings event is the inbox latency probe.

  • Batched inbox (#2773, plan audit-batched-claims U2; ADR-062 § #2765), craig_mq::inbox_batch, re-exported at the crate root. The database side of an opted-in subscription; the session that collects, settles and arbitrates is subscribe_idempotent_batched (below).

    • handle_batch(&BatchInbox, consumer_queue, envelopes, handler) → BatchReport runs up to K deliveries through ONE transaction and one COMMIT. BatchInbox \{ pool, publisher, policy, is_statement_timeout }: BatchPolicy::new(k) refuses 0 and anything above PREFETCH (16) with a typed BatchPolicyError; is_statement_timeout: fn(&E) → bool recognises the batch’s 2 s statement cap in a handler error (craig-security’s classifier, plan U4, will downcast its anyhow::Error to sqlx::Error and test 57014). The handler bound is handle_idempotently’s plus `Clone + Sync; each admitted envelope gets its own handler.clone().

    • BatchReport \{ verdicts, flush, outcome }: one BatchVerdict per input, in input order — Committed(Box<Committed>) (pass it to finish_committed), Deferred(DeferReason) (run it solo after settlement), Carried (lead the next batch) or Arbitrate (run it solo; its claim arbitrates). DeferReason is closed: Contended (55P03, 40P01), ClaimTimeout (57014), Vanished, DuplicateId (a second copy of an id, before its claim), BatchBudget (the 5 s handler deadline, a batch statement’s 57014, or a classified handler error; uncounted). flush is Count, Budget or Drained; outcome is Committed or Arbitrated(AbortClass) (Statement, Connection, ClientTimeout, CommitFailed, CommitTimedOut; the last two are uncertain; an unhashable payload is Arbitrate whatever the outcome). Any error no savepoint absorbs, a client round-trip timeout or a COMMIT error makes every admitted and deferred verdict Arbitrate (Carried stays); the aborted transaction is dropped, and sqlx’s rollback-on-drop and release ping decide reuse, as on the single path. A tier-2 panic unwinds out of handle_batch to the caller’s contain.

    • Committed holds the provisional outcome as data (ProvisionalOutcome: Processed, Deduplicated, Failed \{ failure, last_error, error_count }, TerminalUnsurfaced, Collision), never the handler’s error type. finish_committed(&BatchInbox, consumer_queue, Committed) → Result<(), InboxError<RenderedError>> runs its post-commit work with no transaction open and returns what handle_idempotently would have: Ok, the counted failure’s Handler(RenderedError) (Display handler: <text>, the text rendered before the commit) or HandlerPanicked, the terminal surface (SurfaceFailed leaves failed_at NULL), or IdentityCollision.

    • Budget (D3, pub constants with compile-time asserts): claim phase lock_timeout 50 ms and statements 1 s, batch statements 2 s, handler deadline 5 s, commit phase 1 s for both timeouts, every statement’s client round trip its server timeout + 1 s (and BEGIN’s the pool’s acquire timeout + 1 s), `admit stops at 5 s of hold, BATCH_HOLD_BUDGET 21 s (under craig-db’s 30 s statement_timeout_ms). Each phase sets its timeouts before its savepoint; resync (3 s) drains a dropped handler statement before every rollback that follows the handler. The commit phase runs the pending deferred constraint checks as an ordinary statement (SET CONSTRAINTS ALL IMMEDIATE) under its 1 s caps, because PostgreSQL disables statement_timeout before it processes a COMMIT; COMMIT is left with the WAL flush, and a deferred check that fails or overruns is a certain rollback (Statement). A BEGIN that outlives its bound finishes in a detached task whose late transaction drops with its rollback queued, since a top-level BEGIN dropped mid-flight queues none in sqlx 0.8.6.

    • Handler obligations: now() is the batch’s start, so per-event times use clock_timestamp() (the batch’s own inbox stamps do); no SET LOCAL (it would persist into later envelopes); no savepoint (two per envelope already, under PostgreSQL’s 64-entry subtransaction cache).

    • Metrics (metrics::inbox_batch): craig_mq_inbox_transactions_total\{queue, mode} (+1 per successful attempt-transaction BEGIN: batch per handle_batch, single per handle_idempotently pass), craig_mq_inbox_batches_total\{queue, outcome} (committed / arbitrated; a failed BEGIN counts as arbitrated, and in …_batch_envelopes), craig_mq_inbox_batch_envelopes{queue} (buckets 1–16), craig_mq_inbox_batch_seconds\{queue, stage} (acquire, hold, commit; buckets 0.5 ms to 30 s with 15, 21 and 30 s), craig_mq_inbox_batch_flushes_total\{queue, reason} and craig_mq_inbox_batch_deferrals_total\{queue, reason} (a committed batch’s deferrals). An abort logs one value-free warn! (class, SQLSTATE, batch size). Each committed envelope’s inbox attempt timings event reports from finish_committed with its confirmed outcome, acquire_us and commit_us 0.

  • Batched subscription (#2774, plan audit-batched-claims U3, D2 and D6): Subscriber::subscribe_idempotent_batched(BatchInbox, queue_name, routing_keys, shutdown, heartbeat, handler), the opt-in alternative to subscribe_idempotent for a consumer whose per-envelope commit caps its throughput. Its handler bound, queue declaration and bindings, and settle queue label are subscribe_idempotent’s; `queue_name is &'static str and is also the route of the inbox’s DLX surfaces. The pool and publisher are cloned out of the BatchInbox, so the spawned session owns them and builds each round’s BatchInbox from them. Supervision (reconnect, backoff, settlement teardown) is the regular subscriptions' loop.

    • The round: wait for a delivery (liveness tick, shutdown, receive clock as today) unless carried deliveries are held; take those, the one waited for and the buffered ones (now_or_never), up to K, examining at most K buffered items (rejected bodies and consumer errors included, so a malformed backlog cannot hold a collected delivery back) and honouring shutdown and a due liveness tick between them; an undecodable body or a consumer error as today. A redelivered delivery runs solo, never in a batch. The rest run through one handle_batch inside one contain boundary, each envelope’s handler under its own consumer span with its producer’s trace context as the parent (as is its post-commit work), and are routed by verdict: Committed to settlement, Deferred and Arbitrate solo, Carried to the next round. The handler is held behind an Arc; every clone of it runs inside a containment boundary, so a panicking Clone fails that batch or solo run, never the session.

    • Settlement after a confirmed commit, per delivery: first each processed or deduplicated delivery (its finish_committed does no I/O) in its own contain, acked, then a beat; then, in arrival order, each delivery with post-commit work (a counted failure, a terminal surface, a collision) in its own contain, settled as subscribe_idempotent settles handle_idempotently’s result (the inbox’s `Display markers, else the 2-strike ladder), a beat after each. A stalled DLX confirm (10 s) therefore delays only later surfaces, and the next beat by at most that timeout, never the plain acks. A panic in a delivery’s post-commit work leaves its effects durable: it is nacked with requeue (settle outcome nack_requeue), and its redelivery re-claims the durable row: a processed one dedups, a counted failure below the cap retries, a terminal or collision row re-runs its surface or record. A settlement failure tears the session down, as today (#1197).

    • Arbitration: when the batch aborts or a tier-2 panic unwinds out of it, every admitted and deferred delivery stays unacked on this consumer, with no nack, strike or marker, and runs solo; on a tier-2 panic every candidate runs solo, the ones the batch would have carried included, and the batch counts as arbitrated in craig_mq_inbox_batches_total. The solo list (redelivered, deferred, arbitrated) runs one at a time through handle_idempotently inside the #1203 boundary, settled as on the single path, a beat after each.

    • Shutdown is checked between rounds, between drained items, before each settlement with post-commit work and before each solo run: a round whose batch has started first finishes it and acks its processed and deduplicated deliveries. What is unsettled when the session closes redelivers and dedups or re-runs through its claim.

    • Handler obligations (the batch’s shared transaction): per-event times use clock_timestamp() (now() is the batch’s start); no SET LOCAL; no savepoint; every write through the transaction, never committed or rolled back by the handler.

    • craig_mq_consumer_settle_seconds gains the outcome nack_requeue. Under fault-injection, craig_mq::fault::arm_batch_settle_fault(queue) ends the next round on that consumer queue right after its confirmed commit with nothing settled, and arm_finish_panic(queue) panics the next committed delivery’s post-commit work; each is one-shot, keyed by queue, and disarmed when its guard drops.

  • The legacy pre-ADR-062 path (handle_idempotently_at_least_once: three autocommit statements; best-effort at-least-once — the #1178 defect) was DELETED with its last caller in A6 (#1244, epic &77): every consumer service now runs the transactional attempt machine.

craig-mq-error (#832, ADR-047)

Leaf crate holding StageError { Serialize(serde_json::Error), Unpublishable(Unpublishable), Db(sqlx::Error) } and Unpublishable { TooLarge, RoutingKeyTooLong } (#2827; re-exported by craig-mq) — the typed error stage_event returns. It lives in its own crate (deps: serde_json + sqlx + thiserror only) so craig-common can provide From<StageError> for ApiError WITHOUT craig-common depending on craig-mq (amqp) or craig-mq depending on craig-common (axum). Mirrors the craig-validation leaf-crate precedent; see ADR-047 for the layering rationale.

#1229 adds panic_message_bounded (moved from craig-mq, which re-exports it)
PANIC_MESSAGE_MAX_BYTES (previously a craig-mq private const, now pub here): the leaf home lets craig_common::supervisor extract bounded panic text without a lapin dependency — the same layering rationale as StageError.

craig-fault-core (epic &83 C9 / #1504, ADR-067 §D7)

Leaf crate (deps: parking_lot only) holding OpCountdown<K> — the shared "fail the next N calls whose key matches the armed key, then pass" countdown at the heart of the contested-environment fault injectors (CipherErrorInjector in craig-crypto, ObjectStoreErrorInjector in craig-store). It lives in its own leaf so those injectors SHARE the countdown body instead of duplicating it (the quality-budget B8 duplicate-block gate flagged the copy when C9 added the third injector). Arc-backed, so a cloned host (axum clones its state per request) observes ONE counter. Test-support only: each host crate pulls it behind its default-off fault feature (craig-crypto/fault-injection, craig-store/test-util), so it is absent from every release artifact — the release-artifact-gate lint proves it via those host features.

craig-policy (epic &56, ADR-070)

Tooling-only leaf crate (deps: serde / serde_json / toml / chrono / thiserror) holding the policy-provenance and scenario-corpus schemas — never a runtime dependency of any service (rulesets stay the verified snapshot, ADR-023/024):

  • ruleset_ref — the <ruleset-file>#<json-path> addressing layer into JDM documents (RulesetRef/RefPath grammar + resolve_in, whose optional expected-value compare is the ADR-070 content tether: a rule inserted above a cited index or an edited threshold becomes a hard ValueMismatch).

  • citation — the citations.toml manifest schema (CitationManifest/Citation, the typed six-variant Authority enum, the derivation honesty field), load_manifest, collected-issue validate, and check_against_rulesets (resolves + tethers every key against the live ruleset files). Consumed by the georgia_manifest battery test today and the cargo xtask policy family (#660–#663) as it lands.

  • scenario — the scenario-inventory schema (ADR-071: ScenarioEntry with first-class ScenarioOracle rows, ordered Level, closed stage/entity vocabularies), pure validation (validate_entry/validate_global_ids/ the §8 no-literal precondition rule), declaration-anchored resolve_binding, derived evaluate coverage, and the bidirectional check_oracle_enforcement join. Consumed by cargo xtask scenarios audit (#665).

  • source — the tooling-only PolicySource trait (#660): PammsGitSource (shallow public clones under the jurisdiction’s gitignored .policy-cache/, with the three Canopy #1347 cache_sync guards — -- dash-proofing, bare-name + current_dir clone destinations, and the in-crate head_commit non-git-dir guard; since #1619 every cache read canonicalizes under the cache root — traversal/out-of-root/symlink refs are a typed error on the hash path and collapse to manual-verification on resolve), ManualSource, the typed policy-source.toml config (SourceKind), and sha256_hex. Consumed by cargo xtask policy sync-cache [--pin|--repin <who>].

  • sync_manifest + load — the .policy-cache/sync-manifest.toml schema (per-repo HEAD
    per-cited-file hash; the comparison cache — durable pins live in citations.toml) and the crate-shared strict-TOML loader (load::toml_file / LoadError).

craig-crypto

  • FieldEncryptor — AES-256-GCM-SIV column-level field encryption. from_env() loads the key per the CRAIG_<SVC>__ENCRYPTION_* configuration; used for encrypted PII columns (e.g. craig-cases narratives). Encryption is fail-closed per ADR-020. A key-load refusal (EnvVar / Base64 / KeyLength) carries a fixed class only (EnvVar also names the variable), never the key’s decoded length, a byte or offset of its value, or the value (#2152), so a caller may keep it in any error chain.

  • StorageContext { table, column, row_id, sibling } (Copy; new(table, column, row_id) / with_sibling(&str) / aad() → Result<Vec<u8>>), CANARY_CONTEXT, FORMAT_VERSION = 2, envelope_version_of(&str) → Option<u8> (#1007, envelope format v2 — ADR-048 § Amendment — #1007): every encrypt / encrypt_str / decrypt / decrypt_str takes the context BY VALUE and binds its canonical bytes (CGEF || 0x02 || len(table) || table || len(column) || column || row_id(16) [|| len(sibling) || sibling]) as AEAD associated data — there is no context-free variant; a ciphertext decrypts only under the exact context it was produced for, v1 blobs are refused by their version byte, and is_encrypted stays magic-only (the keyed reader’s refusal of non-envelope cells closes the header bypass).

  • seal_artifact(&[u8], &ArtifactContext) → Result<Vec<u8>> / open_artifact(&[u8], &ArtifactContext) → Result<Vec<u8>> (#2176, P-D4 D1 / R-D25) — whole-file sealing of a generated artifact, raw bytes in and out, under the encryptor’s key and AES-256-GCM-SIV. ArtifactContext { kind: ArtifactKind, submission_id, attempt_id, generated_on: ArtifactDate } (Copy; ArtifactKind::AfcarsExport is the one kind; ArtifactDate::parse takes the export’s pinned %Y%m%d, exactly eight ASCII digits, else InvalidArtifactContext). The binary envelope is CGAF || 0x01 || nonce(12) || ciphertext || tag(16); the AAD is CGAF || 0x01 then each context field behind a one-byte length (the kind as the token afcars-export); the nonce is HKDF-SHA256 of the key under craig-crypto/artifact-nonce/v1 || AAD, never caller-supplied, so one attempt seals byte-identically and two distinct contexts (the AAD is injective) derive independent nonces. open_artifact refuses a wrong key, a foreign context or any tampered byte past the header (Decrypt), a non-CGAF input — plaintext or a cell envelope (MissingMagic) — and another version (UnsupportedArtifactVersion), never a pass-through; is_encrypted stays CGEF-only. Seal and open fault through CipherOp::Encrypt / Decrypt (ADR-067 §D7).

  • hmac_domain(field_domain, version, canonical) → Result<String> + BLIND_INDEX_SCHEME_V1 (ADR-049, C3 MR1) — per-field domain-separated deterministic blind index (HKDF info craig-crypto/blind-index/<domain>/v<version>; takes bytes, so Date canonicalization works; no cross-column HMAC correlation). The global-domain hmac() stays in the public API (KAT-pinned) but has no production callers post-C3 — every SSN site migrated to the per-field domain. Callers go through craig_search::FieldSpec::blind_index, not this primitive directly.

  • KCV_SENTINEL (kcv:none) + CANARY_SENTINEL (canary:none; #2143 moved it here from craig-seed, value unchanged) — the keyless crypto_key_lineage row’s kcv and canary (ADR-048 §D2), written by every keyless lineage writer (craig-seed’s keyless render, craig-reporting’s generate commit). A real KCV is base64, so it never collides with the sentinel; a verifier recognises a keyless row by kcv == KCV_SENTINEL alone and never decrypts the canary sentinel.

  • ES256 on aws-lc-rs (#2683, ADR-084); craig-crypto is the only CRAIG crate importing aws_lc_rs::signature. Es256PublicKey is a P-256 point validated at construction (from_coordinates(x, y), from_sec1 — the 65-byte uncompressed form only), with as_sec1, coordinates, to_jwk. Es256SigningKey (Clone, one key pair behind an Arc, redacted Debug): generate, from_parts(d, public) (refuses a d that derives another point), from_d(d), from_private_jwk, public_key, to_private_jwk, to_pkcs8_der (unencrypted PKCS#8 v1, zeroized; the form jsonwebtoken’s ES256 `EncodingKey takes, #2694), sign_jws (64-byte fixed r‖s) and sign_der (the same signature as minimal DER). Signatures are randomized. verify_jws accepts only the fixed form (JwsVerifyError), verify_der only strict DER — short-form lengths, minimal positive INTEGERs, r and s in [1, n), nothing trailing — so undecodable DER is DerVerifyError::MalformedSignature and only well-formed DER that fails is BadSignature. Every error is value-free.

  • jwk — the EC P-256 JWK codec, pure serde and base64ct. JwkDocument (parse, or embedded with serde) reads one JWK three ways: private_jwk() (the env key {kty,crv,x,y,d}, strict), strict_public_key() (a partner signer key: strict, d refused) and tolerant_public_key() (an actor-peer key: other members ignored, d refused). The strict readings accept WebCrypto’s export members (#2697): ext (a boolean) and key_ops, which must be exactly ["sign"] on a private key and ["verify"] on a partner key (JwkRefusal::WrongUse otherwise). x, y and d must each be exactly 32 bytes of unpadded base64url. Es256PrivateJwk (from_json, to_json) zeroizes d on drop and never prints it; Es256PublicJwk serializes as {"kty":"EC","crv":"P-256","x":…,"y":…}. JwkError { member, reason } names the member and the rule, never the value.

craig-search (ADR-049)

Generic capability-based encrypted-search framework (C3 / sub-epic &67). Leaf crate: no craig-common dependency; sqlx is an optional feature (executor glue only — it also pulls tokio for the #1138 concurrent page+count try_join!), so the capability core + planner are database-free.

  • Capability model (capability module): FieldSpec { column, logical_type, scheme }; FieldScheme (Plaintext | Opaque { at_rest } | BlindIndex { at_rest, spec, sibling_hmac }); LogicalType; OpaqueKind; BlindIndexSpec { field_domain, version, canon, codec } (+ Canon, Codec); const fn capability(scheme, type) → Capability { substring, equality, ordering } — the whole search-capability policy in one const table (substring ⇒ Plaintext+Text; Opaque ⇒ nothing). FieldSpec::blind_index(enc, &BindValue) is THE single blind-index derivation (canonicalize per the registry spec, then hmac_domain) — planner query, service write, seeder, and verify-seed all call it.

  • Predicate AST (predicate): UserPredicate (Equality/Substring/Relation), SubstringTarget (Field/Concat/AnyOf), RelationSpec (IN-subquery join filters), ParamId. Constructors are const fn`s that `assert! the required capability, so an illegal scheme/operation pairing is a compile-time error.

  • Planner (plan, with entity + runtime): SearchEntity (entity — the descriptor trait binding a service DTO as Filters) + plan(…​) → SearchPlan { table, where_sql, binds, order_by, order_dir, sibling_matches } (sibling_matches, #1759: the effective BlindIndex specs a keyed, present equality term matched; empty for a keyless plan). Injection-safe by construction (SQL from registry &'static literals
    $N only; user values reach only BindValue binds), WHERE TRUE base, bound NULL-guards for absent filters, LIKE metacharacters escaped (ESCAPE '\'), fail-closed (UnsupportedFilter/UnenforceablePolicy error, never widen). In runtime: ScopeConstraints (None/Worker/Supervisor/AdminUnits(Vec<String>) — Clone, not Copy) — the separate non-degradable policy channel (unconditional equality, no NULL-guard; AdminUnits → {col} = ANY($n) over ONE BindValue::TextArray, SearchEntity::admin_unit_column() REQUIRED on every impl, no column → UnenforceablePolicy("admin_unit"), #1903); SearchMode { Optional, Required } mirroring EncryptionMode without the craig-common dep; BindValue. SearchRuntime (plan) carries the optional FieldEncryptor + mode.

  • Executor (exec, feature sqlx): execute_search::<T>(pool, &plan, projection: Option<&Projection>, limit, offset) → (Vec<T>, i64) — ONE plan feeds both the list and the count query, so they cannot drift. projection: None renders the legacy SELECT *; Some renders the validated column list (#1158 — heavy columns never fetched; T decodes the projected shape). List SQL itself renders via the sqlx-free SearchPlan::list_sql(projection).

  • Boot lineage verification (lineage, feature sqlx, #2138 — lifted from craig-cases so craig-reporting shares it): the crypto_key_lineage verify half (ADR-048 §D3). A service binds one LineageScope { registry, key_env, mode_env } and calls boot_verified_encryptor once at boot, after migrations and before the service’s supervisor, workers and listener start; load_encryptor (the mode × key-load decision) and verify_key_lineage (the (lineage row, loaded key) matrix: a matching real KCV boots only if the canary decrypts; a mismatched KCV, keyed data without a key, or a sentinel row under a key refuse; an absent row boots only if no registry-covered column holds an envelope) are the two halves. Every refusal is a BootVerifyError; the key-load and keyed-data-without-a-key refusals name the scope’s env vars in their remedy, and a key-load refusal carries only a value-free reason (KeyLoadReason), never the decoder’s detail. The crate does no logging; callers log the outcome. craig-cases' verdicts are unchanged by the lift. The write half (#2143): establish_lineage(&mut PgConnection, Option<&FieldEncryptor>, &LineageScope) runs INSIDE the caller’s transaction — INSERT … ON CONFLICT (id) DO NOTHING of the row for the loaded key (the sentinel pair when keyless), then the row that won is read back and checked with the same boot matrix — so the anchor commits or rolls back atomically with the caller’s first ciphertext (craig-reporting’s afcars_generate commit). Every refusal is a value-free LineageWriteError (Db | Crypto | Scheme | Mismatch); none carries key material or a cell.

  • Read projection (plan, #1158): Projection wraps &'static [&'static FieldSpec]; Projection::new validates ONCE (refuses empty / duplicate column names — EmptyProjection / DuplicateProjectionColumn, both 500-class), so rendering is infallible; fields() exposes the SAME slice so a consumer’s decrypt walk and SELECT share one binding (the craig-cases reports summary seam is the first instance). Column provenance is registry literals by convention — pin per instance with a subset-of-ALL test.

  • Write/decrypt walk (row): EncryptableRow + FieldRef (Text/TextRequired/Jsonb)
    the impl_encryptable_row! declarative column→field table macro (single-sibling hmac: "col" ⇒ field or the braced multi-sibling table — #1064 added the latter when persons gained a second BlindIndex pair); encrypt_row/decrypt_row walk encrypted_fields(registry) under a RowContext { table, row_id } (#1007 — EffectiveRegistry::row(id) in the service, <module>::TABLE + model.id in the seeder; RowContext::cell(column, sibling) is the ONE per-cell StorageContext derivation) and bind each cell’s storage context — for a BlindIndex base the STORED sibling — into the AEAD; a keyed Required read of a populated non-envelope cell is SearchError::PlaintextInEncryptedCell (never a passthrough; Optional keeps it); take_encrypted_fields(src, dst, registry) (#1139) moves retained pre-encryption plaintext into a stored row’s shape for a create-echo response — registry-driven, so a new field can never silently echo ciphertext (RowSlotKindMismatch on shape disagreement). A registry-encrypted column the shape does not expose is a hard RowMissingColumn/RowMissingHmacSlot (fail closed and loud, never a silent plaintext write); JSONB uses the {"v": "<ct>"} envelope (jsonb_envelope_ciphertext(&Value) is the public shape reader raw-DB verifiers consult — #1027); a BlindIndex sibling is derived from the plaintext via FieldSpec::blind_index before the base encrypts (absent base clears a stale sibling; keyless ⇒ NULL). verify_sibling_matches(row, ctx, matched, enc) (#1759) re-derives each sibling a plan matched from the decrypted base (constant-time compare) — a search consumer calls it after decrypt_row; a new entity with a BlindIndex predicate must too.

  • SearchError (thiserror): Crypto, UnsupportedFilter, UnenforceablePolicy, MissingKeyRequired, CanonMismatch, TooManyBinds, RowMissingColumn, RowSlotKindMismatch, RowMissingHmacSlot, CiphertextWithoutKey, JsonbCodec, EmptyProjection, DuplicateProjectionColumn, BlindIndexSiblingMismatch (#1759) — ADR-020’s fail-closed matrix, uniformly typed. From<SearchError> for ApiError lives in craig-common behind its search feature (UnsupportedFilter → generic 400 with no field oracle; server-side faults → redacted 500; ADR-047 layering precedent).

  • validate_registry / RegistryError — runtime well-formedness the const layer cannot cover: dangling/mistyped _hmac siblings, duplicate columns, duplicate blind-index domains (cross-column correlation), invalid domains, out-of-envelope blind-index bases (UnsupportedBlindIndexBase). Called from each registry’s registry_is_well_formed test.

craig-cases-fields (ADR-049)

The craig-cases instance of the craig-search capability model — per-entity FieldId enums
FieldSpec registries for reports, referrals, persons, cases, investigations, and the twelve P-C ledgers person_demographic_facts (#1991), child_parenting_facts, child_prior_permanency_facts, child_assistance_facts, child_sibling_facts, person_siblings (#1992), child_icwa_facts (#1993), and person_parentage_facts, child_parents and parental_rights_actions (#1994), and permanency_plans, child_review_events and contacts (#1995 — contacts registered because its visit columns take a FieldSpec, plan D8), and custody_episodes and legal_status_facts (#2342), and person_identifiers (#1806), and medicaid_applications (#1807), and person_residences (#3192), and medicaid_application_reports (#3193) (each module exposes spec(), ALL, ALL_FIELD_IDS, and a registry_is_well_formed test; resolve::DEFAULT_REGISTRY carries all twenty-four — boot verification and verify-seed walk it; the service’s EffectiveRegistries binds person_identifiers, medicaid_applications and medicaid_application_reports (encrypted entities) and carries no ledger field, since no boundary consumes an all-plaintext ledger’s registry). Every ledger table is all Plaintext and never on the scheme ALLOWLIST (scheme-frozen: its mutation trigger admits only the close and retire updates on a window ledger and only the retire update on an event ledger). contacts is all Plaintext and not on the ALLOWLIST either, but it is not a ledger and nothing freezes its scheme (a contact is updated in place). The afcars module is the cases side of the AFCARS element map: CaptureUnit (U1a … U5, Ord), AFCARS_CAPTURE_STAGE (= U5, the last unit — every owned key is due, #1995), LAST_UNIT (= U5, #2054 — the stage at which cargo xtask rules check holds the map complete), OWNED_ELEMENTS (the cases-owned dictionary keys with the unit that captures each; the (a)(1)–(a)(4) header facts are not among them — P-D’s projection supplies those), owned_after_unit(key), and AFCARS_ELEMENT_COLUMNS (Mapping::Column / DateWithIndicator / Each / Gated / Named per key — Named the (c)(1) / (c)(2) cross-table named overrides, #1994 — exactly the owned keys whose unit is at or before the stage). Since #2018 Mapping is not this crate’s: it is the shared craig_reporting_contracts::afcars_capture::Mapping, the one shape the craig-placement map (craig_placement_contracts::afcars) is written in too. tests/afcars_elements.rs holds that map to the federal dictionary (the federal layer’s federal-afcars-2020.json) and to DEFAULT_REGISTRY. No direct sqlx dependency (deps: craig-search core + craig-crypto + craig-reporting-contracts for Mapping; sqlx arrives only transitively, via craig-reporting-contracts → craig-reference) so tools/craig-seed and xtask verify-seed consume the same registries as the service. The SearchEntity search descriptors and EncryptableRow write tables deliberately live in the craig-cases service next to the DTOs/row types they bind (which pull sqlx) — this crate stays the pure capability source of truth both consult. Three BlindIndex fields are on persons: ssn_last_four (("ssn", 1, AsIs) + sibling ssn_hmac), ssn (("ssn_full", 1, AsIs) + ssn_full_hmac, #1064), and date_of_birth (("dob", 1, IsoDate) + dob_hmac, #677 — the first Date-canon index; the write walk strict-parses the slot’s ISO text so write and query hash identical %Y-%m-%d bytes); person_identifiers is the second BlindIndex entity (#1806): value (("person_identifier", 1, AsIs) + sibling value_hmac). medicaid_applications (#1807) is encrypted with no index: citizenship_status is Opaque CGEF text with no sibling digest (deliberate — an immigration status — though craig-cases otherwise encrypts identifiers only). medicaid_application_reports (#3193) is encrypted the same way: program_id, the id a partner’s program gave a child, is Opaque CGEF text with no sibling digest. Everything else is Plaintext or Opaque.

craig-reporting-fields (ADR-049)

The craig-reporting instance of the craig-search capability model (#2138, plan P-D2 U1), the counterpart of craig-cases-fields. It exposes one item, DEFAULT_REGISTRY: &[(&str, &[&FieldSpec])]: every reporting entity’s (table, registry) pair. Since P-D2 U2 (#2139) it lists the afcars_records module: three AFCARS record tables (child_records, record_removals, record_living_arrangements, each a module with TABLE and ALL) holding the 13 R11 columns, every one an Opaque TEXT envelope under CRAIG_REPORTING_FIELD_ENCRYPTION_KEY. craig-reporting’s boot lineage verifier (craig_search::lineage) scans these on its lineage-absent arm, and the write / decrypt boundaries consult them. The plaintext record columns are not here: they live in craig-reporting’s afcars::records::schema. Deps: craig-search core only — no axum, no sqlx.

craig-bootstrap (Plan Q Step 2)

Shared post-bootstrap setup helpers layered on craig_api::bootstrap(); absorbs the ~85% of service-main setup duplicated across services.

  • spawn_outbox_worker(db, publisher, service_name, shutdown) → JoinHandle<()> — drains event_outbox rows (staged by domain handlers in-tx) to RabbitMQ; watches shutdown.

  • init_object_store() → Result<Store> — loads ObjectStoreConfig + opens the Store (local FS in tests, Garage in devstack, S3 in prod).

  • build_shared_http_client(pkg_name, pkg_version) → Result<reqwest::Client> — wraps craig_common::build_shared_client() with an identifying User-Agent.

  • attach_standard_extensions<S>(router, ctx: StandardExtensionContext) → Router<S> — layers the standard axum extension stack (authz + jurisdiction + authz_ctx + service_token + actor_issuer); generic over router state. (#1186 removed the former mq_health layer — MQ health rides craig_api::AppState.mq as MqRequirement::Required so the outer-router health handlers can see it.)

  • build_authz_source(http_client, env_prefix, service_token) → Arc<dyn RulesetSource> — reads <prefix>__RULES_ENGINE_URL; picks RulesClient::with_service_token vs anonymous.

  • policy_ttl(seconds) → Duration.

  • AuthzEngine boot (craig_bootstrap::authz): AuthzBootSpec<'a> (authz_source, subscriber, service_name, jurisdiction, policy_ttl, eval_budget, require_full_coverage, shutdown, audit_sink — ADR-050, required, never defaulted — and workers — #1186 U4: the WorkerHealth registry on which the boot registers authz-invalidation
    authz-ttl-refresh as Critical workers, plus — #1228 — the authz-eval liveness sentinel (Critical) watching the dedicated !Send-eval OS thread via ZenAuthzEngine::eval_thread_ended / WorkerHealth::watch_liveness; the bounded ≤20-attempt warmup one-shot is dropped-detached by design); AuthzBootResult (engine, engine_concrete — the three join-handle fields are gone, supervision owns the tasks); boot_authz_engine(spec) → Result<AuthzBootResult> — the ~80-LOC sequence (boot → retry once → degrade to ZenAuthzEngine::boot_degraded, an empty cache over the REAL source (#786 — the former empty-InMemoryRulesetSource substitution falsely attested universal absence and never self-healed; with require_full_coverage a double fetch failure refuses to boot); enforce coverage; spawn invalidation + warmup + TTL).

craig-api

  • Ctx (ctx module, #2309): what a handler acts with, as one extractor: the service state (app), the caller (claims), the authorization engine (authz) and the deployment jurisdiction (jurisdiction). It reads what State<AppState>, Extension<Claims>, Extension<Arc<dyn AuthzEngine>> and Extension<Jurisdiction> read, from any router state that holds an AppState (FromRef), and consumes nothing of the request, so it sits before a body extractor. A router that lacks one of the three layers answers 500 as a problem document and names the missing type in the server log only. A handler takes it in one of two forms. One that hands the context to a shared core declares ctx: Ctx and passes it on (the ledger handlers). One that uses the four itself destructures them in the parameter (Ctx { app, claims, authz, jurisdiction }: Ctx), so its body reads as it did with four extractors; where those six lines would push the function or its route file over a length budget, it declares ctx: Ctx and reads the fields (ctx.claims). The services move to it one at a time (#2309). validate-authz-coverage reads both authz and ctx.authz as the engine.

  • request_claims (ADR-062 §B, #1245 — epic &77 B1a): THE transactional HTTP idempotency substrate (the response-cache middleware was DELETED in B2 #1194 — zero senders; the Idempotency-Key header is no longer honored anywhere; the orphaned idempotency_responses tables were DROPPED ×8 in BF #1270). Each service prunes its request_claims table hourly via the request-claims-retention worker (craig_mq::spawn_local_sweep, advisory lock "CRAIGRCL", 5k batches) on the deployment-global CRAIGREQUEST_CLAIMSWINDOW_DAYS horizon (default 30; 0 ⇒ registered Disabled (info log); an unparseable value also disables, with an ERROR log — never a guessed horizon; the request_claims_retention_overrun watchdog is the second indicator). Newtypes ClientRequestId / ClaimScope / EntityKind / IntentHash (grammar v1:<64 hex>, constructible only via intent_hash_v1); intent_hash_v1(scope, jurisdiction, actor, path, &intent_v1_body) hashes the versioned envelope {v, scope, jurisdiction, actor, path, body} (normalization pins in the module doc: lowercase-hyphenated UUIDs, byte-as-submitted strings, money rescale(2) in the projection ctor, None ⇒ explicit null, no default injection); claim_first(tx, &spec, entity_id) = the FIRST statement of the domain tx (one locking INSERT … ON CONFLICT DO UPDATE … RETURNING with xmax-based insert detection) → Claimed | Replay { entity_id } | 409 IDEMPOTENCY_CONFLICT (one fixed body for every mismatch class — no leak); precheck(executor, &spec) = the unlocked pre-volatile-deps fast path, never the guard; replay_entity_gone(kind) = the typed 409 for a replay whose entity vanished; ClaimedCreate<T> (#2309) = what a claim-first closure returns, Fresh(T) or Replayed(id), and ClaimedCreate::resolve(kind, load) = the entity the handler answers with: the fresh one, or on a replay the one load reads back by id, else replay_entity_gone(kind). Backing table request_claims (identical migration ×8 DB-owning services; 30 d prune horizon — knob + pruner ship in B2).

  • The actor in a claim (#2740, ADR-085 D3). intent_hash_v1 and ClaimSpec.actor take a craig_auth::Actor, and the envelope’s actor hashes as Actor::encoding(): a worker’s digest is byte-identical to the one hashed over its bare UUID before, and a service’s (service:<name>) is the same before and after the switch to the internal issuer. A claim stores its actor as the request_claims column pair created_by_sub (a worker’s UUID) / created_by_sub_service (a service’s service:<name>), exactly one set. ClaimSpec::worker_uuid() is the actor’s subject for a worker-only route, else the 403 worker_required. The former request_claims::parse_actor_sub is removed; a handler reads Claims::worker_subject().

  • D3’s pre-switch legacy comparison (#2740; deleted at the switch, ITI U17). A digest a service stored before #2740 hashed its IdP UUID sub. legacy_service_intent_hash_v1(scope, jurisdiction, uuid, path, body) recomputes that digest from Claims::legacy_service_uuid(), and claim_first_with_legacy(tx, &spec, legacy, entity_id) takes it as a LegacyServiceClaim { uuid, intent }: a stored claim that misses the spec still replays when it holds that UUID in created_by_sub, no created_by_sub_service, and the legacy digest. claim_first is the same call with no legacy shape; precheck never applies it. Of the three handlers a service token reaches, craig-exchange’s screening-run stage uses it; craig-cases' report submission compares the legacy digest itself on its received_request_id duplicate, and its report-attachment upload passes the UUID to upload_attempts (below).

  • upload_attempts (ADR-062 §U): the HTTP-side upload-attempt orchestration over craig_store::attempts. AttemptRequest.actor (#2740) is the request’s Actor, stored as the attempt’s created_by / created_by_service pair: a worker’s UUID, or a service’s service:<name>. AttemptRequest.legacy_service_uuid is Claims::legacy_service_uuid() on a route a service token reaches, else None: an existing attempt whose created_by is that UUID is probed as that claimant, so an upload a service claimed before #2740 replays (D3’s legacy comparison, deleted at the switch, ITI U17).

  • mark_replayed() (#2764, crate root): marks the current request a replay, so the ApiServer stack stamps Idempotent-Replayed: true (request_claims::IDEMPOTENT_REPLAYED, #2707) on its 2xx. The claim substrates mark their own replays; a service calls it only for a replay it resolves outside request_claims (craig-cases' report resubmission and its SSA-screening forward), on the request’s own task. Outside an ApiServer request it is a no-op. A stray call stamps a false header and games the coverage gate’s replay evidence. Its fresh-claim counterpart stays crate-private, so a service cannot clear a substrate’s mark.

  • AppState (Clone) — db: DbPool, auth: AuthLayer, mq: MqRequirement (Required(MqHealth) | NotApplicable; no Option, no Default — omission is a compile error), workers: WorkerHealth (#1186 / ADR-061).

  • Supervisor (supervisor module, #1186): install() (creates THE process shutdown token
    registers the signal-bridge), token(), expect(&[WorkerSpec]), health() → WorkerHealth (the registry handle: watch / watch_optional / watch_liveness / mark_disabled / snapshot), drain(WORKER_DRAIN_DEADLINE), check_exit(). Mains follow serve(…​).await?; supervisor.drain(..).await; supervisor.check_exit()?;. #1229: the module (with shutdown_signal and the WorkerCheckEntry wire mapper) LIVES in craig_common::supervisor so the DB/MQ-less BFF can supervise its workers; every craig_api path above is a re-export and stays valid.

  • ServerOptions { cors_origins: String, body_limit: usize } (default 2 MiB).

  • attachment_body_limit module (#974) — AttachmentBodyLimit::resolve(configured: Option<usize>, per_file_cap) → Result<_, AttachmentBodyLimitError> (unset derives per_file_cap
    MULTIPART_FRAMING_HEADROOM
    (1 MiB); an explicit value must EXCEED the cap) + .layer() → DefaultBodyLimit, the inner per-route cap the three attachment-accepting services lay on their upload `MethodRouter`s (the ADR-042 §D9 precedent, generalized).

  • ApiServer — router(state, service_routes, opts, api_doc) (CORS, compression, tracing, auth, body limit; mounts /livez + /readyz + /healthz + /metrics, optional Swagger UI at /swagger-ui under its route-scoped CSP with the online validator off, #2790); serve(router, port, shutdown: CancellationToken) with the bounded HTTP_DRAIN_DEADLINE (20s) HTTP drain and every connection write-idle bounded (#1951), delegating to the test seam serve_with_listener(listener, router, shutdown, drain_deadline); the test-util seam serve_with_write_idle_budget(listener, router, shutdown, drain_deadline, write_idle_budget) injects the budget. The router also mounts the shared POST /v1/admin/events/replay (admin_replay::routes); served_document(doc) merges its document (admin_replay::ReplayApiDoc) into the service’s, and both the served Swagger document and print_openapi_if_requested go through it, so every service built on craig-api documents the route (#2577).

  • Bootstrap helpers (bootstrap.rs, re-exported): bootstrap(prefix, service_name) → (settings, BootstrapResult { db, auth, publisher, subscriber, _telemetry, mq_health }) (used by 7 of 8 services); granular primitives connect_database / init_auth / connect_mq (for non-standard compositions; craig-intake’s integrated mode formerly used them and is now MQ-less — a connect_mq caller composing its own channels gets connection-only readiness gating until it attaches a publisher channel, #1235); shutdown_signal() (SIGTERM/SIGINT / Ctrl-C — the former shutdown_token() free-token helper is retired by #1186; use Supervisor::install()). Since #1226/#1227 the JWKS refresh loop is token-aware, and since #1236 the #1160 pool acquire-wait probe is too — both ride BootstrapResult.background (BackgroundWorkers: one shared shutdown token + named handles) to adopt_background_workers(&supervisor, br.background.take()) — registered Observed (jwks-refresh + db-pool-probe in every service’s worker set) with the supervisor’s shutdown bridged in once. Since #2826 the now-public init_mq returns MqHandles, whose PublisherChannelMonitor rides the required BackgroundWorkers::publisher_channel field and is adopted Critical as mq-publisher-channel: it reads the parent connection and the publisher channel at registration and every 100 ms, and a close with the shutdown token live kills it, so the process fails fast (ADR-061); MqHealth::publisher_channel() exposes the attached channel; OidcDiscovery::start_refresh_task carries the same token-aware contract (craig-web’s three detached refresh tasks — one OIDC discovery + two JWKS verifiers — stay detached pending its #1229 supervision story). Since #1307 (ADR-063) bootstrap() is a thin composition of the phased halves bootstrap_data_plane(prefix, service_name) → DataPlane { settings, db, _telemetry } → bootstrap_control_plane(prefix, service_name, DataPlane). The 8 stateful mains boot through bootstrap_verified(prefix, service_name, &Migrator) (M3b): data plane → verify_schema(FloorCheck::Enforce, gate hint derived from the service name) → control plane — verify-only serving boot, structurally ordered so a JWKS/MQ failure can never mask a schema refusal; BootstrapError::SchemaVerify carries the remedy-first refusal.

  • Migrate process mode (#1307, ADR-063 D2/D4, migrate_mode.rs re-exported): run_migrate_mode_if_requested(env_var, service, &Migrator) → Result<bool, MigrateModeError> — the <binary> migrate gate. Exact argv shape (migrate alone; --print-openapi together is a typed conflict; non-Unicode argv is a typed error); called BEFORE print_openapi_if_requested (it does no I/O on the not-this-mode path); logging-only telemetry (no OTLP); ONE required env (CRAIG_<SVC>DATABASE_URL); the core run_migrate_gate(url, service, &Migrator) → ApplyOutcome builds a minimal 1-connection pool (recorded deviation: DbPool::connect_with, not raw PgConnection — reuses the tested apply_by_verdict path; intent kept: no metrics, no probe) and applies by verdict. Since #1399 U1 the gate body runs connect → pre_apply (a refusal is MigrateModeError::PreApply(E) — nothing applied, hardening and post_apply skipped) → apply_by_verdict → harden → post_apply; the typed seam is ProcessHooks<E> { pre_apply, post_apply, tool, runtime_read_only } (process_hooks.rs; ProcessHooks::new(pre, post) / ProcessHooks::none()) consumed by the run_migrate_gate_with_hooks / run_migrate_mode_with_hooks / run_process_modes_with_hooks trio (MigrateModeError<E = Infallible> / ProcessModeError<E = Infallible>; the with_post_apply trio is gone) — the plain forms pass ProcessHooks::none(). ProcessHooks::with_runtime_read_only(&'static [&'static str]) (#2337) names the service’s attestation tables; the harden step revokes INSERT / UPDATE / DELETE / TRUNCATE on each from every non-owner grantee, table- and column-level (DbPool::harden_runtime_read_only, after the #1550 harden_meta_tables; a listed table that does not exist fails the gate). craig-cases and craig-placement pass gate_hooks::hooks() / gate::hooks(). The floor lint reads the argument, which must be an array literal or a same-file const passed through a .with_runtime_read_only(…) method call (ADR-063 D4, #2572). Since M3a the 8 mains call run_process_modes_if_requested(service, &Migrator, &OpenApi) → Result<bool, ProcessModeError> (craig-cases and, since #2337, craig-placement call the _with_hooks form) — the ONE home of the mode-ordering contract (migrate first, --print-openapi second) and of the CRAIG<SVC>DATABASE_URL name derivation.

  • multipart module (#462) — parse_upload_multipart(multipart, max_upload_bytes, text_fields) → Result<(UploadedFile, HashMap<String, String>), ApiError> (streaming size-cap + named text fields); UploadedFile { filename, content_type, data }. Each collected text part is capped at TEXT_PART_MAX_BYTES (8 KiB, #2632: craig-common’s shared MULTIPART_TEXT_PART_MAX_BYTES); an over-cap part is a malformed-multipart 400 naming the part and the cap, never its value. The canonical bootstrap orchestrator shape services follow is in Developer Guide § Service Initialization.

  • download::buffered_download_response(body, &range, filename, content_type) (#2177): download_response’s four-header head over a body already in memory (one frame, `Content-Length = the served length, no stream-outcome metric), for a download transformed before it is served (the AFCARS export is opened, P-D4 D2). Its strong ETag is the body’s sha256, and range selects the slice as on the streamed path (#1948).

  • download::DownloadRange (#1948): the extractor every download handler takes — a GET’s Range / If-Range (craig_common::download_range::RangeHeaders) parsed into craig_store::RangeRequest, which Store::get_stream resolves against the object’s head. Both streamed responses then answer 200, 206 (Content-Range, the slice’s length, no digest audit) or the 416 problem document, with Accept-Ranges: bytes and the strong ETag (deployment guide § Streaming downloads rollout).

  • http_observability::request_span_layers(router) (#1953): the request-span stack ApiServer installs — request_id_layer (adopt or mint X-Request-Id, echo it) outside the http_request span, which records the id as request_id, outside tower-http’s TraceLayer; every event inside the request span carries request_id.

  • download::audited_download_response(obj, filename, content_type, DeclaredDigest { service, object_key, sha256 }) (#1949): download_response’s stream with a trailing sha256 audit. The forwarded frames are hashed, and the comparison runs exactly when the body’s verdict becomes `completed (its head’s full Content-Length served): a mismatch with the declared §U digest logs one error and records metrics::download_stream::record_digest_mismatch(service) (download_digest_mismatch_total{service}). A failed or abandoned body is never compared. service is the caller’s env!("CARGO_PKG_NAME"). Used by the NCANDS export download.

  • invitation module (#1859, lifted from craig-placement’s #1848 enrollment, ADR-076 D3): one-time invitation codes. mint() → MintedCode { code, hash, prefix } draws 128 bits from the OS-seeded CSPRNG and renders them as 22 URL-safe base64 characters; hash(code) is the lowercase SHA-256 hex, the only form kept at rest; prefix_of(code) is the first PREFIX_LEN (6) characters, the operator’s handle; verify(code, stored_hash) compares the digests in constant time (subtle). Redeem::new(code) is one redemption attempt over any table whose row implements Redeemable (TABLE, id(), code_hash(), is_open_at(now); the table carries id, code_hash, redeemed_at and redeemed_by_sub). Redeem::code_hash() is the digest a request intent binds in place of the code. lock_open(executor, now) selects by digest FOR UPDATE and returns the row only if the code verifies and the row is open, so an unknown, expired, redeemed or revoked code is the same None and the caller answers one uniform 404. stamp(executor, &row, sub, now) writes the redemption under that lock. Neither a code nor its digest is logged or rendered by Debug. craig-placement’s portal enrollment is the first consumer.

craig-ledger (plan afcars-placement-capture U1a #2015, ADR-079 D1)

  • The service-neutral cores of the ADR-078 D1 ledgers, lifted out of craig-cases (#2015, behaviour-neutral) so every service that keeps a D1 ledger runs the same statements. The wire is craig-ledger-contracts; the HTTP routes, their API description and the per-ledger tables stay in the owning service. No axum, no utoipa.

  • store — the traits a service’s table type implements (in craig-cases, each ledger’s existing local marker type, e.g. PersonDemographicFacts): LedgerFilter<K> (BINDS, predicate(first), bind), implemented by the TABLE for every identity it filters or locks by (its key, its route key, a foreign list filter); LedgerTable (TABLE, Key, RouteKey, Facts, Reason: RetiredReason, KEY_COLUMNS / FACT_COLUMNS, the key and facts row codecs, fact_dates); KeyedTable (blanket: a table that filters by its own key and route key); WindowLedger (EXCL, UQ_ONE_OPEN); EventLedger (EVENT_DATE, ORDER_BY, Time: EventTime, event_time, inherit, FIRST_RECORDED defaulting to false); EventTime (require_not_after_now(field, jurisdiction); NaiveDate implements it on the jurisdiction’s business clock and, since #2018 for the removal ledger’s instants, DateTime<Utc> against the server’s current instant, the jurisdiction unused). The stored rows StoredRow<T> (alias Row<L>) and StoredEventRow<T> (alias EventRowOf<L>) deref to the wire row and convert with into_contract(); StoredEventRow::first_recorded_at() is Some only for a ledger that sets FIRST_RECORDED (the first_recorded_at column, NULL a decode error). begin_snapshot(pool) (#2040) opens a read-only REPEATABLE READ transaction: a read that serves rows a commit-time rule binds together (a removal episode and its responses, a legal-status row and its custody episode) reads them all in it, so a commit between two of its statements is wholly seen or wholly unseen.

  • store::window — the generic window store: record_change / record_backfill (an Entry), correct (a Correction), retract, close, current, read, in_force_at, row_of, and the row helpers lock_live_row / retire_row over StoredRowOf. store::event — the generic event store: record (an EventEntry), correct (an EventCorrection; the stated facts, then EventLedger::inherit from the predecessor), history, at_anchor, live_through (#2082: every live row dated on or before a cutoff, by the ledger’s order — at_anchor answers one per identity). Every closing or retiring UPDATE names its acting worker (#2016): retract, close and retire_row take an actor: Uuid, written as retired_by (a retire) or closed_by beside closed_at = now() (a close); record_change’s implicit close and both `correct`s write the entry’s `recorded_by. Every table handed to retire_row, and every EventLedger table (the decoder reads it unconditionally), carries retired_by; every WindowLedger table also carries closed_at / closed_by.

  • refusal — the table-agnostic refusals and the D1 window reads: WindowRead, require_body_dates, window_period_invalid, not_a_change, require_on_or_before_today, require_instant_not_after (#2018, the instant twin: 400 ledger-instant-after-now), require_window_ordered, overlap_or_db, row_not_found, require_fact_date_on_or_before_event (#2082: 400 ledger-fact-date-after-event). #2461: MIN_STORABLE_DATE is PostgreSQL’s minimum date, -4713-11-24. require_storable refuses an earlier date as the 400 ledger-date-before-minimum on its field, never the 500 the bind would raise, and admits the floor itself. require_on_or_before_today applies it to every body and fact date first, and WindowRead::require_storable applies it to a read’s as_of, from and to before they are bound. The event-ledger reads call require_storable on their as_of (#2902): cases' list_event and list_statuses, and placement’s trafficking list.

  • act — the claimed-act skeleton: Ctx (what a handler hands the core; craig-api’s extractor, re-exported), RoutePath, ClaimedAct, RetractAct, claim_act (the one claimed transaction), retract_with (the retraction both ledger classes share; it calls craig_api::guards::deny_pure_service first) and row_legs. ClaimedAct::run and ClaimedAct::publish both receive the act’s actor (the spec’s acting worker: the inserted row’s recorded_by, the retired row’s retired_by, the closed row’s closed_by; publish attributes the audit event to it, which craig-cases emits as user_id; #2016). The owning service keeps its route traits, act enums and handlers (craig-cases: LedgerRoute, EventRoute, Act, EventAct; craig-placement since #2018: the EpisodePath / OpenPath routes and the OpenEpisode / CorrectRemoval / RetractEpisode acts; since #2019 the RecordExit / CorrectExit / RetractExit exit acts, the HistoricalEpisode act and the ExitResponsesTable event ledger).

  • intents — the replay intent specs every ledger act claims under: Scope, LedgerScopes, EventScopes, spec_of, statement_spec, retract_spec, close_spec.

  • Tests: the moved unit tests keep their expected SQL strings; tests/core_db.rs (requires the devstack, #[ignore]) runs record → correct → history → at_anchor → retract over two scratch event tables, one with FIRST_RECORDED true (its BEFORE INSERT trigger carries the chain root’s instant onto every successor) and one without, and refuses an act on a row not live on the route.

craig-retention (#1129, ADR-058)

The audit-class archive-then-prune engine both archiving services (craig-security, craig-rules) wire their tables into. Each table’s ArchiveTableSpec names its crash-atomic unit, an ArchiveUnit (#3173), and documents each statement’s bind contract:

  • Rows: one batch. Oldest rows past the hot window → NDJSON + sha256 → no-overwrite conditional puts (data THEN manifest, fresh UUIDv7 archive_id) → ONE transaction: id-keyed DELETE (count-mismatch rolls back) + the service’s BookkeepFn closure (local ledger row + staged event) → commit.

  • Partitions: one attempt at the oldest closed day partition (closed once its end, the next day at 00:00 UTC, has left the hot window). Keyset pages on (time, id) are written as the same objects under <prefix>/<service>/<table>/<day>/<attempt>/ → a PartitionManifest (craig.partition-manifest.v1: table, day, attempt, row total, each object’s keys, digest and count) at <attempt>/partition.manifest.json → ONE transaction: BookkeepFn per object + a drop that counts the partition under a lock and drops it only on an equal count (any other count rolls back as PruneCountMismatch) → commit. An empty partition is dropped with no object. A row past the byte cap holds the partition (ArchiveError::PartitionHeld; the table is set aside for the run). Shutdown between pages abandons the attempt, leaving its objects outside the ledger. An attempt is one unit of the pass budget, never cut by it.

Bounded round-robin passes (SCHEDULED_PASS_BUDGET 120 — the scheduled tick AND each pass of the archive_run background job since #1934; the 8-batch endpoint budget went with the inline HTTP drain) under the retention-archive advisory lease (LEASE_KEY) on a detached connection; poison rows quarantine with an exclusion set that PassStates PRESERVES across passes (D13); per-table error isolation.

Public surface: ArchiveEngine::{new, run_pass}, PassStates::{open, cumulative, close}
run_passes (one pass over preserved states — the job loop), ArchiveTable/ArchiveTableSpec/ArchiveUnit/BookkeepFn, PartitionManifest/PartitionObject (with PARTITION_MANIFEST_FORMAT and PARTITION_MANIFEST_NAME), ArchiveManifest/ColumnSpec/schema_fingerprint (the self-describing sidecar: full column shape + fingerprint, [min, max] id range per D17, D9 store identity), AdvisoryLease, boot_probe (D10 write/read/delete probe + the D9 Local-backend refusal — deliberately OUTSIDE the engine so it stays testable against a tempdir store), spawn_archive_worker (takes the operator’s enabled consent explicitly, D11 defense-in-depth), and the retention_quarantined_total / retention_bookkeep_divergence_total / archive_last_success_timestamp otel instruments.

Load-bearing library defaults (#1168, audit F33): the engine’s object I/O (put_create data/manifest, purge deletes) is bounded ONLY by object_store’s client defaults — the puts are bare awaits and craig-store sets no `ClientOptions/RetryConfig. Verified against the vendored 0.13.2 source: 30 s per request + 5 s connect (client/mod.rs ClientOptions::default), 10 retries under a 180 s retry budget (client/retry.rs RetryConfig::default). These defaults are what refuted the audit’s "stalled upload delays shutdown indefinitely" — worst case an in-flight batch holds shutdown ≈ the 180 s retry budget, not forever (and the timeout-less Local backend is already refused at boot per D9). On object_store upgrades: re-verify these two Default impls; if they loosen, pin explicit ClientOptions/RetryConfig in craig-store instead of inheriting the change silently (ADR-058 § Amendment #1168).

craig-store

  • ObjectStoreConfig — CRAIG_STORE__* env. Fields: backend (Local/S3), bucket, local_root, s3_endpoint, s3_region, s3_access_key, s3_secret_key, max_upload_bytes (default 50 MiB); load(); Debug redacts credentials.

  • StoreBackend (Local | S3); Store (Clone) — from_config(config), put/get/delete/ list/health_check/max_upload_bytes.

  • StoreError (ObjectStore / NotFound / TooLarge / DisallowedContentType / InvalidFilename / Config); From<StoreError> for ApiError.

  • validate_upload(content_type, size, validation); StoredFileName (#2524, #2844), the typed stored file name: StoredFileName::parse(name) is its only producer and strips /, \, every control character (C0, DEL, C1), every Unicode General_Category = Format (Cf) character via craig_validation::is_unicode_format_char (bidi embeddings/overrides/isolates, zero-width space, ZWNJ/ZWJ, BOM, soft hyphen, Plane-14 tag chars), and the line/paragraph separators (U+2028/U+2029), trims whitespace and dots, caps at 255 bytes on a char boundary, and refuses a name left empty (InvalidFilename); NewUploadAttempt.file_name, AttemptProbe.file_name, derive_object_key and craig-api’s AttemptRequest.safe_name take it, never a String; UploadValidation { max_bytes, allowed_mime_types }; DEFAULT_ALLOWED_MIME_TYPES (12 types). Import note: use object_store::ObjectStoreExt as _.

  • attempts (ADR-062 §U, SU1 #1247) — the generation-fenced, digest-verified upload-attempt state machine: UploadAttempt/NewUploadAttempt/AttemptStatus/FailureReason; claim_attempt (row id = client_request_id; the locking upsert) + the CAS transitions mark_stored/finalize_attempt (promote-lock-first + AttemptFinalizer effects + result stamp, one tx)/supersede/fail_attempt/reopen_attempt (generation++ + key rotation); classify_replay(existing, probe) → ReplayDecision (the §U decision table, pure); store_blob_create (declared-digest gate → read-back precheck → put_create; convergent even on non-honoring backends — devstack Garage ignores If-None-Match BY DESIGN, see the garage_put_create canary) + verify_stored_blob; sha256_hex/derive_object_key ({kind_prefix}/{target_path}/{attempt_id}/g{n}/{safe_name})/rotated_object_key/ wins_pointer (the (created_at,id) replace-kind order); UploadAttemptReconciler (1 h grace / 5 min interval / batch 100 / 31 d tombstone retention; digest-verified promotion, reap+event one tx, abandoned-key sweep, terminal prune). The upload_attempts table ships per-service in SU2; consumers integrate in SU3–SU6. Since #2740 (ADR-085 D3) an attempt’s claimant is an AttemptCreator, Worker(uuid) or Service("service:<name>"), stored as the created_by / created_by_service column pair (exactly one set) and compared opaquely by classify_replay. UploadAttempt::creator() rebuilds it, creator_encoding() gives the encoding for a TEXT actor column or an event’s user_id, and worker_creator() refuses a service-claimed attempt for a kind only a worker uploads to.

#1129 (ADR-058 D9/D12): Store::put_create (PutMode::Create — typed StoreError::AlreadyExists, mapped to 409; archive objects are immutable once written), Store::delete_if_exists (NotFound → Ok(false) — the idempotent purge delete), and Store::is_local_backend (the archiver’s boot refusal probe); StoreBackend is re-exported at the crate root.

craig-reference

  • Domain enums (strum 0.27: Display/EnumString/EnumIter + serde snake_case + utoipa ToSchema): demographics (Sex; RaceCategory — the eight 45 CFR 1355.44(b)(7) categories in CFR order, american_indian_or_alaska_native / asian / black_or_african_american / native_hawaiian_or_other_pacific_islander / white / unknown / abandoned / declined, and its wire struct RaceResponses — eight bool answers keyed by those tokens, absent race is Option::None, a present value always carries all eight (#1991, replacing the five-value Race); Ethnicity — hispanic / non_hispanic / unknown / abandoned / declined (#1991; unable_to_determine deleted); YesNoUnknown — the tribal-membership answer set, reused by the ICWA ledger’s icwa_applies; the child-fact answer sets (#1992, the dictionary’s tokens): YesNo, YesNoNotApplicable (yes / no / not_applicable), YesNoAbandoned (yes / no / abandoned), SupportStatus (child_has_received_support_assistance / no_support_assistance_received) and SourceApplies (applies / does_not_apply; since #2056 also each (e)(3) ffh_type_* answer, FosterFamilyHomeType::answer_in); the ICWA answer sets (#1993, the dictionary’s tokens): InquiryMother (yes / no / the_biological_or_adoptive_mother_is_deceased), InquiryFather (yes / no / the_biological_or_adoptive_father_is_deceased), InquiryIndianCustodian (yes / no / child_does_not_have_an_indian_custodian), InquiryLegalGuardian (yes / no / child_does_not_have_a_legal_guardian) and IcwaCourtDetermination (yes_icwa_applies / no_icwa_does_not_apply / no_court_determination); the parent answer sets (#1994, the dictionary’s tokens): ParentRole (mother / father / legal_guardian / putative_parent) and ParentalRightsKind (voluntary / involuntary / not_applicable); the permanency sets (#1995): ReviewKind (periodic_review / permanency_hearing) and ContactLocation (childs_residence / other_location); MaritalStatus, Language, DobVerification (#3192, the persons.dob_verification vocabulary: how a date of birth was verified, eight tokens from birth_certificate to not_verified), MilitaryBranch); intake (ReporterType — the reporter’s STATUS axis; ReportSource — the NCANDS Child File #10 RptSrc vocabulary, 15 variants social_services_personnel(1) … anonymous_reporter(13) other(88) unknown(99), captured at intake since #648; AbuseType, Disposition — the seven NCANDS Child File outcomes, one variant per RptDisp / Mal*Lev code since #648, RelationshipToChild, RelationshipToCaregiver, MaltreaterRelationship, ChildRelationshipToCaregiver); cases (HouseholdRole, PermanencyGoal — since #1995 the per-child permanency_plans.plan, no longer a case-plan column, ClosureReason); contacts/court/placement (ContactType — admits_visit(), the ONE visit truth-table predicate (home_visit / office_visit / school_visit), CourtOrderType — hearing_kind(), the ONE type-to-ReviewKind map (review_hearing → periodic_review, permanency_hearing → permanency_hearing, else none), LicenseType, ProviderKind (#2055, the foster_homes.provider_kind set family_home | congregate_facility, a CRAIG fact with no AFCARS dictionary set), PlacementType — re-cut by #2056 to foster_family_home plus the 14 federal (e)(4) tokens verbatim (trial_home_visit became placed_at_home), setting_class() the one class table and is_caregiving() false for exactly the six non-caregiving settings; SettingClass (#2056: Family / Congregate / NonCaregiving, provider_kind() the ProviderKind a named home must have, None for non-caregiving); FosterFamilyHomeType (#2056, the six (e)(3) categories licensed_home / therapeutic_foster_family_home / shelter_care_foster_family_home / relative_foster_family_home / pre_adoptive_home / kin_foster_family_home, the wire ffh_types list); ArrangementLocation (#2080, the placements.arrangement_location vocabulary, (e)(5), four tokens), FosterParentsMaritalStatus (#2080, placements.foster_parents_marital_status, (e)(7), four tokens), FosterParentsRelationship (#2080, placements.relationship_to_foster_parents, (e)(8), three tokens), IcwaFosterCarePreference (#2080, placements.icwa_preference_met, (i)(6), six tokens: the five (i)(5) categories and placement_does_not_meet_icwa_placement_preferences); PlacementEndReason — left_care since #2019 (the arrangement ends because the agency’s responsibility ended); #2023 removed the six exit-like tokens (transfer, disruption, runaway, left_care remain), ExitReason (#2019, the exit_responses.exit_reason vocabulary, (g)(3), eight reasons and no not_applicable), TransferAgencyType (#2019, a transfer exit’s receiving agency, (g)(4)), RemovalManner — since #2018 the removal_responses.removal_manner vocabulary, a CRAIG fact with no AFCARS element, RemovalEnvironment (#2081, the removal_responses.environment vocabulary, (d)(3), seven tokens), AdoptiveMaritalStatus (#2083, the exit_responses.adoptive_marital_status vocabulary, (h)(1), five tokens), AdoptionJurisdiction (#2083, exit_responses.jurisdiction_kind, (h)(13), three tokens), IcwaAdoptivePreference (#2083, exit_responses.adoptive_icwa_preference_met, (i)(11), five tokens), ConditionStatus / ConditionHistory / SchoolEnrollment / EducationalLevel (#2084, the child_health_facts.condition_status and condition_<category> / child_education_facts.school_enrollment and educational_level vocabularies: (b)(10) four tokens / three / (b)(11) six / (b)(12) seventeen), PlacementStatus — planned / active / ended / cancelled (#2018) / retracted (#2020), strum::VariantNames); exchange (ExchangeDirection, IcpcDirection, IcpcRequestType, TransactionOrigin — #1818, where an exchange_transactions row came from: manual / trigger / collection (#3188), the column CHECK’s three tokens and the transactions list’s ?origin= filter); financial (PaymentType, RateClass (#2056, plan D5 — the rate family a caregiving arrangement bills under: foster_care / kinship / therapeutic / pre_adoptive / group_home / residential / supervised_independent_living, the seven pre-U3 placement payment-type tokens, so no stored rate or payment re-keys; craig-financial derives it from the setting and its (e)(3) flags under the bundle’s RateClassPolicySpec), SubsidyProgram — 7 GA 22.8 kinship programs incl. closed cohorts, const fn open_for_enrollment; SubsidyAgreementStatus — 6-state ADR-052 interval vocabulary; plus the SUBSIDY_*_REASON_CODES consts + subsidy_reason_codes(status) service-validated vocabularies, #1067; SubsidyProgramFamily + const fn program_family(program) — the #1071/ADR-057 D8 family taxonomy {err} / {sg, nrsg, ersg, enrsg} / {rcs, ercs} with .programs() per family and the canonical SubsidyProgramFamily::ALL order every inter-family lock taker shares, so create-vs-import stays deadlock-free by construction). PartnerType was deleted at Plan T3.3 (partner_type is an open snake_case token validated by PartnerTypeRegistry membership).

  • fips module — State enum (50 + DC + 5 territories, USPS abbreviation); AdminUnit { name, fips_code, state, unit_type }; admin_units_for_state(state); State::fips_code(). The counties tables (3,235 county-equivalents, 2020 Census vintage) were ported ONCE from canopy-reference and are hand-maintained — no in-tree generator (#765 records the decision); the #781 fips.rs pins (summed national total, per-state spot checks, STATES coverage) catch an added or dropped row, and review catches the rest.

  • translate module — admin_unit_to_fips / full_fips_code (the *_str_to_ncands NCANDS short-code wrappers were retired by #1766; the five AFCARS string wrappers were DELETED by #1968 — zero callers; the AFCARS 2020 element vocabulary is the federal ruleset, the federal layer from P-A U1 — plan afcars-federal-ruleset).

  • shines module — the standalone SHINES conformer’s PLACEHOLDER RefVal crosswalks (ADR-042; the authoritative code tables are #692’s go-live dependency): reporter_type_to_shines_rep_type / report_source_to_shines_source (#648 — total over ReportSource, unique, pinned; each placeholder value is the NCANDS codebook label, e.g. "Education Personnel") / bool_to_shines_yn / opt_bool_to_shines_yn / gender_to_shines_code(&str) → Option<&'static str> (a Gender-table value → F / M / U; U a #692 placeholder) / code_table_placeholder_id(ShinesCodeTable, &str) → Option<u16> (the value’s 1-based DFCS list position, a #692 placeholder; None outside the table) — #2097. The per-enum crosswalks race_to_shines_id / RACE_ID_OTHER_OR_UNKNOWN / marital_status_to_shines_id / language_to_shines_id / sex_to_shines_code were REMOVED by #2101: the SHINES per-person values are SHINES pick-list values, mapped by the two functions above.

  • shines_codes module (#2097, ADR-042 § Amendment 2026-09-29) — the eleven SHINES portal pick-lists as committed const tables, pinned by a parity test to the DFCS CSV at crates/craig-reference/data/shines/field-dropdowns.csv: ShinesCodeTable (AllegedMaltreatorRelationship, RelationshipCollateral, RelationshipPrincipal, ReporterType, Gender, State, County, MaritalStatus, Language, Race, Ethnicity) with entries() → &'static [CodeEntry], get(&str) → Option<&'static CodeEntry> (exact wire value), csv_header(), is_coded(); CodeEntry { code, label, display }. The three relationship lists send their 2-letter code; the rest send the label. A value is meaningful only with its table (codes repeat across tables).

  • caretaker_relationship module (#1714) — the two "Relationship to Primary Caregiver" lists as typed enums, PrincipalRelationshipToCaretaker (75 codes) and CollateralRelationshipToCaretaker (99), each with code(), label() and an exact from_code(&str), pinned by tests to their ShinesCodeTable by code and label in DFCS order. RelationshipToCaretaker is Principal(..) or Collateral(..): from_code(PersonDesignation, &str) parses from the list the designation selects and refuses a code only the other list carries (22 codes are Principal-only, 46 Collateral-only, and "Step-Child" is SR on one and SV on the other); table_for(designation), code(), designation(). The wire value stays the code. craig-intake’s SHINES entry rules and mapper both read a person entry’s rel_to_primary_caretaker through it, the designation (else the household flag) choosing the list.

  • federal_partner_category (Plan T1.4) — FederalPartnerCategory 9-variant federal-closed enum (tanf ccwis afcars ncands iv_e icpc medicaid education_slds child_support); consumed by StateBundle::federal_mapping() + FederalPartnerMappingRegistry; no sqlx::Type.

  • ncands module — the literal NCANDS sex/race/ethnicity/abuse/report-source/disposition codes. The AFCARS dictionary (the sex / ethnicity / permanency / placement / discharge element codes) lives in the federal layer from P-A U1 — craig_reference::afcars, the pre-2020 numeric codes, was DELETED by #1968 (plan afcars-federal-ruleset). The ncands module carries the literal NCANDS Child File codes (report_source_to_rptsrc / disposition_to_rptdisp / abuse_type_to_chmal / sex_to_chsex / ethnicity_to_ncands / race_to_ncands, numeric, codebook rev 2025-09-12 — race_to_ncands(&RaceResponses) sets ChRacUD when unknown, abandoned or declined is true and each named flag from its answer; ethnicity_to_ncands folds unknown / abandoned / declined into the unable-to-determine code 3 — federal-wire-ready, returning None where CRAIG has no faithful code per ADR-040; added #644 — disposition_to_rptdisp is TOTAL since #648, u8 bijective onto 1..=7, serving #11 and #27/29/31/33; report_source_to_rptsrc(ReportSource) → u8 is TOTAL and injective onto {1..=13, 88, 99}, serving #10 — it REPLACED reporter_type_to_rptsrc, which was None for every mandated / professional reporter because the reporter STATUS does not determine the source; validate_report_source joins the validators). The CRAIG-internal *_to_ncands / *_from_ncands short mnemonics and their translate::*_str_to_ncands wrappers are gone (disposition by #648, reporter type and abuse type by #1766: none had a production caller). Since #1630 the TOTAL abuse_type_to_chmal also maps sex_trafficking → 7, labor_trafficking → 8 (Other) and sexual_exploitation → 4 — sharing SexualAbuse’s slot: the Child File de-duplicates by CODE, so a victim alleging both folds into one ChMal-4 slot. `validation module — validate_enum<T> + 29 specific validators (validate_race deleted by #1991), all returning the typed ReferenceValidationError (InvalidEnum { field, reason } / UnknownState { abbr } / UnknownAdminUnit { name, state }; Display reproduces the historical prose byte-for-byte, so handlers wrap .to_string() into the RFC 7807 detail unchanged — #839).

craig-alloc (#3149, #3150)

  • The process allocator of the long-running binaries. On a musl target it declares mimalloc as the global allocator; on any other target it declares nothing, so a host build keeps the system allocator.

  • A binary opts in with use craig_alloc as _; in its main.rs. The twelve service and BFF binaries do. The CLI, craig-manage, craig-seed, the mock server and craig-config-fetch do not: a short-lived tool gains nothing.

  • xtask links it too (#3191). Its scans parse the whole tree on every core, and the battery builds its tests for musl: on musl’s malloc one test that re-measures every scan took about 95 seconds in a car, and the suite about four times as long as with mimalloc. The car’s gate steps run a host-built xtask and were never affected. the_musl_test_binary_carries_the_workspace_allocator (xtask, musl only) pins the link.

  • Why not musl’s own: the shipped binaries are static musl, and musl’s malloc serialises allocation across threads.

  • Why mimalloc: it is the allocator main was running when the trial on real train cars closed (#3150, 2026-11-29), and nothing had regressed under it. The trial did not show it to be the better allocator. jemalloc (tikv-jemallocator) ran from 2026-11-22 and mimalloc from 2026-11-25; over 131 full cars the stage times did not separate them for the services. Medians of the 34 mimalloc cars against the 43 jemalloc cars before them: whole car 2,719 s against 2,742 s, dev start 773 against 797, integration 612 against 602, e2e 552 against 561, each inside the other’s range. jemalloc’s first 25 cars were within 11 s of musl’s malloc on every stage. No merged change’s train car failed in its car job under mimalloc. The readings and how they were taken are on #3150.

  • The one place an allocator moved a car was xtask’s test binary (#3191, above), and that was measured against musl’s malloc only.

  • The devstack measurement that preceded the trial (#3121) ran unoptimized builds on a lightly loaded shared host, so it is weak evidence: there jemalloc and mimalloc were within a few percent of each other on CPU and latency, both ahead of musl’s malloc; mimalloc used the most resident memory, roughly double musl’s, and had one stalled run that was not investigated. Building for glibc instead was not measured: it would give up the static binaries.

  • Alternatives compared (#3121): musl’s malloc (the baseline), tikv-jemallocator and mimalloc.

  • Cost: the build compiles mimalloc’s C sources, as it compiled jemalloc’s. The crate’s own test (the_musl_test_binary_carries_mimalloc, musl only) shows mimalloc is linked into a binary that declares it; it does not show every allocation reaches it.

  • Not measured: the services under load with each allocator (the cars are dominated by builds and test orchestration, and the CI perf jobs were not comparable across the two periods, because the seed size changed inside the mimalloc period, #3170); resident memory beyond the #3121 reading; memory behaviour over days (no soak has run).

  • Deps: mimalloc (musl only).

craig-zen-eval (#2312)

  • The one dedicated zen-engine evaluation thread. zen’s evaluate future is !Send, so each process that evaluates a decision owns an OS thread with a current-thread tokio runtime behind a 256-slot channel; evaluation is strictly serial. Three consumers spawn one each: craig-authz (authz-eval, in every service), craig-financial’s administrative-authority surface (authority-eval) and the craig-rules service (zen-eval). A leaf crate (zen-engine, tokio, serde_json; no craig crate).

  • EvalHandle<D>::spawn(EvalThreadSpec<D>, wedge_threshold) builds the thread and returns only after its warm-up evaluation answered, so no request’s budget pays for the cold start; a failed or panicked warm-up is EvalSpawnError::WarmUp. EvalThreadSpec names the thread, the deadman’s operator hint, the depth ceiling every evaluation runs under, the watchdog’s sample period, and an optional late channel.

  • EvalHandle::evaluate(decision, input, budget, diag) puts the send, the queue wait and the evaluation under one budget. EvalError is Timeout { budget_ms, dispatched }, WorkerUnavailable, Engine (zen’s text) or Output (a result that does not serialise, or a top-level null). D is the caller’s diagnostic: craig-authz and the authority surface pass the ruleset name, craig-rules the evaluation id.

  • LateResult<D>: a success whose caller’s budget had already elapsed goes to the spec’s late channel with its diagnostic (craig-rules converges the attempt’s timeout row to late_completed from it); a late failure, and any late result on a thread with no channel, is dropped. A request whose caller has gone before it is reached is skipped without evaluation.

  • deadman: the wedge watchdog. The loop stamps its one in-flight evaluation for exactly the zen future; when one runs past wedge_threshold(budget) (max(10 × budget, 60 s)) the watch flips, and EvalHandle::ended() resolves on that or on the thread’s death, which is the future each consumer registers as a Critical worker.

  • apply_function_timeout(ms) publishes the JS function-node bound into zen’s process-global configuration; one process has one owner of it.

  • The test-util feature (test-only) adds EvalHandle::detached() and test_support::zen_interrupt_ms.

craig-validation (#486)

  • Canonical DTO field-length cap constants shared across the contracts crates so every #[garde(length(max = …))] references a named cap: NAME_MAX, PHONE_MAX, IDENTIFIER_MAX, IDENTIFIER_LONG_MAX, CODE_MAX, ENUM_STRING_MAX, SHORT_TEXT_MAX, DESCRIPTION_MAX, REASON_MAX, NARRATIVE_MAX, NARRATIVE_ENCRYPTED_MAX, NAME_ENCRYPTED_MAX, SSN_LAST_FOUR_MAX.

  • FieldError — the wire shape for a field-level validation error.

  • Sha256Hex (epic &65 / #940) — a construction-validated lowercase-hex SHA-256 digest newtype (exactly 64 hex chars; (de)serializes as a bare JSON string via serde try_from/into), plus the MAX_ATTACHMENTS count const (5). Backend-agnostic so the IntakeSink seam and the SHINES signed-attachment manifest (ADR-042 §D9) share one type without the trait referencing a backend.

  • MAX_REPORT_CHILDREN (#1696) — the fleet-wide children-list count cap (10): the intake edge (validate_children_array, typed 400 batch-too-large), the three SDK ReportBuilder`s and the craig-cases create boundary (through the `craig_cases_contracts::reports re-export; typed 422 screening-report-too-large) share it, so the screening act’s per-child window is one hop by construction. Pinned across languages by sdks/test-vectors/report-limits.json.

  • required_nullable (2080) — deserialize_with for an Option<T> field WITHOUT [serde(default)]: the key must be present (null = unanswered), a missing key is serde’s missing field error, also through [serde(flatten)]; pair it with [schema(required = true, nullable)].

  • bounded_page_limit(limit, max) (#2119) — a paged export query’s effective limit: max when absent, the value inside 1..=max, None outside it (the handler’s typed 400 naming limit). The NCANDS and AFCARS export queries' page_limit both call it.

  • contains_nul(value) + NUL_REFUSAL (#2830) — whether a string holds a NUL (U+0000), which Postgres stores in neither TEXT (SQLSTATE 22021) nor jsonb (22P05). JSON_NUL_REFUSAL (#2854) is the JSON documents' text, NUL_REFUSAL plus " in any string or key".

  • The NUL walk and its garde bindings (#2854), behind two optional features, both off by default so the default dependency set stays serde + utoipa: json (adds serde_json) gives json_has_nul(&Value), an iterative walk of every string leaf and object key; garde (adds garde) gives validate_no_nul (a required String) and validate_option_no_nul (an Option<String>, also bound as inner(custom(…​)) on a keep / clear / set field), refusing with NUL_REFUSAL. A JSON field’s NUL refusal is part of its size bound (json_bounds, below), which refuses with JSON_NUL_REFUSAL. Every contracts crate and service that binds a NUL refusal binds these (each crate-local text_guards.rs re-exports them under the same names, and names the features it uses in its own Cargo.toml), so a NUL in a stored free-text field or a SELECT-bound filter is the house 422 naming the field instead of a redacted 500.

  • json_bounds (2633), behind json: the size bound of a request field that is free-form JSON. JsonBounds { depth, nodes, string_bytes } states the most containers on the path to a value, the most values in the document, and the most UTF-8 bytes in one string value or object key. json_excess(&Value, &JsonBounds) is one iterative walk that returns the first limit exceeded (JsonExcess::{Depth, Nodes, StringBytes, Nul}) and stops there. With garde, json_within(&BOUNDS) and json_option_within(&BOUNDS) bind it as [garde(custom(json_within(&RECORD_JSON)))]; the refusal is the house 422 naming the field and the limit, never the value. Seven named bounds, one per class of field. RULE_SET_JSON is at least four times the deepest, largest and longest-stringed shipped rule set, measured directly; the others rest on the byte lengths of a seeded development stack’s documents and on judgment (their depth was not measured, and no exchange payload at all):

    Constant depth nodes string bytes For

    RULE_SET_JSON

    32

    50,000

    65,536

    a rule set’s decision graph

    RULE_INPUT_JSON

    16

    5,000

    16,384

    one evaluation’s input

    RECORD_JSON

    16

    2,000

    16,384

    a document stored on a record as sent

    BATCH_JSON

    32

    100,000

    65,536

    a batch of records sent to an exchange partner

    SUBMISSION_NARRATIVE_JSON

    16

    5,000

    32,768

    an intake submission’s free-form narrative, at the edge

    SUBMISSION_JSON

    32

    10,000

    32,768

    a whole intake submission as craig-cases stores it

    CREDENTIAL_JSON

    4

    32

    1,024

    a JWK or a partner credential’s reference names

  • is_lowercase_token(value) (#2854) — the lowercase identifier token ^[a-z0-9][a-z0-9_.-]*$ (non-empty, no cap): craig-exchange’s identifier fields (is_identifier_token, #2824 / #2831), craig-placement’s home document_type and craig-cases' contact attachment_type (#2835 / #2838), each with its own byte cap beside it.

  • is_unicode_format_char(c: char) → bool (#2831) — const predicate returning true iff c has Unicode General_Category = Format (Cf, Unicode 17.0: the joiners ZWNJ/ZWJ U+200C/U+200D, which UTS #39 marks Identifier_Status=Restricted since Unicode 15.0, BiDi controls, BOM, and Plane-14 tag characters U+E0001 / U+E0020..=U+E007F), with zero runtime dependencies and an exhaustive '\0'..=char::MAX test against unicode-properties.

  • The storable/display escapes and the byte cap (#2864), default features, for a value the caller must keep rather than refuse (craig-security’s audit consumer, craig-mq’s inbox bookkeeping): escape_nul(&str) → Cow<str> writes each NUL as the literal text \u{0000} (Postgres stores a NUL in neither TEXT nor jsonb); escape_display(&str) → Cow<str> also writes each is_unicode_format_char character as \u{XXXX} (upper-case hex, four to six digits), the form for a column an operator UI shows. Both return a clean input borrowed; neither is injective (a literal \u{202E} reads like an escaped U+202E); other control and separator characters (newline, CR, ESC, U+0085, U+2028 / U+2029) pass through. cap_bytes(input, escape, max) → Cow<str> is one pass over the raw characters: each becomes a piece (itself or its escape under escape), whole pieces are kept while the running length stays within max, and anything left out becomes the suffix …[truncated N bytes] (N = the escaped length minus the kept prefix); an input whose escape fits is returned as exactly escape(input). Proptests pin the no-escapable-character, length, prefix, exact-N and no-panic properties.

craig-matching (ADR-019)

  • Pure-Rust signal computation for the report-person linking pipeline (Layer 1 of ADR-019; no DB/HTTP).

  • JsonbEntry { first_name, last_name, date_of_birth: Option<NaiveDate>, dob_approximate, sex }; PersonRecord { id, first_name, last_name, date_of_birth, sex }.

  • SignalSet { name_exact, name_similarity_score, dob_exact, dob_within_30, dob_year_match, sex_match, phone_match, name_similarity_algorithm }.

  • compute_signals(entry, candidate, &dyn NameSimilarity) → SignalSet (pure).

  • NameSimilarity trait (score(a, b) → f32 in [0,1] + algorithm_name()); TrigramJaccard impl (strsim-backed). v1: phone_match is hardcoded false (no phone column yet).

craig-ledger-contracts (plan afcars-placement-capture U1a #2015, ADR-079 D1)

  • The service-neutral wire of the ADR-078 D1 ledgers, moved verbatim (docs, derives, field order, serde / utoipa / garde attributes) out of craig-cases-contracts' ledger module (#2015; no wire change). The owning service supplies a ledger’s identity key K, its facts F and its closed retired-reason set R; the types here fix everything else. Field caps reference craig-validation.

  • RetiredReason — a ledger’s closed retirement-reason set: the two tokens the shared acts write, CORRECTED (a correction supersedes the row) and RETRACTED (entered in error), plus as_str / from_token; an owning service may add its own reasons.

  • The window-ledger wire: the act bodies LedgerRecordRequest<F> (client_request_id, the window, the facts flattened), LedgerCorrectRequest<F> (the bounds optional), LedgerRetractRequest (note, refusing a NUL at validate() since #2837) and LedgerCloseRequest (effective_until); the reads LedgerAsOfQuery and LedgerPeriodQuery { from, to }; the row LedgerRow<K, F, R> (key and facts flattened beside the window and the provenance, retired_reason: Option<R>). Since #2016 each actor sits beside its instant: … recorded_at, recorded_by, supersedes_id, closed_at, closed_by, retired_at, retired_by, retired_reason, retired_note (closed_at: Option<DateTime<Utc>>, closed_by / retired_by: Option<Uuid>; closed_* is null on an open row and on a row born with its end).

  • The event-ledger wire: EventStatementRequest<F> (the record AND the correction body), EventAsOfQuery (concrete as_of: Option<NaiveDate> — utoipa’s IntoParams derive cannot take a generic field) and the row EventRow<K, F, R> (no window; since #2016 retired_by: Option<Uuid> sits between retired_at and retired_reason). EventThroughQuery (#2082, the every-row read’s query).

  • No storage: the crate never depends on sqlx, craig-db, craig-mq or craig-api — tests/architecture_invariants.rs pins the manifest (the craig-portal include_str! precedent). Its src is on the xtask DTO-length lint’s policy paths.

craig-cases-contracts

  • The shared request/response + event DTO types for craig-cases, used by the service, the BFF, the CLI, and the test-lib clients (so the wire shapes stay single-sourced). Field caps reference craig-validation; errors map to ApiError.

  • ledger (#1992; the shared wire lifted to craig-ledger-contracts in #2015) — the route keys PersonKey { person_id }, CaseChildKey { case_id, person_id } and SiblingKey { person_a, person_b } (SiblingKey::of(one, other) orders the pair, None for a self-pair); the parent keys (#1994) ChildParentKey { person_id, parent_person_id } and CaseChildParentKey { case_id, person_id, parent_person_id }; LedgerRetiredReason (corrected / retracted / order_corrected / order_deleted), which implements craig_ledger_contracts::RetiredReason. The row aliases LedgerRow<K, F> = craig_ledger_contracts::LedgerRow<K, F, LedgerRetiredReason> and EventRow<K, F> = craig_ledger_contracts::EventRow<K, F, LedgerRetiredReason>, and a re-export of the act bodies and reads (LedgerRecordRequest<F>, LedgerCorrectRequest<F>, LedgerRetractRequest, LedgerCloseRequest, LedgerAsOfQuery, LedgerPeriodQuery, EventStatementRequest<F>, EventAsOfQuery), so every craig_cases_contracts::ledger path stays valid. The event-ledger list read (#1994): EventAsOfQuery absent = the history; as_of = one row per stored identity, the latest with its event date on or before it.

  • demographics (#1991) — DemographicsFacts (the five facts, null = unanswered) and the aliases RecordDemographicsRequest / CorrectDemographicsRequest / DemographicsRow over the ledger generics. persons::RefusedKey keeps race / ethnicity / tribal_affiliation on the person create / update bodies ONLY to refuse them (typed 400 demographics-via-ledger); it is never serialized and has no schema presence.

  • child_facts (#1992) — the five child-fact ledgers' facts ParentingFacts, PriorPermanencyFacts, AssistanceFacts (+ receives()), SiblingCountFacts and IcwaFacts (#1993), each with a garde validator that refuses its within-element gate as a 422 (the DB CHECK is the belt) — IcwaFacts’ gates are one-way (a dependent only under its enabling gate token, `tribe_notified ungated, a gate alone admitted — except an order of preference yes, which needs its date (present_iff, #2004); the timely tribe notice’s yes needs tribe_notified = yes) — and the row aliases ParentingFactsRow / PriorPermanencyFactsRow / AssistanceFactsRow / SiblingCountFactsRow / IcwaFactsRow.

  • siblings (#1992) — the sibling ledger wire: NoFacts {} (the link has no domain columns), RecordSiblingRequest { client_request_id, sibling_person_id, effective_from, effective_until }, CorrectSiblingRequest (the bounds only — the pair is the identity) and SiblingRow.

  • parentage (#1994) — ParentageFacts { parents_abandoned: bool (required), sole_legal_parent: Option<bool> (None = not assessed) } and ParentageRow.

  • child_parents (#1994) — ChildParentFacts { role: ParentRole, legal_responsibility: Option<bool> } (garde: never Some(true) for a putative parent), RecordChildParentRequest { client_request_id, parent_person_id, effective_from, effective_until, facts flattened }, CorrectChildParentRequest { parent_person_id, statement: LedgerCorrectRequest<_> flattened } (the body names the row’s parent — the pair is the identity) and ChildParentRow.

  • parental_rights (#1994) — ParentalRightsFacts (effective_on, kind, the petition, death and termination dates, parent_deceased, court_order_id and the six 2028 ICWA findings, each D5 CHECK a garde twin; effective_on_resolved() — the stated date, else the earliest component date — is what the store writes and the gates read), ParentalRightsStatement { parent_person_id, statement: EventStatementRequest<ParentalRightsFacts> flattened } (record AND correct) and ParentalRightsRow = EventRow<CaseChildParentKey, ParentalRightsFacts>.

  • permanency (#1995) — PermanencyPlanFacts { plan: PermanencyGoal, established_on: Option<NaiveDate> } (the date required on a new plan, kept by a correction that omits it), PermanencyPlanStatement = EventStatementRequest<PermanencyPlanFacts> and PermanencyPlanRow = EventRow<CaseChildKey, _>.

  • reviews (1995) — ReviewEventFacts { kind: ReviewKind, held_on: Option<NaiveDate>, court_order_id: Option<Uuid> } (court_order_id is [schema(read_only)] and garde-refused on a request: provenance only the court-order act writes, served on every row), ReviewEventStatement and ReviewEventRow.

  • court_orders / contacts / case_plans (#1995) — CourtOrderHearing { held_on, children } (garde: 1..=HEARING_CHILDREN_MAX (25) children, each once) as hearing: Option<_> on the create and update bodies; ContactVisit { visited_child_id, location: ContactLocation } as the create’s visit: Option<_> and the update’s visit: Option<Option<_>> (double_option: omitted = unchanged, null = clear); the case-plan create / update bodies no longer carry permanency_goal.

  • outbound_principals (#1827, ADR-075; #2343; #3193) — the service-only projection’s wire: OutboundStageKind (case / investigation / custody_episode / medicaid_application), OutboundStage (+ custody: Option<OutboundCustody> on a custody stage and on a Medicaid-application stage, where it is the episode the application was submitted on: the instants, retracted and the served OutboundCustodyRow`s; + `application: Option<OutboundApplication> on a Medicaid-application stage: the day it was submitted, the citizenship status, prior medical assistance and the legal administrative unit, its Debug printing neither of the middle two), OutboundPrincipal (+ gtid: Option<OutboundGtid>: custody arms only, decrypted per response, never stored by exchange; + identifier: Option<OutboundIdentifier>: Medicaid-application arms only, the child’s live identifier under its kind, decrypted per response; the Debug of each never prints the value), OutboundReadQuery (+ identifier, the GTID row a custody read serves), GTID_KIND, and the id pages OutboundStagesPage, ReportOutboundStages, PersonOutboundStages; custody, application, gtid and identifier are omitted when absent, so the case and investigation arms answer unchanged bytes.

  • custody (#2342, plan custody-episodes-doe-slds D2–D3, ADR-081) — the legal-status and custody-episode wire: the requests LegalStatusRecordRequest (optional until: LegalStatusUntil) and LegalStatusCorrectRequest, the query CustodyEpisodesQuery, the responses CustodyActResponse and CustodyEpisode over LegalStatusFacts, the closed vocabularies StoredCustodyClass, CustodyEpisodeRetiredReason, CustodyEvent and CustodyAct, and the ids-only CustodyEventPayload staged under the five CASE_CUSTODY_* / CASE_LEGAL_STATUS_CHANGED routing keys.

  • person_identifiers (#1806, plan custody-episodes-doe-slds D5) — the external person-identifier wire: the requests PersonIdentifierRecordRequest and PersonIdentifierEndRequest, the masked row PersonIdentifier and the audited full-value PersonIdentifierReveal, the closed vocabularies IdentifierProvenance, IdentifierRetiredReason and PersonIdentifierAct, and the ids-only PersonIdentifierEventPayload staged under case.person_identifier_recorded / case.person_identifier_ended.

  • medicaid_application_reports (#3193) — what a medical-assistance agency said about a referred application: the service-only write’s body MedicaidPartnerReport (tagged kind: a receipt naming the application by id, an outcome naming a person by identifier and the application by the receipt’s reference; strict; each text 1 to 64 printable ASCII bytes, is_report_text; its Debug prints nothing the partner stated), the answer MedicaidPartnerReportAnswer over MedicaidPartnerReportOutcome (applied / replayed / unknown / withdrawn), the stored report as a reader sees it, MedicaidApplicationReport (its Debug never prints the program id), the closed vocabularies MedicaidReportKind and MedicaidReferralStatus, the path MEDICAID_PARTNER_REPORTS_PATH, and the strict ids-only MedicaidApplicationReportReceivedPayload under case.medicaid_application_report_received.

  • medicaid_applications (#1807, plan partner-auth-medicaid-application D7) — the Initial Medicaid Application’s wire: MedicaidApplicationSubmitRequest (deny_unknown_fields; the tokens as strings, parsed by the act so a refusal never echoes them), the answer row MedicaidApplication (the decrypted CitizenshipStatus, and since #3193 its reports, the partner’s reports in stored order), the closed vocabularies CitizenshipStatus / PriorMedicalAssistance / MedicaidApplicationRetiredReason (as_str / from_token, exact match), the list query MedicaidApplicationListQuery (child_id), and the strict ids-only MedicaidApplicationEventPayload under case.medicaid_application_submitted / _retracted (MedicaidApplicationAct::routing_key); never a citizenship status on an event.

  • events (#1313 U4) — cross-service event contracts published by craig-cases, the craig-placement-contracts pattern: ELIGIBILITY_EVALUATED + the STRICT EligibilityEvaluatedPayload (deny_unknown_fields, no defaults on the money fields — financial prices federal money from it, so absent/misnamed money fields fail deserialization into counted-attempt/DLX). Per-child ALWAYS (child_id required, the hard-checks F0 ruling); determination_revision is the U5 ordering key; ffp_rate is Decimal-as-string (#774); user_id (#2323) is the act’s effective actor, the one defaulted field. craig-cases stages one per child in the IV-E determination act’s transaction (U6). U5 adds CASE_IVE_DETERMINATION_INVALIDATED + the STRICT IveDeterminationInvalidatedPayload (case_id + determination_revision — the pair financial’s invalidation SET converges on); craig-cases stages it from its exchange.screening_run_invalidated consumer (U5b). #1995 adds CASE_PERMANENCY_PLAN_ESTABLISHED + the STRICT PermanencyPlanEstablishedPayload (event_id, person_id, case_id, action: PermanencyPlanAction — established / corrected / retracted — plan, established_on, supersedes_id, act_id, act_at, current: Option<PermanencyPlanCurrent { event_id, plan, established_on }>); consumers apply the latest per (person_id, case_id) by (act_at, act_id). #2304 adds CASE_CREATED + CaseCreatedPayload (case_id, case_number, admin_unit, assigned_worker, supervisor, user_id) and CASE_ASSIGNMENT_CHANGED + CaseAssignmentChangedPayload (case_id, the old and new worker / supervisor pair, assignment_revision, admin_unit, user_id). craig-cases stages them and financial, placement and exchange decode them, replacing three hand-parsers. The #1084 supervisor keys are required keys with nullable values, assignment_revision (#1214) is required, admin_unit (#1901) decodes any non-string as None, and user_id (#2248) is defaulted; unknown keys are ignored. Golden-JSON tests pin both wire shapes.

  • SsnDigest (1430, plan Plan::SSA SD12) — the versioned SSN blind-index digest newtype. Canonical wire form is one string v{version}:{44-char base64} (serde try_from/into String; the version is the per-field blind-index rotation version, stamped by the producing boundary). PartialEq IS the constant-time compare (subtle::ct_eq over the full canonical bytes; no Hash/Ord); Debug redacts the digest (version only) and there is deliberately no Display; SsnDigestError is categorical (never echoes input). Wire-only in A4 — no sqlx::Type (B1 decides the column shape); no ToSchema (consuming DTO fields annotate [schema(value_type = String)] + #[garde(skip)], the Sha256Hex precedent). Its one consumer since #3175 is the human SSN attestation (the verification read and the attest); the SSA screening binds a person identifier instead.

  • craig-exchange-transport::EgressControlledTransport (#1465, plan Plan::SSA B4 / S13) — the hardened egress the typed SSA worker sends through (the generic DirectHttpTransport is untouched): https-only with a literal-loopback http dev carve-out, exact-host allowlist (empty = deny-all; EgressPolicy::from_hosts takes the comma-split settings shape), DNS resolve-vet-PIN (https-class hosts must not resolve into internal address space; the connection binds to the vetted address), redirects surfaced as BadStatus, and the 1 MiB chunked-read response byte cap (MAX_RESPONSE_BYTES — the A1-deferred cap). check_egress is the no-send pre-check the worker runs BEFORE its custody read. Every refusal is a categorical `egress: `-prefixed token — no URL, host, or body byte echoes.

  • persons::{ScreeningIdentifierReleaseRequest, ScreeningIdentifierReleaseResponse} (#3175, replacing the #1463 SSN release wire) — the screening identifier release (ADR-065): the request names the staged identifier_id, released only while that row is the person’s live identifier of the screening kind; the response’s Debug redacts the value; the correlation trio (screening_run_id/screening_member_id/requested_by) is audit attribution asserted by the allowlisted exchange service, not authentication.

  • screening_wire (#1464, plan Plan::SSA B3) — the screening request-path wire: the cases intent body (RequestCaseScreeningBody), the staging request/response (StageScreeningRunRequest/StageScreeningRunResponse, members carrying identifier_id), housed HERE (not craig-exchange-contracts, a deliberately pristine leaf) because the staging wire IS the screening cohort in motion; both services consume it. requested_by/requested_by_name are stage-time attribution asserted by the allowlisted cases service (the §D2 posture).

  • screening_cohort (#1462, plan Plan::SSA B1 / H1) — the ONE shared definition of the SSA screening cohort binding: cohort_hash(&[(person_id, identifier_id)], as_of) (sha256 hex over the domain tag craig.ssa.cohort.v2 + as-of + sorted pairs framed uuid \0 uuid \n — the ADR-057 manifest_checksum precedent; #3175 moved it from SSN digests to identifier ids), SCREENING_FRESHNESS_MONTHS (= 12, UD11 RATIFIED policy — deliberately a const, not a knob) and screening_is_fresh (stale ON the anniversary, fail-closed on calendar overflow). craig-exchange stores the hash at stage time (B3); cases-side D3 assembly recomputes it over the current household to decide whether a run’s witness is still assertable.

  • ive_surface (#2324, plan ive-determination-inputs U1) — the IV-E determination input surface: IveSurfaceResponse { rule_set_name, identity: IveRulesetIdentity { rule_set_id, revision }, inputs }, IveInputView { key, scope: IveScope (case | child), title, description, kind } and IveInputKind (boolean, enum with labelled options, integer / number with a minimum and an optional maximum, date; internally tagged and flattened into the view). project_ive_surface(name, identity, ruleset_bytes) is the one parser of a ruleset’s metadata.ive.inputs[] and its strict-subset inputNode schema (a repeated JSON key is refused); IveSurfaceError names each refusal. IVE_SERVER_KEYS is the closed registry of server-derived keys a schema may list undeclared (child_age, ssa_deprivation_evidence). Since #1719 (U2) craig-cases serves the response as GET /v1/cases/ive-surface (registered in its OpenAPI), and cargo xtask rules check runs the projection on every *-ive-eligibility ruleset (by file stem or name; mandatory) and on any other ruleset carrying metadata.ive.

  • safety_surface (#3104): project_safety_surface(name, identity, ruleset_bytes, server_keys) is the one parser of a ruleset’s metadata.safety.attestable_facts[] and its closed inputNode schema, whose required must list every property; SafetySurfaceError names each refusal. SafetySurfaceResponse (rule_set_name, identity, facts[], each fact a key, title, description and a boolean or bounded integer kind) is what craig-cases serves as GET /v1/cases/safety-surface. SAFETY_SERVER_KEYS is the (empty) registry of server-derived keys. declared_surface holds the parts this projection shares with the IV-E one (the duplicate-rejecting JSON reader, the schema-string read, the property kinds and the text caps).

  • investigations (#3104): SubmitSafetyAssessmentRequest is closed (deny_unknown_fields) and carries client_request_id, surface (the identity the answers were given against), facts, worker_override and worker_override_reason, which is required and non-blank with an override. SafetyFacts is a map of fact keys to SafetyFactValue (a boolean or a u32 count); a string, fraction, negative number, null or object value is refused at deserialisation. SafetyFacts and the screening AttestedFacts are transparent newtypes over one hand-deserialised reports::FactMap, which refuses a repeated key and the 33rd entry.

craig-rules-contracts (#305)

  • The shared request DTOs for the craig-rules HTTP boundary — rule_sets::{CreateRuleSetRequest, UpdateRuleSetRequest, ImportRuleSetRequest}, evaluation::EvaluateRequest, and lifecycle::{PromotePreviewRequest, PromoteExecuteRequest, RollbackRuleSetRequest} — used by the service and the test-lib RulesClient so the request wire shapes stay single-sourced. A leaf crate (serde / serde_json / uuid / utoipa / chrono / sha2 / garde / craig-validation only; never depends on services/* or craig-test-lib, avoiding the dependency cycle per the test-framework-hardening §D8.2 contracts pattern). The content / input fields carry zen-engine-polymorphic JDM as serde_json::Value and refuse any NUL (U+0000) in a string leaf or object key at validate(), alongside the stored text fields (context_type, version, description, reason), and version is capped at CODE_MAX (64 bytes; #2836). Response types (store::RuleSet, store::RuleEvaluation) remain in craig-rules — they are sqlx::FromRow store models, not yet lifted (tracked with the broader response-typing follow-up).

craig-reporting-contracts (#304)

  • afcars_release (#2121) — the AFCARS release tokens both source projections stamp on their audits: AfcarsReleaseRequestor (craig-reporting) and AfcarsReleasePurpose (afcars-2020 federal reporting), each a closed set of one; placement’s placement.afcars_released payload and cases' case.person_pii_exported AFCARS wrapper use them.

  • The shared request DTOs for the craig-reporting HTTP boundary — afcars::GenerateAfcarsRequest + ncands::GenerateNcandsRequest — used by the service and the test-lib ReportingClient so the request wire shapes stay single-sourced. A leaf crate (serde / utoipa / garde / craig-validation only; never depends on services/* or craig-test-lib, avoiding the dependency cycle per the test-framework-hardening §D8.2 contracts pattern). The garde field-length validation derives move with the DTOs (so reporting_period stays CODE_MAX-capped). Response types (store::models::{AfcarsSubmission, NcandsSubmission, …​}) remain in craig-reporting — they are sqlx::FromRow store models, not yet lifted (the broader response-typing follow-up).

  • afcars::AfcarsReadyForTransmission (#2179) — the ready_for_transmission act’s answer (submission, report half, ready_by, ready_at, the certified export generation and file digest), decoded by the test-lib ReportingExportsClient; AfcarsSubmission itself stays a store model.

  • afcars_capture::Mapping (#2018, #2054) — the ONE type for how an owning service captures an AFCARS element key (Column / DateWithIndicator / Each / Gated / Named, and — for a craig-cases fact the owner reports about a person it names, or a count derived from both services — Person { via: PersonVia, fact } / Derived { placement, cases }; PersonVia is CaregiverSlot(CaregiverSlot::First | Second) or a person-id Column), so the craig-cases map (craig_cases_fields::afcars) and the craig-placement map (craig_placement_contracts::afcars) are written in a single shape; both crates take this leaf as a regular dependency. afcars_capture::OWNED_ELSEWHERE (#2054) lists the 18 dictionary keys neither map owns, each with its owning plan’s issue (P-D #1965, P-E #1966); cargo xtask rules check proves the three lists partition the dictionary.

  • afcars_crosswalk::Crosswalk::lookup(series, value) → Option<CrosswalkAnswer> (#2141): Code(&str) | Unmapped; None when no table binds the series or the table lacks the value (impossible for a verified crosswalk, a crosswalked series and a token of its vocabulary).

craig-financial-contracts (#303)

  • The shared request DTOs for the craig-financial HTTP boundary — rates::{CreateRateRequest, UpdateRateRequest} + payments::CalculatePaymentRequest + adjustments::CreateAdjustmentRequest + claims::GenerateClaimRequest — used by the service and the test-lib Financial*Client family so the request wire shapes stay single-sourced. A leaf crate (serde / utoipa / garde / craig-validation + the field-type crates uuid / rust_decimal / chrono; never depends on services/* or craig-test-lib, avoiding the dependency cycle per the test-framework-hardening §D8.2 contracts pattern). The garde field-length and NUL (craig_validation::contains_nul, #2839) validation derives move with the DTOs (the handlers' body.validate()? calls behave identically). rust_decimal::Decimal carries the workspace serde-str feature, so money fields ride the wire as strings. payments::PaymentResponse (#978) is the first lifted response type — the client-side wire mirror of the payment row the lifecycle endpoints return (nullable-origin since #1068: the placement trio is Option, and agreement_id/term_id mark subsidy-origin UNIT-MONTH rows — daily_rate = gross = the monthly award); the remaining response types (store::models::{RateTable, PaymentAdjustment, ClaimingRecord}) stay in craig-financial as sqlx::FromRow store models (the broader response-typing follow-up). subsidy_generation (#1068/ADR-053) adds the generation-trigger pair: GenerateSubsidyPaymentsRequest with the strict canonical YearMonth token (one parser, property-tested: never-panics, byte-identical roundtrip, exact grammar) and the per-run GenerationReport counters both the endpoint and the financial.subsidy_generation_completed event carry (#1070 F2 adds the serde-defaulted skipped_before_payments_begin — months skipped before a guardianship agreement’s stored money boundary; #1071 D5 adds the serde-defaulted skipped_before_cutover — months before an imported agreement’s payment_cutover_month; both absent on older reports; #2228 adds the serde-defaulted queue_retired_below_floor — reconcile-queue pairs the drain settled unrepaired because their month fell below the reconcile floor). subsidy_agreements (#1069 M2/ADR-055, reshaped by #1070 U1/ADR-056) carries the native enrollment surface: CreateSubsidyAgreementRequest (body of POST /v1/financial/subsidy-agreements) is a #[serde(tag = "program")] 7-variant enum — Err(CreateErrAgreementBody) is the #1069 one-shot body VERBATIM (untagged serialization byte-stable, so persisted F8 canonical hashes survive the upgrade; the wire gains only the tag), Sg/Nrsg share CreateGuardianshipAgreementBody (the two-step PENDING mint: signed_at + the anchoring placement_id, the U3 per-program relationship-evidence rule — required non-blank for sg, optional for nrsg — the required caregiver_assessment_evidence_key, guardianship-family-only predecessor_agreement_id lineage; the F8 canonical hash covers the TAGGED body), and the four closed cohorts (Ersg/Enrsg/ Rcs/Ercs) share the empty CreateClosedProgramBody the service refuses with the typed closed-program problem. CreateSubsidyPartyRequest (1–10 signatories, ≥ 1 caregiver, never the child — validated server-side) rides both live arms. Every body deliberately omits what is derived server-side (child/case/worker + the residence-start snapshot from the verified placement, coverage/terms starts, review anchors, the ERR approval clock, all approval attribution); client_request_id is the F8 idempotency key — exact replay returns 200 with the existing agreement, same-id different-payload is a typed 409, checked against the canonical payload hash BEFORE any volatile dependency. ActivateSubsidyAgreementRequest (#1070 F4/F7, body of POST /v1/financial/subsidy-agreements/{id}/activate) carries NO dates beyond the optional past-dated tanf_terminated_on attestation — transfer_on is DERIVED from the S2S-projected episode_exit.exit_on (#2022), never caller-typed; fields: the CAS expected_head_interval_id, the required court_order_evidence_key, tanf_terminated_on?, legal_reference?. Replay recognition keys on the transfer alone — differing evidence keys / attestation / legal reference on a retry after success are IGNORED, never merged. SubsidyAgreementDetail gains the five serde-defaulted #1070 columns (guardianship_transfer_on, payments_begin_month, court_order_evidence_key, caregiver_assessment_evidence_key, tanf_terminated_on). subsidy_imports (#1071/ADR-057) carries the conversion surface: ClosedCohortProgram (a 4-variant serde enum — rcs/ercs/ersg/enrsg; open programs are UNREPRESENTABLE at the wire, D2), CreateImportBatchRequest, StageImportRecordRequest (the FULL historical record: identity + parties + interval/term chains, each entry carrying its recorded ImportStampRecord — the D9 posture means NO server facts and NO authz denorms exist on the DTO), ImportWarning/ImportBlocker/PaymentAssessment (the persisted stage outcomes), StageOutcome + the StageOutcomeKind replay vocabulary (staged/already_staged/restaged/already_imported/rejected), ImportRecordView/ ImportBatchDetail/ImportBatchCounts/ImportRecordPage, and FinalizeReport/FinalizeRejectionRow. THREE pub canonicalization fns live HERE so the service and the xtask conversion tool cannot drift (risk 4 — a tool-hash == service-hash parity vector pins it): canonical_record_payload (deterministic re-serialization — BTreeMap-ordered keys, null optionals, ISO dates, RFC 3339 UTC stamps, money normalized to 2 dp so "450.5" ≡ "450.50"), canonical_hash (sha256 hex of the compact serialization), and manifest_checksum (sha256 over the lexicographically-sorted (external_reference, canonical_hash) pairs, NUL/newline-delimited — order-invariant between the tool’s file order and the service’s row order). subsidy_backpay (#1115, plan backpay-import-path U1/U2) carries the below-floor backpay ledger contract: the frozen priced row BackpayPricedRow / BackpayRowKind, the typed BackpayBlocker
    the BackpayBlockerToken vocabulary (the stage refusals plus the three finalize tokens judged_row_changed, canonical_hash_mismatch (#2224), and unpublishable_event (#2827)), and the finalize pass’s report BackpayFinalizeReport / BackpayFinalizeStatus (finalizing/staging/finalized) / BackpayDivergence. FOUR pub fns live HERE so the service, the craig backpay tool and the U-AUTHZ routes cannot drift: priced_row_hash (sha256 hex of the priced row’s compact struct serialization), record_key (the agreement id and the month, :-joined), key_manifest_checksum (sha256 over the sorted record keys, each fed as key \n: the batch’s completeness manifest) and content_checksum (sha256 over the sorted (record_key, canonical_hash) pairs, each fed as key \0 hash \n — the import manifest’s framing, delegated to subsidy_imports::manifest_checksum — over the staged and materialized records the finalizer reviewed, ruling F1). subsidy_review_sweep (#1069 M3) extends the #1096 sweep contracts with the per-diem-handoff leg: SweepHandoffCandidate (pinned evidence payment + perdiem_started_on, the truth date the termination carries) and the report-only SweepMovedChild (per diem on a DIFFERENT placement — visibility, never executed) join the preview/run views; ExecuteSweepRequest grows the acknowledged_suspend/acknowledged_terminate/acknowledged_handoff handshake (server 409s on any mismatch with the pinned sets — a UI that never rendered a leg cannot execute it); SweepReport and SweepRunCounters grow leg3_actionable/handoff_terminated/leg3_moved_children, and SweepRunView grows mode_per_diem_handoff — all M3 additions serde(default) so pre-leg events/rows still deserialize. afcars (#2123) carries the afcars-facts query, page and opaque base64url child-id cursor; base64 joins the leaf deps.

craig-placement-contracts (#979)

  • The shared event contract for placement activation — the first contracts crate to carry a cross-service event payload rather than HTTP DTOs. events::PlacementActivatedPayload + the events::PLACEMENT_ACTIVATED routing-key constant are compiled by BOTH the craig-placement producer and the craig-financial consumer, so the billing contract (field names, foster_home_id nullability, started_at as the proration anchor) cannot drift the way the untyped placement.created shapes did pre-#979. A leaf crate (serde + uuid / chrono; never depends on services/* or craig-test-lib). Deliberately carries no child age/DOB — event payloads are PII-free; craig-financial resolves age authoritatively from craig-cases person data. #2020 adds an optional field replaces_placement_id (serde(default), omitted when None): the retracted arrangement the activated row re-records, so a plain activation carries no such key and an older envelope decodes as None. #2277 adds user_id (serde(default), always serialized): the acting worker’s sub (the creator of a born-active row, the activating worker on planned → active), audit-only — craig-financial does not read it; an older envelope decodes as None.

  • events::PlacementEndedPayload + the events::PLACEMENT_ENDED routing-key constant (#1070 F9) — the placement-ended twin: { placement_id, end_reason?, ended_at?, user_id? } (#2277: user_id the ending worker, audit-only and serde(default)), compiled by the producer, craig-financial’s subscription binding, AND its dispatch arm (it replaced an ad-hoc producer-side json! whose end_reason the financial consumer silently dropped, making the two sides undriftable). end_reason is Option for wire honesty: the producer omits it when the row has none, and a consumer reading an older envelope degrades to reason-blind behavior, never a deserialization failure.

  • subsidy::PlacementSubsidyEligibility (#1069 M2/ADR-055 + #1070/ADR-056) — the minimal subsidy-eligibility projection of one placement (child/case ids, assigned-worker denorm, placement_type/status wire tokens (since #2056 placement_type is the federal setting token), ffh_types (#2056: the family row’s applying (e)(3) categories, typed FosterFamilyHomeType so an unknown category fails the decode, serde-defaulted, null otherwise), started_on), the response of craig-placement’s GET /v1/placement/placements/{id}/subsidy-eligibility and the type craig-financial’s PlacementClient S2S read decodes. Exactly the facts subsidy enrollment and guardianship activation need (data minimization — the full placement row carries cancel and retract detail eligibility must not see). #1070 adds three serde-defaulted fields: ended_on (#2022’s guardianship witness compared it with episode_exit.exit_on; since #2059 the witness reads residence.ended_on instead and no financial code reads this field; None while the placement is live) and end_reason; it also added permanency_goal, which P-C U6b (#1997) REMOVED — the activation’s reunification refusal (the non-reunification-order proxy, ⁂ #1073) reads the child’s current craig-cases permanency plan at the transfer date since #1996. started_on/ended_on are the placement’s first/last day on the JURISDICTION’s business calendar (Eastern for Georgia), projected placement-side via BusinessClock::date_of so the consumer never converts timestamps. Type/status stay snake_case strings — the crate is a serde-only leaf; consumers parse into craig_reference enums and fail closed on unknowns. #2021 adds the serde-defaulted episode_exit: { exit_on, exit_reason } | null, served for the episode’s latest effective arrangement or, since #2059, a member of its residence run, with a live exit; exit_reason is the typed ExitReason (an unknown token fails the decode); craig-financial’s guardianship witness reads it (#2022). #2059 adds the serde-defaulted residence: ResidenceRun { started_on, ended_on, arrangement_ids } | null — the placement’s residence run (P-B2 D5; arrangement ids only, never a unit id), served for an effective caregiving placement; financial’s witness requires its ended_on to equal the exit day and its residence floor measures from its started_on.

  • episodes (P-B1 U3, #2018; U4, #2019; ADR-079 D2 + D4) — the removal-episode wire: EpisodeKey, RemovalFacts { removal_at, removal_manner } and its 43 required-nullable AFCARS answers (#2081; with RemovalFacts::unanswered and REMOVAL_ANSWER_KEYS), ExitFacts { exit_at, exit_reason, transfer_agency_type } and its 21 required-nullable AFCARS answers ((h) less (h)(14), (i)(10)–(i)(13); #2083; with ExitFacts::unanswered and EXIT_ANSWER_KEYS) (#2019; a garde rule answers 422 unless transfer_agency_type is present exactly when the reason is transfer_to_another_agency), ResponseRow<F> over the shared craig-ledger-contracts event row (plus first_recorded_at; RemovalResponseRow = ResponseRow<RemovalFacts>, ExitResponseRow = ResponseRow<ExitFacts>), ResponseRetiredReason (corrected or retracted), EpisodeRow (the episode with its live removal response and, since #2019, exit: null exactly when exit_at is null, else the live exit on a live episode or the exit retired with it on a retracted one), the strict act bodies OpenEpisodeRequest / CorrectRemovalRequest, ExitRequest (#2019; one body for the exit record and the exit correction) and HistoricalEpisodeRequest (#2019; the episode, its removal and its exit in one act) (the retractions reuse craig_ledger_contracts::LedgerRetractRequest), and the cancel’s CancelPlacementRequest / PlacementCancelled.

  • trafficking (#2082) — the two trafficking event-ledger wires: TraffickingStatementFacts / TraffickingReportFacts, the strict TraffickingStatementRequest / TraffickingReportRequest, the rows TraffickingStatementRow / TraffickingReportRow, TRAFFICKING_ANSWER_KEYS, and the re-exported EventAsOfQuery / EventThroughQuery / LedgerRetractRequest.

  • child_facts (#2084) — the two per-child window-ledger wires: ChildKey { child_id }, the facts HealthFacts b)(10): condition_status and eleven condition_<category> answers) and EducationFacts ((b)(11), (b)(12), (b)(14, the key consts HEALTH_FACT_KEYS / EDUCATION_FACT_KEYS (every key REQUIRED, null = unanswered), the strict hosts ChildFactsRecordRequest<F> / ChildFactsCorrectRequest<F>, and the rows HealthFactsRow / EducationFactsRow.

  • education_reports (#3188) — what a partner reported about a child’s schooling, as craig-exchange hands it to craig-placement: the strict EducationPartnerReport \{ child_id, listing_id, interface, identifier_kind, as_of, school_name, school_district, grade_level, enrollment_date } (capped; NUL refused; no idempotency key, since the route’s own rule makes a repeat harmless), the route’s path EDUCATION_PARTNER_REPORTS_PATH and its answer EducationPartnerReportAnswer \{ outcome: applied | stale | listing_ended }. craig-exchange’s collection run is the one writer. The staff read is EducationPartnerReportsQuery \{ child_id } answered EducationPartnerReports \{ reports: [EducationPartnerReportView] }. The two events' payloads (EducationReportReceivedPayload, EducationReportWithdrawnPayload) and ReportWithdrawnReason carry ids, the interface and a day or a reason only.

  • partner_listings (#3188) — EXCHANGE_LISTING_ENDED and the strict ListingEndedPayload \{ listing_id, interface, person_id }: craig-exchange stopped listing a person with a partner. craig-exchange stages it and craig-placement consumes it, both against this one type.

  • arrangements (P-B1 U5, #2020; P-B3 U1, #2080) — the arrangement-correction wire: the strict retract body RetractPlacementRequest { client_request_id, note } (note 1–1000 characters, REASON_MAX) and its lenient answer PlacementRetracted (status, retracted_from, the retract trio); the strict HistoricalPlacementRequest (the past arrangement’s type, optional home, started_at, ended_at, end_reason and optional replaces_placement_id; the record is never activated, never occupies and never bills) and its lenient answer PlacementRecorded; and ArrangementFacts, the arrangement’s 16 required-nullable AFCARS answers ((e)(5)–(e)(8), (i)(5)–(i)(8); #2080; strict, one field per placements fact column, ArrangementFacts::default() every answer unanswered; with ARRANGEMENT_FACT_KEYS, the key list in declaration order), flat on HistoricalPlacementRequest and PlacementRecorded (and on craig-placement’s create body and placement read), and whole as the placements PUT’s arrangement_facts object, the complete state.

  • events::EpisodeFactsChangedPayload + events::PLACEMENT_EPISODE_FACTS_CHANGED and events::PlacementCancelledPayload + events::PLACEMENT_CANCELLED (#2018) — the placement.episode_facts_changed (EpisodeLedger — ExitResponses since #2019, the two trafficking ledgers since #2082 — and EpisodeAct closed tokens) and placement.cancelled payloads; strict (deny_unknown_fields), ids and tokens only, user_id the attribution key.

  • events::PlacementRetractedPayload + events::PLACEMENT_RETRACTED and events::PlacementRecordedPayload + events::PLACEMENT_RECORDED (#2020) — the placement.retracted payload (retracted_from: the closed RetractedFrom token, active or ended) and the placement.recorded payload (started_at, optional replaces_placement_id); strict, user_id the attribution key. craig-financial compiles both into its bound keys.

  • afcars (#2018, #2019, #2054) — the placement side of the AFCARS element map, in the shared craig_reporting_contracts::afcars_capture::Mapping: PlacementCaptureUnit (one variant per landing unit, in merge order: B1U3, B1U4, B2U1, B2U3, B2U5, B3U1 … B3U5), AFCARS_CAPTURE_STAGE (= B3U5 = LAST_UNIT since #2084), LAST_UNIT (= B3U5), OWNED_ELEMENTS (all 67 placement keys, each on its unit), owned_after_unit(key) and AFCARS_ELEMENT_COLUMNS — (d)(1) removal_responses.removal_at, (d)(2) removal_responses.first_recorded_at, (d)(3), (d)(4), (i)(1), (i)(4) the removal’s own removal_responses answer columns (#2081), (e)(1) placements.started_at, (e)(2) the generated placements.foster_family_home, (e)(3) the six placements.ffh_type_* flags, (e)(4) placements.placement_type (#2056), (e)(5)–(e)(8), (i)(5)–(i)(8) the arrangement’s own placements fact columns (#2080), (d)(5)–(d)(6)(i) the episode_trafficking_statements answer columns and (d)(6)(ii) trafficking_law_enforcement_reports.reported_on (#2082), (g)(1) exit_responses.exit_at, (g)(2) exit_responses.first_recorded_at, (g)(3) exit_responses.exit_reason, (g)(4) exit_responses.transfer_agency_type, (h)(1), (h)(2), (h)(13), (h)(15) and (i)(10)–(i)(13) the adoption / guardianship exit’s own exit_responses answer columns (#2083), (b)(9) a Named override over health_records.health_assessment / visit_date / active and the episode’s removal_at / exit_at, (b)(10) the child_health_facts answer columns (Gated), (b)(11), (b)(12), (b)(14) the child_education_facts answer columns (#2084); (h)(3)–(h)(7) / (h)(8)–(h)(12) Person facts through the exit’s first / second adoptive slot (#2083); (e)(9)–(e)(13) / (e)(14)–(e)(18) Person facts through the arrangement’s first / second caregiver slot (persons.birth_year else year_of_birth_declared, person_demographic_facts.tribal_member, its seven race_* flags, ethnicity, persons.sex); (b)(20) Derived over person_siblings, removal_episodes and placements; (b)(21) Derived over the same inputs plus the arrangement’s setting identity (placements.foster_home_id / placements.kinship_household_id, #2058).

  • kinship_households (P-B2 U5, #2058, plan afcars-placement-facts D4) — the case-less setting identity of a home-less family arrangement: KinshipHousehold { id, admin_unit, created_at } (the household read and each list row), KinshipHouseholdChoice (externally tagged: {"existing": <id>} or {"new": {…}}) and NewKinshipHousehold { admin_unit? } (strict; admitted only while the episode has no unit stamp). The create and historical bodies carry the choice as kinship_household; PlacementRecorded gains kinship_household_id.

  • caregivers / portal (#2058) — a binding keys foster_home_id XOR kinship_household_id (was placement_id) on the binding view, the create body and the placement.caregiver_bound / caregiver_ended payloads. SubjectCaregiverBinding (craig-financial’s authoritative bindings read) also carries the REQUIRED child_arrangement_ids (the household’s active arrangements, ascending — the portal’s child scope) and payment_arrangement_ids (every non-cancelled household arrangement, ascending — the payment-agreement anchors), both empty on a home binding. PortalUnitKind Placement → KinshipHousehold (wire kinship_household).

craig-security-contracts (#306)

  • The shared request DTOs and wire rows for the craig-security HTTP boundary, across the admin, changes, detection, nist, reviews, partners, signer_keys, worker_identities and worker_admin_units modules (admin-unit / major-change / detection-rule / NIST-control / review / partner / partner-key / signer-key create+update bodies; worker_identities: the #1857 batched contact lookup WorkerContactsRequest → WorkerContacts of WorkerContact, and the admin work-line write SetWorkerContactRequest; worker_admin_units: AssignWorkerAdminUnitRequest, the WorkerAdminUnit row and the #1900 service-only AdminUnitsSnapshot) — used by the service and the test-lib Security*Client family so the wire shapes stay single-sourced. A leaf crate (serde / serde_json / utoipa / garde / craig-validation + chrono; never depends on services/ or craig-test-lib, avoiding the dependency cycle per the test-framework-hardening §D8.2 contracts pattern). The garde field-length validation derives move with the DTOs. The polymorphic findings / remediation_plan / public_key_jwk fields stay JSON values (STRUCTURAL-VALUE carve-outs); VerifyPartnerRequest stays service-internal (the test-lib verify_partner builds its body internally). Response types (store::models::) remain in craig-security — they are sqlx::FromRow store models, not yet lifted (the broader response-typing follow-up).

craig-intake-contracts (#637)

  • The single shared request DTO for the craig-intake public/partner report boundary — report::SubmitReportRequest, the body of POST /public/v1/reports (and the partner submit path). A leaf crate (serde / serde_json / chrono / utoipa / uuid / garde / craig-validation, plus ammonia / unicode-normalization / thiserror for SanitizedText; no craig-reference — the free-text fields are SanitizedText, the rest plain String / bool / date / JSON values, capped by garde, not domain-enum-typed; never depends on services/* or craig-test-lib, per the test-framework-hardening §D8.2 contracts pattern). The garde field-length validation derives move with the DTO, so the handler’s body.validate()? is unchanged; the polymorphic children / adults / narrative fields stay JSON values (STRUCTURAL-VALUE carve-outs), so the struct derives PartialEq but not Eq.

  • sanitized::SanitizedText (#2524, re-exported at the root) — intake free text, sanitized when it deserializes. Its only producers, SanitizedText::parse and the Deserialize impl that calls it, strip markup (ammonia, no tags allowed), control characters (tab and line feed kept) and the bidi format controls (U+202A..U+202E, U+2066..U+2069), NFC-normalize (unicode-normalization), and truncate to TEXT_MAX_CHARS (8 192) chars. The value is plain text, never entity-encoded: consumers escape at output. parse refuses a raw value over RAW_MAX_BYTES (32 768: four bytes per capped char) before any pass, and markup the sanitizer cannot reach a fixpoint on within eight passes (RAWTEXT / RCDATA wrappers, or a tag split around stray <, eight deep), with UnsanitizableText::TooLong / TooDeep (thiserror; value-free messages). Garde’s length rules measure the sanitized value (HasSimpleLength, bytes); it serializes as a plain string. craig-intake’s typed views and its walker over the untyped per-person / narrative JSON all run it (ADR-042 § Amendment 2026-10-19).

  • Why single-sourced (the decision note for #637): before #637 the report request shape existed three times — the service’s SubmitReportRequest, the craig-web BFF’s hand-built serde_json::json! envelope coupled to it only by a // matches SubmitReportRequest comment, and the SDK’s ReportSubmission. craig-web now constructs SubmitReportRequest directly, so BFF↔service field drift is a compile error (this surfaced a real drift — mandated_reporter_category, collected by the form but absent from the DTO and silently dropped; tracked as a data-loss fix in #638).

  • Why the SDK is NOT unified (the trust boundary, #307): craig-intake-sdk’s `ReportSubmission builder stays a separate, partner-facing ergonomic type (domain enums, its own SemVer). The intake submit endpoint is untrusted ingress — the server owns the typed contract and validates/rejects arbitrary input; the SDK and the test-lib IntakeClient speak the wire shape as external callers (the IntakeClient stays raw Value, #307 closed not-applicable-by-design). Sharing one type across the server’s deserialization target and the partner-facing builder would couple two distinct trust postures — the coupling the #307 analysis rejected.

craig-signing

  • The JWS signing contract’s canonical form, with deliberately minimal deps (serde_json, sha2) so every signing client can share it: canonicalize_json(value) → Result<String> (recursive key sort + compact JSON, matches server + browser) and hash_payload(canonical) → String (SHA-256 hex). It holds no key and signs nothing: the detached JWS is craig_intake_sdk::signing::sign_detached(config, payload), which re-exports both functions and signs through craig-crypto (#2683).

craig-webauthn (plan passkey-signer-credentials U1 #2192, ADR-082 D6)

  • The narrow WebAuthn verifier for passkey signer credentials. It accepts one profile: ES256 (COSE alg -7) on P-256, none attestation, discoverable credentials, user verification required. No I/O, no state: every challenge is derived by the caller from a canonical document. No OpenSSL: webauthn-rs needs openssl, which deny.toml bans.

  • Ceremonies: verify_registration_ceremony(policy, attestation_object, client_data_json, challenge) → Result<AttestationObject> (client data, then the attestation object, then the policy) and verify_assertion_ceremony(policy, public_key, authenticator_data, client_data_json, der_signature, challenge) → Result<AuthenticatorData> (parse the authenticator data, verify the signature, then client data, then the policy; no field is relied on before its signature verifies). verify_assertion(public_key, authenticator_data, client_data_json, der_signature) is the signature check alone: craig-crypto’s verify_der over an Es256PublicKey (#2683), strict DER, a high-S signature accepted as it stands.

  • Parsers: parse_authenticator_data (37-byte prefix, attested credential data, extension outputs, no trailing bytes), parse_attestation_object (exactly fmt = "none", an empty attStmt, authData with a credential), ClientData::{parse, verify}. CBOR is decoded with cbor4ii through a private position-tracking reader with a 256-level nesting budget, because extension outputs follow the length-less COSE key (#2192).

  • Values: Policy::new(RpId, Vec<Origin>, require_device_bound) and check_authenticator_data (RP ID hash, UP, UV, BS only with BE per WebAuthn L3 §7.1/§7.2, BE when device-bound); newtypes RpId, Origin (https://… or :port, stored as browsers serialize it: lowercase scheme and host, no default port), Challenge (32 bytes; sha256_of), CredentialId (1–1023 bytes), Kid (wa_ + base64url(SHA-256(id)), 46 chars), CeremonyType; AttestedCredential (kid, public_key → craig_crypto::Es256PublicKey, validated when the COSE key is decoded, public_key_jwk → craig_crypto::jwk::Es256PublicJwk), Flags.

  • Errors: one WebAuthnError variant per failed check (Malformed(Part), ChallengeMismatch, OriginNotAllowed, RpIdHashMismatch, UserNotVerified, BackupStateWithoutEligibility, BackupEligibleRefused, UnsupportedKey, BadSignature, …), so callers can trace the cause while answering a uniform 401.

  • Contract vectors: every *.json under sdks/test-vectors/webauthn/. chromium-virtual.json is Chromium’s virtual authenticator, with its capture script; capture-manual.js captures a real authenticator for the manual compatibility pass (Testing reference).

craig-intake-sdk

  • IntakeClient — partner API client. new(base_url, api_key) (default reqwest, 30 s); with_client(http, base_url, api_key); with_signing(config) → Self (ECDSA P-256 detached JWS auto-sign); submit_report(report) → Result<ReportConfirmation, IntakeError> (3 retries, exp backoff, X-JWS-Signature when signing); check_status(report_id) → Result<ReportStatus>.

  • ReportBuilder — validates 20+-char description + required fields (reporter / incident / children / adults / narrative / relationship fields).

  • ReportSubmission, ReportConfirmation { id, submitted_at }, ReportStatus { id, status, submitted_at, updated_at } (no PII); ReporterType (Anonymous/Mandated/ConcernedCitizen); ReportSource (the 15 NCANDS RptSrc tokens — REQUIRED on ReportSubmission since #648; the builder refuses to build without one; pinned against sdks/test-vectors/report-sources.json in all three SDKs); ConcernType; IntakeError (BadRequest/Unauthorized/RateLimited/NotFound/ServerError/Network; decodes RFC 9457).

  • Child::with_relationship_to_caretaker / Adult::with_relationship_to_caretaker (#1714) — set rel_to_primary_caretaker to a typed RelationshipToCaretaker’s code and `designation to the list that holds it, so the server reads the code from the same list. The three relationship types are re-exported from craig-reference, and the parity test pins them to sdks/test-vectors/caretaker-relationship-codes.json. The Python and TypeScript SDKs type the same entries (#3180), and sdks/test-vectors/person-entries.json holds all three to one wire shape.

  • signing module — SigningConfig (from_jwk(jwk_json, key_id), key_id()), canonicalize_json, hash_payload, sign_detached (shares the craig-signing contract).

craig-exchange-contracts (Plan L + Plan T1.2)

  • Typed ExchangeAdapter trait (RPITIT; ADR-038 §1 Tier-T) — unchanged by the erased seam.

  • ExchangeAdapterKind enum DELETED at Plan T3.1 (ADR-032 §1.3 open-TEXT carriage) — adapter identity is the &'static str from ErasedAdapter::kind(); validity = registry membership.

  • ErasedAdapter (object-safe, Plan T1.2 per ADR-032 A1) — send_value(endpoint, auth, payload, format) / test_connectivity_value(endpoint, auth) / kind / dispatch_class (#1428, REQUIRED — no default, so a hand-written impl must choose); the *_value methods return BoxFuture<'a, Result<…, ErasedAdapterError>> with one 'a shared by &'a self and auth (#2426), and send_value threads format: Option<&str>. #2295 removed audit_value, which no production path called.

  • #2426 (TP-2 D2) — OutboundAuth (None / Bearer(SecretString) / Basic { username, password: SecretString } / ApiKey { header, key: SecretString }), re-exported at the root: the credential ONE call presents, handed through ExchangeAdapter::send(endpoint_url, auth, payload) / test_connectivity(endpoint_url, auth) and the erased pair, so adapters stay per-kind singletons while two partners of one kind hold different credentials. Redacted Debug (the scheme and an API key’s header name, never a value or the username), no Serialize, kind() → none / bearer / basic / api_key (D1’s auth_type vocabulary). All three macro arms forward it; typed_only’s `send_value still refuses first. Deps gain secrecy.

  • DispatchClass (#1428, exhaustive by design) — Generic (the generic exchange pipeline may stage/dispatch Value payloads for the kind) vs TypedOnly (the SSA family: every generic checkpoint hard-rejects the kind; payloads move only through a dedicated typed pipeline).

  • ErasedAdapterError — Serde / Inner(Box<dyn PartnerError>) / TypedOnlyDispatch { kind } (#1428 — categorical, names only the kind token) / Invalid (#779). Display and Error are written out, since a derive cannot name a PartnerError object as a source; the wording and the source chain are what the derive gave. failure() answers the partner’s PartnerFailure, and None for a failure of the boundary itself.

  • #3196, the failure view (failure.rs): what a partner’s failure meant, readable without the partner’s error type. PartnerFailure<'a> (Transport / Timeout / Malformed / BadStatus \{ status, body: &'a str }) and the PartnerFailureView trait: failure(&self) → PartnerFailure<'_>, and digests_body(&self) → bool, whether a refused body may contribute a digest to the failure the host stores (no default: only the partner crate knows whether its partner’s bodies can echo an identifier). ExchangeAdapter::Error and CollectionAdapter::Error are bound by PartnerError (an error that is Send + Sync + 'static and has the view; implemented for every such type), so the view crosses the erased seam and the dispatch host classifies any partner’s failure with one function and no downcast (craig-exchange’s settlement::partner_failure). Infallible has the view, for an adapter that cannot fail.

  • #3196, the inquiry contract (inquiry.rs): Inquiry<Q, A> is one question to one outside source about one person: interface() (the adapter-kind token of the partner row holding the endpoint), authority() → Option<SourceAuthority> (Authoritative, NonAuthoritative, or None when no contract with the source exists and nothing may be sent) and ask(endpoint, auth, question) → Result<A, InquiryFailure>. InquiryFailure is closed and carries nothing the source said; token() is the job class stored today (partner-timeout, partner-connect, partner-transport, partner-status, partner-malformed, auth-unsupported, partner-fault, partner-refused, partner-error) plus identifier-unusable, and retryable() is false only for identifier-unusable and partner-refused, which a resend cannot change. The first pair is the SSA benefit screening: SsaBenefitQuestion \{ identifier: SecretString, request_date } (its Debug prints no value) and SsaBenefitAnswer (Found \{ month, benefits } or NoRecord); SsaBenefitInquiry names the registered form.

  • #3192, the person-index contract (person_index.rs): PersonIndex is the conversation with a jurisdiction’s register of people: interface(), find(endpoint, auth, &IndexSubject) → Result<Vec<IndexCandidate>, InquiryFailure>, register(endpoint, auth, &IndexRegistration) → Result<IndexId, InquiryFailure> and participate(endpoint, auth, &IndexParticipation) → Result<(), InquiryFailure>. IndexSubject \{ first_name, last_name, sex, date_of_birth } is all a find sends. IndexId is 1 to INDEX_ID_MAX (64) printable ASCII bytes; admitted(Vec<IndexCandidate>) holds an answer to MAX_CANDIDATES (250), a score of at most FULL_SCORE (100) and each text’s cap, and answers Malformed otherwise. No type’s Debug prints what describes a person. A person index is the canonical page.

  • #3193, the referral and return contracts (ADR-091). referral.rs: ReferralLeg is interface(), leg(), assemble(&ReferralContext) → Result<Value, AssemblyRefusal> and classify(&SentRecord, &Value) → ReferralVerdict; ReferralContext \{ application: &ApplicationView, child: &PrincipalView, custody: &CustodyView, case_number, correlation_id }; ReferralVerdict::Accepted carries a ReferralReceipt, the partner’s reference, which ReferralReceipt::parse takes only as 1 to REPORT_TEXT_MAX (64) printable ASCII bytes with no space and whose Debug withholds it. returns.rs: ReturnLeg is interface(), leg(), max_bytes(), decode(content_type, body) → Result<Collected, ReturnRefusal> and acknowledge(&ReturnRun) → Acknowledgement \{ status, content_type, body }, both pure; ReturnRun is Completed \{ settled: Vec<(PartnerReport, ReportOutcome)>, unread } or Refused(ReturnRefusal); returns::admitted(Collected) holds a decoded call to MAX_REPORTS (500) and each report’s caps, and returns::decode_refusal reads a leg’s Busy as Malformed, since only a host can know it is busy. collection.rs: PartnerReport gains MedicaidReferral(MedicaidReferralReport \{ identifier_kind, identifier_value, reference, case_reference, program_id, status: Option<ReferralStatus>, reported_on }), whose Debug prints none of the partner’s four texts; PartnerReport::subject() → ReportSubject (Person(id) or Reference) replaces person_id(). A referral leg and A return are the canonical pages.

  • #3196, the triggered-send contract (trigger.rs): TriggerLeg is a LegSpec and three pure rules, admits(stage, principal, today), assemble(ctx) → Result<Value, AssemblyRefusal> and classify_ack(sent, response) → AckVerdict. LegSpec \{ interface, leg, entity, stage, rule, opens_stage, discriminator, scope, reentry_gated, settles_listing } is data: LegEntity (case, investigation, report, custody episode, person identifier, Medicaid application; as_str() is the stored token, reaches() the stage kind a resolve maps it to), StageKind (case, investigation, custody episode, Medicaid application; the last, #3193, is the stage of a referral leg and never of a triggered-send leg a partner states), ResolveRule (AdmitNew, CloseExisting, RetireSubject, RemoveAndSend, ResendClose) and LegScope (Stage, Person). LegSpec::fault() → Option<SpecFault> names a spec that contradicts itself. A leg reads the specification’s own views, StageView, PrincipalView, CustodyView, CustodyRowView and IdentifierView (a person’s identifier with its kind; Debug prints no value), assembles from a RecordContext (since #3193 with application: Option<&ApplicationView>, set on a Medicaid-application stage only), and judges an answer against a SentRecord (deliberately not Debug). AckVerdict is Accepted(body), Rejected \{ code }, Mismatch, Malformed or, from a referral leg alone, Receipt(receipt): the partner’s reference, which the host hands to the application’s owner and does not store (a leg stated through the module interface legs cannot give one; it crosses as Malformed). craig-exchange’s trigger substrate runs every leg through it. See Writing a partner crate.

  • impl_erased_adapter! three-arm macro: typed-partner + SHINES-passthrough (both Generic)
    typed_only (#1428 — send_value refuses unconditionally with TypedOnlyDispatch; the payload-free connectivity probe still forwards); pub use futures_util::future::BoxFuture. The typed-partner arm takes a REQUIRED correlation = Some("<field>") | None carrier (#1815).

  • CORRELATION_KEY ("craig_correlation_id", #1815) — the key the send worker injects the job’s correlation under in every manual payload object; carry_correlation(&mut payload, carrier) moves it onto the typed partner’s declared id field before from_value (replacing that field’s value), or removes it when the carrier is None. The SHINES envelope carries it at its top level under the same key (#2398).

  • #3188, the collection seam (collection.rs): the inbound mirror of ExchangeAdapter, for a leg in which CRAIG fetches what a partner published about the people CRAIG told it about. A partner crate implements CollectionAdapter (interface(), leg(), collect(endpoint_url, auth) → Collected); the registry holds the object-safe ErasedCollection, which every typed collection is, its future boxed and its typed error boxed as ErasedAdapterError::Inner. What crosses the seam is a product record, never a partner’s wire: PartnerReport (first variant Education(EducationReport \{ person_id, identifier_kind, as_of, school_name, school_district, grade_level, enrollment_date })), so the host admits and applies reports without knowing a partner’s JSON, and nothing is marshalled through JSON at the seam. Collected \{ reports, unattributable } counts the records that named no person CRAIG can identify; they are never matched on another key. A document that does not exist yet is an empty Collected; one that cannot be fetched or read is an error and nothing of it is answered. Deps gain chrono and uuid.

  • #3200 — built for wasm32-unknown-unknown (ADR-090), the crate takes chrono without its clock and uuid without a random version, from target-specific dependency entries: the contracts carry dates and ids, read no clock and mint no id (The specification builds for WebAssembly). Every other target inherits the workspace entries as before.

craig-exchange-transport (Plan V Step 1)

  • OutboundTransport (object-safe; Send + Sync + 'static) — send(TransportRequest) → BoxFuture<', Result<TransportResponse, TransportError>> + probe(ProbeRequest) → BoxFuture<', Result<(), TransportError>>. The single wire-egress seam (every partner adapter and SHINES route through Arc<dyn OutboundTransport>; inside a partner module it is the host’s, lent through the contract).

  • #3188 — fetch(FetchRequest \{ endpoint, timeout, auth }) → BoxFuture<'_, Result<TransportResponse, TransportError>>: a GET of a document a partner published, for a collection leg. It is REQUIRED (no default), so a transport chooses. DirectHttpTransport fetches under a send’s guards (the internal-address refusal, the credential channel, the 1 MiB response cap; a 2xx is Ok, anything else BadStatus); EgressControlledTransport fetches under its allowlist, https rule, pinned address, redirect ban and the same cap, and refuses any auth but None; WebMethodsTransport refuses, since the broker stub has no service that fetches; StubTransport answers a queue set by with_fetch_results (an empty 204 past it) and records fetch_requests(). The cap is not raised for a fetch: a document larger than it is published in pages. JsonAdapterCore::fetch_json::<I, E>(endpoint, auth) is the shared GET-and-decode under the send timeout; a 204 is None (the partner has published nothing, which is no failure), and a body that is not an I is the partner enum’s malformed arm, with serde’s category and position only.

  • Value-objects (public fields): TransportRequest { endpoint, body: Vec<u8>, headers: Vec<(String,String)>, timeout }; ProbeRequest { endpoint, timeout, method: ProbeMethod } (Head partners / Get SHINES); TransportResponse { status: u16, body: Vec<u8> }. Both request structs also carry auth: OutboundAuth (#2426), apart from headers, so no header-logging path carries a credential.

  • TransportError (thiserror, Clone) — Timeout / Connect / BadStatus { status, body } / Transport(String) / AuthUnsupported (#2426, value-free); reqwest is never named in a pub signature.

  • DirectHttpTransport::new(reqwest::Client); WebMethodsTransport::new(reqwest::Client, broker_base_url) (.with_service; Plan V Step 3 broker stub — NOT wired into prod boot; #557); StubTransport (behind test-util — canned-response, request-recording double); pub use futures_util::future::BoxFuture.

  • #2426 (TP-2 D2) — the credential channel: DirectHttpTransport applies Bearer / Basic through reqwest’s bearer_auth / basic_auth and an ApiKey as a sensitive HeaderValue in its named header, on send and probe (an API key that is no valid header value fails with the value-free TransportError::Transport("outbound auth: invalid header value")); WebMethodsTransport and EgressControlledTransport refuse any auth but None with TransportError::AuthUnsupported before an envelope, a DNS lookup or a client exists; StubTransport records the whole request, auth included (it is test-util-only); pub use craig_exchange_contracts::OutboundAuth. Deps gain craig-exchange-contracts and secrecy.

  • #788 — the HTTP-JSON plumbing the partner adapters share on top of the seam: JsonAdapterCore::new(Arc<dyn OutboundTransport>) (.with_connect_timeout / .with_send_timeout, defaults DEFAULT_CONNECT_TIMEOUT 5 s / DEFAULT_SEND_TIMEOUT 30 s) with probe_health::<E>(endpoint_url, auth) (HEAD {url}/health) and send_json::<O, I, E>(endpoint_url, auth, payload) (JSON POST + typed decode; #2426 sets each call’s auth on the request); the PartnerTransportError trait (timeout / bad_status / transport constructors
    the ONE from_transport per-arm mapping — Timeout and BadStatus keep dedicated variants, the #1460 body bound applied at construction, and AuthUnsupported (#2426) joins Connect / Transport in the catch-all); and the partner_error! macro that stamps out a partner’s five-variant error enum with the hand-written Display wording ("{prefix}: …"). A partner crate delegates to it, unless its data classification forbids body text in errors (Georgia’s SSA source keeps its own value-free enum, ADR-065). The xtask partner_plumbing test pins the shape on the reference partner: its adapter delegates through core.send_json( / core.probe_health( with no mapping fn, and its error.rs is the macro invocation alone (one enum, no derive).

  • #1821, #3196 — partner_error! implements craig-exchange-contracts' PartnerFailureView for every enum it stamps (the two decode variants share Malformed; BadStatus lends its bounded body). Its body_digest argument is required: keep or omit is the enum’s digests_body answer. Georgia’s CPRS keeps a digest; its other nine partners omit it. The view’s types live in craig-exchange-contracts and are not re-exported here.

  • #3200 — the host feature (ADR-090) holds everything that opens a connection: DirectHttpTransport, EgressControlledTransport with EgressPolicy, check_egress, ip_is_internal and MAX_RESPONSE_BYTES, and WebMethodsTransport, with the reqwest and tokio dependencies. The [workspace.dependencies] entry switches it on, so every service and tool builds as before. Without it the crate is the trait, the request and response types, TransportError, JsonAdapterCore, PartnerTransportError and partner_error!, and builds for wasm32-unknown-unknown, which is how a partner crate built into a module takes it. The crate’s own tests switch host and test-util on through a development dependency on itself, so testing the package alone still compiles every test.

craig-partner-host (#3200)

The host that loads a jurisdiction’s partner modules from its configuration layer (ADR-090; Partner modules is the canonical page). wit/craig-partner.wit is the module contract. craig-exchange links it with runtime, and craig-mock-server with simulators.

  • No feature: Manifest::parse(&str) → Result<Manifest, ManifestError>, the checked partners/manifest.toml (name, version, contract, limits \{ fuel, memory_bytes }, build \{ partner_set, simulators } and interfaces, each \{ kind, typed_only, seed }), and the layer’s file names (PARTNERS_DIR, MANIFEST_FILE, PARTNER_SET_FILE, SIMULATORS_FILE, SOURCE_DIR). The task runner links this much and no runtime.

  • runtime: PartnerModules::from_snapshot(&ConfigSnapshot) → Result<Option<Self>, LoadError> (None when no layer holds partners/) and from_parts(Manifest, &[u8]); partner_set() → PartnerSet, whose adapters, legs, collections, inquiry, person index, referral legs and return legs each call the module (a module built for contract 1.0 has no person index, and one built before 1.2 no referral or return leg; the set then has none; Versions); with_send_ceiling(Duration), the longest the host waits on a partner (default: the transport’s 30 s send timeout); manifest() and partner_set_digest(). Each call into the module runs in a fresh instance under the manifest’s limits, and a module’s failure fails that one call.

  • simulators (the mock server only): SimulatorModule::from_snapshot / from_parts, start() → Arc<SimulatorSet> (one world: one long-lived instance, called one request at a time), SimulatorSet::mocks() (each kind’s MockRoutes, with its caller where the module’s callers export lists the kind; a module built before contract 1.2 has none) and simulator(kind), and ModuleSimulator::holds(&SimPerson).

  • stand-in-sources (test only): partner_set_as_reported(), which grants the SSA benefit inquiry the standing its module reports. Without it the inquiry is granted nothing and sends nothing.

craig-partner-sdk (#3200)

What a partner crate and a partner module are written against besides the contracts (ADR-090). It builds for wasm32-unknown-unknown, the target a jurisdiction’s partner module is built for, so it depends on nothing that needs a socket, a clock or a source of randomness (how that is held).

  • SimPerson \{ person_id, first_name, last_name, date_of_birth, sex, identifiers }: a person a partner simulator may know, as the seed’s people file and the mock-server’s control surface carry one. deny_unknown_fields; garde::Validate holds it to the product’s own caps (NAME_MAX, ENUM_STRING_MAX, and SIM_IDENTIFIERS_MAX 16 entries, SIM_IDENTIFIER_KIND_MAX 16 bytes, SIM_IDENTIFIER_VALUE_MAX 32 bytes), and a refusal names the field and the bound, never the value.

  • PartnerSimulator (Send + Sync): load(&[SimPerson]) brings the partner’s records for those people to what its rule says, and clear() forgets everything.

  • MockRoutes \{ router: axum::Router, simulator: Option<Arc<dyn PartnerSimulator>>, caller: Option<Arc<dyn PartnerCaller>> }: one partner’s mock, with MockRoutes::stateless(router) for a mock that keeps no state.

  • PartnerCaller (Send + Sync, #3193): the calls a simulated partner makes of CRAIG. due() → Vec<DueCall \{ leg, content_type, body }> changes nothing, and answered(leg, status, body) tells the simulator what CRAIG answered.

  • now() → DateTime<Utc> and IdSource::next_id() → Uuid: the clock and the ids a simulator uses. Natively they are the system clock and a random time-ordered id; inside a module they are the host’s clock, an import of the module contract, and a name-based id of the source’s ordinal, since a module has no randomness.

  • boundary: how the contracts' values cross the module boundary. day_number / date_of, instant_parts / instant_of, id_halves / id_of, and module_conversions!, which writes the conversion of every record of the contract between its contract type and its form in a set of generated bindings. The host and the guest both expand it, each over its own bindings. person_index_conversions! (#3192) does the same for the person index’s records, apart, because the host binds that interface apart; referral_conversions! and return_conversions! (#3193) do so for what contract 1.2 added, and leg_view_conversions! holds the views a leg and a referral leg both read, which the host generates once for each of the two interfaces.

  • guest (WebAssembly only): the half that runs inside a module. PartnerSetSource and export_partner_set!(Source) export a partner set, with the host’s transport handed to the source as an OutboundTransport; PartnerSetSource::person_index defaults to none, as referral_legs and returns do, so a source written for an earlier minor of the contract builds unchanged; SimulatorSetSource, Mock and export_simulators!(Source) export the simulators, a Mock carrying its routes' caller.

The simulator’s three types moved here from craig-state-bundle, which reaches the database driver through the reference data and so cannot be built for that target. craig-state-bundle keeps MockRouteFactory, stateless_mock and SimLoaded.

craig-partner-test-harness (#836)

Test-support LEAF crate (a dev-dependency of the reference partner here, and of a jurisdiction’s partner crates in its configuration layer; never in a release artifact): the shared integration-test legs a partner crate’s tests/round_trip.rs delegates to, each defined ONCE and generic over PartnerUnderTest — a DESCRIPTOR trait a test file implements on a local zero-sized type (the reference partner’s struct Registry; impl PartnerUnderTest for Registry { type Adapter = subject::Adapter; … }, where subject is the crate’s adapter or the one its built module provides; the orphan rule forbids implementing the foreign trait on the foreign adapter): accepted_round_trip / rejected_via_sentinel / connectivity (mock-server legs — the test site spawns craig_mock_server::spawn_for_routes over the crate’s own mock and passes the base URL), hands_transport_the_exact_request (the byte-identity proof over the recording StubTransport), bad_status_body_is_bounded (1460), fault_leg(base_url, FaultLeg::{LatencyTimeout, StatusBadStatus, MalformedResponse}) (the ADR-067 partner-crate triple — records the executed fault through craig_fault_core BEFORE asserting, under the surface id + leg ids derived from the adapter’s kind() — the kind-derived convention the registry’s ids follow; registry MEMBERSHIP stays the contested census’s check), and erased_dispatch_refuses_violation (#779), manual_send_correlation_on_the_wire(carrier) (#1815 — the injected CORRELATION_KEY is on the recorded wire on the declared carrier, or the body is the fixture’s bytes exactly when the carrier is None), and forwards_auth (#2426 — each credential type, Bearer, Basic and ApiKey, reaches the recording StubTransport on the typed send, the erased send and the erased probe). A partner crate supplies its fixture(s), one impl PartnerUnderTest (construction, the accepted / sentinel payloads, its own ack assertions and an optional wire-contract-violating payload) and one [tokio::test] per leg whose NAME the contested-surfaces registry pins. The fault legs read the adapter error’s own PartnerFailureView (#3196; FaultClass and the per-crate classify are gone).

Feature modules (#3200, test-only; ADR-090): modules::BuiltModules loads a layer’s committed partner modules with craig-partner-host (of_layer, from_parts) and hands back each part as the kit’s cases take it (adapter / erased_adapter, leg, collection, inquiry, mock, simulator, mock_kinds, partner_set with the standing the module reports, person_index, and shipped_set as a boot takes it); OnModule<P, M: Built> is P’s `PartnerUnderTest over the module’s adapter, and ModuleAdapter<O, I> the typed adapter behind it. The same cases on the built modules says how a crate uses them.

#3196 adds the conformance kit’s other modules. leg: a LegCase \{ leg, served, refused } per triggered-send leg and the checks spec_is_coherent, admission_follows_the_rule, assembly_is_pure, a_refused_subject_refuses_assembly, the_record_is_acknowledged(case, adapter, base_url), an_undecodable_ack_is_malformed and no_arbitrary_answer_is_accepted (generated JSON). simulator: a SimulatorUnderTest descriptor and the_same_people_make_the_same_world, a_person_not_given_is_not_known, a_person_out_of_reach_changes_nothing, clear_forgets_everyone. set: is_fully_described(set, Described \{ legs, collections, inquiry }), with undescribed(set, legs), undescribed_collections(set, cases) and undescribed_inquiry(set, case), which report a registered leg or inquiry with no case, a case that names nothing registered, and an interface whose registered collections and described collection legs differ in number. collection: a CollectionCase \{ collection, unpublished, published, attributed, unattributable } and nothing_published_is_an_empty_answer, a_published_document_comes_back_attributed, a_fault_reads_as_its_failure(collection, endpoint, leg) and the_collection_is_registered_under_its_interface(case, set). inquiry: an InquiryCase \{ inquiry, endpoint, known, unknown, unusable } and a_known_person_is_found, an_unknown_person_is_no_record, an_unusable_identifier_is_refused_unsent, a_refused_question_is_partner_refused, an_unreachable_source_is_asked_again, a_fault_reads_as_its_failure(inquiry, endpoint, known, leg) and the_inquiry_is_registered_under_its_interface(case, set). referral_leg (#3193): a ReferralCase \{ leg, application, child, custody, case_number, carried, stranger } and a_referral_carries_the_identifier, a_referral_carries_the_application, an_accepted_answer_yields_its_receipt(case, adapter, base_url) and a_rejected_answer_yields_no_receipt(case, adapter, base_url). return_leg (#3193): a ReturnCase \{ leg, content_type, wellformed, reports, partly_unreadable, readable, unreadable, malformed } and a_wellformed_call_decodes_to_its_reports, a_malformed_call_is_refused, an_unreadable_record_is_counted_not_fatal, a_body_over_the_legs_cap_is_refused and the_acknowledgement_names_each_reports_outcome. The kit’s own tests show each check failing on a leg, a simulator or an inquiry built with the matching flaw. Deps gain craig-state-bundle, chrono, proptest and uuid.

Placement rationale (recorded in its Cargo.toml): craig-test-lib would drag craig-store/craig-db/sqlx/lapin into every partner test build (and add a partner→(dev)test-lib dev-cycle class); a test-util module inside craig-exchange-transport could host only the stub legs. Deps: contracts, transport (test-util), fault-core, reqwest, serde_json; under modules, the module host.

Partner adapter crates

A jurisdiction’s partner crates are not in this repository (#3200, ADR-090): they live in its configuration layer and reach CRAIG as two WebAssembly modules (Partner modules). Georgia’s eleven (craig-partner-{caps,cprs,doe-slds,empi,gateway-income,ies,ions,smile,stars,tcm,wic}), the crate that exports them as a partner set and the one that exports their ten mocks are in craig-config-georgia under partners/src, with their tests. The one partner crate here is the reference partner, craig-partner-testonia-registry (below), which is what a jurisdiction’s crates are written after.

craig-plugin-contracts (Plan W Step 1, ADR-033)

  • The stable seam the plugin subsystem is reached through. PluginManifest::parse (typed Plugin.toml + validator); the serializable render contract (RenderCtx, FetchOutcome, PanelState, RenderedFragment, PluginError, PluginRenderFn) — owned values only, WASM-ready; FetchOutcome::classify (2xx-data → Data, 204/empty/404 → Empty, else → Error).

  • PluginSource (#[async_trait], Tier-O object-safe per ADR-038 §1) — get / list / async render; the v1 backend is CompileTimePluginSource over the CRAIG_PLUGINS linkme slice (v2 = WASM). PluginRegistry (pre-materialized, boot-validated) + PluginBootError. No reqwest (the host fetches; the plugin is pure). See ADR-033.

craig-plugin-macros (Plan W Step 2, ADR-033)

  • CRAIG’s first first-party proc-macro ([lib] proc-macro = true). The [craig_plugin(slug = "…", manifest = "…")] attribute annotates a plugin author’s sync-pure fn(&RenderCtx) → Result<RenderedFragment, PluginError> and expands to a [linkme::distributed_slice(CRAIG_PLUGINS)] registration carrying the slug, the include_str!(concat!(CARGO_MANIFEST_DIR, "/", manifest))’d `Plugin.toml, and the render fn itself — so dispatch is registry-driven (registry.render(slug, ctx)), with no hardcoded match slug.

  • The macro core operates over proc_macro2 types so the parse + codegen is unit-testable; an ident-safety guard rejects a non-kebab slug with a clean syn::Error. Consumers need linkme as a direct dep (the expansion references ::linkme) + a cargo-machete ignore for it (macro-only use).

craig-plugin-example (Plan W Step 6, ADR-033) — under plugins/

  • The reference plugin and first #[craig_plugin] consumer; the first member of the plugins/ tree (NOT crates/). A context-free dashboard panel: a sync render fn + a four-state Askama template (data/empty/error; loading is shell-owned) + a Plugin.toml declaring one context-free craig endpoint (the open-cases count). CSP-clean (classes + data-* only).

  • Opt-in: compiled into craig-web behind the plugin-example Cargo feature (NOT in default)
    the #[cfg(feature = "plugin-example")] use craig_plugin_example as _; linkme force-link in main.rs; devstack/e2e enable it via the CRAIG_WEB_FEATURES Dockerfile build-arg. This is the template every future plugins/<name> (jurisdiction) plugin follows.

  • Placement (#3050): no jurisdiction baseline places the panel, because a release craig-composition links no test-only plugin and refuses to boot on a baseline that places one. craig-composition’s own plugin-example feature also compiles in services/craig-composition/fixtures/dashboard-demo.toml, which the loader appends to the dashboard baseline at boot (skipping a slug the baseline already places), so the devstack shows the panel and a release build cannot carry the placement.

  • Test coverage (#2874): cargo xtask feature-matrix compiles the plugin axis, and the battery runs craig-web’s suite on default features only. That compile-only coverage is a recorded choice while #2296 decides whether the plugin framework stays. The devstack and e2e already boot craig-web with the plugin linked, and the registry’s checks have their own unit tests over hand-built registrations. AppState::test_fixture overlays the plugin’s one term, term-open-cases, in both locales when the feature is on, so cargo nextest run -p craig-web --features plugin-example passes as a by-hand check. If #2296 keeps the framework, the battery gains that run.

craig-composition-engine (Plan X Step 1, ADR-035)

  • The pure (NO-I/O) composition engine ported from canopy, adapted to CRAIG’s BundleContribution / Claims model. Consumed by the services/craig-composition host (the I/O, DB, cache, and RMQ live there, not here).

  • merge — apply_merge_patch_7396 (RFC 7396) + apply_json_patch_6902 (RFC 6902 via json-patch): the layer-merge primitives for the 5-layer top-down walk.

  • role_filter::filter_items_by_role — role filtering applied AFTER merge.

  • user_delta — the slug-anchored user_delta_v1 envelope (UserDelta / UserDeltaError)
    apply_user_delta / validate_user_delta (incl. the CRAIG no-required-hidden floor). #2634: a repeated slug in hidden_slugs or slug_order is refused (DuplicateSlug, the host’s 422), not deduplicated, so a stored delta reads exactly as written. With the membership check, each list holds at most the baseline’s size.

  • hash — canonicalize (RFC 8785 JCS) + composition_version (SHA-256 content hash for cache validation).

  • defaults::system_defaults — the compiled EMPTY product-default surfaces.

  • types — RawComposition / ComposedSurface / ComposedItem / ComposableSurface / DashboardLayout / CaseDetailShell / ShellSpec / CompositionKey + the newtype slugs JurisdictionSlug / RoleSlug / ItemSlug.

#890 (epic &63): bounded_apply_json_patch_6902(doc, ops, &PatchBounds) is the resource-ceilinged RFC 6902 apply the composition loader uses (PatchBounds::DEFAULT = 256 ops / 4 MiB canonical result): over-long op lists refuse before any work, the patch runs on a scratch clone so the caller’s document mutates only on full success, and copy/move amplification hits the ResultTooLarge wall. Typed BoundedPatchError distinguishes resource refusals from RFC 6902 semantic failures.

craig-bff (plan portals U4, ADR-076 D6)

  • The shared browser-facing BFF substrate, extracted from craig-web behaviour-neutrally so services/craig-portal (U5) and the follow-on portals build on the SAME session, login, CSRF, transport and failure-rendering code instead of a copy. Depends on craig-auth / craig-common / craig-i18n + the BFF stack (axum, tower-cookies, askama, reqwest); never on a database or the message bus (the ADR-004 stateless-aggregator floor — craig-web’s architecture_invariants scans this crate’s manifest alongside its own).

  • static/css/ — the shared stylesheets tokens.css / chrome.css / components.css, the set the crate’s own failure template links (#1867). Not compiled in: each host’s image stage COPY`s `crates/craig-bff/static into /app/static before the host’s own static/, served by the host’s ServeDir; craig-web layers screens.css, the portal portal.css.

  • state::BffConfig — the host’s policy: client_id / redirect_uri / the post-login, login-failure and post-logout redirects / login_path / cookies: CookieNames (derived from a prefix — craig-web’s craig- reproduces its pre-extraction names) / session_secure + session_max_age_secs / refresh_failure: Preserve | Drop (#961 posture; the portals drop) / locale_policy: Negotiate | SessionThenNegotiate / admit: fn(&[String]) → AdmitVerdict (Admitted | Refused(key) — the audience verdict, whose refusal names the 403 body’s message key: craig-web’s worker gate #1842 / #2371 answers bff-admit-worker-only (WORKER_ONLY_REFUSAL_KEY) or bff-admit-dual-role (DUAL_ROLE_REFUSAL_KEY); craig-portal’s pure-portal rule portal-admit-refused, portal-admit-dual-role or portal-admit-no-role) / branding. state::BffState — the trait a host’s app state implements (cookie key, OIDC discovery, the two login verifiers, the HTTP client, trusted proxies, the i18n engine).

  • session — WebSession (zeroize-on-drop), SessionUser, FlashMessage, SessionSnapshot, PkceState, CookieNames, and the cookie helpers (load_session / save_session / clear_session / the #960 id_token pair / set_flash / take_flash), every name from the host’s CookieNames. Every cookie is minted at Path=/ under the host’s Secure posture (BffConfig::session_secure): every helper that mints or removes one, set_flash / take_flash included, takes it as its secure flag (#2258). Every removal (take_flash, clear_session and the callback’s PKCE cleanup) goes through the crate-private expire_cookie, whose removal names Path=/ and the cookie’s mint-time Secure flag. It therefore expires the cookie from any route (#2095). The callback expires the PKCE cookie only when the callback’s state matches the cookie’s: a mismatch (another tab’s /login, a replayed callback) leaves it to the login that minted it (#2259).

  • oidc — login (PKCE + state + nonce), callback (BOTH tokens verified by auth_verify before a session is minted, the audience verdict, establish_session), logout (RP-initiated with id_token_hint), generic over S: BffState; refresh — refreshed_snapshot, the per-request loader with the #961 rotation and the host’s refresh-failure policy.

  • middleware — session_context (one decrypt per request; on the way out it answers a handler-level session expiry, session_expired_response, with the same 401 + HX-Redirect when the request is htmx, #2581), verify_csrf (#763 / #950), require_auth (the audience verdict on both the snapshot and the cookie-fallback path; a refused request goes to the host’s login_path — a 303 for a browser navigation, 401 + HX-Redirect for an htmx request, so an htmx fragment navigates the page instead of swapping the login hop, #1944), set_locale (the host’s LocalePolicy; the {prefix}locale signed cookie is the session tier) and its write side store_locale_preference(state, cookies, locale) → bool (#1487: a host’s language form stores the choice through it; false, storing nothing, for a locale the engine does not negotiate; the cookie is signed, host-only, HttpOnly, SameSite=Lax and a year long; craig-web’s POST /personalize/language and the portal’s POST /language both call it).

  • transport — Transport — Transport::new(caller, http, streaming_http), the host’s http_client caller label given once (#1954; caller() reads it), with OutboundIdentity::{Actor, SubjectToken} (ADR-076 D2: the portal relays the user’s own token in X-Craig-Subject under the BFF’s service bearer), the verb helpers, UpstreamError, HasTransport; fetch — the typed single / detail / paged fetch helpers; upload — the multipart relay (each text part capped at craig-common’s MULTIPART_TEXT_PART_MAX_BYTES; an over-cap part is UploadError::TextPartTooLong { part }, the bff-upload-text-too-long flash, #2632); form — minted_form_get! (takes the host state type)
    helpers; page — PageContext / Breadcrumb / flash_error_redirect (generic over S: BffState; PageContext.languages: Vec<LanguageChoice { tag, name, current }> is what a nav’s language switcher lists, each under its own name from bff-language-name, and is empty while the host negotiates one locale, #1487); csp — STRICT_CSP
    the three security-header layers; error — BffApiError (SessionExpired renders session_expired_response: a 303 to /login, or 401 + HX-Redirect for htmx) rendered through the crate’s own failure template and the embedded bff.ftl (en + es, in craig-i18n’s catalog) — every BffApiError category, the failure page’s chrome and the three sign-in flashes are message keys. The upload-relay flashes (UploadError::flash_key, bff-upload-), both CSRF 403 bodies (bff-csrf-) and the host’s admit-refusal key render the same way (#1865). craig-portal never flashes the crate’s UploadError copy; it maps each variant to its own portal keys.

craig-i18n (P3.1, ADR-044)

  • The shared Mozilla-Fluent i18n engine, extracted from craig-web’s former i18n.rs so the BFF worker UI and the craig-intake edge (the public portal, Phase 3.2) consume ONE engine + ONE public catalog. Leaf-shaped: depends only on craig-state-bundle (the TerminologyContribution overlay type) + the Fluent stack (fluent-bundle/fluent-syntax/unic-langid) + axum (the middleware).

  • I18n — load (disk {locales_dir}/{lang}/*.ftl + the embedded public catalog + the jurisdiction terminology overlay, pre-resolved into a locale → key → Arc<str> table), translate (locale → default-locale → raw-key fallback), the encapsulating accessors has_message / default_locale / available_locales (the storage map is private), and the consuming builder negotiate_complete_locales_only (#1487, replacing #1332’s pin_negotiation_to_default — keeps in the negotiation set only the locales that resolve every key the default locale resolves; every negotiate_locale tier is membership-gated, so a signal for an incomplete locale falls through. craig-web applies it at boot, and with the product’s catalogs the set is en alone; a product catalog or a bundle’s terminology overlay completes a second locale; each locale left out is logged with its missing-key count; the messages table is untouched). TerminologyBootError is the ADR-034 §8 bilingual-coverage boot gate.

  • negotiate_locale — pure precedence resolver (?lang= query → caller candidates → Accept-Language → default), shared by the BFF hosts' middleware (whose candidate is the stored language choice) and the edge.

  • locale_layer — a session-less Axum middleware (reads Extension<I18n>) that negotiates + runs the request under the task_local! locale scope; with_locale / translate_current / current_locale back the Askama t() filter.

  • Embedded public catalog (catalog/{en,es}/public.ftl, include_str!; bilingual key-parity since #722, pinned by a crate test) — the source of truth for the report-/public- keys, folded into every load so a consumer with no on-disk locales/ (the stateless edge, ADR-017) still resolves both product locales. Note: this injects an es bucket into every consumer — craig-web negotiates only complete locales for exactly that reason (#1332, #1487, the ADR-044 amendments). The embedded bff.ftl also holds bff-language-name, each language’s own name.

  • test-util feature → I18n::for_test for downstream unit tests needing a controlled catalog.

craig-state-bundle (Plan T1.5)

  • Bundle contract crate (ADR-032 A6 + §2.1 + ADR-038 §3/§4): the StateBundle trait and the data types a jurisdiction’s reference data is expressed in. It holds no jurisdiction’s data and selects nothing: a deployment’s one bundle is the ConfigBundle loaded at boot from its configuration layers (craig-config-bundle). Tests may implement the trait with a fake.

  • StateBundle trait (name / jurisdiction_code / contribute / federal_mapping + the #1072 DEFAULTED pair subsidy_policy() / uas_codes() + the U-FMAP DEFAULTED fmap_rates() — effective-dated FmapRateSpec { effective_from, rate_percent } 'static strings, empty = "no FMAP data, consumers refuse to price FFP") + the #2056 DEFAULTED rate_class_policy() (plan D5, non-Option: product vocabulary) returning RateClassPolicySpec { family_home_precedence, family_home_default, settings } — the first applying (e)(3) category in precedence order picks a family row’s RateClass, else family_home_default; settings maps each congregate setting; the default TODAYS_PAYMENT_TYPES (pre-adoptive, else therapeutic, else licensed → foster care, else relative or kin → kinship, else foster care; the group homes, the residential settings and SIL) keeps every stored payment-type token) + the #2207 DEFAULTED pair business_timezone() → Option<&'static str> (an IANA tzdb name craig_common::BusinessClock parses — no chrono in this crate; None = no declared zone: business dates run on UTC and the AFCARS surface refuses jurisdiction-unregistered) / subsidy_writes_enabled() → bool (default false = every craig-financial subsidy write act refuses with 400 unsupported-jurisdiction; reads are never gated; a jurisdiction declares it only after meeting the ADR-053 § Amendment #1797 checklist) + the #2341 DEFAULTED legal_statuses() → Vec<LegalStatusSpec> (empty = no vocabulary; a consumer refuses any act that needs a status) — the per-bundle-identity mappings are trait methods (the D3 federal_mapping doctrine), not contribution fields.

  • BundleContribution 8-field aggregate: adapters (factory pairs, A4) / mock_routes (A5) / partner_types / seed_data: SeedContribution
    the Phase-2 axes theme: ThemeContribution (ADR-036) / terminology: TerminologyContribution (ADR-034) / compositions: CompositionContribution (ADR-035 §8) / field_ownership: FieldOwnershipContribution (ADR-037 §4, #634); grows additively.

  • Theme types (ADR-036 §2): TokenPair, ModeTokens, ThemeBranding, Palette { light, dark, high_contrast: Option, branding }, ThemeContribution { palette: Option<Palette> }; simple_statehouse_palette() / product_default_palette() / foundation_palette() (#1853 — "The Foundation" household palette from theme/foundation.toml, the one craig-portal DECLARES under ruling R3; same 36-role schema + HC layer; NOT the product default). These are the product palettes, the ones a bundle/theme.toml may name; a jurisdiction’s own palette is explicit values in that file. Palette VALUES are generated from theme/*.toml by build.rs at BUILD time — one PALETTES table, every entry emitted by the same codegen (toml/serde are build-deps only — no runtime toml in this crate). merge_high_contrast(base, overrides) is the one high-contrast merge: build.rs and the configuration loader both call it, and it refuses an override of a token the base mode lacks.

  • Theme RENDERER (ADR-036 §4 amendment, 2026-06-25 / #710): the pure materialize_theme_css(&ThemeContribution) → Result<Arc<str>, ThemeBootError> + ThemeBootError live here (the private render_*/validate_palette helpers stay module-private). Shared by craig-web + craig-intake so both emit byte-identical CSS; each host loads its bundle at boot + holds its own Arc<str> (host-local materialization).

  • Terminology types (ADR-034 §3): TerminologyCatalog { lang, source }, TerminologyContribution { catalogs }.

  • Field-ownership types (ADR-037 §4; #634 / ADR-076 D10): FieldSurfaceDecl { surface, fields: &'static [&'static str] }, FieldOwnershipContribution { surfaces } (the empty default = no governed surface), the single-sourced FOSTER_HOME_PORTAL_SURFACE ("foster_home_portal")
    FOSTER_HOME_PORTAL_FIELDS (the six table.column tokens — STATE placements.status, SHARED education_records.school_name / grade_level, health_records.next_due_date, foster_homes.phone / primary_contact) and foster_home_portal_surface() — the ONE construction site of the roster: a jurisdiction’s bundle/field_surfaces.toml names the surface key, and the roster stays product, so two jurisdictions can never disagree on it. A DECLARATION only (ADR-038 §3 pre-materialized primitive data): the owner classifications live in the jurisdiction layer’s field_ownership.toml, read fail-closed by the consuming service (craig-placement, craig_placement::field_ownership); no loader dependency enters this crate, so the BFFs / exchange / reporting inherit nothing.

  • Seed types: RateTableSpec { payment_type, age_min, age_max, daily_rate }, SeedContribution { rate_tables }.

  • Subsidy reference types (#1072): SubsidyPolicySpec { foster_home_approval_clock_days, err_qualifying_home_types, err_disqualifying_home_types, guardianship_residence_months } (#2056: the ERR pair of (e)(3) categories — a family anchor qualifies when one qualifying category applies and no disqualifying one does; it replaced err_qualifying_placement_types) (the #1069-U1 policy-seam lift — pure data; the derivations stay in craig-financial)
    UasCodeSpec { code, label, program, tanf_reportable, cohort_closed, effective_from, effective_until } — the effective-dated UAS payment-classification vocabulary. Dates are ISO &'static str`s parsed fail-fast by the consumer at boot (the `RateTableSpec.daily_rate doctrine — no chrono in the contract crate). Defaults (None / empty) = the bundle contributes no subsidy reference data; consumers fail closed.

  • Legal-status types (#2341, plan custody-episodes-doe-slds D1): LegalStatusSpec { token, label, custody_class }, CustodyClass::{InCustody, NotInCustody}, and LegalStatusVocabulary::resolve(Vec<_>) → Result<_, LegalStatusVocabularyError::{MalformedToken, DuplicateToken}>. A token is 1 to LEGAL_STATUS_TOKEN_MAX (16) ASCII uppercase letters or digits. parse(&str) → Option<LegalStatus> is total and exact (no trim, no case fold), and only parse constructs a LegalStatus. The check lives here so a bundle’s tests run it against its partner wire. craig-cases resolves the list at boot (craig_cases::legal_status) and refuses to start on an error; an empty list boots.

  • Person-identifier kinds (#1806, plan custody-episodes-doe-slds D5): the defaulted identifier_kinds() → Vec<IdentifierKindSpec> (default empty: a consumer refuses every identifier act), IdentifierKindSpec { token, label, format }, IdentifierFormat::Digits(n) (exactly n ASCII digits, no trim; accepts(&str)), and IdentifierKindVocabulary::resolve(Vec<_>) → Result<_, IdentifierKindVocabularyError::{MalformedToken, DuplicateToken, MalformedFormat}>, checked in declaration order: a token is ^[a-z][a-z0-9_]{0,15}$ (IDENTIFIER_KIND_TOKEN_MAX 16), declared once, with a format inside Digits(IDENTIFIER_DIGITS_MIN..=IDENTIFIER_DIGITS_MAX) (5..=32, so a mask to the last four always fits). parse(&str) → Option<IdentifierKind> is exact; IdentifierKind::accepts applies its format. craig-cases resolves the list at boot (craig_cases::identifier_kind) and refuses to start on an error.

  • Medicaid application gate (#1807, plan partner-auth-medicaid-application D6): the defaulted medicaid_application_identifier_kind() → Option<&'static str> (default None: ungated) names the identifier kind a Medicaid application submit needs, held live by the child through commit. craig-cases resolves it at boot against identifier_kinds() (resolve_medicaid_application_gate) and refuses to start on a kind the bundle does not declare (IdentifierKindBootError::UndeclaredMedicaidKind).

  • BootContext { transport: Arc<dyn OutboundTransport> } (Plan V — swapped from http_client).

  • 4 registries with duplicate-detecting from_bundles → BundleMergeError::DuplicateEntry { kind, key }: AdapterRegistry / PartnerTypeRegistry / FederalPartnerMappingRegistry / MockRouterRegistry (#2295 removed AuditCodecRegistry).

  • ErasedAdapterFactory = Arc<dyn Fn(&BootContext) → Arc<dyn ErasedAdapter> + Send + Sync>; ErasedCollectionFactory = Arc<dyn Fn(&BootContext) → Arc<dyn ErasedCollection> + Send + Sync> (#3188), the same shape for a collection; MockRouteFactory = Arc<dyn Fn() → MockRoutes + Send + Sync>, where MockRoutes is craig-partner-sdk’s: a partner mock’s router and, for a partner simulator, its `Arc<dyn PartnerSimulator> (stateless_mock(routes) wraps a mock that keeps no state). SimLoaded is what a people load answers on the mock-server’s simulator control surface (Partner simulators); the SimPerson it loads is `craig-partner-sdk’s too (#3200).

  • #3196: PartnerSet \{ adapters, collections, legs }, what craig-exchange boots on and the module host builds from a jurisdiction’s partner-set module (PartnerModules::partner_set()): each adapter and each collection as a factory under its interface token, and each Arc<dyn TriggerLeg>. PartnerSet::validate() → Result<(), PartnerSetError> builds nothing and refuses a leg or collection whose interface has no adapter in the set (LegWithoutAdapter, CollectionWithoutAdapter), a leg whose spec has a fault (IncoherentLeg), one (interface, leg) registered twice (DuplicateLeg) and two opening legs for one interface and stage kind (TwoOpeningLegs). PartnerSet::manifest(&BootContext) → Vec<InterfaceManifest> is what the set provides, per interface in token order: its dispatch class and its triggered-send and collection legs by token, read off the registered parts (each adapter and collection is built once to be asked), so no hand-written list can drift from them. craig-exchange boots on the set its layer’s modules provide: it validates it, logs the manifest, registers the adapters and collections the configuration lists and every leg. ssa_benefits: Option<(&'static str, SsaBenefitInquiryFactory)> is the SSA benefit screening’s inquiry under the kind token of the interface whose partner row holds the source’s endpoint, at most one; validate() refuses one whose interface has no adapter (InquiryWithoutAdapter) and the manifest lists it under that interface as ssa_benefits (SSA_BENEFITS_INQUIRY). person_index: Option<(&'static str, PersonIndexFactory)> (#3192) is the jurisdiction’s person index, held the same way: at most one, refused when its interface has no adapter (PersonIndexWithoutAdapter), and listed under that interface as person_index (PERSON_INDEX_INQUIRY). referral_legs: Vec<Arc<dyn ReferralLeg>> and returns: Vec<Arc<dyn ReturnLeg>> (#3193) are held as they are: a referral leg needs an adapter (LegWithoutAdapter) and a pair no triggered-send or referral leg has (DuplicateLeg), a return leg an adapter (ReturnWithoutAdapter) and a pair no other return leg has (DuplicateReturn); the manifest lists each interface’s referral_legs and return_legs. A triggered-send leg whose entity or stage is a Medicaid application is refused (ApplicationLeg): an application is referred by a referral leg, and the legs interface a module states its triggered-send legs through cannot name that kind.

  • PRODUCT_PARTNER_TYPES: [&str; 14] — the neutral product partner-type taxonomy (single-sourced).

  • Further defaulted trait items: search_schemes() (#1025), holiday_calendar() (#895) and outbound_triggers() (the outbound trigger matrix, OutboundTriggerSpec), each empty by default.

craig-config: rulesets (#3125)

  • craig_config::rulesets::{ruleset_dirs, ruleset_files, RulesetFile, FIXTURE_JURISDICTION_MARKER}: the one walk over the ruleset files of a layers directory (one directory per layer; every *.json directly under each, sorted; a FIXTURE-JURISDICTION marker tags a layer’s files). cargo xtask rules check and craig rules drift both walk through it, so the files the gate compiles are the files the operator compares with a deployment. A missing directory is an error, never an empty walk; a file that is not JSON stops it, named and not quoted.

craig-config-bundle

  • ConfigBundle: a jurisdiction’s reference data loaded from configuration (ADR-087, ADR-072 § Amendment — #2956). It reads the bundle/ directory of the layers a craig_config::ConfigSnapshot holds and implements StateBundle over them, so a consumer of the trait cannot tell loaded data from a test’s fake. name() and jurisdiction_code() both return the jurisdiction the snapshot’s manifest names.

  • ConfigBundle::check(&ConfigSnapshot) → Vec<BundleError> parses and validates every bundle file and returns every error it finds, each naming the layer, the file and the key (BundleError::{Read, UnknownFile, Invalid, Duplicate}). ConfigBundle::load(&ConfigSnapshot) → Result<&'static ConfigBundle, BundleErrors> refuses on any error. ConfigBundle::boot(&ConfigSnapshot) → Result<&'static ConfigBundle, BootError> loads and then installs the bundle’s business timezone into the process clock registry (craig_common::clock); every service and craig-seed boot through it, before the router is built, and a BootError refuses startup.

  • The trait’s data types hold &'static strings and slices, so a successful load leaks the parsed bundle once. A process loads its bundle once, at boot; tests go through craig_test_lib::config::bundle, which caches one bundle per layer per process.

  • BUNDLE_DIR (bundle) and BUNDLE_FILES are the directory and the closed set of file names. A file under bundle/ outside the set is refused, so a misspelt name never reads as "no data". An absent file means the trait’s own default for that item.

  • Checks are structural: the parse (each file is a deny_unknown_fields schema; enum tokens are snake_case), enum membership, duplicates, and the references between files (the Medicaid identifier kind must be a declared identifier kind; a terminology entry must name an existing .ftl under terminology/<lang>/ for its own language; a field surface must be one the product has a roster for; a theme gives a product palette’s name or explicit values, exactly one; a high-contrast override must name a token of its base mode; a bundle that declares subsidy writes must come with the subsidy policy, a UAS entry for every subsidy program, an administrative-authority family giving an office for every operation, and the eligibility ruleset, #1797). What a value means stays with the service that consumes it (FMAP ordering in craig-cases, UAS windows in craig-financial).

  • adapter_names() is the list bundle/adapters.toml gives. contribute().adapters is empty: adapters are code, and craig-exchange resolves the names against the partner modules its configuration layers hold (Partner modules).

  • cargo xtask config check-bundle <dir> runs check over a working copy (CLI Reference).

  • Deps: craig-common, craig-config, craig-financial-contracts (the authority family’s table reader), craig-reference, craig-state-bundle, serde, serde_path_to_error, toml, thiserror.

The bundle/ file map

A jurisdiction layer’s bundle/ directory holds one TOML file per kind of reference data. A file holding a list is an array of tables named for the file (, ); a map is one table ([federal_mapping]); settings.toml is top-level keys. fixtures/config/testonia/bundle/ carries one file of every kind and is the worked example of each schema.

File Trait item Absent means

settings.toml

business_timezone, subsidy_writes_enabled, medicaid_application_identifier_kind

no declared zone, false, no gate

adapters.toml

the adapter names craig-exchange registers

no adapters

partner_types.toml

partner types added to the product taxonomy

the 14 product types; a product token in the file is a duplicate error

federal_mapping.toml

federal_mapping

empty

rate_tables.toml

contribute().seed_data.rate_tables, order kept

empty

theme.toml

contribute().theme: a product palette’s name, or explicit token values per mode

the product default palette

terminology.toml and terminology/<lang>/*.ftl

contribute().terminology, order kept

no overlay

field_surfaces.toml

contribute().field_ownership (surface keys; the rosters are product)

no governed surface

compositions.toml

contribute().compositions

none

subsidy_policy.toml

subsidy_policy

None

rate_class_policy.toml

rate_class_policy

TODAYS_PAYMENT_TYPES

uas_codes.toml, fmap_rates.toml, legal_statuses.toml, identifier_kinds.toml, search_schemes.toml

the same-named methods

empty

holidays.toml

holiday_calendar

empty

outbound_triggers.toml

outbound_triggers

empty

Consumers refuse what they cannot do without data: a bundle with no FMAP rates refuses an eligible determination, one with no holiday calendar refuses a holiday-skipping window, and one with no AFCARS crosswalk boots while AFCARS generation answers crosswalk-absent.

craig-authority-evidence (#3125, ADR-074, ADR-088)

  • check_pair(ruleset, evidence) → Result<EvidenceReport, EvidenceCheckError> (async): the offline evidence check of an administrative-authority family document. It parses the document’s declaration and the evidence file, checks one against the other, evaluates every evidence key through the rules engine against the document, judges every outcome against the evaluated floor, and reports sha256(ruleset || "\n" || evidence).

  • reason_names_digest(reason, digest): whether a promote reason quotes that digest as authority-evidence:<hex>.

  • Two callers, so they cannot disagree: cargo xtask authority-evidence (the gate over the shipped pairs) and craig rules promote, which refuses a thin-corpus promote of the family unless its reason quotes the digest it recomputes.

  • Deps: craig-auth (the office roles), craig-financial-contracts (the declaration and evidence types), zen-engine.

craig-partner-testonia-registry (#3196)

  • The reference partner (ADR-089): the resident registry of the fixture jurisdiction, adapter kind testonia_registry, identifier kind tid. TestoniaRegistryAdapter (RegistryEntry out, RegistryAck back, TestoniaRegistryError), thirteen legs over that one record type (legs::legs(), RegistryLeg, each leg a named constant such as RegistryLeg::STAGE_OPENED) covering every resolve rule, entity and scope, and partner_set(). An entry about a residence carries the stay (RegistryStay: its dates and the token of its latest status row) exactly as the stage view held it, so a test of the dispatch host can see in the record what the host read when it assembled it. Behind mock: mock::RegistrySimulator, a closed world of residents keyed by person id (enroll, withdraw, held), its routes() and the control routes _sim/residents/{person_id}. The registry’s benefit desk is the reference SSA benefit inquiry (RegistryBenefitInquiry, src/inquiry.rs): registered in partner_set() under the registry’s interface, non-authoritative by construction, its wire one JSON question and answer at <endpoint>/benefits, which the simulator answers for the resident carrying the identifier. Its school roll is the reference collection (RegistrySchoolRoll, leg school_roll, src/collection.rs): one JSON document at <endpoint>/roll, each pupil whose row echoes a person id reported as PartnerReport::Education, the rest counted, and 204 for nothing published; the simulator serves the roll a test publishes (publish, _sim/roll).

  • A development dependency only: no service or tool links it, and no build of the mock-server carries its mock. Its tests hand mock::routes to craig_mock_server::spawn_for_routes. Deps: the specification’s crates (craig-exchange-contracts, craig-exchange-transport, craig-state-bundle, craig-validation).

craig-test-lib

  • TestConfig — env vars with devstack defaults (from_env(), token_url(), realm_url()); KeycloakTokenProvider (per-username token caching, refresh within 30 s of expiry; #1163 adds a transparent cross-process file cache at the workspace root — .token-cache.json + the .token-cache.mints.log mint counter, both gitignored/0600 — so a battery mints O(roles) ROPC grants instead of O(tests); invalidated automatically on devstack restart via the recorded token_url; any file failure degrades to the pre-#1163 per-process mint). service_token(config, client_id, secret) (#1880) — a devstack service client’s client_credentials bearer from token_url(): the one mint behind every suite’s service-principal helper and portal_subject::portal_channel_token; a refusal is an error naming the client, the status and the body.

  • shared_http_client() — a reqwest::Client for integration tests (30 s timeout, pool_max_idle_per_host(4)), built once by TestHarness::new() and Arc-cloned across all `ServiceClient`s (one connection pool, not per-client).

  • ServiceClient — generic Bearer-token HTTP (get/get_with_query/post/put/delete/get_raw/ post_multipart/get_bytes); ApiResponse<T> { status, body: Option<T>, raw }.

  • Typed clients (RulesClient/CasesClient/PlacementClient/ExchangeClient/FinancialClient/ ReportingClient/SecurityClient/IntakeClient) — all take reqwest::Client as the first arg.

  • TestHarness — full fixture sharing the connection pool: admin_*client() / supervisor*client() / caseworker*client() / readonly*client() / county_director*client() / regional_director*client() / state_office*_client(); built-in creds (admin/jane.doe/bob.smith/carol.reader/dana.county/rita.regional/sam.state); pinned UUIDs ADMIN_SUB / SUPERVISOR_SUB / CASEWORKER_SUB / READONLY_SUB / COUNTY_DIRECTOR_SUB / REGIONAL_DIRECTOR_SUB / STATE_OFFICE_SUB (use these when filtering by worker).

  • EventCollector (wait_for_event(predicate), events()); builders (rand_name(prefix), RuleSetBuilder, PersonBuilder, FosterHomeBuilder, PlacementBuilder — since #2018 PlacementBuilder::new(episode_id), an arrangement inside an existing removal episode). #2018 episode fixtures: removal_episodes — ensure_episode / ensure_episode_removed_at (get or create the child’s live episode on the caller’s connection) and fixture_episode / fixture_episode_removed_at (the same against the devstack craig_placement database), raw rows with no craig-cases check; the API-level given::given_removal_episode; and EpisodesClient (the episode routes, with record_exit / correct_exit / retract_exit / record_historical_episode since #2019; the harness’s <role>_episodes_client()). Gotcha: global-property tests race under nextest concurrency — sequence them in ONE test. spawn_for_routes() from tools/craig-mock-server is the harness a partner crate’s round_trip tests stand their own mock in; spawn_for_test() mounts no partner.

  • concurrent — the concurrent_fire_* family (see the module doc’s when-to-use table)
    wait_for_blocked_behind(pool, blocker_pid, timeout) (#1187): the pid-scoped deterministic wait for two-phase lock-interleave tests — polls pg_blocking_pids until a backend parks behind YOUR transaction’s pid, returns a typed BlockedWaitError::Timeout instead of panicking. Never use a db-wide "any ungranted lock" poll: it false-triggers on sibling tests under the 8-wide integration profile (test protocol: the ADR-060 implementation plan § Tests).

  • pools (#2133) — close_until_empty(&PgPool): re-runs close() until the pool’s size() is zero. sqlx 0.8’s Pool::close can return while one connection, whose release was mid-ping, lands back in IDLE and stays open for the pool’s life. Use it before any backend census (the rewrite-fence suites' exclusive lease); waiting for the backend to leave pg_stat_activity stays the caller’s job.

  • list_fence (#1916) — the list-scope fence rig the services' list_scope_fence_tests drive their REAL list handlers with: FixedScope(ListScope) (an AuthzEngine double that admits every row check and answers one fixed list scope), unreachable_db() (a lazy DbPool over TEST-NET that never dials, so an arm that wrongly reaches the query blocks on the acquire bound instead of passing), custom_scope() (the #1407 Custom payload no decoder claims) and admin_claims(). The handler AppState is craig_api::detached_test_state, behind craig-api’s test-util feature, which each consumer enables in its own dev-dependencies.

  • rule_set_fixtures (#2284) — craig-rules rule_sets rows a devstack test writes by direct SQL, kept in the #1556 snapshot protocol. seed_rule_set and peer_write(PeerWrite) commit the row change and its snapshot in one transaction, with no API call and no event, so the #1188 / #1217 peer-write semantics hold. The OwnedRuleSet guard (adopt for an API-created row) deletes the row’s evaluations, snapshots and row in one transaction on drop, also while a failing test unwinds. Probes: has_census_gap, residue.

  • template_db (#1162) — migrated-template scratch databases: migration_set_fingerprint(&Migrator) (name suffix that changes exactly when the migration set does), ensure_template(admin, base, migrator) (idempotent, cross-process-safe via Postgres-native coordination, sweeps stale-fingerprint siblings), create_from_template(admin, new_db, template) (file-copy clone with a bounded 55006 retry). Replaces per-test full-migration replay in every migrated-scratch harness (cases keyed harness, security authz/archive harnesses, rules retention tests); per-test isolation + per-test field keys (ADR-048 §D6) unchanged. Full protocol: the module docs.

  • inproc (#3119) — the core of an in-process service suite: DbTemplate and ThrowawayDb (a database cloned from a service’s migrated template, dropped with the value), shipped_engine(jurisdiction) and shipped_authz_source(jurisdiction) (the real authz engine and its source over the pinned layer’s rulesets; the module has no allow-all engine), refusing_peer() (a base URL nothing listens on), serve(router) (a loopback listener, returning the base URL) and outbox_events(&pool, event_type) (staged EventEnvelope`s in staging order). `inproc::allow_all_census is the scanner behind no_inproc_suite_uses_an_allow_all_engine (testing reference § The in-process tier).

Client SDKs + browser library

  • TypeScript SDK — @craig/intake-sdk (sdks/typescript/): IntakeClient (submitReport / checkStatus, JWS auto-sign), ReportBuilder, loadSigningConfig / canonicalize / signDetached, IntakeError. Dep jose ^5; shared vectors sdks/test-vectors/canonical.json. Person entries are typed (#3180): Child / Adult (the Rust SDK’s fields, the wire keys), built with child() / adult(), which fill the flags; PRINCIPAL_RELATIONSHIPS / COLLATERAL_RELATIONSHIPS and their code types; and withRelationshipToCaretaker(person, { designation, code }), which writes the code and its designation together.

  • Python SDK — craig-intake-sdk (sdks/python/): async IntakeClient (httpx), ReportBuilder, load_signing_config / canonicalize / sign_detached, IntakeError. Deps httpx / joserfc / cryptography. Person entries are typed (#3180): the Child / Adult dataclasses (the Rust SDK’s fields, the wire keys), the PrincipalRelationship / CollateralRelationship literals, and with_principal_relationship / with_collateral_relationship, which write the code and its designation together and raise ValueError for a code the named list does not hold.

  • Browser signing — services/craig-web/static/js/craig-sign.js (~5 KB ES module, zero deps): generateKeyPair / exportKey / loadPrivateKey / canonicalize / signPayload (WebCrypto ECDSA P-256). All four implementations share the same canonicalization contract (craig-signing).

Edit this page · latest