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
-
ApiErrorenum — 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) andFrom<anyhow::Error>(internal anyhow paths). New code should prefer typedthiserrorerrors + aFrom<TypedError> for ApiErrorimpl over routing throughanyhow. -
BadRequest+Conflictcarry atype_url: Option<&'static str>populated bybad_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_detailis the one renderer for a deserialize failure’s client detail or log text — the path plus serde’smissing/unknown/duplicate fieldtemplate orINVALID_VALUE, never the value (RedactedJsonError,deserialize_redacted,from_slice_redacted).from_slice_redacted_keepingalso keeps a caller’s own fixed refusal text verbatim, on an exact match only (#2335: craig-intake keepsUnsanitizableText’s, so a refused free-text field names its cause). `problemreads an upstream refusal bounded (read_bounded→BoundedBody,BODY_CAP64 KiB) and lifts adetailonly from a validated RFC 9457 document (UpstreamProblem,lift/lift_str, bounded toDETAIL_CHARS);log_droppedlogs a dropped body’s shape only.extract::{Path, Query, Form}joinextract::{Json, Multipart}as drop-in wrappers whose rejection is a value-free problem document; theirpath_rejection_detail/query_rejection_detail/form_rejection_detailalso back craig-bff’sextract::{Path, Query, Form}family, which keeps the BFFs' plain-text shape (PlainRejection;Query::try_from_urifor 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’sparse_upload_multipart, craig-intake’s attachment proxy and craig-bff’suploadrelay — 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::Mutexfor short sync critical sections (no poisoning);tokio::sync::Mutexwhen the lock crosses.await;std::sync::Mutex/RwLockare forbidden in CRAIG-authored code (preferparking_lot). -
write_idle(#1951) — the server-side write-progress bound:bounded(TcpListener) → BoundedListener(production budget;bounded_with(listener, budget)is the test seam) foraxum::serve, andWriteIdleIo::new(stream, budget)for axum-server acceptors (intake’s TLS path). A connection whose writes make no progress forceiling::RESPONSE_WRITE_IDLE_BUDGET(120 s) ends withTimedOut;BoundedListenerkeepsConnectInfo<SocketAddr>. -
roles_claim::RolesClaimPath(#2684): the validated roles-claim path (CRAIG_IDENTITY_ROLES_CLAIM_PATH, defaultrealm_access.roles) and the one reader the JWS, introspection and BFF paths share;settings::IdentitySettingsloads it, failing boot on a malformed path. -
owner_only(#2761): owner-only, durable file writes (ADR-085 D12’s writer).write_durable(target, bytes)stagesbytesin a fresh sibling.<file name, at most 64 bytes>.<uuid v7>.tmpintarget’s directory, created exclusively (`0600on Unix),sync_all`s it, renames it over `targetand 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; aStagedFiledropped unpublished removes its sibling (best-effort), and one left by a crash stays (no sweeper).ensure_private_dir(dir)createsdir0700, 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’sApiServer, 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 toSwaggerUi::new),SWAGGER_UI_CSP, and theswagger_ui_cspmiddleware, which sets that policy on a response to/swagger-uior 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 toMAX_PER_PAGE = 500); derivesDeserialize+IntoParams.PageResponse<T> { data: Vec<T>, page, per_page, total: i64 }— derivesSerialize+ToSchema. -
ServiceSettings— loaded fromCRAIG_<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 readsettings.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 fromFinancialSettings; 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);Debugredactsdatabase_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 intoServiceSettingsassettings.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, noDefault). The first three implementDefaultmirroring their serde defaults;retention_archivestays on the core (security + rules + exchange consume it). -
supervisormodule (#1229 — moved from craig-api, which re-exports every name): the ADR-061 worker supervision + liveness registry (Supervisor,WorkerHealth,shutdown_signal, theWorkerCheckEntryhealthz wire mapper). Lives HERE so the DB/MQ-less craig-web BFF can supervise its workers without sqlx/lapin; panic text comes fromcraig_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 viatracing-subscriber. -
rate_limit::RetainingIpLimiter(#1136) — per-IP keyedgovernorlimiter with amortized key retention: every 4096thallow()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-exportsgovernor::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 onFinancialSettings(settings.financial.subsidy_review_sweepsince #998, nests asCRAIG_FINANCIALSUBSIDY_REVIEW_SWEEP*; all default off).metrics::subsidy_review_sweep— run/leg counters, backlog gauges, duration histogram, last-success timestamp, lease skips.problem_typesgainsSWEEP_RUN_STATE(+SWEEP_PREVIEW_EXPIRED/SWEEP_TOKEN_ISSUEDsince #1939;SWEEP_ALREADY_RUNNINGwas RETIRED by #1939 — a held lease is thesweep_executejob’swaiting_for_lease, never an HTTP 409). -
SubsidyErrSettings(#1069 M2) /SubsidySgSettings(#1070, ADR-056) — the enrollment consent knobs onFinancialSettings(settings.financial.subsidy_err/.subsidy_sgsince #998, nesting asCRAIG_FINANCIALSUBSIDY_ERR*/CRAIG_FINANCIALSUBSIDY_SG*; both{ enabled: bool }, default OFF — enabling is the operator’s recorded consent to the ⁂ #1073 money-policy readings). ONEsubsidy_sgknob covers the sg AND nrsg family and gates the create arms
the witnessed activation ONLY — existing agreements' lifecycle (generator, ALL transitions incl. the correctiveguardianship_finalized, reviews, sweep) is deliberately grandfathered.problem_typesgainsCLOSED_PROGRAM(#1070 — closed-cohort creation refusals naming the closure date + the #1071 import path). -
problem_typesgainsSUBSIDY_AUTHORITY_NOT_READY(503 — the detail is ONE closed reason token),SUBSIDY_AUTHORITY_UNCONFIGURED(403),SUBSIDY_AUTHORITY_EVALUATION_FAILED(500) andSUBSIDY_APPROVAL_CONTEXT_STALE(409) — the administrative-authority fail-closed map (#1787, ADR-074 decision 11).ApiError::internal_typedis the FIRST typed 500: a NAMED invariant breach with a client-safe detail rendered verbatim (the redacted catch-allinternalstays the default).metrics::authority_surface::record_verified— theauthority_surface_verified{jurisdiction}gauge, the operator alert for the human approval acts' 503. -
problem_typesgainsADMIN_UNITS_UNAVAILABLE(503 — the detail is ONE closed reason token:pending/stale/unreachable/forbidden/malformed/unconfigured), the engine’s refusal when a ruleset consultsclaims.admin_unitsand the worker’s units are not ready (#1903, ADR-077 D3);metrics::admin_units_snapshot::record_verified— theadmin_units_snapshot_verified{jurisdiction}gauge (theauthority_surface_verifiedshape; both ride ONE gauge helper).ServiceSettingsgains the sharedsecurity_base_urlleaf (lifted fromPlacementSettings, env names unchanged) andadmin_units: AdminUnitsSettings { max_age_secs: 300 }(CRAIG_<SVC>ADMIN_UNITSMAX_AGE_SECS; boot refuses 0). -
problem_typesgainsINVALID_KINSHIP_HOUSEHOLD(409 — akinship_household.existingchoice names no household) andCAREGIVER_BINDING_OVERLAP(409 — one person’s bindings on one caregiving unit never overlap), and losesARRANGEMENT_HAS_BINDINGS(a binding keys the kinship household, not the arrangement, so no binding blocks a retract) (P-B2 U5, #2058). -
problem_typesgains five 400 types for refusals a handler makes on a well-formed body (#3073;VALIDATION_FAILEDstays the 422 of body-shape validation):DUPLICATE_ENTRY(a list names one identity twice),SCREENING_COHORT_HASH_MISMATCH(a screening stage’scohort_hashis 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) andINVALID_SIGNER_JWK(a partner signer key that is not exactly a P-256 public key). -
problem_typescarries the collection run’s two (#3188):COLLECTION_UNDECLARED(400, fieldleg: the deployment holds no collection for that interface and leg) andCOLLECTION_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 jobrefused_at_start, a token whose meaning #3190 widens from a consent knob read off to any precondition an attempt reads at its start.ExchangeSettingsgainscollections, the twin oftriggers. Since #3196 both are anInterfaceConsents: a map from interface token to itsenabledknob, with no field per partner, loaded from the same variables (CRAIG_EXCHANGETRIGGERS<INTERFACE>ENABLEDand theCOLLECTIONStwin).enabled(interface) → boolis false for an interface with no variable;interfaces()lists the ones a variable names, which craig-exchange checks against its build at boot. Since #3190ExchangeSettingsalso carriescollection_schedule(CollectionScheduleSettings { interval_seconds },CRAIG_EXCHANGECOLLECTION_SCHEDULE__INTERVAL_SECONDS, default 0 = no schedule): a group of its own, because theCOLLECTIONSgroup’s keys are interface tokens. -
problem_typesgainsIVE_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) andIVE_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, planive-determination-inputsU2). -
problem_typesgainsSAFETY_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) andSAFETY_FACT_UNANSWERED(422 — a declared fact has no answer; the detail lists the missing keys) (#3104). -
problem_typesgainsRULESET_MOVED(409 — an evaluate’sexpectnames a(rule_set_id, revision)other than the active one; the detail names the active identity, no zen run, no audit row) (#2325, planive-determination-inputsU1b). -
SubsidyImportSettings(#1071, ADR-057 D12) — the conversion-import gate onFinancialSettings(settings.financial.subsidy_importsince #998, nesting asCRAIG_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, planbackpay-import-pathG-B) — the below-floor backpay consent gate onFinancialSettings(settings.financial.subsidy_backpay, nesting asCRAIG_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 atbackpay_finalizeattempt 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’sbundle/settings.tomldeclares an IANA name (StateBundle::business_timezone()— the Georgia layerAmerica/New_York, the Texas layerAmerica/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)(Nonewhen undeclared — the AFCARS surface’sjurisdiction-unregistered),from_iana(&str)(#2207 — a tzdb name → clock,Noneotherwise),today(),date_of(DateTime<Utc>),timezone_name(),tz()(#895 — the zone itself, for local wall-clock arithmetic).Copy; resolvetoday()ONCE per unit of work and thread theNaiveDatethrough 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 throughConfigBundle::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-zonesfeature, 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_layerscopes the active jurisdiction’s clock in a task-local per request, aswith_localedoes for|t.format_date, the episode removal and exit prefills and the historical arrangement days render an RFC 3339 instant as itsdate_ofon that clock; a date-onlyYYYY-MM-DDis never projected. Outside the scope (a handler called from a unit test) the clock is the UTC fail-safe.
-
-
export_window(#2119, planafcars-pipeline-sourcesD3) — the window rule every AFCARS source projection applies once:check_export_window(clock, from, to, as_of, now)admitsfrom/toonly as local midnights withfrom < toand anas_ofat leastEXTENDED_REQUEST_CEILINGin the past, returning anExportWindow(the instants plusfrom_d,to_d,period_end) or aWindowFault { 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, planinvestigation-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-windowruleset 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 fromclock.date_of(received_at)counting dates that are not a skipped weekend (theWeekdaysunit never counts one) nor a skipped holiday, day one = the first counted date≥ d0(day-one) or> d0, to daycount; 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_holidaysREQUIRES calendar coverage ofd0 ..= 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);DateOutOfRangefor out-of-range arithmetic / the2·count + 366visited-date cap. Consumed by craig-cases (MR-E) with the bundle-suppliedStateBundle::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_hashare OIDC id-token-only claims (#813);JwksProviderverifiestypagainst a configurable expected value (default"Bearer"; the craig-web id-token verifier sets"ID"viawith_token_type). The token on the wire (under a BFF relay, the service principal) is read only through the bearer accessorsbearer_sub,bearer_username,bearer_email,bearer_name,bearer_roles,bearer_has_role(role),bearer_is_service,bearer_is_portal_principalandbearer_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. Alsochannel(),is_portal_channel(),service_id(),service_role_id(),has_scope(scope),require_scope(scope), andacting_worker(), which returns the view below. -
ActingWorker<'_>(#2522): theCopyview of who acted, the lifted actor under a relay, else the bearer. Readsusername(),email(),name(),roles(),has_role(role),is_service(),is_portal_principal(); the role gatesrequire_role,require_any_role,require_caseworker_or_above,require_supervisor_or_above,require_admin,require_eligibility_worker_or_above,require_icpc_coordinator_or_above; andclaims(), 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 rawsubwhen the claims name no actor, so a log line never fails.ActingWorker::sub()is removed (#2740, ADR-085 D3): a raw use readsClaims::actor(),Claims::worker_subject()orlog_id()instead. -
The acting principal (
actormodule, #2740, ADR-085 D3), re-exported at the crate root.ActorisWorker(Subject)orService(ServiceName); a service never has a subject.-
Subjectwraps a worker’s UUID (uuid();DisplayandSerializeare the bare UUID’s). -
ServiceNameis 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)isNoneotherwise. It is not craig-reference’s enum of the core services:craig-intake,craig-webandcraig-cliare 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.Serializewrites it as a JSON string;Actor::parse_encoding(s)inverts it and accepts only the canonical forms.subject()andservice()project the two variants. -
Claims::actor()reads the acting identity (the lifted actor under a relay, else the bearer, asacting_worker()does) by an ordered rule: its ownservice:<name>role (today’s IdP service token) isActor::Service(name); else a UUIDsubisActor::Worker; else asubequal to itsazpthat is a valid name isActor::Service(sub)(the internal issuer’s bare service principal, whosesubis its client id); else a typed 500. The first rule never readsservice_id()’s `azpfallback, since a worker token carries anazptoo. -
Claims::worker_subject()is the subject for an operation that acts for a worker. A service is a 403 with the problem typeworker_required(problem_types::WORKER_REQUIRED), never a 500. -
Claims::legacy_service_uuid()isSomeonly when the actor is a service and the actingsubparses 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 asub. -
Claims::test_service(name)(test-fixturesfeature): a bare service principal in the internal issuer’s shape (plan ITI § C):sub=azp=name, noservice:role, no user fields. Itsactor()isActor::Service(name).
-
-
ClaimsBuilder(test-fixturesfeature only): the one way a test outside craig-auth builds aClaims;actor(..)lifts a second token as a verified actor would be. (craig_test_lib::jwt_mutation::ClaimsBuilderis unrelated: it builds JWT claim JSON.) -
Construction rule: production
Claimscome only from craig-auth’s JWT, introspection and actor-token decoders.Claimshas no publicDeserialize(#2684), and the introspection body typeIntrospectionResponseand itsinto_claims()are crate-private (#2526);crates/craig-auth/tests/decode_surface.rspins their visibility. Thetest-fixturesfeature 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). -
Claimsroles come from the configured roles-claim path (#2684), never a fixedrealm_accessfield.
craig-authz (ADR-023 / ADR-024)
-
AuthzEnginetrait (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 surfacingAuthzErrorso craig-rules' bootstrap fallback can distinguish source-attestedPolicyMissing(the ONLY admitting class) from a real deny or a runtime fault (incl. the #786PolicyLoadrefresh-fault variant → 500); the defaults report an opaque non-admitting deny (test doubles inherit unchanged), and the typed list seam surfaces a miss asErr(PolicyMissing)where the untyped path keepsOk(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 (ZenAuthzEnginebuilds the input viabuild_check_input(…, Action::Update)+ injectsfield/field_ownerintoresource.attrs) read through a NEW disjointfield_permissionoutput token, socheck/auto_scope_listare untouched. -
ZenAuthzEngine— concrete impl overzen_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, computesResourceType × Jurisdictioncoverage.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 (notcfg(test)).ZenAuthzEngine::set_units_sourceinstalls the production source (craig_bootstrap::admin_units::SecurityUnitsSource); the engine DEFAULTS toStaticUnitsSource::not_ready(Unconfigured).CachedRuleset.consults_unitsis recorded once at compile from the JDM census;units_foranswers[]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 503ADMIN_UNITS_UNAVAILABLE(never[], neverFieldPermission::None, passed through by the untypedauto_scope_list). The evaluation input’sclaims.admin_unitsis ALWAYS a JSON array. -
calling_service(&Claims) → Result<Actor, ApiError>andaudit_actor(&Actor) → AuditActor(#3116) — the audit actor a publisher states for the principal its handler holds.calling_servicereads the bearer’sservice:<name>role only (never a relayed worker, neverazp) and is a 403 for any other token;audit_actornames a worker by subject and a service byservice:<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> }. -
Actionenum —Read | List | Create | Update | Delete | Approve(snake_case). -
ResourceTypeenum — one variant per protected resource across every service (snake_case,IntoEnumIteratorfor the boot coverage check; the enum incraig-authz/src/types.rsis 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).AdminUnitsis 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:SomeiffCustomcarries exactly{"binding":"caregiver"}; every other scope or payload isNoneand the caller falls back toApiError::custom_list_scope_unsupported()—Customstays fail-closed at every boundary that does not call it. -
FieldPermission—Read | Write | Propose | None(ADR-037 §3; the per-field analogue ofListScope;Propose= a non-owner’s effective permission on a shared field underAction::Update). -
CoverageWarning::Missing { jurisdiction, missing }— boot signal; bails whenCRAIG_<SVC>__AUTHZ_REQUIRE_FULL_COVERAGE=true. -
RulesetSourcetrait +InMemoryRulesetSource(tests) +craig_rules_client::RulesClient(prod).RulesetCache=HashMap<name, CachedRuleset>behindtokio::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 iscraig_bootstrap::OutboxAuditSink(one-shot outbox tx, fire-and-forget,warn!-only failures).NoopAuditSink(explicit discard) +RecordingAuditSink(test assertions) ship alongside. The engine stagesauthz.cache_misson every source-attested miss (attributed:sub/is_service/service_id; never onPolicyLoadfaults) andauthz.cache_refreshedon 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_refreshedenvelope 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) →checkForbidden (PolicyMissing),auto_scope_listListScope::Denied(untyped path; the typed seam surfacesErr(PolicyMissing)),resolve_field_permissionFieldPermission::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(…)— bindsruleset.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 withinclude=content, whichGET /v1/rules/setsleaves out by default since #3170);get_by_name(name) → Option<FetchedRuleset>(404 → None). Implementscraig_authz::RulesetSource. -
evaluate(&EvaluateRequest, &RelayedAuth, timeout) → Result<EvaluatedRuleset, EvaluateError>(hard-checks U2) —POST /v1/rules/evaluateunder ACTOR-RELAY auth (the inboundAuthorization+X-Craig-Actorpair forwarded verbatim), per-request hop-budget timeout, strict decode (output+rule_set_revision+evaluation_idall required — never a defaulted verdict; #1627 adds the tolerantrule_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) isEvaluateError::Transport— the callers' fail-closed 503; only a body read in full that does not decode isMalformed, carrying theserde_json::Error. #1623:with_metrics_caller(caller)(builder-style) routes evaluate’s send throughcraig_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), insertsClaimsinto extensions);auth_middleware()Tower fn;require_role(claims, role) → Result<(), Response>. Every 401 the middleware answers is the RFC 9457application/problem+jsondocument with the sharedunauthorizedtype and a fixed, value-free detail (#2920), the body each service’s OpenAPI documents for it.
craig-db
-
DbPool— wrapssqlx::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, orRewriteFenceHeld { holders: Vec<FenceHolder> }when the eager probe finds the field-scheme rewrite fence held —crates/craig-db/src/rewrite_fence.rs;connect_lazy_withkeepssqlx::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 viaverify_schema, below);snapshot() → PoolSnapshot;probe_acquire() → ProbeSample. -
DbPoolOpts { max_connections: u32, idle_timeout: Duration, statement_timeout_ms: u64, rewrite_fence: RewriteFence }(RewriteFence::ParticipantbyDefault— every pool connection takes the shared session advisory lockSCHEME_REWRITE_LOCK_SQL_KEYinafter_connect;Rewriteris reserved for the #1399 U2b tool). -
Pool observability (#1160):
PoolSnapshot { max, size, idle }(cheap atomic reads for the scrape-timedb_pool_connections_*gauges) andProbeSample { wait, error }fromprobe_acquire— one timed acquire-and-release;PoolTimedOutis the session-exhaustion signal, catching the server-ceiling case (size < maxwhile 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 sacquire_timeoutremains 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_gategives 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_migrationsexecutes 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-019after_connecttimeout hook fires only on new physical connections, so a migration’s plain session-scopedSET(e.g.SET statement_timeout = 0) would otherwise serve traffic for up tomax_lifetime. Convention for migration authors: useSET LOCALfor per-migration overrides so one migration’s setting cannot bleed into later migrations in the same run (cargo xtask validate-migration-constraintsreports plainSET statement_timeoutsites). -
Schema state machine (ADR-063, #1306,
schema_statemodule): the ONE classifier both process modes consume. Pure coreclassify(&[AppliedRecord], &[EmbeddedMigration]) → SchemaState(Dirty | ChecksumMismatch | Diverged | Behind | Ahead | Exact, deterministic precedence;Behind ⇒ applied ⊊ embeddedby construction)
embedded_up_migrations(&Migrator)(down-files filtered, matching sqlx apply semantics). Consumers onDbPool:verify_schema(migrator, FloorCheck, gate_hint) → Result<SchemaVerified, SchemaVerifyError>(serving boot: plain-SELECT inspection, no DDL, no advisory lock, SELECT-only-role safe;Aheadtolerated only while theschema_compat_floortable’smin_required_version ≤ max(embedded)) andapply_by_verdict(migrator) → Result<ApplyOutcome, SchemaApplyError>(migration gate:Exact/Aheadno-op,Behindapplies viarun_migrations, everything else refuses). Only SQLSTATE42P01maps to Behind-from-zero; every other DB error passes through typed. Theschema_compat_floorsingleton 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.tomlbans a directlapindependency 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;auditisNoneonly on an envelope decoded from a message that carried none, or on a capture of such a delivery.auditis omitted from the wire whenNone, and its decode never fails the envelope: any JSON underauditis 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, orNamed, built only byAuditActor::named(text), which classes a UUID in any spelling asSuband empty text orsystemasSystem), 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_wiredecodes per field and marks a header whose field it replacedis_degraded(); each enum’sUnknownvariant 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 eachResourceTypeto theAuditResourceof the same token (From). A DLX wrapper and a_parkcapture 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). Everypublishand 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 asPublishError::Unpublishable(Unpublishable)(sizes only, never a value). 12 MiB is an application policy under RabbitMQ 4.2’smax_message_size(16,777,216 payload bytes, inclusive, framing not subtracted), whichdevstack/rabbitmq/rabbitmq.confpins; 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 onlyChannel::wait_for_confirmsdrains, 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 mostMAX_IN_FLIGHT_CONFIRMS(1024) unresolved confirms, awaited or timed out, and a send past that is refused unframed asPublishError::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 byAMQP_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 setbasic_qosprefetch 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_errorstamp
InboxError::HandlerPanicked), counted bydlq_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: 'staticon all subscribe/inbox handler bounds (pre-1.0 breaking, #1203). Every queue is declaredx-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 aterror!("operator action required") while the supervisor keeps retrying. -
stage_event(tx, envelope) → Result<(), StageError>— transactional-outbox staging (ADR-022 §D3.1): serialize once withtrace_contextomitted, compute the effective post-JSONBbyte length (accounting for scientific-notation integralf64values that Postgresjsonbexpands to plain decimals), verify the routing key (⇐ 255UTF-8 bytes) and effective body (⇐ MAX_STAGE_BYTES, reserving 1130 bytes below the 12 MiBMAX_PUBLISH_BYTESapplication publish policy for drain-time W3C trace injection) viacheck_envelope_bounds(2827), andINSERTthe envelope in the caller’s tx. Returns the typedcraig_mq_error::StageError(re-exported ascraig_mq::StageError, includingStageError::Unpublishablewhen 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;auditis 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)): anAuditActionvariant, anAuditResourcevariant, anOption<Uuid>expression and anAuditActorexpression (AuditActor,SubandSystemare 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 apub(crate) async fn publish_x(tx, a, b) → Result<(), StageError>staging throughstage_json_eventwith the invoking module’sconst SOURCE. The six convertedevents.rsmodules (cases, exchange, financial, placement, reporting, security) are macro-generated except the recorded hand-written residue (runtime-computed routing keys, conditional key omission, apubwrapper a bin needs); composition’s jurisdiction-suffixed invalidation and the other staging call sites (payment_events.rs, theupload_finalizers.rstrio, rules) stage throughstage_json_event/stage_eventdirectly — the call-site contract is on the macro’s rustdoc. -
OutboxWorker(spawned bycraig_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 oneUPDATE; a pass of 2 s or more logsoutbox drain pass slownaming its slowest phase. A row the publisher refuses as unpublishable is retired the way a malformed row is (#2825):published_atstamped,attemptsuntouched,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 withlast_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 typedDeadLetterDelivery(#1181): envelope +dlq.-strippedoriginal_queue+ the derived per-occurrence identity (valid_parkcapture first — carried verbatim through the parking hop, #1197 — thenx-death, then the validated_dlxwrapper, else tokenless) behindoccurrence_token()/occurred_at()/park_count()accessors, and returnsResult<(), 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).configis a validatedDlqRetryConfig { 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 #1199dlq_queue_depthgauges for the family queues (metrics::dlq; craig-security recordsdlq_outcomes_totalvia the re-exportedDeadLetterOutcome).OccurrenceTokenis a bounded validated newtype;publish_dlxtakes 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 isfor<'t> FnOnce(EventEnvelope, &'t mut Transaction<'static, Postgres>) → BoxFuture<'t, Result<(), E>>(craig_mq::BoxFutureis 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 5sonly after the lock, a 15 s attempt deadline; after the handler’sOk,SET CONSTRAINTS ALL IMMEDIATEruns the deferred constraint checks inside the savepoint under the same 5 s cap (#2775), soCOMMIThas 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 andINBOX_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 inevent_inbox_collisionswith adlxcol:token and nacks without requeue — the canonical row is never touched. The terminal DLX surface is mandatory-published from durable row state (occurred_at:= storedreceived_at— re-surfaces byte-identical); a failed/unroutable surface leavesfailed_atNULL and nacks requeue-TRUE (the source-queue copy is the durable envelope). Callers propagateInboxErrortosubscribeunmapped — the subscriber’s settlement keys on itsDisplay.consumer_queue(#1196, epic &75 C1) stays the subscription’s own queue name: the surface routes underdlq.<consumer_queue>and records it as_dlx.original_queue, matching the broker dead-letter path. -
Delivery timings (#2699,
metrics::delivery_timing).handle_idempotentlykeeps ONE stage clock per delivery across its re-claim passes and reports once, after them, on everyOkorErrreturn (a tier-2 panic or a dropped future reports nothing):-
craig_mq_inbox_attempt_stage_seconds\{queue, stage}(f64 histogram, units;queueis theconsumer_queue) records one sample per stage the delivery ran.acquireisPgPool::begin: the pool wait, then sqlx’stest_before_acquireping of a reused connection or a new connection’s setup, thenBEGIN(not split further: the split needs sqlx’s#[doc(hidden)]API).claimis the claimINSERT, plus theFOR UPDATEclassification on the conflict path.handlerruns from theSET LOCAL statement_timeoutto the handler’s return.completeis, after a handler’sOk, the deferred constraint checks (SET CONSTRAINTS ALL IMMEDIATE, #2775), then the savepoint release or rollback plus theprocessed_atstamp or the accountingUPDATE.commitisCOMMITalone (or a vanished-row pass’sROLLBACK).surfaceis the terminal or collision path’s post-commit DLX work.totalspans 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’snack_requeue).queueis the consumer queue forsubscribe,subscribe_idempotentandsubscribe_idempotent_batched, and the literalexclusivefor everysubscribe_exclusivequeue, whose per-instance names would mint a series per boot. -
craig_mq_consumer_receive_seconds{queue}(samequeuelabel) times a regular subscription’s wait for each delivery: from the end of the previous settlement (or the session’s start) untilconsumer.nextyields 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(targetcraig_mq::inbox):envelope_id,queue,outcome(processed/deduplicated/failed/terminal/collision, orerrorwhen no branch classified the delivery, e.g. aBEGINorCOMMITerror),acquire_us…surface_usandtotal_us(integer µs, 0 for a stage not run), andpool_size/pool_idleread at entry.inbox delivery settled(targetcraig_mq::subscriber):queue,outcome,receive_us,settle_us, andenvelope_idwhen the body decoded. To see them on a service (devstack or an instrumented battery), setRUST_LOGto includecraig_mq=debug, e.g.RUST_LOG=info,craig_mq=debug; compose sets noRUST_LOGon a CRAIG service, so its default level hides them. The on-demand reproduction that reads theinbox attempt timingsevent 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 issubscribe_idempotent_batched(below).-
handle_batch(&BatchInbox, consumer_queue, envelopes, handler) → BatchReportruns up to K deliveries through ONE transaction and oneCOMMIT.BatchInbox \{ pool, publisher, policy, is_statement_timeout }:BatchPolicy::new(k)refuses 0 and anything abovePREFETCH(16) with a typedBatchPolicyError;is_statement_timeout: fn(&E) → boolrecognises the batch’s 2 s statement cap in a handler error (craig-security’s classifier, plan U4, will downcast itsanyhow::Errortosqlx::Errorand test57014). The handler bound ishandle_idempotently’s plus `Clone + Sync; each admitted envelope gets its ownhandler.clone(). -
BatchReport \{ verdicts, flush, outcome }: oneBatchVerdictper input, in input order —Committed(Box<Committed>)(pass it tofinish_committed),Deferred(DeferReason)(run it solo after settlement),Carried(lead the next batch) orArbitrate(run it solo; its claim arbitrates).DeferReasonis 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’s57014, or a classified handler error; uncounted).flushisCount,BudgetorDrained;outcomeisCommittedorArbitrated(AbortClass)(Statement,Connection,ClientTimeout,CommitFailed,CommitTimedOut; the last two are uncertain; an unhashable payload isArbitratewhatever the outcome). Any error no savepoint absorbs, a client round-trip timeout or aCOMMITerror makes every admitted and deferred verdictArbitrate(Carriedstays); 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 ofhandle_batchto the caller’scontain. -
Committedholds 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 whathandle_idempotentlywould have:Ok, the counted failure’sHandler(RenderedError)(Displayhandler: <text>, the text rendered before the commit) orHandlerPanicked, the terminal surface (SurfaceFailedleavesfailed_atNULL), orIdentityCollision. -
Budget (D3,
pubconstants with compile-time asserts): claim phaselock_timeout50 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 (andBEGIN’s the pool’s acquire timeout + 1 s), `admitstops at 5 s of hold,BATCH_HOLD_BUDGET21 s (under craig-db’s 30 sstatement_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 disablesstatement_timeoutbefore it processes aCOMMIT;COMMITis left with the WAL flush, and a deferred check that fails or overruns is a certain rollback (Statement). ABEGINthat outlives its bound finishes in a detached task whose late transaction drops with its rollback queued, since a top-levelBEGINdropped mid-flight queues none in sqlx 0.8.6. -
Handler obligations:
now()is the batch’s start, so per-event times useclock_timestamp()(the batch’s own inbox stamps do); noSET 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-transactionBEGIN:batchperhandle_batch,singleperhandle_idempotentlypass),craig_mq_inbox_batches_total\{queue, outcome}(committed/arbitrated; a failedBEGINcounts 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}andcraig_mq_inbox_batch_deferrals_total\{queue, reason}(a committed batch’s deferrals). An abort logs one value-freewarn!(class, SQLSTATE, batch size). Each committed envelope’sinbox attempt timingsevent reports fromfinish_committedwith its confirmed outcome,acquire_usandcommit_us0.
-
-
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 tosubscribe_idempotentfor a consumer whose per-envelope commit caps its throughput. Its handler bound, queue declaration and bindings, and settlequeuelabel aresubscribe_idempotent’s; `queue_nameis&'static strand is also the route of the inbox’s DLX surfaces. The pool and publisher are cloned out of theBatchInbox, so the spawned session owns them and builds each round’sBatchInboxfrom 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. Aredelivereddelivery runs solo, never in a batch. The rest run through onehandle_batchinside onecontainboundary, 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:Committedto settlement,DeferredandArbitratesolo,Carriedto the next round. The handler is held behind anArc; every clone of it runs inside a containment boundary, so a panickingClonefails that batch or solo run, never the session. -
Settlement after a confirmed commit, per delivery: first each processed or deduplicated delivery (its
finish_committeddoes no I/O) in its owncontain, acked, then a beat; then, in arrival order, each delivery with post-commit work (a counted failure, a terminal surface, a collision) in its owncontain, settled assubscribe_idempotentsettleshandle_idempotently’s result (the inbox’s `Displaymarkers, 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 outcomenack_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
arbitratedincraig_mq_inbox_batches_total. The solo list (redelivered, deferred, arbitrated) runs one at a time throughhandle_idempotentlyinside 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); noSET LOCAL; no savepoint; every write through the transaction, never committed or rolled back by the handler. -
craig_mq_consumer_settle_secondsgains the outcomenack_requeue. Underfault-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, andarm_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/RefPathgrammar +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 hardValueMismatch). -
citation— thecitations.tomlmanifest schema (CitationManifest/Citation, the typed six-variantAuthorityenum, thederivationhonesty field),load_manifest, collected-issuevalidate, andcheck_against_rulesets(resolves + tethers every key against the live ruleset files). Consumed by thegeorgia_manifestbattery test today and thecargo xtask policyfamily (#660–#663) as it lands. -
scenario— the scenario-inventory schema (ADR-071:ScenarioEntrywith first-classScenarioOraclerows, orderedLevel, closed stage/entity vocabularies), pure validation (validate_entry/validate_global_ids/ the §8 no-literal precondition rule), declaration-anchoredresolve_binding, derivedevaluatecoverage, and the bidirectionalcheck_oracle_enforcementjoin. Consumed bycargo xtask scenarios audit(#665). -
source— the tooling-onlyPolicySourcetrait (#660):PammsGitSource(shallow public clones under the jurisdiction’s gitignored.policy-cache/, with the three Canopy #1347cache_syncguards —--dash-proofing, bare-name +current_dirclone destinations, and the in-cratehead_commitnon-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 typedpolicy-source.tomlconfig (SourceKind), andsha256_hex. Consumed bycargo xtask policy sync-cache [--pin|--repin <who>]. -
sync_manifest+load— the.policy-cache/sync-manifest.tomlschema (per-repo HEAD
per-cited-file hash; the comparison cache — durable pins live incitations.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 theCRAIG_<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 (EnvVaralso 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): everyencrypt/encrypt_str/decrypt/decrypt_strtakes 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, andis_encryptedstays 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::AfcarsExportis the one kind;ArtifactDate::parsetakes the export’s pinned%Y%m%d, exactly eight ASCII digits, elseInvalidArtifactContext). The binary envelope isCGAF || 0x01 || nonce(12) || ciphertext || tag(16); the AAD isCGAF || 0x01then each context field behind a one-byte length (the kind as the tokenafcars-export); the nonce is HKDF-SHA256 of the key undercraig-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_artifactrefuses a wrong key, a foreign context or any tampered byte past the header (Decrypt), a non-CGAFinput — plaintext or a cell envelope (MissingMagic) — and another version (UnsupportedArtifactVersion), never a pass-through;is_encryptedstaysCGEF-only. Seal and open fault throughCipherOp::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 infocraig-crypto/blind-index/<domain>/v<version>; takes bytes, soDatecanonicalization works; no cross-column HMAC correlation). The global-domainhmac()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 throughcraig_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 keylesscrypto_key_lineagerow’skcvandcanary(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 bykcv == KCV_SENTINELalone 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.Es256PublicKeyis a P-256 point validated at construction (from_coordinates(x, y),from_sec1— the 65-byte uncompressed form only), withas_sec1,coordinates,to_jwk.Es256SigningKey(Clone, one key pair behind anArc, redactedDebug):generate,from_parts(d, public)(refuses adthat derives another point),from_d(d),from_private_jwk,public_key,to_private_jwk,to_pkcs8_der(unencrypted PKCS#8 v1, zeroized; the formjsonwebtoken’s ES256 `EncodingKeytakes, #2694),sign_jws(64-byte fixedr‖s) andsign_der(the same signature as minimal DER). Signatures are randomized.verify_jwsaccepts only the fixed form (JwsVerifyError),verify_deronly strict DER — short-form lengths, minimal positive INTEGERs, r and s in [1, n), nothing trailing — so undecodable DER isDerVerifyError::MalformedSignatureand only well-formed DER that fails isBadSignature. 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,drefused) andtolerant_public_key()(an actor-peer key: other members ignored,drefused). The strict readings accept WebCrypto’s export members (#2697):ext(a boolean) andkey_ops, which must be exactly["sign"]on a private key and["verify"]on a partner key (JwkRefusal::WrongUseotherwise).x,yanddmust each be exactly 32 bytes of unpadded base64url.Es256PrivateJwk(from_json,to_json) zeroizesdon drop and never prints it;Es256PublicJwkserializes 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 (
capabilitymodule):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 oneconsttable (substring ⇒Plaintext+Text;Opaque⇒ nothing).FieldSpec::blind_index(enc, &BindValue)is THE single blind-index derivation (canonicalize per the registry spec, thenhmac_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 areconst fn`s that `assert!the required capability, so an illegal scheme/operation pairing is a compile-time error. -
Planner (
plan, withentity+runtime):SearchEntity(entity— the descriptor trait binding a service DTO asFilters) +plan(…) → SearchPlan { table, where_sql, binds, order_by, order_dir, sibling_matches }(sibling_matches, #1759: the effectiveBlindIndexspecs a keyed, present equality term matched; empty for a keyless plan). Injection-safe by construction (SQL from registry&'staticliterals
$Nonly; user values reach onlyBindValuebinds),WHERE TRUEbase, bound NULL-guards for absent filters, LIKE metacharacters escaped (ESCAPE '\'), fail-closed (UnsupportedFilter/UnenforceablePolicyerror, never widen). Inruntime:ScopeConstraints(None/Worker/Supervisor/AdminUnits(Vec<String>)—Clone, notCopy) — the separate non-degradable policy channel (unconditional equality, no NULL-guard;AdminUnits→{col} = ANY($n)over ONEBindValue::TextArray,SearchEntity::admin_unit_column()REQUIRED on every impl, no column →UnenforceablePolicy("admin_unit"), #1903);SearchMode { Optional, Required }mirroringEncryptionModewithout thecraig-commondep;BindValue.SearchRuntime(plan) carries the optionalFieldEncryptor+ mode. -
Executor (
exec, featuresqlx):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: Nonerenders the legacySELECT *;Somerenders the validated column list (#1158 — heavy columns never fetched;Tdecodes the projected shape). List SQL itself renders via the sqlx-freeSearchPlan::list_sql(projection). -
Boot lineage verification (
lineage, featuresqlx, #2138 — lifted from craig-cases so craig-reporting shares it): thecrypto_key_lineageverify half (ADR-048 §D3). A service binds oneLineageScope { registry, key_env, mode_env }and callsboot_verified_encryptoronce at boot, after migrations and before the service’s supervisor, workers and listener start;load_encryptor(the mode × key-load decision) andverify_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 aBootVerifyError; 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 NOTHINGof 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’safcars_generatecommit). Every refusal is a value-freeLineageWriteError(Db|Crypto|Scheme|Mismatch); none carries key material or a cell. -
Read projection (
plan, #1158):Projectionwraps&'static [&'static FieldSpec];Projection::newvalidates 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-ALLtest. -
Write/decrypt walk (
row):EncryptableRow+FieldRef(Text/TextRequired/Jsonb)
theimpl_encryptable_row!declarative column→field table macro (single-siblinghmac: "col" ⇒ fieldor the braced multi-sibling table — #1064 added the latter when persons gained a secondBlindIndexpair);encrypt_row/decrypt_rowwalkencrypted_fields(registry)under aRowContext { table, row_id }(#1007 —EffectiveRegistry::row(id)in the service,<module>::TABLE+model.idin the seeder;RowContext::cell(column, sibling)is the ONE per-cellStorageContextderivation) and bind each cell’s storage context — for aBlindIndexbase the STORED sibling — into the AEAD; a keyedRequiredread of a populated non-envelope cell isSearchError::PlaintextInEncryptedCell(never a passthrough;Optionalkeeps 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 (RowSlotKindMismatchon shape disagreement). A registry-encrypted column the shape does not expose is a hardRowMissingColumn/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); aBlindIndexsibling is derived from the plaintext viaFieldSpec::blind_indexbefore 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 afterdecrypt_row; a new entity with aBlindIndexpredicate 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 ApiErrorlives incraig-commonbehind itssearchfeature (UnsupportedFilter→ generic 400 with no field oracle; server-side faults → redacted 500; ADR-047 layering precedent). -
validate_registry/RegistryError— runtime well-formedness theconstlayer cannot cover: dangling/mistyped_hmacsiblings, duplicate columns, duplicate blind-index domains (cross-column correlation), invalid domains, out-of-envelope blind-index bases (UnsupportedBlindIndexBase). Called from each registry’sregistry_is_well_formedtest.
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<()>— drainsevent_outboxrows (staged by domain handlers in-tx) to RabbitMQ; watchesshutdown. -
init_object_store() → Result<Store>— loadsObjectStoreConfig+ opens theStore(local FS in tests, Garage in devstack, S3 in prod). -
build_shared_http_client(pkg_name, pkg_version) → Result<reqwest::Client>— wrapscraig_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 formermq_healthlayer — MQ health ridescraig_api::AppState.mqasMqRequirement::Requiredso 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; picksRulesClient::with_service_tokenvs 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: theWorkerHealthregistry on which the boot registersauthz-invalidation
authz-ttl-refreshas Critical workers, plus — #1228 — theauthz-evalliveness sentinel (Critical) watching the dedicated!Send-eval OS thread viaZenAuthzEngine::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 toZenAuthzEngine::boot_degraded, an empty cache over the REAL source (#786 — the former empty-InMemoryRulesetSourcesubstitution falsely attested universal absence and never self-healed; withrequire_full_coveragea double fetch failure refuses to boot); enforce coverage; spawn invalidation + warmup + TTL).
craig-api
-
Ctx(ctxmodule, #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 whatState<AppState>,Extension<Claims>,Extension<Arc<dyn AuthzEngine>>andExtension<Jurisdiction>read, from any router state that holds anAppState(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 declaresctx: Ctxand 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 declaresctx: Ctxand reads the fields (ctx.claims). The services move to it one at a time (#2309).validate-authz-coveragereads bothauthzandctx.authzas 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; theIdempotency-Keyheader is no longer honored anywhere; the orphanedidempotency_responsestables were DROPPED ×8 in BF #1270). Each service prunes itsrequest_claimstable hourly via therequest-claims-retentionworker (craig_mq::spawn_local_sweep, advisory lock "CRAIGRCL", 5k batches) on the deployment-globalCRAIGREQUEST_CLAIMSWINDOW_DAYShorizon (default 30;0⇒ registeredDisabled(info log); an unparseable value also disables, with an ERROR log — never a guessed horizon; therequest_claims_retention_overrunwatchdog is the second indicator). NewtypesClientRequestId/ClaimScope/EntityKind/IntentHash(grammarv1:<64 hex>, constructible only viaintent_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, moneyrescale(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 lockingINSERT … ON CONFLICT DO UPDATE … RETURNINGwithxmax-based insert detection) →Claimed|Replay { entity_id }| 409IDEMPOTENCY_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)orReplayed(id), andClaimedCreate::resolve(kind, load)= the entity the handler answers with: the fresh one, or on a replay the oneloadreads back by id, elsereplay_entity_gone(kind). Backing tablerequest_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_v1andClaimSpec.actortake acraig_auth::Actor, and the envelope’sactorhashes asActor::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 therequest_claimscolumn paircreated_by_sub(a worker’s UUID) /created_by_sub_service(a service’sservice:<name>), exactly one set.ClaimSpec::worker_uuid()is the actor’s subject for a worker-only route, else the 403worker_required. The formerrequest_claims::parse_actor_subis removed; a handler readsClaims::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 fromClaims::legacy_service_uuid(), andclaim_first_with_legacy(tx, &spec, legacy, entity_id)takes it as aLegacyServiceClaim { uuid, intent }: a stored claim that misses the spec still replays when it holds that UUID increated_by_sub, nocreated_by_sub_service, and the legacy digest.claim_firstis the same call with no legacy shape;prechecknever 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 itsreceived_request_idduplicate, and its report-attachment upload passes the UUID toupload_attempts(below). -
upload_attempts(ADR-062 §U): the HTTP-side upload-attempt orchestration overcraig_store::attempts.AttemptRequest.actor(#2740) is the request’sActor, stored as the attempt’screated_by/created_by_servicepair: a worker’s UUID, or a service’sservice:<name>.AttemptRequest.legacy_service_uuidisClaims::legacy_service_uuid()on a route a service token reaches, elseNone: an existing attempt whosecreated_byis 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 theApiServerstack stampsIdempotent-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 outsiderequest_claims(craig-cases' report resubmission and its SSA-screening forward), on the request’s own task. Outside anApiServerrequest it is a no-op. A stray call stamps a false header and games the coverage gate’sreplayevidence. 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; noOption, noDefault— omission is a compile error),workers: WorkerHealth(#1186 / ADR-061). -
Supervisor(supervisormodule, #1186):install()(creates THE process shutdown token
registers thesignal-bridge),token(),expect(&[WorkerSpec]),health() → WorkerHealth(the registry handle:watch/watch_optional/watch_liveness/mark_disabled/snapshot),drain(WORKER_DRAIN_DEADLINE),check_exit(). Mains followserve(…).await?; supervisor.drain(..).await; supervisor.check_exit()?;. #1229: the module (withshutdown_signaland theWorkerCheckEntrywire mapper) LIVES incraig_common::supervisorso the DB/MQ-less BFF can supervise its workers; everycraig_apipath above is a re-export and stays valid. -
ServerOptions { cors_origins: String, body_limit: usize }(default 2 MiB). -
attachment_body_limitmodule (#974) —AttachmentBodyLimit::resolve(configured: Option<usize>, per_file_cap) → Result<_, AttachmentBodyLimitError>(unset derivesper_file_cap(1 MiB); an explicit value must EXCEED the cap) +
MULTIPART_FRAMING_HEADROOM.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-uiunder its route-scoped CSP with the online validator off, #2790);serve(router, port, shutdown: CancellationToken)with the boundedHTTP_DRAIN_DEADLINE(20s) HTTP drain and every connection write-idle bounded (#1951), delegating to the test seamserve_with_listener(listener, router, shutdown, drain_deadline); thetest-utilseamserve_with_write_idle_budget(listener, router, shutdown, drain_deadline, write_idle_budget)injects the budget. The router also mounts the sharedPOST /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 andprint_openapi_if_requestedgo 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 primitivesconnect_database/init_auth/connect_mq(for non-standard compositions; craig-intake’s integrated mode formerly used them and is now MQ-less — aconnect_mqcaller composing its own channels gets connection-only readiness gating until it attaches a publisher channel, #1235);shutdown_signal()(SIGTERM/SIGINT / Ctrl-C — the formershutdown_token()free-token helper is retired by #1186; useSupervisor::install()). Since #1226/#1227 the JWKS refresh loop is token-aware, and since #1236 the #1160 pool acquire-wait probe is too — both rideBootstrapResult.background(BackgroundWorkers: one shared shutdown token + named handles) toadopt_background_workers(&supervisor, br.background.take())— registeredObserved(jwks-refresh+db-pool-probein every service’s worker set) with the supervisor’s shutdown bridged in once. Since #2826 the now-publicinit_mqreturnsMqHandles, whosePublisherChannelMonitorrides the requiredBackgroundWorkers::publisher_channelfield and is adoptedCriticalasmq-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_taskcarries 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 halvesbootstrap_data_plane(prefix, service_name) → DataPlane { settings, db, _telemetry }→bootstrap_control_plane(prefix, service_name, DataPlane). The 8 stateful mains boot throughbootstrap_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::SchemaVerifycarries the remedy-first refusal. -
Migrate process mode (#1307, ADR-063 D2/D4,
migrate_mode.rsre-exported):run_migrate_mode_if_requested(env_var, service, &Migrator) → Result<bool, MigrateModeError>— the<binary> migrategate. Exact argv shape (migratealone;--print-openapitogether is a typed conflict; non-Unicode argv is a typed error); called BEFOREprint_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 corerun_migrate_gate(url, service, &Migrator) → ApplyOutcomebuilds a minimal 1-connection pool (recorded deviation:DbPool::connect_with, not rawPgConnection— reuses the testedapply_by_verdictpath; intent kept: no metrics, no probe) and applies by verdict. Since #1399 U1 the gate body runs connect →pre_apply(a refusal isMigrateModeError::PreApply(E)— nothing applied, hardening andpost_applyskipped) →apply_by_verdict→ harden →post_apply; the typed seam isProcessHooks<E> { pre_apply, post_apply, tool, runtime_read_only }(process_hooks.rs;ProcessHooks::new(pre, post)/ProcessHooks::none()) consumed by therun_migrate_gate_with_hooks/run_migrate_mode_with_hooks/run_process_modes_with_hookstrio (MigrateModeError<E = Infallible>/ProcessModeError<E = Infallible>; thewith_post_applytrio is gone) — the plain forms passProcessHooks::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 #1550harden_meta_tables; a listed table that does not exist fails the gate). craig-cases and craig-placement passgate_hooks::hooks()/gate::hooks(). The floor lint reads the argument, which must be an array literal or a same-fileconstpassed through a.with_runtime_read_only(…)method call (ADR-063 D4, #2572). Since M3a the 8 mains callrun_process_modes_if_requested(service, &Migrator, &OpenApi) → Result<bool, ProcessModeError>(craig-cases and, since #2337, craig-placement call the_with_hooksform) — the ONE home of the mode-ordering contract (migrate first,--print-openapisecond) and of theCRAIG<SVC>DATABASE_URLname derivation. -
multipartmodule (#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 atTEXT_PART_MAX_BYTES(8 KiB, #2632: craig-common’s sharedMULTIPART_TEXT_PART_MAX_BYTES); an over-cap part is amalformed-multipart400 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 strongETagis the body’s sha256, andrangeselects the slice as on the streamed path (#1948). -
download::DownloadRange(#1948): the extractor every download handler takes — a GET’sRange/If-Range(craig_common::download_range::RangeHeaders) parsed intocraig_store::RangeRequest, whichStore::get_streamresolves against the object’s head. Both streamed responses then answer200,206(Content-Range, the slice’s length, no digest audit) or the416problem document, withAccept-Ranges: bytesand the strongETag(deployment guide § Streaming downloads rollout). -
http_observability::request_span_layers(router)(#1953): the request-span stackApiServerinstalls —request_id_layer(adopt or mintX-Request-Id, echo it) outside thehttp_requestspan, which records the id asrequest_id, outside tower-http’sTraceLayer; every event inside the request span carriesrequest_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 fullContent-Lengthserved): a mismatch with the declared §U digest logs oneerrorand recordsmetrics::download_stream::record_digest_mismatch(service)(download_digest_mismatch_total{service}). A failed or abandoned body is never compared.serviceis the caller’senv!("CARGO_PKG_NAME"). Used by the NCANDS export download. -
invitationmodule (#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 firstPREFIX_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 implementsRedeemable(TABLE,id(),code_hash(),is_open_at(now); the table carriesid,code_hash,redeemed_atandredeemed_by_sub).Redeem::code_hash()is the digest a request intent binds in place of the code.lock_open(executor, now)selects by digestFOR UPDATEand returns the row only if the code verifies and the row is open, so an unknown, expired, redeemed or revoked code is the sameNoneand 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 byDebug. 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_RECORDEDdefaulting tofalse);EventTime(require_not_after_now(field, jurisdiction);NaiveDateimplements 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 rowsStoredRow<T>(aliasRow<L>) andStoredEventRow<T>(aliasEventRowOf<L>) deref to the wire row and convert withinto_contract();StoredEventRow::first_recorded_at()isSomeonly for a ledger that setsFIRST_RECORDED(thefirst_recorded_atcolumn, NULL a decode error).begin_snapshot(pool)(#2040) opens a read-onlyREPEATABLE READtransaction: 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(anEntry),correct(aCorrection),retract,close,current,read,in_force_at,row_of, and the row helperslock_live_row/retire_rowoverStoredRowOf.store::event— the generic event store:record(anEventEntry),correct(anEventCorrection; the stated facts, thenEventLedger::inheritfrom the predecessor),history,at_anchor,live_through(#2082: every live row dated on or before a cutoff, by the ledger’s order —at_anchoranswers one per identity). Every closing or retiring UPDATE names its acting worker (#2016):retract,closeandretire_rowtake anactor: Uuid, written asretired_by(a retire) orclosed_bybesideclosed_at = now()(a close);record_change’s implicit close and both `correct`s write the entry’s `recorded_by. Every table handed toretire_row, and everyEventLedgertable (the decoder reads it unconditionally), carriesretired_by; everyWindowLedgertable also carriesclosed_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: 400ledger-instant-after-now),require_window_ordered,overlap_or_db,row_not_found,require_fact_date_on_or_before_event(#2082: 400ledger-fact-date-after-event). #2461:MIN_STORABLE_DATEis PostgreSQL’s minimumdate,-4713-11-24.require_storablerefuses an earlier date as the 400ledger-date-before-minimumon its field, never the 500 the bind would raise, and admits the floor itself.require_on_or_before_todayapplies it to every body and fact date first, andWindowRead::require_storableapplies it to a read’sas_of,fromandtobefore they are bound. The event-ledger reads callrequire_storableon theiras_of(#2902): cases'list_eventandlist_statuses, and placement’s traffickinglist. -
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 callscraig_api::guards::deny_pure_servicefirst) androw_legs.ClaimedAct::runandClaimedAct::publishboth receive the act’sactor(the spec’s acting worker: the inserted row’srecorded_by, the retired row’sretired_by, the closed row’sclosed_by;publishattributes the audit event to it, which craig-cases emits asuser_id; #2016). The owning service keeps its route traits, act enums and handlers (craig-cases:LedgerRoute,EventRoute,Act,EventAct; craig-placement since #2018: theEpisodePath/OpenPathroutes and theOpenEpisode/CorrectRemoval/RetractEpisodeacts; since #2019 theRecordExit/CorrectExit/RetractExitexit acts, theHistoricalEpisodeact and theExitResponsesTableevent 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 withFIRST_RECORDEDtrue (itsBEFORE INSERTtrigger 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 UUIDv7archive_id) → ONE transaction: id-keyed DELETE (count-mismatch rolls back) + the service’sBookkeepFnclosure (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>/→ aPartitionManifest(craig.partition-manifest.v1: table, day, attempt, row total, each object’s keys, digest and count) at<attempt>/partition.manifest.json→ ONE transaction:BookkeepFnper object + a drop that counts the partition under a lock and drops it only on an equal count (any other count rolls back asPruneCountMismatch) → 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();Debugredacts 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 UnicodeGeneral_Category = Format(Cf) character viacraig_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_keyand craig-api’sAttemptRequest.safe_nametake it, never aString;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 transitionsmark_stored/finalize_attempt(promote-lock-first +AttemptFinalizereffects + 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 ignoresIf-None-MatchBY DESIGN, see thegarage_put_createcanary) +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). Theupload_attemptstable ships per-service in SU2; consumers integrate in SU3–SU6. Since #2740 (ADR-085 D3) an attempt’s claimant is anAttemptCreator,Worker(uuid)orService("service:<name>"), stored as thecreated_by/created_by_servicecolumn pair (exactly one set) and compared opaquely byclassify_replay.UploadAttempt::creator()rebuilds it,creator_encoding()gives the encoding for a TEXT actor column or an event’suser_id, andworker_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 structRaceResponses— eightboolanswers keyed by those tokens, absent race isOption::None, a present value always carries all eight (#1991, replacing the five-valueRace);Ethnicity—hispanic/non_hispanic/unknown/abandoned/declined(#1991;unable_to_determinedeleted);YesNoUnknown— the tribal-membership answer set, reused by the ICWA ledger’sicwa_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) andSourceApplies(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) andIcwaCourtDetermination(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) andParentalRightsKind(voluntary/involuntary/not_applicable); the permanency sets (#1995):ReviewKind(periodic_review/permanency_hearing) andContactLocation(childs_residence/other_location);MaritalStatus,Language,DobVerification(#3192, thepersons.dob_verificationvocabulary: how a date of birth was verified, eight tokens frombirth_certificatetonot_verified),MilitaryBranch); intake (ReporterType— the reporter’s STATUS axis;ReportSource— the NCANDS Child File #10 RptSrc vocabulary, 15 variantssocial_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-childpermanency_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-ReviewKindmap (review_hearing→periodic_review,permanency_hearing→permanency_hearing, else none),LicenseType,ProviderKind(#2055, thefoster_homes.provider_kindsetfamily_home | congregate_facility, a CRAIG fact with no AFCARS dictionary set),PlacementType— re-cut by #2056 tofoster_family_homeplus the 14 federal (e)(4) tokens verbatim (trial_home_visitbecameplaced_at_home),setting_class()the one class table andis_caregiving()falsefor exactly the six non-caregiving settings;SettingClass(#2056:Family/Congregate/NonCaregiving,provider_kind()theProviderKinda named home must have,Nonefor non-caregiving);FosterFamilyHomeType(#2056, the six (e)(3) categorieslicensed_home/therapeutic_foster_family_home/shelter_care_foster_family_home/relative_foster_family_home/pre_adoptive_home/kin_foster_family_home, the wireffh_typeslist);ArrangementLocation(#2080, theplacements.arrangement_locationvocabulary, (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 andplacement_does_not_meet_icwa_placement_preferences);PlacementEndReason—left_caresince #2019 (the arrangement ends because the agency’s responsibility ended); #2023 removed the six exit-like tokens (transfer,disruption,runaway,left_careremain),ExitReason(#2019, theexit_responses.exit_reasonvocabulary, (g)(3), eight reasons and nonot_applicable),TransferAgencyType(#2019, a transfer exit’s receiving agency, (g)(4)),RemovalManner— since #2018 theremoval_responses.removal_mannervocabulary, a CRAIG fact with no AFCARS element,RemovalEnvironment(#2081, theremoval_responses.environmentvocabulary, (d)(3), seven tokens),AdoptiveMaritalStatus(#2083, theexit_responses.adoptive_marital_statusvocabulary, (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, thechild_health_facts.condition_statusandcondition_<category>/child_education_facts.school_enrollmentandeducational_levelvocabularies: (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 anexchange_transactionsrow 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’sRateClassPolicySpec),SubsidyProgram— 7 GA 22.8 kinship programs incl. closed cohorts,const fn open_for_enrollment;SubsidyAgreementStatus— 6-state ADR-052 interval vocabulary; plus theSUBSIDY_*_REASON_CODESconsts +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 canonicalSubsidyProgramFamily::ALLorder every inter-family lock taker shares, so create-vs-import stays deadlock-free by construction).PartnerTypewas deleted at Plan T3.3 (partner_type is an open snake_case token validated byPartnerTypeRegistrymembership). -
fipsmodule —Stateenum (50 + DC + 5 territories, USPS abbreviation);AdminUnit { name, fips_code, state, unit_type };admin_units_for_state(state);State::fips_code(). Thecountiestables (3,235 county-equivalents, 2020 Census vintage) were ported ONCE fromcanopy-referenceand are hand-maintained — no in-tree generator (#765 records the decision); the #781fips.rspins (summed national total, per-state spot checks,STATEScoverage) catch an added or dropped row, and review catches the rest. -
translatemodule —admin_unit_to_fips/full_fips_code(the*_str_to_ncandsNCANDS 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 — planafcars-federal-ruleset). -
shinesmodule — 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 overReportSource, 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;Ua #692 placeholder) /code_table_placeholder_id(ShinesCodeTable, &str) → Option<u16>(the value’s 1-based DFCS list position, a #692 placeholder;Noneoutside the table) — #2097. The per-enum crosswalksrace_to_shines_id/RACE_ID_OTHER_OR_UNKNOWN/marital_status_to_shines_id/language_to_shines_id/sex_to_shines_codewere REMOVED by #2101: the SHINES per-person values are SHINES pick-list values, mapped by the two functions above. -
shines_codesmodule (#2097, ADR-042 § Amendment 2026-09-29) — the eleven SHINES portal pick-lists as committedconsttables, pinned by a parity test to the DFCS CSV atcrates/craig-reference/data/shines/field-dropdowns.csv:ShinesCodeTable(AllegedMaltreatorRelationship,RelationshipCollateral,RelationshipPrincipal,ReporterType,Gender,State,County,MaritalStatus,Language,Race,Ethnicity) withentries() → &'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_relationshipmodule (#1714) — the two "Relationship to Primary Caregiver" lists as typed enums,PrincipalRelationshipToCaretaker(75 codes) andCollateralRelationshipToCaretaker(99), each withcode(),label()and an exactfrom_code(&str), pinned by tests to theirShinesCodeTableby code and label in DFCS order.RelationshipToCaretakerisPrincipal(..)orCollateral(..):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" isSRon one andSVon 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’srel_to_primary_caretakerthrough it, the designation (else the household flag) choosing the list. -
federal_partner_category(Plan T1.4) —FederalPartnerCategory9-variant federal-closed enum (tanf ccwis afcars ncands iv_e icpc medicaid education_slds child_support); consumed byStateBundle::federal_mapping()+FederalPartnerMappingRegistry; nosqlx::Type. -
ncandsmodule — 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 (planafcars-federal-ruleset). Thencandsmodule 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 whenunknown,abandonedordeclinedistrueand each named flag from its answer;ethnicity_to_ncandsfoldsunknown/abandoned/declinedinto the unable-to-determine code 3 — federal-wire-ready, returningNonewhere CRAIG has no faithful code per ADR-040; added #644 —disposition_to_rptdispis TOTAL since #648,u8bijective onto 1..=7, serving #11 and #27/29/31/33;report_source_to_rptsrc(ReportSource) → u8is TOTAL and injective onto {1..=13, 88, 99}, serving #10 — it REPLACEDreporter_type_to_rptsrc, which wasNonefor every mandated / professional reporter because the reporter STATUS does not determine the source;validate_report_sourcejoins the validators). The CRAIG-internal*_to_ncands/*_from_ncandsshort mnemonics and theirtranslate::*_str_to_ncandswrappers are gone (disposition by #648, reporter type and abuse type by #1766: none had a production caller). Since #1630 the TOTALabuse_type_to_chmalalso mapssex_trafficking→ 7,labor_trafficking→ 8 (Other) andsexual_exploitation→ 4 — sharingSexualAbuse’s slot: the Child File de-duplicates by CODE, so a victim alleging both folds into one ChMal-4 slot. `validationmodule —validate_enum<T>+ 29 specific validators (validate_racedeleted by #1991), all returning the typedReferenceValidationError(InvalidEnum { field, reason }/UnknownState { abbr }/UnknownAdminUnit { name, state }; Display reproduces the historical prose byte-for-byte, so handlers wrap.to_string()into the RFC 7807detailunchanged — #839).
craig-alloc (#3149, #3150)
-
The process allocator of the long-running binaries. On a musl target it declares
mimallocas 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 itsmain.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
xtaskand 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
mainwas 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 start773 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 itscarjob 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-jemallocatorandmimalloc. -
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
evaluatefuture 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 isEvalSpawnError::WarmUp.EvalThreadSpecnames 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.EvalErrorisTimeout { budget_ms, dispatched },WorkerUnavailable,Engine(zen’s text) orOutput(a result that does not serialise, or a top-levelnull).Dis 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’stimeoutrow tolate_completedfrom 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 pastwedge_threshold(budget)(max(10 × budget, 60 s)) the watch flips, andEvalHandle::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-utilfeature (test-only) addsEvalHandle::detached()andtest_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 serdetry_from/into), plus theMAX_ATTACHMENTScount const (5). Backend-agnostic so theIntakeSinkseam and the SHINES signed-attachment manifest (ADR-042 §D9) share one type without the trait referencing a backend. -
MAX_REPORT_CHILDREN(#1696) — the fleet-widechildren-list count cap (10): the intake edge (validate_children_array, typed 400batch-too-large), the three SDKReportBuilder`s and the craig-cases create boundary (through the `craig_cases_contracts::reportsre-export; typed 422screening-report-too-large) share it, so the screening act’s per-child window is one hop by construction. Pinned across languages bysdks/test-vectors/report-limits.json. -
required_nullable(2080) —deserialize_withfor anOption<T>field WITHOUT[serde(default)]: the key must be present (null= unanswered), a missing key is serde’smissing fielderror, also through[serde(flatten)]; pair it with[schema(required = true, nullable)]. -
bounded_page_limit(limit, max)(#2119) — a paged export query’s effectivelimit:maxwhen absent, the value inside1..=max,Noneoutside it (the handler’s typed 400 naminglimit). The NCANDS and AFCARS export queries'page_limitboth call it. -
contains_nul(value)+NUL_REFUSAL(#2830) — whether a string holds a NUL (U+0000), which Postgres stores in neitherTEXT(SQLSTATE 22021) norjsonb(22P05).JSON_NUL_REFUSAL(#2854) is the JSON documents' text,NUL_REFUSALplus " 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(addsserde_json) givesjson_has_nul(&Value), an iterative walk of every string leaf and object key;garde(addsgarde) givesvalidate_no_nul(a requiredString) andvalidate_option_no_nul(anOption<String>, also bound asinner(custom(…))on a keep / clear / set field), refusing withNUL_REFUSAL. A JSON field’s NUL refusal is part of its size bound (json_bounds, below), which refuses withJSON_NUL_REFUSAL. Every contracts crate and service that binds a NUL refusal binds these (each crate-localtext_guards.rsre-exports them under the same names, and names the features it uses in its ownCargo.toml), so a NUL in a stored free-text field or aSELECT-bound filter is the house 422 naming the field instead of a redacted 500. -
json_bounds(2633), behindjson: 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. Withgarde,json_within(&BOUNDS)andjson_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_JSONis 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_JSON32
50,000
65,536
a rule set’s decision graph
RULE_INPUT_JSON16
5,000
16,384
one evaluation’s input
RECORD_JSON16
2,000
16,384
a document stored on a record as sent
BATCH_JSON32
100,000
65,536
a batch of records sent to an exchange partner
SUBMISSION_NARRATIVE_JSON16
5,000
32,768
an intake submission’s free-form narrative, at the edge
SUBMISSION_JSON32
10,000
32,768
a whole intake submission as craig-cases stores it
CREDENTIAL_JSON4
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 homedocument_typeand craig-cases' contactattachment_type(#2835 / #2838), each with its own byte cap beside it. -
is_unicode_format_char(c: char) → bool(#2831) —constpredicate returningtrueiffchas UnicodeGeneral_Category = Format(Cf, Unicode 17.0: the joinersZWNJ/ZWJU+200C/U+200D, which UTS #39 marksIdentifier_Status=Restrictedsince Unicode 15.0, BiDi controls, BOM, and Plane-14 tag charactersU+E0001/U+E0020..=U+E007F), with zero runtime dependencies and an exhaustive'\0'..=char::MAXtest againstunicode-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 neitherTEXTnorjsonb);escape_display(&str) → Cow<str>also writes eachis_unicode_format_charcharacter 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 underescape), whole pieces are kept while the running length stays withinmax, 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 exactlyescape(input). Proptests pin the no-escapable-character, length, prefix, exact-Nand 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). -
NameSimilaritytrait (score(a, b) → f32in [0,1] +algorithm_name());TrigramJaccardimpl (strsim-backed). v1:phone_matchis hardcodedfalse(nophonecolumn 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'
ledgermodule (#2015; no wire change). The owning service supplies a ledger’s identity keyK, its factsFand its closed retired-reason setR; the types here fix everything else. Field caps referencecraig-validation. -
RetiredReason— a ledger’s closed retirement-reason set: the two tokens the shared acts write,CORRECTED(a correction supersedes the row) andRETRACTED(entered in error), plusas_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 atvalidate()since #2837) andLedgerCloseRequest(effective_until); the readsLedgerAsOfQueryandLedgerPeriodQuery { from, to }; the rowLedgerRow<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_*isnullon an open row and on a row born with its end). -
The event-ledger wire:
EventStatementRequest<F>(the record AND the correction body),EventAsOfQuery(concreteas_of: Option<NaiveDate>— utoipa’sIntoParamsderive cannot take a generic field) and the rowEventRow<K, F, R>(no window; since #2016retired_by: Option<Uuid>sits betweenretired_atandretired_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.rspins the manifest (the craig-portalinclude_str!precedent). Itssrcis 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 toApiError. -
ledger(#1992; the shared wire lifted tocraig-ledger-contractsin #2015) — the route keysPersonKey { person_id },CaseChildKey { case_id, person_id }andSiblingKey { person_a, person_b }(SiblingKey::of(one, other)orders the pair,Nonefor a self-pair); the parent keys (#1994)ChildParentKey { person_id, parent_person_id }andCaseChildParentKey { case_id, person_id, parent_person_id };LedgerRetiredReason(corrected/retracted/order_corrected/order_deleted), which implementscraig_ledger_contracts::RetiredReason. The row aliasesLedgerRow<K, F>=craig_ledger_contracts::LedgerRow<K, F, LedgerRetiredReason>andEventRow<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 everycraig_cases_contracts::ledgerpath stays valid. The event-ledger list read (#1994):EventAsOfQueryabsent = 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 aliasesRecordDemographicsRequest/CorrectDemographicsRequest/DemographicsRowover theledgergenerics.persons::RefusedKeykeepsrace/ethnicity/tribal_affiliationon the person create / update bodies ONLY to refuse them (typed 400demographics-via-ledger); it is never serialized and has no schema presence. -
child_facts(#1992) — the five child-fact ledgers' factsParentingFacts,PriorPermanencyFacts,AssistanceFacts(+receives()),SiblingCountFactsandIcwaFacts(#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_notifiedungated, a gate alone admitted — except an order of preferenceyes, which needs its date (present_iff, #2004); the timely tribe notice’syesneedstribe_notified = yes) — and the row aliasesParentingFactsRow/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) andSiblingRow. -
parentage(#1994) —ParentageFacts { parents_abandoned: bool (required), sole_legal_parent: Option<bool> (None = not assessed) }andParentageRow. -
child_parents(#1994) —ChildParentFacts { role: ParentRole, legal_responsibility: Option<bool> }(garde: neverSome(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) andChildParentRow. -
parental_rights(#1994) —ParentalRightsFacts(effective_on,kind, the petition, death and termination dates,parent_deceased,court_order_idand 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) andParentalRightsRow = 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>andPermanencyPlanRow = EventRow<CaseChildKey, _>. -
reviews(1995) —ReviewEventFacts { kind: ReviewKind, held_on: Option<NaiveDate>, court_order_id: Option<Uuid> }(court_order_idis[schema(read_only)] and garde-refused on a request: provenance only the court-order act writes, served on every row),ReviewEventStatementandReviewEventRow. -
court_orders/contacts/case_plans(#1995) —CourtOrderHearing { held_on, children }(garde: 1..=HEARING_CHILDREN_MAX(25) children, each once) ashearing: Option<_>on the create and update bodies;ContactVisit { visited_child_id, location: ContactLocation }as the create’svisit: Option<_>and the update’svisit: Option<Option<_>>(double_option: omitted = unchanged,null= clear); the case-plan create / update bodies no longer carrypermanency_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,retractedand the servedOutboundCustodyRow`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, itsDebugprinting 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; theDebugof each never prints the value),OutboundReadQuery(+identifier, the GTID row a custody read serves),GTID_KIND, and the id pagesOutboundStagesPage,ReportOutboundStages,PersonOutboundStages;custody,application,gtidandidentifierare omitted when absent, so the case and investigation arms answer unchanged bytes. -
custody(#2342, plancustody-episodes-doe-sldsD2–D3, ADR-081) — the legal-status and custody-episode wire: the requestsLegalStatusRecordRequest(optionaluntil: LegalStatusUntil) andLegalStatusCorrectRequest, the queryCustodyEpisodesQuery, the responsesCustodyActResponseandCustodyEpisodeoverLegalStatusFacts, the closed vocabulariesStoredCustodyClass,CustodyEpisodeRetiredReason,CustodyEventandCustodyAct, and the ids-onlyCustodyEventPayloadstaged under the fiveCASE_CUSTODY_*/CASE_LEGAL_STATUS_CHANGEDrouting keys. -
person_identifiers(#1806, plancustody-episodes-doe-sldsD5) — the external person-identifier wire: the requestsPersonIdentifierRecordRequestandPersonIdentifierEndRequest, the masked rowPersonIdentifierand the audited full-valuePersonIdentifierReveal, the closed vocabulariesIdentifierProvenance,IdentifierRetiredReasonandPersonIdentifierAct, and the ids-onlyPersonIdentifierEventPayloadstaged undercase.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 bodyMedicaidPartnerReport(taggedkind: areceiptnaming the application by id, anoutcomenaming a person by identifier and the application by the receipt’s reference; strict; each text 1 to 64 printable ASCII bytes,is_report_text; itsDebugprints nothing the partner stated), the answerMedicaidPartnerReportAnsweroverMedicaidPartnerReportOutcome(applied/replayed/unknown/withdrawn), the stored report as a reader sees it,MedicaidApplicationReport(itsDebugnever prints the program id), the closed vocabulariesMedicaidReportKindandMedicaidReferralStatus, the pathMEDICAID_PARTNER_REPORTS_PATH, and the strict ids-onlyMedicaidApplicationReportReceivedPayloadundercase.medicaid_application_report_received. -
medicaid_applications(#1807, planpartner-auth-medicaid-applicationD7) — 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 rowMedicaidApplication(the decryptedCitizenshipStatus, and since #3193 itsreports, the partner’s reports in stored order), the closed vocabulariesCitizenshipStatus/PriorMedicalAssistance/MedicaidApplicationRetiredReason(as_str/from_token, exact match), the list queryMedicaidApplicationListQuery(child_id), and the strict ids-onlyMedicaidApplicationEventPayloadundercase.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 STRICTEligibilityEvaluatedPayload(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_idrequired, the hard-checks F0 ruling);determination_revisionis the U5 ordering key;ffp_rateis 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 addsCASE_IVE_DETERMINATION_INVALIDATED+ the STRICTIveDeterminationInvalidatedPayload(case_id+determination_revision— the pair financial’s invalidation SET converges on); craig-cases stages it from itsexchange.screening_run_invalidatedconsumer (U5b). #1995 addsCASE_PERMANENCY_PLAN_ESTABLISHED+ the STRICTPermanencyPlanEstablishedPayload(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 addsCASE_CREATED+CaseCreatedPayload(case_id,case_number,admin_unit,assigned_worker,supervisor,user_id) andCASE_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 asNone, anduser_id(#2248) is defaulted; unknown keys are ignored. Golden-JSON tests pin both wire shapes. -
SsnDigest(1430, planPlan::SSASD12) — the versioned SSN blind-index digest newtype. Canonical wire form is one stringv{version}:{44-char base64}(serdetry_from/intoString; the version is the per-field blind-index rotation version, stamped by the producing boundary).PartialEqIS the constant-time compare (subtle::ct_eqover the full canonical bytes; noHash/Ord);Debugredacts the digest (version only) and there is deliberately noDisplay;SsnDigestErroris categorical (never echoes input). Wire-only in A4 — nosqlx::Type(B1 decides the column shape); noToSchema(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, planPlan::SSAB4 / S13) — the hardened egress the typed SSA worker sends through (the genericDirectHttpTransportis untouched): https-only with a literal-loopback http dev carve-out, exact-host allowlist (empty = deny-all;EgressPolicy::from_hoststakes 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 asBadStatus, and the 1 MiB chunked-read response byte cap (MAX_RESPONSE_BYTES— the A1-deferred cap).check_egressis 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 stagedidentifier_id, released only while that row is the person’s live identifier of the screening kind; the response’sDebugredacts 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, planPlan::SSAB3) — the screening request-path wire: the cases intent body (RequestCaseScreeningBody), the staging request/response (StageScreeningRunRequest/StageScreeningRunResponse, members carryingidentifier_id), housed HERE (notcraig-exchange-contracts, a deliberately pristine leaf) because the staging wire IS the screening cohort in motion; both services consume it.requested_by/requested_by_nameare stage-time attribution asserted by the allowlisted cases service (the §D2 posture). -
screening_cohort(#1462, planPlan::SSAB1 / H1) — the ONE shared definition of the SSA screening cohort binding:cohort_hash(&[(person_id, identifier_id)], as_of)(sha256 hex over the domain tagcraig.ssa.cohort.v2+ as-of + sorted pairs frameduuid \0 uuid \n— the ADR-057manifest_checksumprecedent; #3175 moved it from SSN digests to identifier ids),SCREENING_FRESHNESS_MONTHS(= 12, UD11 RATIFIED policy — deliberately a const, not a knob) andscreening_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, planive-determination-inputsU1) — 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 }andIveInputKind(boolean,enumwith labelledoptions,integer/numberwith aminimumand an optionalmaximum,date; internally tagged and flattened into the view).project_ive_surface(name, identity, ruleset_bytes)is the one parser of a ruleset’smetadata.ive.inputs[]and its strict-subset inputNode schema (a repeated JSON key is refused);IveSurfaceErrornames each refusal.IVE_SERVER_KEYSis 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 asGET /v1/cases/ive-surface(registered in its OpenAPI), andcargo xtask rules checkruns the projection on every*-ive-eligibilityruleset (by file stem orname; mandatory) and on any other ruleset carryingmetadata.ive. -
safety_surface(#3104):project_safety_surface(name, identity, ruleset_bytes, server_keys)is the one parser of a ruleset’smetadata.safety.attestable_facts[]and its closed inputNode schema, whoserequiredmust list every property;SafetySurfaceErrornames each refusal.SafetySurfaceResponse(rule_set_name,identity,facts[], each fact a key, title, description and abooleanor boundedintegerkind) is what craig-cases serves asGET /v1/cases/safety-surface.SAFETY_SERVER_KEYSis the (empty) registry of server-derived keys.declared_surfaceholds 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):SubmitSafetyAssessmentRequestis closed (deny_unknown_fields) and carriesclient_request_id,surface(the identity the answers were given against),facts,worker_overrideandworker_override_reason, which is required and non-blank with an override.SafetyFactsis a map of fact keys toSafetyFactValue(a boolean or au32count); a string, fraction, negative number,nullor object value is refused at deserialisation.SafetyFactsand the screeningAttestedFactsare transparent newtypes over one hand-deserialisedreports::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, andlifecycle::{PromotePreviewRequest, PromoteExecuteRequest, RollbackRuleSetRequest}— used by the service and the test-libRulesClientso the request wire shapes stay single-sourced. A leaf crate (serde / serde_json / uuid / utoipa / chrono / sha2 / garde /craig-validationonly; never depends onservices/*orcraig-test-lib, avoiding the dependency cycle per the test-framework-hardening §D8.2 contracts pattern). Thecontent/inputfields carry zen-engine-polymorphic JDM asserde_json::Valueand refuse any NUL (U+0000) in a string leaf or object key atvalidate(), alongside the stored text fields (context_type,version,description,reason), andversionis capped atCODE_MAX(64bytes; #2836). Response types (store::RuleSet,store::RuleEvaluation) remain in craig-rules — they aresqlx::FromRowstore 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) andAfcarsReleasePurpose(afcars-2020 federal reporting), each a closed set of one; placement’splacement.afcars_releasedpayload and cases'case.person_pii_exportedAFCARS wrapper use them. -
The shared request DTOs for the craig-reporting HTTP boundary —
afcars::GenerateAfcarsRequest+ncands::GenerateNcandsRequest— used by the service and the test-libReportingClientso the request wire shapes stay single-sourced. A leaf crate (serde / utoipa / garde /craig-validationonly; never depends onservices/*orcraig-test-lib, avoiding the dependency cycle per the test-framework-hardening §D8.2 contracts pattern). Thegardefield-length validation derives move with the DTOs (soreporting_periodstaysCODE_MAX-capped). Response types (store::models::{AfcarsSubmission, NcandsSubmission, …}) remain in craig-reporting — they aresqlx::FromRowstore models, not yet lifted (the broader response-typing follow-up). -
afcars::AfcarsReadyForTransmission(#2179) — theready_for_transmissionact’s answer (submission, report half,ready_by,ready_at, the certified export generation and file digest), decoded by the test-libReportingExportsClient;AfcarsSubmissionitself 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 };PersonViaisCaregiverSlot(CaregiverSlot::First | Second)or a person-idColumn), 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 checkproves the three lists partition the dictionary. -
afcars_crosswalk::Crosswalk::lookup(series, value) → Option<CrosswalkAnswer>(#2141):Code(&str)|Unmapped;Nonewhen 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-libFinancial*Clientfamily so the request wire shapes stay single-sourced. A leaf crate (serde / utoipa / garde /craig-validation+ the field-type cratesuuid/rust_decimal/chrono; never depends onservices/*orcraig-test-lib, avoiding the dependency cycle per the test-framework-hardening §D8.2 contracts pattern). Thegardefield-length and NUL (craig_validation::contains_nul, #2839) validation derives move with the DTOs (the handlers'body.validate()?calls behave identically).rust_decimal::Decimalcarries the workspaceserde-strfeature, 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 isOption, andagreement_id/term_idmark subsidy-origin UNIT-MONTH rows —daily_rate = gross =the monthly award); the remaining response types (store::models::{RateTable, PaymentAdjustment, ClaimingRecord}) stay in craig-financial assqlx::FromRowstore models (the broader response-typing follow-up).subsidy_generation(#1068/ADR-053) adds the generation-trigger pair:GenerateSubsidyPaymentsRequestwith the strict canonicalYearMonthtoken (one parser, property-tested: never-panics, byte-identical roundtrip, exact grammar) and the per-runGenerationReportcounters both the endpoint and thefinancial.subsidy_generation_completedevent carry (#1070 F2 adds the serde-defaultedskipped_before_payments_begin— months skipped before a guardianship agreement’s stored money boundary; #1071 D5 adds the serde-defaultedskipped_before_cutover— months before an imported agreement’spayment_cutover_month; both absent on older reports; #2228 adds the serde-defaultedqueue_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 ofPOST /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/NrsgshareCreateGuardianshipAgreementBody(the two-step PENDING mint:signed_at+ the anchoringplacement_id, the U3 per-program relationship-evidence rule — required non-blank for sg, optional for nrsg — the requiredcaregiver_assessment_evidence_key, guardianship-family-onlypredecessor_agreement_idlineage; the F8 canonical hash covers the TAGGED body), and the four closed cohorts (Ersg/Enrsg/Rcs/Ercs) share the emptyCreateClosedProgramBodythe service refuses with the typedclosed-programproblem.CreateSubsidyPartyRequest(1–10 signatories, ≥ 1caregiver, 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_idis 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 ofPOST /v1/financial/subsidy-agreements/{id}/activate) carries NO dates beyond the optional past-datedtanf_terminated_onattestation —transfer_onis DERIVED from the S2S-projectedepisode_exit.exit_on(#2022), never caller-typed; fields: the CASexpected_head_interval_id, the requiredcourt_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.SubsidyAgreementDetailgains 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 recordedImportStampRecord— the D9 posture means NO server facts and NO authz denorms exist on the DTO),ImportWarning/ImportBlocker/PaymentAssessment(the persisted stage outcomes),StageOutcome+ theStageOutcomeKindreplay vocabulary (staged/already_staged/restaged/already_imported/rejected),ImportRecordView/ImportBatchDetail/ImportBatchCounts/ImportRecordPage, andFinalizeReport/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,nulloptionals, ISO dates, RFC 3339 UTC stamps, money normalized to 2 dp so"450.5"≡"450.50"),canonical_hash(sha256 hex of the compact serialization), andmanifest_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, planbackpay-import-pathU1/U2) carries the below-floor backpay ledger contract: the frozen priced rowBackpayPricedRow/BackpayRowKind, the typedBackpayBlocker
theBackpayBlockerTokenvocabulary (the stage refusals plus the three finalize tokensjudged_row_changed,canonical_hash_mismatch(#2224), andunpublishable_event(#2827)), and the finalize pass’s reportBackpayFinalizeReport/BackpayFinalizeStatus(finalizing/staging/finalized) /BackpayDivergence. FOUR pub fns live HERE so the service, thecraig backpaytool 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 askey \n: the batch’s completeness manifest) andcontent_checksum(sha256 over the sorted(record_key, canonical_hash)pairs, each fed askey \0 hash \n— the import manifest’s framing, delegated tosubsidy_imports::manifest_checksum— over thestagedandmaterializedrecords 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-onlySweepMovedChild(per diem on a DIFFERENT placement — visibility, never executed) join the preview/run views;ExecuteSweepRequestgrows theacknowledged_suspend/acknowledged_terminate/acknowledged_handoffhandshake (server 409s on any mismatch with the pinned sets — a UI that never rendered a leg cannot execute it);SweepReportandSweepRunCountersgrowleg3_actionable/handoff_terminated/leg3_moved_children, andSweepRunViewgrowsmode_per_diem_handoff— all M3 additionsserde(default)so pre-leg events/rows still deserialize.afcars(#2123) carries theafcars-factsquery, page and opaque base64url child-id cursor;base64joins 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+ theevents::PLACEMENT_ACTIVATEDrouting-key constant are compiled by BOTH the craig-placement producer and the craig-financial consumer, so the billing contract (field names,foster_home_idnullability,started_atas the proration anchor) cannot drift the way the untypedplacement.createdshapes did pre-#979. A leaf crate (serde +uuid/chrono; never depends onservices/*orcraig-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 fieldreplaces_placement_id(serde(default), omitted whenNone): the retracted arrangement the activated row re-records, so a plain activation carries no such key and an older envelope decodes asNone. #2277 addsuser_id(serde(default), always serialized): the acting worker’s sub (the creator of a born-activerow, the activating worker onplanned → active), audit-only — craig-financial does not read it; an older envelope decodes asNone. -
events::PlacementEndedPayload+ theevents::PLACEMENT_ENDEDrouting-key constant (#1070 F9) — the placement-ended twin:{ placement_id, end_reason?, ended_at?, user_id? }(#2277:user_idthe ending worker, audit-only andserde(default)), compiled by the producer, craig-financial’s subscription binding, AND its dispatch arm (it replaced an ad-hoc producer-sidejson!whoseend_reasonthe financial consumer silently dropped, making the two sides undriftable).end_reasonisOptionfor 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/statuswire tokens (since #2056placement_typeis the federal setting token),ffh_types(#2056: the family row’s applying (e)(3) categories, typedFosterFamilyHomeTypeso an unknown category fails the decode, serde-defaulted,nullotherwise),started_on), the response of craig-placement’sGET /v1/placement/placements/{id}/subsidy-eligibilityand the type craig-financial’sPlacementClientS2S 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 withepisode_exit.exit_on; since #2059 the witness readsresidence.ended_oninstead and no financial code reads this field;Nonewhile the placement is live) andend_reason; it also addedpermanency_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_onare the placement’s first/last day on the JURISDICTION’s business calendar (Eastern for Georgia), projected placement-side viaBusinessClock::date_ofso the consumer never converts timestamps. Type/status staysnake_casestrings — the crate is a serde-only leaf; consumers parse intocraig_referenceenums and fail closed on unknowns. #2021 adds the serde-defaultedepisode_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_reasonis the typedExitReason(an unknown token fails the decode); craig-financial’s guardianship witness reads it (#2022). #2059 adds the serde-defaultedresidence: 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 itsended_onto equal the exit day and its residence floor measures from itsstarted_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; withRemovalFacts::unansweredandREMOVAL_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; withExitFacts::unansweredandEXIT_ANSWER_KEYS) (#2019; a garde rule answers 422 unlesstransfer_agency_typeis present exactly when the reason istransfer_to_another_agency),ResponseRow<F>over the shared craig-ledger-contracts event row (plusfirst_recorded_at;RemovalResponseRow=ResponseRow<RemovalFacts>,ExitResponseRow=ResponseRow<ExitFacts>),ResponseRetiredReason(correctedorretracted),EpisodeRow(the episode with its live removal response and, since #2019,exit:nullexactly whenexit_atisnull, else the live exit on a live episode or the exit retired with it on a retracted one), the strict act bodiesOpenEpisodeRequest/CorrectRemovalRequest,ExitRequest(#2019; one body for the exit record and the exit correction) andHistoricalEpisodeRequest(#2019; the episode, its removal and its exit in one act) (the retractions reusecraig_ledger_contracts::LedgerRetractRequest), and the cancel’sCancelPlacementRequest/PlacementCancelled. -
trafficking(#2082) — the two trafficking event-ledger wires:TraffickingStatementFacts/TraffickingReportFacts, the strictTraffickingStatementRequest/TraffickingReportRequest, the rowsTraffickingStatementRow/TraffickingReportRow,TRAFFICKING_ANSWER_KEYS, and the re-exportedEventAsOfQuery/EventThroughQuery/LedgerRetractRequest. -
child_facts(#2084) — the two per-child window-ledger wires:ChildKey { child_id }, the factsHealthFactsb)(10):condition_statusand elevencondition_<category>answers) andEducationFacts((b)(11), (b)(12), (b)(14, the key constsHEALTH_FACT_KEYS/EDUCATION_FACT_KEYS(every key REQUIRED,null= unanswered), the strict hostsChildFactsRecordRequest<F>/ChildFactsCorrectRequest<F>, and the rowsHealthFactsRow/EducationFactsRow. -
education_reports(#3188) — what a partner reported about a child’s schooling, as craig-exchange hands it to craig-placement: the strictEducationPartnerReport \{ 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 pathEDUCATION_PARTNER_REPORTS_PATHand its answerEducationPartnerReportAnswer \{ outcome: applied | stale | listing_ended }. craig-exchange’s collection run is the one writer. The staff read isEducationPartnerReportsQuery \{ child_id }answeredEducationPartnerReports \{ reports: [EducationPartnerReportView] }. The two events' payloads (EducationReportReceivedPayload,EducationReportWithdrawnPayload) andReportWithdrawnReasoncarry ids, the interface and a day or a reason only. -
partner_listings(#3188) —EXCHANGE_LISTING_ENDEDand the strictListingEndedPayload \{ 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 bodyRetractPlacementRequest { client_request_id, note }(note 1–1000 characters,REASON_MAX) and its lenient answerPlacementRetracted(status,retracted_from, the retract trio); the strictHistoricalPlacementRequest(the past arrangement’s type, optional home,started_at,ended_at,end_reasonand optionalreplaces_placement_id; the record is never activated, never occupies and never bills) and its lenient answerPlacementRecorded; andArrangementFacts, the arrangement’s 16 required-nullable AFCARS answers ((e)(5)–(e)(8), (i)(5)–(i)(8); #2080; strict, one field perplacementsfact column,ArrangementFacts::default()every answer unanswered; withARRANGEMENT_FACT_KEYS, the key list in declaration order), flat onHistoricalPlacementRequestandPlacementRecorded(and on craig-placement’s create body and placement read), and whole as the placements PUT’sarrangement_factsobject, the complete state. -
events::EpisodeFactsChangedPayload+events::PLACEMENT_EPISODE_FACTS_CHANGEDandevents::PlacementCancelledPayload+events::PLACEMENT_CANCELLED(#2018) — theplacement.episode_facts_changed(EpisodeLedger—ExitResponsessince #2019, the two trafficking ledgers since #2082 — andEpisodeActclosed tokens) andplacement.cancelledpayloads; strict (deny_unknown_fields), ids and tokens only,user_idthe attribution key. -
events::PlacementRetractedPayload+events::PLACEMENT_RETRACTEDandevents::PlacementRecordedPayload+events::PLACEMENT_RECORDED(#2020) — theplacement.retractedpayload (retracted_from: the closedRetractedFromtoken,activeorended) and theplacement.recordedpayload (started_at, optionalreplaces_placement_id); strict,user_idthe attribution key. craig-financial compiles both into its bound keys. -
afcars(#2018, #2019, #2054) — the placement side of the AFCARS element map, in the sharedcraig_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_UNITsince #2084),LAST_UNIT(=B3U5),OWNED_ELEMENTS(all 67 placement keys, each on its unit),owned_after_unit(key)andAFCARS_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 ownremoval_responsesanswer columns (#2081), (e)(1)placements.started_at, (e)(2) the generatedplacements.foster_family_home, (e)(3) the sixplacements.ffh_type_*flags, (e)(4)placements.placement_type(#2056), (e)(5)–(e)(8), (i)(5)–(i)(8) the arrangement’s ownplacementsfact columns (#2080), (d)(5)–(d)(6)(i) theepisode_trafficking_statementsanswer 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 ownexit_responsesanswer columns (#2083), (b)(9) aNamedoverride overhealth_records.health_assessment/visit_date/activeand the episode’sremoval_at/exit_at, (b)(10) thechild_health_factsanswer columns (Gated), (b)(11), (b)(12), (b)(14) thechild_education_factsanswer columns (#2084); (h)(3)–(h)(7) / (h)(8)–(h)(12)Personfacts through the exit’s first / second adoptive slot (#2083); (e)(9)–(e)(13) / (e)(14)–(e)(18)Personfacts through the arrangement’s first / second caregiver slot (persons.birth_yearelseyear_of_birth_declared,person_demographic_facts.tribal_member, its sevenrace_*flags,ethnicity,persons.sex); (b)(20)Derivedoverperson_siblings,removal_episodesandplacements; (b)(21)Derivedover the same inputs plus the arrangement’s setting identity (placements.foster_home_id/placements.kinship_household_id, #2058). -
kinship_households(P-B2 U5, #2058, planafcars-placement-factsD4) — 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": {…}}) andNewKinshipHousehold { admin_unit? }(strict; admitted only while the episode has no unit stamp). The create and historical bodies carry the choice askinship_household;PlacementRecordedgainskinship_household_id. -
caregivers/portal(#2058) — a binding keysfoster_home_idXORkinship_household_id(wasplacement_id) on the binding view, the create body and theplacement.caregiver_bound/caregiver_endedpayloads.SubjectCaregiverBinding(craig-financial’s authoritative bindings read) also carries the REQUIREDchild_arrangement_ids(the household’sactivearrangements, ascending — the portal’s child scope) andpayment_arrangement_ids(every non-cancelled household arrangement, ascending — the payment-agreement anchors), both empty on a home binding.PortalUnitKindPlacement→KinshipHousehold(wirekinship_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_identitiesandworker_admin_unitsmodules (admin-unit / major-change / detection-rule / NIST-control / review / partner / partner-key / signer-key create+update bodies;worker_identities: the #1857 batched contact lookupWorkerContactsRequest→WorkerContactsofWorkerContact, and the admin work-line writeSetWorkerContactRequest;worker_admin_units:AssignWorkerAdminUnitRequest, theWorkerAdminUnitrow and the #1900 service-onlyAdminUnitsSnapshot) — used by the service and the test-libSecurity*Clientfamily so the wire shapes stay single-sourced. A leaf crate (serde / serde_json / utoipa / garde /craig-validation+ chrono; never depends onservices/orcraig-test-lib, avoiding the dependency cycle per the test-framework-hardening §D8.2 contracts pattern). Thegardefield-length validation derives move with the DTOs. The polymorphicfindings/remediation_plan/public_key_jwkfields stay JSON values (STRUCTURAL-VALUE carve-outs);VerifyPartnerRequeststays service-internal (the test-libverify_partnerbuilds its body internally). Response types (store::models::) remain in craig-security — they aresqlx::FromRowstore 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 ofPOST /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 forSanitizedText; nocraig-reference— the free-text fields areSanitizedText, the rest plainString/bool/ date / JSON values, capped by garde, not domain-enum-typed; never depends onservices/*orcraig-test-lib, per the test-framework-hardening §D8.2 contracts pattern). Thegardefield-length validation derives move with the DTO, so the handler’sbody.validate()?is unchanged; the polymorphicchildren/adults/narrativefields stay JSON values (STRUCTURAL-VALUE carve-outs), so the struct derivesPartialEqbut notEq. -
sanitized::SanitizedText(#2524, re-exported at the root) — intake free text, sanitized when it deserializes. Its only producers,SanitizedText::parseand theDeserializeimpl 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 toTEXT_MAX_CHARS(8 192) chars. The value is plain text, never entity-encoded: consumers escape at output.parserefuses a raw value overRAW_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), withUnsanitizableText::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, thecraig-webBFF’s hand-builtserde_json::json!envelope coupled to it only by a// matches SubmitReportRequestcomment, and the SDK’sReportSubmission. craig-web now constructsSubmitReportRequestdirectly, 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 `ReportSubmissionbuilder 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-libIntakeClientspeak the wire shape as external callers (theIntakeClientstays rawValue, #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) andhash_payload(canonical) → String(SHA-256 hex). It holds no key and signs nothing: the detached JWS iscraig_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,
noneattestation, discoverable credentials, user verification required. No I/O, no state: every challenge is derived by the caller from a canonical document. No OpenSSL:webauthn-rsneedsopenssl, whichdeny.tomlbans. -
Ceremonies:
verify_registration_ceremony(policy, attestation_object, client_data_json, challenge) → Result<AttestationObject>(client data, then the attestation object, then the policy) andverify_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’sverify_derover anEs256PublicKey(#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(exactlyfmt="none", an emptyattStmt,authDatawith a credential),ClientData::{parse, verify}. CBOR is decoded withcbor4iithrough 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)andcheck_authenticator_data(RP ID hash, UP, UV, BS only with BE per WebAuthn L3 §7.1/§7.2, BE when device-bound); newtypesRpId,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
WebAuthnErrorvariant 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
*.jsonundersdks/test-vectors/webauthn/.chromium-virtual.jsonis Chromium’s virtual authenticator, with its capture script;capture-manual.jscaptures 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-Signaturewhen 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 onReportSubmissionsince #648; the builder refuses to build without one; pinned againstsdks/test-vectors/report-sources.jsonin 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) — setrel_to_primary_caretakerto a typedRelationshipToCaretaker’s code and `designationto the list that holds it, so the server reads the code from the same list. The three relationship types are re-exported fromcraig-reference, and the parity test pins them tosdks/test-vectors/caretaker-relationship-codes.json. The Python and TypeScript SDKs type the same entries (#3180), andsdks/test-vectors/person-entries.jsonholds all three to one wire shape. -
signingmodule —SigningConfig(from_jwk(jwk_json, key_id),key_id()),canonicalize_json,hash_payload,sign_detached(shares thecraig-signingcontract).
craig-exchange-contracts (Plan L + Plan T1.2)
-
Typed
ExchangeAdaptertrait (RPITIT; ADR-038 §1 Tier-T) — unchanged by the erased seam. -
ExchangeAdapterKindenum DELETED at Plan T3.1 (ADR-032 §1.3 open-TEXT carriage) — adapter identity is the&'static strfromErasedAdapter::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*_valuemethods returnBoxFuture<'a, Result<…, ErasedAdapterError>>with one'ashared by&'a selfandauth(#2426), andsend_valuethreadsformat: Option<&str>. #2295 removedaudit_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 throughExchangeAdapter::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. RedactedDebug(the scheme and an API key’s header name, never a value or the username), noSerialize,kind()→none/bearer/basic/api_key(D1’sauth_typevocabulary). All three macro arms forward it;typed_only’s `send_valuestill refuses first. Deps gainsecrecy. -
DispatchClass(#1428, exhaustive by design) —Generic(the generic exchange pipeline may stage/dispatchValuepayloads for the kind) vsTypedOnly(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).DisplayandErrorare written out, since a derive cannot name aPartnerErrorobject as a source; the wording and the source chain are what the derive gave.failure()answers the partner’sPartnerFailure, andNonefor 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 thePartnerFailureViewtrait:failure(&self) → PartnerFailure<'_>, anddigests_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::ErrorandCollectionAdapter::Errorare bound byPartnerError(an error that isSend + Sync + 'staticand 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’ssettlement::partner_failure).Infalliblehas 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, orNonewhen no contract with the source exists and nothing may be sent) andask(endpoint, auth, question) → Result<A, InquiryFailure>.InquiryFailureis 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) plusidentifier-unusable, andretryable()is false only foridentifier-unusableandpartner-refused, which a resend cannot change. The first pair is the SSA benefit screening:SsaBenefitQuestion \{ identifier: SecretString, request_date }(itsDebugprints no value) andSsaBenefitAnswer(Found \{ month, benefits }orNoRecord);SsaBenefitInquirynames the registered form. -
#3192, the person-index contract (
person_index.rs):PersonIndexis 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>andparticipate(endpoint, auth, &IndexParticipation) → Result<(), InquiryFailure>.IndexSubject \{ first_name, last_name, sex, date_of_birth }is all a find sends.IndexIdis 1 toINDEX_ID_MAX(64) printable ASCII bytes;admitted(Vec<IndexCandidate>)holds an answer toMAX_CANDIDATES(250), a score of at mostFULL_SCORE(100) and each text’s cap, and answersMalformedotherwise. No type’sDebugprints what describes a person. A person index is the canonical page. -
#3193, the referral and return contracts (ADR-091).
referral.rs:ReferralLegisinterface(),leg(),assemble(&ReferralContext) → Result<Value, AssemblyRefusal>andclassify(&SentRecord, &Value) → ReferralVerdict;ReferralContext \{ application: &ApplicationView, child: &PrincipalView, custody: &CustodyView, case_number, correlation_id };ReferralVerdict::Acceptedcarries aReferralReceipt, the partner’s reference, whichReferralReceipt::parsetakes only as 1 toREPORT_TEXT_MAX(64) printable ASCII bytes with no space and whoseDebugwithholds it.returns.rs:ReturnLegisinterface(),leg(),max_bytes(),decode(content_type, body) → Result<Collected, ReturnRefusal>andacknowledge(&ReturnRun) → Acknowledgement \{ status, content_type, body }, both pure;ReturnRunisCompleted \{ settled: Vec<(PartnerReport, ReportOutcome)>, unread }orRefused(ReturnRefusal);returns::admitted(Collected)holds a decoded call toMAX_REPORTS(500) and each report’s caps, andreturns::decode_refusalreads a leg’sBusyasMalformed, since only a host can know it is busy.collection.rs:PartnerReportgainsMedicaidReferral(MedicaidReferralReport \{ identifier_kind, identifier_value, reference, case_reference, program_id, status: Option<ReferralStatus>, reported_on }), whoseDebugprints none of the partner’s four texts;PartnerReport::subject() → ReportSubject(Person(id)orReference) replacesperson_id(). A referral leg and A return are the canonical pages. -
#3196, the triggered-send contract (
trigger.rs):TriggerLegis aLegSpecand three pure rules,admits(stage, principal, today),assemble(ctx) → Result<Value, AssemblyRefusal>andclassify_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) andLegScope(Stage,Person).LegSpec::fault() → Option<SpecFault>names a spec that contradicts itself. A leg reads the specification’s own views,StageView,PrincipalView,CustodyView,CustodyRowViewandIdentifierView(a person’s identifier with its kind;Debugprints no value), assembles from aRecordContext(since #3193 withapplication: Option<&ApplicationView>, set on a Medicaid-application stage only), and judges an answer against aSentRecord(deliberately notDebug).AckVerdictisAccepted(body),Rejected \{ code },Mismatch,Malformedor, 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 interfacelegscannot give one; it crosses asMalformed). 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 (bothGeneric)
typed_only(#1428 —send_valuerefuses unconditionally withTypedOnlyDispatch; the payload-free connectivity probe still forwards);pub use futures_util::future::BoxFuture. The typed-partner arm takes a REQUIREDcorrelation = Some("<field>") | Nonecarrier (#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 beforefrom_value(replacing that field’s value), or removes it when the carrier isNone. The SHINES envelope carries it at its top level under the same key (#2398). -
#3188, the collection seam (
collection.rs): the inbound mirror ofExchangeAdapter, for a leg in which CRAIG fetches what a partner published about the people CRAIG told it about. A partner crate implementsCollectionAdapter(interface(),leg(),collect(endpoint_url, auth) → Collected); the registry holds the object-safeErasedCollection, which every typed collection is, its future boxed and its typed error boxed asErasedAdapterError::Inner. What crosses the seam is a product record, never a partner’s wire:PartnerReport(first variantEducation(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 emptyCollected; one that cannot be fetched or read is an error and nothing of it is answered. Deps gainchronoanduuid. -
#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 throughArc<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.DirectHttpTransportfetches under a send’s guards (the internal-address refusal, the credential channel, the 1 MiB response cap; a 2xx isOk, anything elseBadStatus);EgressControlledTransportfetches under its allowlist, https rule, pinned address, redirect ban and the same cap, and refuses any auth butNone;WebMethodsTransportrefuses, since the broker stub has no service that fetches;StubTransportanswers a queue set bywith_fetch_results(an empty 204 past it) and recordsfetch_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 isNone(the partner has published nothing, which is no failure), and a body that is not anIis 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 }(Headpartners /GetSHINES);TransportResponse { status: u16, body: Vec<u8> }. Both request structs also carryauth: OutboundAuth(#2426), apart fromheaders, so no header-logging path carries a credential. -
TransportError(thiserror, Clone) —Timeout/Connect/BadStatus { status, body }/Transport(String)/AuthUnsupported(#2426, value-free);reqwestis never named in apubsignature. -
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(behindtest-util— canned-response, request-recording double);pub use futures_util::future::BoxFuture. -
#2426 (TP-2 D2) — the credential channel:
DirectHttpTransportappliesBearer/Basicthrough reqwest’sbearer_auth/basic_authand anApiKeyas a sensitiveHeaderValuein its named header, on send and probe (an API key that is no valid header value fails with the value-freeTransportError::Transport("outbound auth: invalid header value"));WebMethodsTransportandEgressControlledTransportrefuse any auth butNonewithTransportError::AuthUnsupportedbefore an envelope, a DNS lookup or a client exists;StubTransportrecords the whole request,authincluded (it istest-util-only);pub use craig_exchange_contracts::OutboundAuth. Deps gain craig-exchange-contracts andsecrecy. -
#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, defaultsDEFAULT_CONNECT_TIMEOUT5 s /DEFAULT_SEND_TIMEOUT30 s) withprobe_health::<E>(endpoint_url, auth)(HEAD {url}/health) andsend_json::<O, I, E>(endpoint_url, auth, payload)(JSON POST + typed decode; #2426 sets each call’sauthon the request); thePartnerTransportErrortrait (timeout/bad_status/transportconstructors
the ONEfrom_transportper-arm mapping —TimeoutandBadStatuskeep dedicated variants, the #1460 body bound applied at construction, andAuthUnsupported(#2426) joinsConnect/Transportin the catch-all); and thepartner_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 xtaskpartner_plumbingtest pins the shape on the reference partner: its adapter delegates throughcore.send_json(/core.probe_health(with no mapping fn, and its error.rs is the macro invocation alone (oneenum, noderive). -
#1821, #3196 —
partner_error!implements craig-exchange-contracts'PartnerFailureViewfor every enum it stamps (the two decode variants shareMalformed;BadStatuslends its bounded body). Itsbody_digestargument is required:keeporomitis the enum’sdigests_bodyanswer. 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
hostfeature (ADR-090) holds everything that opens a connection:DirectHttpTransport,EgressControlledTransportwithEgressPolicy,check_egress,ip_is_internalandMAX_RESPONSE_BYTES, andWebMethodsTransport, 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,PartnerTransportErrorandpartner_error!, and builds forwasm32-unknown-unknown, which is how a partner crate built into a module takes it. The crate’s own tests switchhostandtest-utilon 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 checkedpartners/manifest.toml(name,version,contract,limits \{ fuel, memory_bytes },build \{ partner_set, simulators }andinterfaces, 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>(Nonewhen no layer holdspartners/) andfrom_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()andpartner_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’sMockRoutes, with itscallerwhere the module’scallersexport lists the kind; a module built before contract 1.2 has none) andsimulator(kind), andModuleSimulator::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::Validateholds it to the product’s own caps (NAME_MAX,ENUM_STRING_MAX, andSIM_IDENTIFIERS_MAX16 entries,SIM_IDENTIFIER_KIND_MAX16 bytes,SIM_IDENTIFIER_VALUE_MAX32 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, andclear()forgets everything. -
MockRoutes \{ router: axum::Router, simulator: Option<Arc<dyn PartnerSimulator>>, caller: Option<Arc<dyn PartnerCaller>> }: one partner’s mock, withMockRoutes::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, andanswered(leg, status, body)tells the simulator what CRAIG answered. -
now() → DateTime<Utc>andIdSource::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, andmodule_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!andreturn_conversions!(#3193) do so for what contract 1.2 added, andleg_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.PartnerSetSourceandexport_partner_set!(Source)export a partner set, with the host’s transport handed to the source as anOutboundTransport;PartnerSetSource::person_indexdefaults to none, asreferral_legsandreturnsdo, so a source written for an earlier minor of the contract builds unchanged;SimulatorSetSource,Mockandexport_simulators!(Source)export the simulators, aMockcarrying 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(typedPlugin.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/ asyncrender; the v1 backend isCompileTimePluginSourceover theCRAIG_PLUGINSlinkmeslice (v2 = WASM).PluginRegistry(pre-materialized, boot-validated) +PluginBootError. Noreqwest(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-purefn(&RenderCtx) → Result<RenderedFragment, PluginError>and expands to a[linkme::distributed_slice(CRAIG_PLUGINS)]registration carrying the slug, theinclude_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 hardcodedmatch slug. -
The macro core operates over
proc_macro2types so the parse + codegen is unit-testable; an ident-safety guard rejects a non-kebab slug with a cleansyn::Error. Consumers needlinkmeas a direct dep (the expansion references::linkme) + acargo-macheteignore 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 theplugins/tree (NOTcrates/). A context-free dashboard panel: a sync render fn + a four-state Askama template (data/empty/error;loadingis shell-owned) + aPlugin.tomldeclaring one context-free craig endpoint (the open-cases count). CSP-clean (classes +data-*only). -
Opt-in: compiled into craig-web behind the
plugin-exampleCargo feature (NOT indefault)
the#[cfg(feature = "plugin-example")] use craig_plugin_example as _;linkmeforce-link inmain.rs; devstack/e2e enable it via theCRAIG_WEB_FEATURESDockerfile build-arg. This is the template every futureplugins/<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-examplefeature also compiles inservices/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-matrixcompiles 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_fixtureoverlays the plugin’s one term,term-open-cases, in both locales when the feature is on, socargo nextest run -p craig-web --features plugin-examplepasses 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/Claimsmodel. Consumed by theservices/craig-compositionhost (the I/O, DB, cache, and RMQ live there, not here). -
merge—apply_merge_patch_7396(RFC 7396) +apply_json_patch_6902(RFC 6902 viajson-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-anchoreduser_delta_v1envelope (UserDelta/UserDeltaError)
apply_user_delta/validate_user_delta(incl. the CRAIG no-required-hidden floor). #2634: a repeated slug inhidden_slugsorslug_orderis 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 slugsJurisdictionSlug/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 oncraig-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’sarchitecture_invariantsscans this crate’s manifest alongside its own). -
static/css/— the shared stylesheetstokens.css/chrome.css/components.css, the set the crate’s own failure template links (#1867). Not compiled in: each host’s image stageCOPY`s `crates/craig-bff/staticinto/app/staticbefore the host’s ownstatic/, served by the host’sServeDir; craig-web layersscreens.css, the portalportal.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’scraig-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 answersbff-admit-worker-only(WORKER_ONLY_REFUSAL_KEY) orbff-admit-dual-role(DUAL_ROLE_REFUSAL_KEY); craig-portal’s pure-portal ruleportal-admit-refused,portal-admit-dual-roleorportal-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’sCookieNames. Every cookie is minted atPath=/under the host’sSecureposture (BffConfig::session_secure): every helper that mints or removes one,set_flash/take_flashincluded, takes it as itssecureflag (#2258). Every removal (take_flash,clear_sessionand the callback’s PKCE cleanup) goes through the crate-privateexpire_cookie, whose removal namesPath=/and the cookie’s mint-timeSecureflag. It therefore expires the cookie from any route (#2095). The callback expires the PKCE cookie only when the callback’sstatematches 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 byauth_verifybefore a session is minted, the audience verdict,establish_session),logout(RP-initiated withid_token_hint), generic overS: 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 same401+HX-Redirectwhen 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’slogin_path— a303for a browser navigation,401+HX-Redirectfor an htmx request, so an htmx fragment navigates the page instead of swapping the login hop, #1944),set_locale(the host’sLocalePolicy; the{prefix}localesigned cookie is the session tier) and its write sidestore_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=Laxand a year long; craig-web’sPOST /personalize/languageand the portal’sPOST /languageboth call it). -
transport—Transport—Transport::new(caller, http, streaming_http), the host’shttp_clientcaller label given once (#1954;caller()reads it), withOutboundIdentity::{Actor, SubjectToken}(ADR-076 D2: the portal relays the user’s own token inX-Craig-Subjectunder 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’sMULTIPART_TEXT_PART_MAX_BYTES; an over-cap part isUploadError::TextPartTooLong { part }, thebff-upload-text-too-longflash, #2632);form—minted_form_get!(takes the host state type)
helpers;page—PageContext/Breadcrumb/flash_error_redirect(generic overS: BffState;PageContext.languages: Vec<LanguageChoice { tag, name, current }>is what a nav’s language switcher lists, each under its own name frombff-language-name, and is empty while the host negotiates one locale, #1487);csp—STRICT_CSP
the three security-header layers;error—BffApiError(SessionExpiredrenderssession_expired_response: a303to/login, or401+HX-Redirectfor htmx) rendered through the crate’s own failure template and the embeddedbff.ftl(en + es, in craig-i18n’s catalog) — everyBffApiErrorcategory, 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’sUploadErrorcopy; 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.rsso 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 oncraig-state-bundle(theTerminologyContributionoverlay 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 alocale → key → Arc<str>table),translate(locale → default-locale → raw-key fallback), the encapsulating accessorshas_message/default_locale/available_locales(the storage map is private), and the consuming buildernegotiate_complete_locales_only(#1487, replacing #1332’spin_negotiation_to_default— keeps in the negotiation set only the locales that resolve every key the default locale resolves; everynegotiate_localetier 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 isenalone; 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).TerminologyBootErroris 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 (readsExtension<I18n>) that negotiates + runs the request under thetask_local!locale scope;with_locale/translate_current/current_localeback the Askamat()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 thereport-/public-keys, folded into every load so a consumer with no on-disklocales/(the stateless edge, ADR-017) still resolves both product locales. Note: this injects anesbucket into every consumer — craig-web negotiates only complete locales for exactly that reason (#1332, #1487, the ADR-044 amendments). The embeddedbff.ftlalso holdsbff-language-name, each language’s own name. -
test-utilfeature →I18n::for_testfor 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
StateBundletrait 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 theConfigBundleloaded at boot from its configuration layers (craig-config-bundle). Tests may implement the trait with a fake. -
StateBundletrait (name/jurisdiction_code/contribute/federal_mapping+ the #1072 DEFAULTED pairsubsidy_policy()/uas_codes()+ the U-FMAP DEFAULTEDfmap_rates()— effective-datedFmapRateSpec { effective_from, rate_percent }'staticstrings, empty = "no FMAP data, consumers refuse to price FFP") + the #2056 DEFAULTEDrate_class_policy()(plan D5, non-Option: product vocabulary) returningRateClassPolicySpec { family_home_precedence, family_home_default, settings }— the first applying (e)(3) category in precedence order picks a family row’sRateClass, elsefamily_home_default;settingsmaps each congregate setting; the defaultTODAYS_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 pairbusiness_timezone() → Option<&'static str>(an IANA tzdb namecraig_common::BusinessClockparses — no chrono in this crate;None= no declared zone: business dates run on UTC and the AFCARS surface refusesjurisdiction-unregistered) /subsidy_writes_enabled() → bool(defaultfalse= every craig-financial subsidy write act refuses with 400unsupported-jurisdiction; reads are never gated; a jurisdiction declares it only after meeting the ADR-053 § Amendment #1797 checklist) + the #2341 DEFAULTEDlegal_statuses() → Vec<LegalStatusSpec>(empty = no vocabulary; a consumer refuses any act that needs a status) — the per-bundle-identity mappings are trait methods (the D3federal_mappingdoctrine), not contribution fields. -
BundleContribution8-field aggregate:adapters(factory pairs, A4) /mock_routes(A5) /partner_types/seed_data: SeedContribution
the Phase-2 axestheme: 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 fromtheme/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 abundle/theme.tomlmay name; a jurisdiction’s own palette is explicit values in that file. Palette VALUES are generated fromtheme/*.tomlbybuild.rsat BUILD time — onePALETTEStable, every entry emitted by the same codegen (toml/serdeare build-deps only — no runtime toml in this crate).merge_high_contrast(base, overrides)is the one high-contrast merge:build.rsand 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>+ThemeBootErrorlive here (the privaterender_*/validate_palettehelpers stay module-private). Shared by craig-web + craig-intake so both emit byte-identical CSS; each host loads its bundle at boot + holds its ownArc<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-sourcedFOSTER_HOME_PORTAL_SURFACE("foster_home_portal")
FOSTER_HOME_PORTAL_FIELDS(the sixtable.columntokens — STATEplacements.status, SHAREDeducation_records.school_name/grade_level,health_records.next_due_date,foster_homes.phone/primary_contact) andfoster_home_portal_surface()— the ONE construction site of the roster: a jurisdiction’sbundle/field_surfaces.tomlnames 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’sfield_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 replacederr_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_ratedoctrine — 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-sldsD1):LegalStatusSpec { token, label, custody_class },CustodyClass::{InCustody, NotInCustody}, andLegalStatusVocabulary::resolve(Vec<_>) → Result<_, LegalStatusVocabularyError::{MalformedToken, DuplicateToken}>. A token is 1 toLEGAL_STATUS_TOKEN_MAX(16) ASCII uppercase letters or digits.parse(&str) → Option<LegalStatus>is total and exact (no trim, no case fold), and onlyparseconstructs aLegalStatus. 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-sldsD5): the defaultedidentifier_kinds() → Vec<IdentifierKindSpec>(default empty: a consumer refuses every identifier act),IdentifierKindSpec { token, label, format },IdentifierFormat::Digits(n)(exactlynASCII digits, no trim;accepts(&str)), andIdentifierKindVocabulary::resolve(Vec<_>) → Result<_, IdentifierKindVocabularyError::{MalformedToken, DuplicateToken, MalformedFormat}>, checked in declaration order: a token is^[a-z][a-z0-9_]{0,15}$(IDENTIFIER_KIND_TOKEN_MAX16), declared once, with a format insideDigits(IDENTIFIER_DIGITS_MIN..=IDENTIFIER_DIGITS_MAX)(5..=32, so a mask to the last four always fits).parse(&str) → Option<IdentifierKind>is exact;IdentifierKind::acceptsapplies 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-applicationD6): the defaultedmedicaid_application_identifier_kind() → Option<&'static str>(defaultNone: ungated) names the identifier kind a Medicaid application submit needs, held live by the child through commit. craig-cases resolves it at boot againstidentifier_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 fromhttp_client). -
4 registries with duplicate-detecting
from_bundles→BundleMergeError::DuplicateEntry { kind, key }:AdapterRegistry/PartnerTypeRegistry/FederalPartnerMappingRegistry/MockRouterRegistry(#2295 removedAuditCodecRegistry). -
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>, whereMockRoutesiscraig-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).SimLoadedis what a people load answers on the mock-server’s simulator control surface (Partner simulators); theSimPersonit 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 eachArc<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 asssa_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 asperson_index(PERSON_INDEX_INQUIRY).referral_legs: Vec<Arc<dyn ReferralLeg>>andreturns: 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’sreferral_legsandreturn_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 thelegsinterface 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) andoutbound_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*.jsondirectly under each, sorted; aFIXTURE-JURISDICTIONmarker tags a layer’s files).cargo xtask rules checkandcraig rules driftboth 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 thebundle/directory of the layers acraig_config::ConfigSnapshotholds and implementsStateBundleover them, so a consumer of the trait cannot tell loaded data from a test’s fake.name()andjurisdiction_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 aBootErrorrefuses startup. -
The trait’s data types hold
&'staticstrings and slices, so a successful load leaks the parsed bundle once. A process loads its bundle once, at boot; tests go throughcraig_test_lib::config::bundle, which caches one bundle per layer per process. -
BUNDLE_DIR(bundle) andBUNDLE_FILESare the directory and the closed set of file names. A file underbundle/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_fieldsschema; 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.ftlunderterminology/<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 listbundle/adapters.tomlgives.contribute().adaptersis 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>runscheckover 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 |
|---|---|---|
|
|
no declared zone, |
|
the adapter names craig-exchange registers |
no adapters |
|
partner types added to the product taxonomy |
the 14 product types; a product token in the file is a duplicate error |
|
|
empty |
|
|
empty |
|
|
the product default palette |
|
|
no overlay |
|
|
no governed surface |
|
|
none |
|
|
|
|
|
|
|
the same-named methods |
empty |
|
|
empty |
|
|
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 reportssha256(ruleset || "\n" || evidence). -
reason_names_digest(reason, digest): whether a promote reason quotes that digest asauthority-evidence:<hex>. -
Two callers, so they cannot disagree:
cargo xtask authority-evidence(the gate over the shipped pairs) andcraig 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 kindtid.TestoniaRegistryAdapter(RegistryEntryout,RegistryAckback,TestoniaRegistryError), thirteen legs over that one record type (legs::legs(),RegistryLeg, each leg a named constant such asRegistryLeg::STAGE_OPENED) covering every resolve rule, entity and scope, andpartner_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. Behindmock:mock::RegistrySimulator, a closed world of residents keyed by person id (enroll,withdraw,held), itsroutes()and the control routes_sim/residents/{person_id}. The registry’s benefit desk is the reference SSA benefit inquiry (RegistryBenefitInquiry,src/inquiry.rs): registered inpartner_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, legschool_roll,src/collection.rs): one JSON document at<endpoint>/roll, each pupil whose row echoes a person id reported asPartnerReport::Education, the rest counted, and204for 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::routestocraig_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.logmint counter, both gitignored/0600 — so a battery mints O(roles) ROPC grants instead of O(tests); invalidated automatically on devstack restart via the recordedtoken_url; any file failure degrades to the pre-#1163 per-process mint).service_token(config, client_id, secret)(#1880) — a devstack service client’sclient_credentialsbearer fromtoken_url(): the one mint behind every suite’s service-principal helper andportal_subject::portal_channel_token; a refusal is an error naming the client, the status and the body. -
shared_http_client()— areqwest::Clientfor integration tests (30 s timeout,pool_max_idle_per_host(4)), built once byTestHarness::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 takereqwest::Clientas 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 UUIDsADMIN_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 #2018PlacementBuilder::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) andfixture_episode/fixture_episode_removed_at(the same against the devstackcraig_placementdatabase), raw rows with no craig-cases check; the API-levelgiven::given_removal_episode; andEpisodesClient(the episode routes, withrecord_exit/correct_exit/retract_exit/record_historical_episodesince #2019; the harness’s<role>_episodes_client()). Gotcha: global-property tests race under nextest concurrency — sequence them in ONE test.spawn_for_routes()fromtools/craig-mock-serveris the harness a partner crate’sround_triptests stand their own mock in;spawn_for_test()mounts no partner. -
concurrent— theconcurrent_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 — pollspg_blocking_pidsuntil a backend parks behind YOUR transaction’s pid, returns a typedBlockedWaitError::Timeoutinstead 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-runsclose()until the pool’ssize()is zero. sqlx 0.8’sPool::closecan 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 leavepg_stat_activitystays the caller’s job. -
list_fence(#1916) — the list-scope fence rig the services'list_scope_fence_testsdrive their REAL list handlers with:FixedScope(ListScope)(anAuthzEnginedouble that admits every row check and answers one fixed list scope),unreachable_db()(a lazyDbPoolover TEST-NET that never dials, so an arm that wrongly reaches the query blocks on the acquire bound instead of passing),custom_scope()(the #1407Custompayload no decoder claims) andadmin_claims(). The handlerAppStateiscraig_api::detached_test_state, behind craig-api’stest-utilfeature, which each consumer enables in its own dev-dependencies. -
rule_set_fixtures(#2284) — craig-rulesrule_setsrows a devstack test writes by direct SQL, kept in the #1556 snapshot protocol.seed_rule_setandpeer_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. TheOwnedRuleSetguard (adoptfor 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:DbTemplateandThrowawayDb(a database cloned from a service’s migrated template, dropped with the value),shipped_engine(jurisdiction)andshipped_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) andoutbox_events(&pool, event_type)(stagedEventEnvelope`s in staging order). `inproc::allow_all_censusis the scanner behindno_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. Depjose ^5; shared vectorssdks/test-vectors/canonical.json. Person entries are typed (#3180):Child/Adult(the Rust SDK’s fields, the wire keys), built withchild()/adult(), which fill the flags;PRINCIPAL_RELATIONSHIPS/COLLATERAL_RELATIONSHIPSand their code types; andwithRelationshipToCaretaker(person, { designation, code }), which writes the code and its designation together. -
Python SDK —
craig-intake-sdk(sdks/python/): asyncIntakeClient(httpx),ReportBuilder,load_signing_config/canonicalize/sign_detached,IntakeError. Depshttpx/joserfc/cryptography. Person entries are typed (#3180): theChild/Adultdataclasses (the Rust SDK’s fields, the wire keys), thePrincipalRelationship/CollateralRelationshipliterals, andwith_principal_relationship/with_collateral_relationship, which write the code and its designation together and raiseValueErrorfor 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).