Implementation Guide

Table of Contents

This guide provides the technical specification for implementing each phase of the CRAIG platform. It is the companion to the Roadmap, which tracks progress at a strategic level. Each section below contains enough detail — database schemas, API endpoints, event flows, and verification steps — for any developer to implement the phase independently.

Shared Architecture

Every CRAIG service follows the same structural pattern. Understanding this pattern once makes each subsequent phase straightforward.

Service Pattern

Each service is a standalone Axum binary (services/craig-<name>/) that:

  1. Loads configuration from environment variables (CRAIG_<SERVICE>__*)

  2. Connects to its own PostgreSQL database (craig_<service>)

  3. Connects to the shared RabbitMQ message bus (craig.events topic exchange)

  4. Validates Keycloak OIDC tokens via the craig-auth middleware

  5. Exposes a versioned REST API under /v1/<service>/…​

  6. Exposes an unauthenticated health check at GET /healthz

Shared Crates

Crate Purpose

craig-common

Configuration loading, ApiError type (RFC 9457 Problem Details), UUID v7 IDs, pagination, structured logging

craig-auth

Keycloak OIDC discovery, JWKS caching, Bearer token validation middleware, role-based access helpers

craig-db

DbPool wrapper around sqlx::PgPool, health check, migration runner

craig-mq

RabbitMQ connection via lapin, Publisher and Subscriber helpers, EventEnvelope message format

craig-api

Axum server builder with standard middleware stack (CORS, compression, tracing, auth), health endpoint

craig-store

Object storage abstraction wrapping the Apache object_store crate — uniform put/get/delete/list API across local filesystem (dev) and S3-compatible backends (production)

craig-reference

Shared domain enums (strum-derived), FIPS codes for all US states and counties, AFCARS/NCANDS field translations, and validation functions. Used by craig-seed for deterministic test data and available to all services for enum-based validation.

Sort & Search Pattern

All paginated list endpoints support server-side sorting and text search via optional query parameters: search, sort_by, sort_dir.

Sort safety: Dynamic ORDER BY columns are validated through a whitelist function that returns hardcoded string literals, preventing SQL injection:

fn validated_sort_column(sort_by: Option<&str>) -> &str {
    match sort_by {
        Some("case_number") => "case_number",
        Some("status") => "status",
        _ => "created_at",  // safe default
    }
}

Search: Parameterized ILIKE clauses search across relevant text columns:

AND ($3::TEXT IS NULL
     OR case_number ILIKE '%' || $3 || '%'
     OR assigned_worker ILIKE '%' || $3 || '%')

The BFF (craig-web) passes search, sort_by, and sort_dir as query parameters to backend API calls and forwards them to Askama templates for rendering sortable headers and preserving state across pagination links via the extra_params() helper.

Standard Event Envelope

All messages on the RabbitMQ craig.events topic exchange use a common JSON envelope:

{
  "id": "01942a3b-...",
  "timestamp": "2025-03-15T14:30:00Z",
  "source_service": "craig-cases",
  "event_type": "case.created",
  "payload": { ... }
}

The event_type field doubles as the AMQP routing key, enabling selective subscription.

Two routing keys are library-emitted rather than service-owned: every engine-hosting service stages authz.cache_miss (source-attested policy absence, acting-worker attribution: { ruleset_name, lookup_jurisdiction, lookup_resource_type, sub, is_service, service_id, request_id }) and authz.cache_refreshed ({ ruleset_name, trigger: rmq_event|ttl_refresh|boot|warmup|lazy_load, old_version, new_version }; new_version: null = upstream eviction) through the craig-authz engine’s injected OutboxAuditSink (ADR-050 / #908) — source_service names the emitter, so these appear under every service, not in any one Publishes table below.

Standard Roles

Services enforce role-based access using Keycloak realm roles:

Role Access Level

admin

Full system administration

supervisor

Unit/district case oversight, approval workflows

caseworker

Assigned cases, standard operations

eligibility_worker

IV-E eligibility determinations, claiming

icpc_coordinator

Interstate compact requests and home studies

readonly

View-only access across all modules

county_director / regional_director / state_office

The ADR-054 office-authority axis for subsidy approvals (office principals also hold a base operational role)

DevStack

All infrastructure runs via Docker Compose for local development:

Service Image Port

PostgreSQL 18

postgres:18-alpine

5432

RabbitMQ 4.2

rabbitmq:4.2-management-alpine

5672 / 15672

Keycloak 26.5

quay.io/keycloak/keycloak:26.5

8180

Garage

dxflrs/garage:v2.2.0

3900 / 3903

Each CRAIG service gets its own database (craig_rules, craig_cases, etc.) created by devstack/postgres/init.sql.

CI/CD

The GitLab CI pipeline (.gitlab-ci.yml) runs six stages — check → build → test → scan → promote → deploy. Every merge request runs one car job on one VM: the gates, the devstack, the integration battery and e2e, as the developer commands a checkout runs (Quality Gates § CI: the car); a merge train is the merge gate (ADR-086). The pre-push hook runs the fast subset. Main and the schedule carry the scans, the release build, the docs site and the pentest/perf/cluster jobs. The deployment guide's CI/CD Pipeline section and troubleshooting's "Pipeline stages" entry carry the current job-by-job detail. No job uses Docker-in-Docker: a job drives its VM’s Docker daemon through the mounted socket, and the scheduled pentest/perf jobs bring the stack up with xtask dev start.

Horizontal Scalability

All CRAIG services are designed to scale horizontally behind a load balancer with no single-instance assumptions.

Stateless Request Handling

Services validate Keycloak JWTs locally (JWKS cached and auto-refreshed) and hold no server-side session state. Any instance can handle any request.

Event Subscription Patterns

The craig-mq crate provides two subscription methods for different scaling needs:

Method Queue Type Use Case

Subscriber::subscribe()

Durable, shared

Competing consumers — only one instance processes each message. Use for event handlers that mutate the database.

Subscriber::subscribe_exclusive()

Exclusive, auto-delete

Fan-out to all instances — every instance receives every matching message. Use for cache invalidation and local state updates.

Cache Invalidation Pattern

Services with in-memory caches (e.g., compiled rule sets in craig-rules) must publish an invalidation event after any mutation so that peer instances converge on the database state:

  1. After a successful write + local conditional cache apply, stage an invalidation event (e.g., rules.cache_invalidated) carrying the originating instance_id

  2. Each instance subscribes on a unique exclusive queue (format!("{service}.cache.{uuid}")) so all instances receive the event

  3. On receipt, each PEER instance runs an identity-aware reconcile pass (#1188: a per-name conditional apply on craig-rules' trigger-enforced (id, revision) token — never a wholesale reload, which could overwrite a concurrent local mutation with staler state); a probe failure fails the delivery so the MQ layer redelivers

  4. The originating instance skips its own event (its cache was already updated by the API handler) — the payload’s instance_id is the discriminator

  5. Since #1216 the event staging IS transactional with the rule-set write (event and mutation commit or vanish together); craig-rules also runs a periodic reconcile sweep (CRAIG_RULES__DECISION_REFRESH_SECONDS) bounding DELIVERY-side event loss to ≤ ~2×interval + pass duration under a healthy DB

Future services with in-memory caches should follow this same pattern.

Testing Infrastructure

Status: Completed

Comprehensive integration test harness for all CRAIG services, inspired by OpenStack Tempest’s design principles adapted for Rust. Tests interact exclusively through public REST APIs (black-box), use Keycloak bearer tokens for authentication, and verify RabbitMQ event publication.

Design Principles

Principle Description

Public API only

Integration tests interact through REST endpoints — never touch PostgreSQL directly. Validates the same contract real consumers use.

Credential isolation

Pre-configured Keycloak test users with different role combinations cover all access patterns. Tests never modify identity data.

Typed service clients

Per-service HTTP clients (RulesClient, CasesClient, PlacementClient) wrapping reqwest with bearer token injection.

Cleanup stack

LIFO teardown — register cleanup callbacks as resources are created, execute in reverse order on test completion.

Self-skipping tests

Integration tests check devstack availability at runtime. If unreachable, tests skip gracefully. cargo test is always safe.

Unique resource names

UUID v7 suffixes on all test-created resources enable safe parallel execution.

Crate: craig-test-lib

Property Value

Location

crates/craig-test-lib/

Type

Library (dev-dependency for services)

Dependencies

reqwest, serde, serde_json, tokio, uuid, chrono, lapin, craig-common

crates/craig-test-lib/
├── Cargo.toml
└── src/
    ├── lib.rs           (re-exports)
    ├── config.rs        (TestConfig: URLs and credentials from env vars)
    ├── token.rs         (KeycloakTokenProvider: ROPC grant + token caching)
    ├── client.rs        (ServiceClient: generic HTTP client with auth)
    ├── clients/
    │   ├── mod.rs
    │   ├── rules.rs     (RulesClient: rule set CRUD, evaluate, evaluations)
    │   ├── cases.rs     (CasesClient: persons, referrals, investigations, cases, plans, contacts, court orders)
    │   ├── placement.rs (PlacementClient: foster homes, placements, kinship, matching)
    │   ├── exchange.rs  (ExchangeClient: partners, agreements, transactions, ICPC)
    │   ├── financial.rs (FinancialClient: payments, adjustments, rates, claims)
    │   └── reporting.rs (ReportingClient: quality issues, AFCARS, NCANDS, metrics)
    ├── harness.rs       (TestHarness: fixture with cleanup stack + client factories)
    ├── events.rs        (EventCollector: RabbitMQ temporary queue for event verification)
    └── builders.rs      (Fluent test data builders with valid defaults)

TestConfig — Loaded from CRAIG_TEST__* env vars with devstack defaults (http://localhost:8180, http://localhost:8001, etc.).

KeycloakTokenProvider — Obtains JWT tokens via Resource Owner Password Credentials grant against the craig-api Keycloak client. Caches tokens per user; re-fetches within 30 seconds of expiry.

ServiceClient — Generic HTTP client: get(), post(), put(), delete() with bearer token injection. Returns ApiResponse<T> carrying both HTTP status and optional deserialized body (enables negative testing).

TestHarness — Fixture struct holding TestConfig, KeycloakTokenProvider, and a cleanup stack. Factory methods produce authenticated per-service clients for each test user.

EventCollector — Creates a temporary exclusive auto-delete RabbitMQ queue bound to the craig.events topic exchange. Collects events and provides wait_for_event() and assertion helpers.

Test Users

User Password Roles Test Purpose

admin

password

admin

Rule set CRUD, admin-only endpoints

jane.doe

password

caseworker, supervisor

Supervisor actions, case plan approval

bob.smith

password

caseworker, eligibility_worker

Standard caseworker, eligibility-specific

Integration Test Plan

craig-rules (~46 tests)

File Count Description

health.rs

2

Healthcheck (unauthenticated), response shape

auth.rs

8

No token → 401, invalid token → 401, role-based access for list/create/delete/evaluations

rule_sets.rs

14

CRUD, pagination, duplicate name → 409, invalid JDM → 400, soft-delete, boundary cases

evaluate.rs

8

Valid/invalid input, audit trail, context tracking, post-update evaluation, edge cases

evaluations.rs

6

List with role guards, filter by context_type/rule_set_name/context_id, pagination

import_export.rs

4

Import valid/invalid JDM, export, roundtrip

events.rs

4

rules.evaluated event, cache invalidation on create/update/delete

craig-cases (~62 tests)

File Count Description

health.rs

1

Healthcheck

auth.rs

4

Authentication and authorization negative cases

persons.rs

8

CRUD, search by name/DOB/SSN, pagination, 404

referrals.rs

8

CRUD, allegations, filters, validation, 404

investigations.rs

8

CRUD, status transitions (valid/invalid), filters, 404

cases.rs

17

CRUD, status transitions, household, filters

case_plans.rs

8

CRUD, approval (supervisor vs caseworker), tasks, transitions

contacts.rs

3

Create, list, pagination

court_orders.rs

3

Create, list, pagination

events.rs

6

Verify 6 domain events (referral, intake, case CRUD, plan)

workflow.rs

3

Full lifecycle, cross-service safety assessment, case closure

craig-placement (~34 tests)

File Count Description

health.rs

1

Healthcheck

auth.rs

4

Authentication and role-based access (caseworker vs supervisor)

foster_homes.rs

10

CRUD, license transitions (valid/invalid), training, capacity/county/status filters

placements.rs

8

CRUD, status transitions, placement history, case_id filter

kinship.rs

4

Create, list, evaluate, filter

matching.rs

3

Search by child, capacity filtering, needs-based matching

events.rs

3

Verify the 3 domain events (placement created/activated/ended); no license-expiring producer exists (#1639)

Unit Test Additions (~33 tests)

Crate Count Tests

craig-common

14

ApiError → correct HTTP status for each variant, Internal redacts detail, ProblemDetails RFC 9457 shape, pagination edge cases, settings defaults and redaction

craig-auth

7

has_role edge cases (empty, multiple, case-sensitive), Claims deserialization, require_role pass/fail

craig-mq

5

EventEnvelope::new() UUID v7 and timestamp, serialization roundtrip, EVENTS_EXCHANGE constant

craig-cases

4

Transition edge cases (same-state, backwards)

craig-placement

3

Transition edge cases (same-state, skip-state)

Actual Test Counts

Category Count

Ruleset evaluation (GA + TX)

67

craig-common unit tests (errors, pagination, settings, IDs)

18

craig-auth unit tests (claims, middleware)

8

craig-mq unit tests (envelope)

5

craig-store unit tests

16

craig-cases transition unit tests

12

craig-placement transition unit tests

7

craig-rules integration tests

43

craig-cases integration tests

64

craig-placement integration tests

30

craig-exchange transition unit tests

11

craig-exchange integration tests

26

craig-financial transition unit tests

11

craig-financial integration tests

22

craig-reporting transition unit tests

10

craig-reporting integration tests

25

craig-security transition unit tests

10

craig-security integration tests

19

craig-seed unit tests

21

craig-cli unit tests (config, output, auth)

28

craig-cli integration tests

43

craig-test-lib doc tests

1 (ignored)

Total

497

Verification

  1. cargo fmt --check --all — clean

  2. cargo clippy --workspace --locked — -D warnings — clean

  3. cargo test --workspace (devstack stopped) — unit + ruleset tests pass, integration tests self-skip, 1 ignored doc test

  4. Start devstack (cargo xtask dev start) and all services

  5. cargo test --workspace — all 497 tests pass (496 + 1 ignored doc test)

Performance Testing

Status: Completed (core program) — the k6 runner (cargo xtask perf), the tests/k6/ script tree, all four profiles, and the #1134 class thresholds shipped; residual scoped items (compose perf profile, deep scenario coverage, profiling tooling) stay open on the Roadmap checklist. See Testing Reference (CRAIG) § Performance Testing for the as-built state. The spec below is the original design record.

Automated performance baselines and regression detection for all CRAIG services using Grafana k6. Rather than building a custom framework (e.g. OpenStack Rally), CRAIG uses industry-standard tooling that integrates directly into CI and requires no additional infrastructure.

Why k6

Factor Rationale

CI-native

CLI tool with exit-code-based threshold assertions — a failing threshold fails the CI job, no dashboard required.

Docker-ready

Official grafana/k6 image runs as a container on the devstack’s network, no binary installation needed.

JavaScript scripts

Low barrier for contributors; test scripts are readable, version-controlled, and shareable.

Built-in metrics

HTTP request duration (p50/p95/p99), iteration rate, error rate, data sent/received — no external collectors needed.

Extensible

xk6 extensions available for RabbitMQ, PostgreSQL, and custom protocols if needed later.

Directory Structure

perf/
├── lib/
│   ├── auth.js           (Keycloak ROPC token acquisition, caching, refresh)
│   ├── config.js         (base URLs, thresholds, VU counts from env vars)
│   └── helpers.js        (response assertion helpers, UUID generation)
├── rules/
│   ├── smoke.js          (1-2 VUs, all endpoints, verify correctness)
│   ├── load.js           (target concurrency, 5-minute sustained)
│   └── stress.js         (ramp to breaking point, measure degradation)
├── cases/
│   ├── smoke.js
│   ├── load.js
│   ├── stress.js
│   └── workflow.js       (full lifecycle: referral → investigation → case → plan)
├── placement/
│   ├── smoke.js
│   ├── load.js
│   └── stress.js
├── cross-service/
│   ├── safety-assessment.js   (cases → rules engine round-trip)
│   └── intake-to-placement.js (full pipeline: referral → case → placement)
└── soak/
    └── moderate-load.js  (30-minute sustained test across all services)

Shared Auth Module (perf/lib/auth.js)

All k6 scripts authenticate against Keycloak using the same ROPC grant as the integration tests:

import http from 'k6/http';

const tokenCache = {};

export function getToken(user, password) {
  const cacheKey = `${user}:${password}`;
  if (tokenCache[cacheKey] && tokenCache[cacheKey].expires > Date.now()) {
    return tokenCache[cacheKey].token;
  }

  const resp = http.post(`${__ENV.OIDC_INTERNAL_URL}/realms/craig/protocol/openid-connect/token`, {
    grant_type: 'password',
    client_id: 'craig-api',
    username: user,
    password: password,
  });

  const body = JSON.parse(resp.body);
  tokenCache[cacheKey] = {
    token: body.access_token,
    expires: Date.now() + (body.expires_in - 30) * 1000,
  };
  return body.access_token;
}

export function authHeaders(user, password) {
  return { headers: { Authorization: `Bearer ${getToken(user, password)}` } };
}

Test Scenarios

Per-Service Tests
Service Script Scenarios

craig-rules

rules/load.js

Rule set list (paginated), single rule set GET, rule evaluation (cache hit), rule evaluation (cache miss after create), CRUD cycle. Measures cache warm-up impact on p95.

craig-cases

cases/load.js

Person search by name/DOB/SSN, referral creation, investigation status transitions, case list with county/worker filters, case plan approval workflow, contact and court order creation. Measures pagination performance at page depths 1, 10, 100.

craig-placement

placement/load.js

Foster home search (by county, capacity, license status), placement creation and lifecycle transitions, kinship option creation with evaluation, matching endpoint with varying filter combinations. Measures query performance across filter cardinalities.

All services

soak/moderate-load.js

20 VUs per service, 30-minute duration. Monitors for memory leaks (response time drift), connection pool exhaustion (sudden error spikes), and Keycloak token refresh under load.

Cross-Service Workflow Tests
Script Workflow

cross-service/safety-assessment.js

Create person → create referral → create investigation → submit safety assessment (craig-cases calls craig-rules synchronously) → verify evaluation result. Measures the full HTTP round-trip latency of the cross-service call. Target: p95 < 500ms.

cross-service/intake-to-placement.js

Full pipeline: create person → referral → investigation (with safety assessment) → open case → add household → create foster home → run matching → create placement. Measures end-to-end latency for the critical path. Target: p95 < 2000ms for the complete pipeline.

Performance Thresholds

Thresholds are defined per scenario and enforced by k6’s --thresholds mechanism — exceeding any threshold causes the k6 process to exit non-zero, failing the CI job.

Endpoint Category p95 Latency p99 Latency Error Rate

Single-entity GET (by ID)

< 50ms

< 100ms

< 0.1%

List/search (paginated)

< 200ms

< 500ms

< 0.1%

Create/update (single entity)

< 100ms

< 250ms

< 0.1%

Rule evaluation (cache hit)

< 100ms

< 200ms

< 0.1%

Cross-service workflow (safety assessment)

< 500ms

< 1000ms

< 0.1%

Full lifecycle pipeline

< 2000ms

< 3000ms

< 0.1%

These thresholds assume the devstack running on a single machine. Production thresholds will be tighter once deployed to dedicated infrastructure with properly sized connection pools.
Example k6 Threshold Configuration
export const options = {
  stages: [
    { duration: '30s', target: 20 },   // ramp up
    { duration: '5m',  target: 20 },   // steady state
    { duration: '30s', target: 0 },    // ramp down
  ],
  thresholds: {
    'http_req_duration{endpoint:get_case}':     ['p(95)<50', 'p(99)<100'],
    'http_req_duration{endpoint:list_cases}':   ['p(95)<200', 'p(99)<500'],
    'http_req_duration{endpoint:create_case}':  ['p(95)<100', 'p(99)<250'],
    'http_req_duration{endpoint:evaluate}':     ['p(95)<100', 'p(99)<200'],
    'http_req_failed':                          ['rate<0.001'],
  },
};

Profiling and Optimization

Performance testing reveals what is slow; profiling reveals why.

Tool Purpose Integration

tokio-console

Async runtime introspection

Add console-subscriber behind a tokio-console cargo feature flag. Enables per-task polling duration, waker counts, and resource utilization analysis. Never enabled in production builds.

Criterion.rs

Micro-benchmarks

benches/ directory in performance-critical crates. Target hot paths: zen-engine rule evaluation, JWT signature validation, pagination offset calculation, EventEnvelope serialization.

reqwest::Client pool metrics

HTTP connection pool utilization

Log pool statistics (idle connections, active connections) at debug level during load tests. Tune pool_max_idle_per_host and pool_idle_timeout based on observed patterns.

PostgreSQL EXPLAIN ANALYZE

Query plan analysis

Run against slow queries identified by load tests. Add targeted indexes. Document query plans for complex joins (e.g., household membership, placement matching).

Connection Pool Tuning Methodology
  1. Run the soak/moderate-load.js test for 30 minutes

  2. Monitor PostgreSQL connection count: SELECT count(*) FROM pg_stat_activity WHERE datname LIKE 'craig_%'

  3. Monitor reqwest pool behavior via debug logs

  4. Adjust db_max_connections and pool_max_idle_per_host based on peak utilization + 20% headroom

  5. Re-run soak test to verify no connection exhaustion

  6. Document optimal settings per deployment size (small: single instance, medium: 2-3 instances, large: 5+ instances)

CI/CD Integration

Two manual CI jobs run k6 against the devstack after the integration test job:

perf-smoke:
  stage: integration
  image: grafana/k6:latest
  services:
    - docker:27-dind
  variables:
    OIDC_INTERNAL_URL: "http://docker:8180"
    RULES_URL: "http://docker:8001"
    CASES_URL: "http://docker:8002"
    PLACEMENT_URL: "http://docker:8003"
  script:
    # Boot devstack (reuse integration-test's approach)
    - k6 run --quiet perf/rules/smoke.js
    - k6 run --quiet perf/cases/smoke.js
    - k6 run --quiet perf/placement/smoke.js
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
      when: manual
      allow_failure: true

perf-load:
  stage: integration
  image: grafana/k6:latest
  services:
    - docker:27-dind
  variables:
    OIDC_INTERNAL_URL: "http://docker:8180"
    RULES_URL: "http://docker:8001"
    CASES_URL: "http://docker:8002"
    PLACEMENT_URL: "http://docker:8003"
  script:
    - k6 run --out json=results/rules-load.json perf/rules/load.js
    - k6 run --out json=results/cases-load.json perf/cases/load.js
    - k6 run --out json=results/placement-load.js perf/placement/load.js
    - k6 run --out json=results/cross-service.json perf/cross-service/safety-assessment.js
  artifacts:
    paths:
      - results/
    expire_in: 30 days
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
      when: manual
      allow_failure: true
  timeout: 30m
The perf-smoke and perf-load jobs will need the same devstack boot sequence as the integration-test job (docker compose with dind). The YAML above is simplified — the full implementation will factor the devstack boot into a shared script or before_script.

Verification

  1. Install k6 locally: brew install k6 / choco install k6 / docker pull grafana/k6

  2. Start devstack: cargo xtask dev start

  3. Run smoke tests: k6 run perf/rules/smoke.js — all checks pass, no errors

  4. Run load tests: k6 run perf/cases/load.js — all thresholds met

  5. Run soak test: k6 run perf/soak/moderate-load.js — no response time drift over 30 minutes

  6. Run cross-service test: k6 run perf/cross-service/safety-assessment.js — p95 < 500ms

  7. Review k6 summary output — all thresholds green, error rate < 0.1%

  8. If any threshold is red, profile with tokio-console and EXPLAIN ANALYZE, optimize, re-run

Object Storage

Status: Completed

Non-machine-readable files — court orders, medical records, birth certificates, ICPC 100A forms, home study photos, generated AFCARS/NCANDS flat files — are stored in an S3-compatible object store rather than in PostgreSQL. The relational database stores only metadata and an object_key (the path within the object store bucket). This keeps the database lean, enables CDN-friendly serving, and avoids PostgreSQL large-object management overhead.

Design Decisions

  • Crate: object_store (Apache Arrow) — production-proven (InfluxDB IOx, DataFusion, Delta Lake), minimal dependencies, unified async API across backends

  • NOT RustFS: RustFS is a standalone S3-compatible server (like Garage), not a client library. For production deployments needing a self-hosted S3-compatible server, Garage or RustFS can serve as the backend — the object_store crate talks to any of them via the S3 protocol.

  • Dev backend: Garage (S3-compatible, written in Rust, AGPL-3.0) for devstack; LocalFileSystem for unit tests

  • Production backend: Any S3-compatible service — AWS S3, Garage, Backblaze B2, Wasabi, Google Cloud Storage, Azure Blob Storage

  • Bucket layout: One bucket per deployment (craig-{env}), prefixed by service and entity type: cases/court-orders/{case_id}/{object_id}.pdf, exchange/icpc/{request_id}/{attachment_id}.pdf, reporting/afcars/{submission_id}.dat

Shared Crate: craig-store

Location: crates/craig-store/

/// Re-exports and thin wrapper around `object_store`.
/// All services that need file storage depend on this crate.

pub struct ObjectStoreConfig {
    pub backend: StoreBackend,       // local | s3
    pub bucket: String,              // e.g. "craig-dev"
    pub local_root: String,          // only for local backend
    pub s3_endpoint: String,         // only for s3 backend (Garage, etc.)
    pub s3_region: String,
    pub s3_access_key: String,
    pub s3_secret_key: String,
    pub max_upload_bytes: usize,     // e.g. 50 * 1024 * 1024
}

pub enum StoreBackend { Local, S3 }

pub struct Store { /* Arc<dyn ObjectStore> */ }

impl Store {
    pub fn from_config(config: &ObjectStoreConfig) -> Result<Self, StoreError>;

    /// Upload bytes to the given path.
    pub async fn put(&self, path: &str, data: Bytes) -> Result<(), StoreError>;

    /// Download bytes by path. Returns StoreError::NotFound if missing.
    pub async fn get(&self, path: &str) -> Result<Bytes, StoreError>;

    /// Delete an object at the given path.
    pub async fn delete(&self, path: &str) -> Result<(), StoreError>;

    /// List object paths under a prefix.
    pub async fn list(&self, prefix: &str) -> Result<Vec<String>, StoreError>;

    /// Maximum allowed upload size in bytes.
    pub fn max_upload_bytes(&self) -> usize;
}

Configuration

Each service that stores files loads object store settings from environment variables:

CRAIG_STORE__BACKEND=s3              # "local" for dev, "s3" for production
CRAIG_STORE__BUCKET=craig-dev
CRAIG_STORE__LOCAL_ROOT=./data/objects
CRAIG_STORE__S3_ENDPOINT=http://localhost:3900  # Garage in devstack
CRAIG_STORE__S3_REGION=garage
CRAIG_STORE__S3_ACCESS_KEY=GKdeadbeefdeadbeefdeadbeef
CRAIG_STORE__S3_SECRET_KEY=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef

DevStack: Garage

Garage (S3-compatible, Rust, AGPL-3.0) is defined in docker-compose.yml with config baked into the image via devstack/garage/Dockerfile. The cargo xtask dev start command initializes Garage after startup using docker compose exec commands against the distroless container:

garage:
  build: ./devstack/garage
  ports:
    - "3900:3900"   # S3 API
    - "3903:3903"   # Admin API
  volumes:
    - garage-meta:/var/lib/garage/meta
    - garage-data:/var/lib/garage/data
  environment:
    RUST_LOG: garage=info
  healthcheck:
    test: ["CMD", "/garage", "status"]
    interval: 5s
    timeout: 3s
    retries: 10

The launch scripts create the layout, import a deterministic API key, create the craig-dev bucket, and grant access — all idempotent (skipped if the bucket already exists).

Database Pattern

Services store object metadata in their own tables. The object_key column replaces the existing file_url / document_url columns — it holds the path within the bucket, not a full URL. Services construct download URLs at request time (pre-signed for S3, direct path for local).

Example migration for existing tables:

-- Exchange: ICPC attachments (already has file_url → rename to object_key)
ALTER TABLE icpc_attachments RENAME COLUMN file_url TO object_key;

-- Cases: court orders (already has document_url → rename to object_key)
ALTER TABLE court_orders RENAME COLUMN document_url TO object_key;

-- Exchange: data sharing agreements (already has document_url → rename to object_key)
ALTER TABLE data_sharing_agreements RENAME COLUMN document_url TO object_key;

Upload and Download API Pattern

Each service that manages files exposes upload/download endpoints following a standard pattern:

POST   /v1/{service}/{entity}/{id}/attachments     — multipart upload → store.put() → save metadata row
GET    /v1/{service}/{entity}/{id}/attachments      — list metadata rows
GET    /v1/{service}/{entity}/{id}/attachments/{aid} — store.get() → stream bytes through service
DELETE /v1/{service}/{entity}/{id}/attachments/{aid} — store.delete() → delete metadata row

Upload handler pseudocode:

async fn upload_attachment(
    Path((entity_id,)): Path<(Uuid,)>,
    State(state): State<AppState>,
    mut multipart: Multipart,
) -> Result<Json<Attachment>> {
    let field = multipart.next_field().await?;
    let filename = field.file_name().unwrap_or("upload").to_string();
    let content_type = field.content_type().unwrap_or("application/octet-stream").to_string();
    let bytes = field.bytes().await?;

    // Validate: max size (e.g. 50 MB), allowed MIME types
    validate_upload(&content_type, bytes.len())?;

    let object_id = Uuid::now_v7();
    let key = format!("{service}/{entity_type}/{entity_id}/{object_id}/{filename}");
    state.store.put(&key.into(), bytes).await?;

    // Save metadata to PostgreSQL
    let attachment = sqlx::query_as!(...)
        .fetch_one(&state.db)
        .await?;

    Ok(Json(attachment))
}

Services That Store Files

Service Entity File Types

craig-cases

Court orders, case plan documents

PDF, DOCX

craig-exchange

ICPC attachments (100A forms, medical records, birth certificates, home study reports), data sharing agreement documents

PDF, images (JPEG/PNG)

craig-placement

Foster home inspection photos, license documents, training certificates

PDF, images (JPEG/PNG)

craig-reporting

Generated AFCARS/NCANDS flat files

DAT, CSV

craig-security

Security review evidence, remediation artifacts

PDF, DOCX, images

Upload Validation

All upload endpoints enforce:

  • Max file size: 50 MB (configurable per service via CRAIG_STORE__MAX_UPLOAD_BYTES)

  • Allowed MIME types: Allowlist per entity type (PDF, JPEG, PNG, DOCX, CSV, DAT — no executables)

  • Filename sanitization: Strip path separators, every control character, every Unicode format (Cf) character, and the line/paragraph separators (U+2028/U+2029); at most 255 bytes (craig_store::StoredFileName)

  • Content-type verification: Check magic bytes match the declared MIME type (defense against disguised executables)

Virus/malware scanning (e.g. ClamAV) is recommended for production deployments but is not included in the MVP. Deployments can add a scanning step by wrapping the Store::put() call or using an S3 event trigger.

Phase Dependency

Object Storage is cross-cutting — it can be implemented independently and adopted by services incrementally. The craig-store crate has no service dependencies (only object_store + config). Services adopt it by adding a dependency on craig-store, migrating file_url/document_url columns to object_key, and wiring upload/download endpoints.

Recommended adoption order:

  1. craig-store crate + Garage devstack container

  2. craig-exchange — ICPC attachments (already has icpc_attachments table with file_url)

  3. craig-cases — court order documents (already has document_url)

  4. craig-placement — foster home and license documents (new table)

  5. craig-reporting — generated AFCARS/NCANDS files (when Phase 7 is built)

  6. craig-security — evidence documents (when Phase 8 is built)

Web UI and CLI Integration

  • craig-web: File upload forms use <input type="file"> with enctype="multipart/form-data". The BFF proxies the multipart upload to the backend service. Download links use pre-signed URLs (S3) or stream through the BFF (local).

  • craig-cli: craig attachment upload <entity-type> <entity-id> <file-path> and craig attachment download <entity-type> <entity-id> <attachment-id> [--output <path>] commands. Upload reads the file into memory and POSTs as multipart; download streams to stdout or a file.

Verification

  1. Start devstack with cargo xtask dev start → verify Garage healthy and bucket created

  2. Upload a file via API → verify object appears in Garage bucket under the correct prefix

  3. Download via API → verify file content matches

  4. Delete via API → verify object removed from Garage

  5. Switch to local backend → verify files written to ./data/objects/ with correct directory structure

  6. Upload oversized file → verify 413 rejection

  7. Upload disallowed MIME type → verify 415 rejection

Phase 1 — Foundation

Status: Completed

Deliverables

Deliverable Description

Workspace root

Cargo.toml (workspace with shared dependency versions), rust-toolchain.toml (stable Rust, rustfmt, clippy)

craig-common

ServiceSettings (config crate, env var loading), ApiError (RFC 9457), Id (UUID v7), PageRequest/PageResponse, telemetry init

craig-db

DbPool (sqlx::PgPool wrapper), connect(), health_check(), run_migrations()

craig-mq

connect(), Publisher, Subscriber, EventEnvelope, EVENTS_EXCHANGE constant

craig-auth

JwksProvider (OIDC discovery + JWKS refresh), AuthLayer, auth_middleware, Claims struct, require_role()

craig-api

AppState, ApiServer::router() (middleware stack), ApiServer::serve(), /healthz

DevStack

docker-compose.yml, postgres init SQL, RabbitMQ definitions, Keycloak realm with test users

CI/CD

6-stage GitLab CI pipeline (lint, test, build, integration, e2e, deploy) in .gitlab-ci.yml

Repository Structure

Cargo.toml
rust-toolchain.toml
.env.example
.gitlab-ci.yml
docker-compose.yml
.githooks/pre-push
devstack/
  keycloak/craig-realm.json
  postgres/init.sql
  rabbitmq/definitions.json
  rabbitmq/rabbitmq.conf
crates/
  craig-common/    (Cargo.toml, src/lib.rs, error.rs, id.rs, pagination.rs, settings.rs, telemetry.rs)
  craig-auth/      (Cargo.toml, src/lib.rs, claims.rs, jwks.rs, middleware.rs)
  craig-db/        (Cargo.toml, src/lib.rs)
  craig-mq/        (Cargo.toml, src/lib.rs, envelope.rs, publisher.rs, subscriber.rs)
  craig-api/       (Cargo.toml, src/lib.rs)
  craig-test-lib/  (Cargo.toml, src/lib.rs, client.rs, config.rs, token.rs, harness.rs, clients/)

Verification

  1. cargo xtask dev start — PostgreSQL, RabbitMQ, and Keycloak start healthy

  2. cargo build — workspace compiles

  3. cargo test — all unit tests pass

  4. cargo clippy — -D warnings — no lint warnings

Phase 2 — Rules and Policy Engine

Status: Completed

Service: craig-rules

Property Value

Binary

services/craig-rules/

Port

8001

Database

craig_rules

Key dependencies

zen-engine 0.55, workspace crates

Database Schema

CREATE TABLE rule_sets (
    id          UUID PRIMARY KEY DEFAULT uuidv7(),
    name        TEXT NOT NULL UNIQUE,
    version     TEXT NOT NULL,
    description TEXT,
    content     JSONB NOT NULL,          -- JDM rule set (GoRules JSON)
    active      BOOLEAN NOT NULL DEFAULT true,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    created_by  TEXT NOT NULL,
    updated_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_by  TEXT NOT NULL
);

CREATE TABLE rule_evaluations (
    id               UUID PRIMARY KEY DEFAULT uuidv7(),
    rule_set_id      UUID NOT NULL REFERENCES rule_sets(id),
    rule_set_name    TEXT NOT NULL,
    rule_set_version TEXT NOT NULL,
    input            JSONB NOT NULL,
    output           JSONB NOT NULL,
    evaluated_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
    evaluated_by     TEXT NOT NULL,
    context_type     TEXT,               -- e.g. "eligibility", "safety-assessment"
    context_id       UUID                -- e.g. case ID or child ID
);

CREATE INDEX idx_rule_evaluations_rule_set_id ON rule_evaluations(rule_set_id);
CREATE INDEX idx_rule_evaluations_context ON rule_evaluations(context_type, context_id);
CREATE INDEX idx_rule_evaluations_evaluated_at ON rule_evaluations(evaluated_at);

REST API (a curated subset; the full route list is Rules Engine API Reference)

Method Path Description Role

GET

/v1/rules/sets

List all rule sets (paginated)

any

GET

/v1/rules/sets/{id}

Get rule set by ID

any

POST

/v1/rules/sets

Create rule set (upload JDM JSON)

admin

PUT

/v1/rules/sets/{id}

Update rule set (creates new version)

admin

DELETE

/v1/rules/sets/{id}

Deactivate rule set (soft delete)

admin

POST

/v1/rules/evaluate

Evaluate input against a named rule set

any

GET

/v1/rules/evaluations

List past evaluations (paginated, filterable)

supervisor+

POST

/v1/rules/sets/{id}/import

Import JDM from file

admin

GET

/v1/rules/sets/{id}/export

Export JDM as file

admin

GET

/v1/rules/jobs/{id}

Poll a background job (#1935, plan background-jobs D5 — the promote/preview enqueue answers 202 + this Location): state / attempt ledger / progress / result ({ preview_id, report } once succeeded) / closed error token; Cache-Control: no-store; never writes

read on background_job — admin, or the creator (human or service principal); an unknown id is 404 BEFORE the check

GET

/healthz

Health check

(unauthenticated)

RabbitMQ Events

Consumes: none. craig-rules binds no domain event — every rule set is evaluated on demand via POST /v1/rules/evaluate. The last binding, case.intake_created → intake-screening, was retired by #1670 (its payload { investigation_id, referral_id } carried no screening fact; the consult moved to the cases screening-decision act — see ADR-003 § Amendment #1670). Earlier producer-less retirements: eligibility.submitted (#1054) and placement.requested (#971).

Publishes:

Routing Key Payload

rules.evaluated

{ rule_set_name, rule_set_version, evaluation_id, context_type, context_id } (#1130 — a POINTER payload: the input/output documents live once in rule_evaluations, addressable by evaluation_id; pre-#1130 they rode every event and were copied a third time into audit_log by the craig-security wildcard subscriber. Success-only by design — failed attempts write disposition-typed rule_evaluations rows instead of events, ADR-006 §Amendment #1048)

rules.authz_fallback_admit

{ sub, is_service, carrier_sub, resource_type, resource_id, action, jurisdiction, reason: "bootstrap_policy_missing" } (#786 — staged on every bootstrap fallback admit: source-attested PolicyMissing + acting-admin-any-action or direct-service-Read/List; resource_id is the gated path id, Uuid::nil() where the gate passes nil, null on the list sites. #1060: sub names the ACTING worker when a Plan E X-Craig-Actor rode the request — the actor its audit header states. #2522: is_service is Claims::is_direct_service() — the fact the admit used — and carrier_sub names the carrying service principal under a lift (null otherwise))

rules.cache_invalidated

{ instance_id } — the peer-instance reconcile trigger staged on every rule-set mutation (§ Cache Invalidation Pattern above)

ruleset.changed.<name>

{ name, version } — the dynamic-suffix twin of rules.cache_invalidated (ADR-006 / ADR-024): the suffix is the rule-set name, so each service’s craig-authz engine binds ruleset.changed.* on its exclusive queue and refreshes one entry

rules.ruleset_promoted

{ rule_set_id, name, version, from_revision, to_revision, preview_id, user_id, reason } — the operator promote flip (#1556 / ADR-006 D2); craig-security parses promote on rule_set

rules.ruleset_rolled_back

{ rule_set_id, name, version, from_revision, to_revision, restored_revision, user_id, reason } — the operator rollback flip (#1556); parsed rollback on rule_set

rules.ruleset_created

{ rule_set_id, name, version, revision, user_id } — the create’s act record (#2322): the cache pair beside it names no actor; user_id the acting worker (spec.actor); craig-security parses create on rule_set

rules.ruleset_updated

{ rule_set_id, name, version, revision, user_id } — the update’s act record (#2322); user_id the acting worker; parsed update on rule_set

rules.ruleset_deleted

{ rule_set_id, name, version, revision, user_id } — the soft delete’s act record (#2322); user_id the acting worker; parsed delete on rule_set

rules.ruleset_imported

{ rule_set_id, name, version, revision, user_id } — the import’s act record (#2322); user_id the acting worker (spec.actor); parsed import on rule_set

rules.evaluations_archived

the archive-batch manifest facts (archive_id, source_service, source_table, record_count, data_key, manifest_key, data_sha256, store_endpoint, store_bucket, first/last_record_id, first/last_record_at, hot_window_days) + archived_by (#1129 / ADR-058 D16) — staged inside the prune transaction; craig-security validate-then-writes it into archive_records

zen-engine Integration

  • JDM rule sets are stored as JSONB in rule_sets.content and deserialized into zen_engine::model::DecisionContent

  • Compiled Decision objects are cached in an in-memory HashMap and reloaded on rule set update

  • Evaluation runs on a dedicated OS thread with a single-threaded tokio runtime because zen-engine’s evaluate future is !Send (uses Rc internally)

  • Every evaluation attempt that resolves a rule set writes to rule_evaluations for audit trail per 45 CFR § 1355.53, disposition-typed since #1048: completed rows carry the output; zen runtime failures and worker loss land as runtime_error; a blown CRAIG_RULESEVAL_TIMEOUT_MS dispatch budget (#784) lands as timeout, converging to late_completed if the evaluation later finishes; and JS function nodes are interrupt-bounded (#1046: v2 {source} nodes at CRAIG_RULESFUNCTION_TIMEOUT_MS, v1 string-content nodes at zen’s hard 500ms) so a runaway script terminates as a runtime_error row rather than wedging the eval thread — see ADR-006 §Amendments #1048/#1046

Jurisdiction Configuration

Each service takes its jurisdiction (e.g. georgia) from the configuration layers CRAIG_CONFIG_SOURCE names; it selects which rule set pack to activate. Rule sets follow a naming convention: {jurisdiction}-{function} (e.g. georgia-ive-eligibility). Callers address a rule set by its full name; there is no event-driven name construction (the last domain-event trigger was retired by #1670).

Sample rule set packs ship as config layers, one repository per jurisdiction (craig-config-georgia, craig-config-texas), pinned in config-sources.lock (Where rule sets live). Other jurisdictions create their own layer repository (e.g. craig-config-navajo-nation) and import their rule sets via the API.

Sample Rule Sets (Georgia DFCS)

The georgia layer (craig-config-georgia) contains five Georgia DFCS policy-based rule sets built in zen-engine JDM format. Each rule set is validated by integration tests in services/craig-rules/tests/georgia_ruleset_evaluation.rs and texas_ruleset_evaluation.rs.

File (georgia layer) Description

georgia-ive-eligibility.json

Title IV-E eligibility per 42 USC §672 and GA Policy Chapter 9 — 8 decision tables covering age (under 18 only — Georgia opted out of the federal extension, Policy 10.1; v3.3 #1659), specified relative, deprivation (5 types), AFDC financial need (≤$1,850 income, ≤$10K resources), citizenship, judicial requirements (the contrary-to-the-welfare OR best-interest finding — one determination, either phrasing — in the FIRST court ruling sanctioning removal, including an earlier TAFC order, plus reasonable efforts to prevent removal within 60 days — Policy 9.4/9.5, 45 CFR 1356.21; a breach of either clock is a judicial_fatal_flaw, not a pending finding; a removal under a voluntary placement agreement (removal_basis, v3.5 #1715) needs no court finding through day 180 of the placement and, past it, a court order signed by day 180 finding continued placement in the child’s best interest — Policy 9.1/9.9/10.2, 45 CFR 1356.22(b); an attested-absent or late order is a judicial_fatal_flaw), and final eligibility decision (the FFP rate is NOT a ruleset output — U-FMAP resolves it from the StateBundle’s effective-dated FMAP reference data as-of the business date)

georgia-safety-assessment.json

Safety assessment per GA Policy 19.11 — binary Safe/Unsafe decision based on present danger indicators, impending danger (5 threshold criteria), child vulnerability factors, and caregiver protective capacities

georgia-timeliness.json

Timeliness monitoring per ASFA and GA state policy — deadline lookup for 10 milestone types (CPS investigation 30d, family assessment 45d, CTW finding 60d, case plan 30d, case plan review 180d, permanency hearing 365d, TPR filing 455d, ICPC home study 60d, VPA best-interest court order 180d (v2.2, #2289)) with dynamic warn/critical/overdue status using cross-field threshold comparisons

georgia-intake-screening.json

Intake screening per GA Policy Chapter 3 — screen-in/screen-out criteria (maltreatment alleged, Georgia jurisdiction, child identifiable, caregiver maltreater, age <18), response priority assignment (IMMEDIATE/PRIORITY_24HR/STANDARD), and investigation track assignment (CPS_INVESTIGATION 30d / FAMILY_ASSESSMENT 45d)

georgia-placement-matching.json

Placement matching per GA Policy 10.4 (Selecting a Placement Resource), 16.1 (Program Designation Types) and 42 USC §671(a)(19)/(a)(31) — level of care determination (basic/therapeutic/residential), placement type preference hierarchy (relative kinship > fictive kin > foster family > residential), sibling joint placement assessment, and proximity/school stability scoring

Sample Rule Sets (Texas DFPS)

The texas layer (craig-config-texas) contains five Texas DFPS policy-based rule sets. Each rule set is validated by integration tests in services/craig-rules/tests/texas_ruleset_evaluation.rs. Texas-specific differences from Georgia include: three-outcome safety model (SAFE/CONDITIONALLY SAFE/UNSAFE), P1/P2 priority system, IV-E extended foster care to 21 (the five § 264.101(a-1) categories), the Appendix 1530-C AFDC needs-standard lookup, 14-day adversary hearing, and 12-month mandatory dismissal deadline.

File (texas layer) Description

texas-ive-eligibility.json

Title IV-E eligibility per 42 USC §672, TFC Chapters 262-263, and DFPS CPS Handbook §14130–14132 (+ Appendices 1530-F/1530-C) — 9 decision tables covering age (extended to 21 with the five Tex. Fam. Code § 264.101(a-1) participation categories: secondary/GED, post-secondary at six-plus class hours per regular term, employment program, employment 80hrs+, medical — each conditioned on the CPS 10420 entry prerequisites, DFPS conservatorship the day before the 18th birthday and a signed Form 2540 VEFCA, plus the CPS 10421 30-day transition window between activities; v1.6 #1718), specified relative, deprivation (6 types including abandonment), AFDC financial need (the Appendix 1530-C needs-standard lookup by certified group size and parent count — 185% on countable income, 100% on countable income after the 1530-F deductions — plus ≤$10K resources; v1.3 #1665), citizenship, judicial requirements (the contrary-to-the-welfare or best-interest finding in the FIRST court ruling sanctioning removal plus reasonable efforts to prevent removal within 60 days — 45 CFR 1356.21, CPS 14132.1 — and, Texas-only, DFPS physically taking the child by the end of the next business day following the finding unless a documented 14132.4 exception applies (a recorded reading, ⁂ #1073) (v1.5, #1716); a breach of any is a judicial_fatal_flaw; a removal under a voluntary placement agreement (removal_basis, v1.7 #1715) stays pending until a court order — CPS 14132.1 starts eligibility with the order and names no voluntary path (a recorded reading, ⁂ #1073)), and final eligibility (the FFP rate is bundle reference data since U-FMAP, not a ruleset output)

texas-safety-assessment.json

Safety assessment per CPS Handbook Sections 2270-2276 — THREE-outcome model (SAFE/CONDITIONALLY_SAFE/UNSAFE) with present danger, impending danger (4 characteristics: observable, out of control, imminent, severe), child vulnerability (includes non-verbal assessment), caregiver protective capacity across 3 dimensions (cognitive/affective/behavioral), and safety plan determination

texas-timeliness.json

Timeliness monitoring per TFC 262-263 and ASFA — deadline lookup for 14 milestone types including Texas-specific: CPS investigation closure (30d — CRAIG’s standard, STRICTER than CPS 2291.3’s 45d from intake, pending the maintainer’s ruling), alternative response (45d — CRAIG’s standard, STRICTER than CPS 2652’s 60d from stage progression to AR, same ruling), adversary hearing (14d per TFC 262.201), status hearing (60d per TFC 263.201), family service plan (45d), initial permanency hearing (180d after the TMC order per TFC 263.304(a)), mandatory dismissal deadline (365d per TFC 263.401), medical exam (3d), relative notification (30d), plus the federal milestones (CTW finding in the first ruling sanctioning removal — 45 CFR 1356.21(c), monitored as 1d; reasonable efforts to prevent removal 60d — 1356.21(b)(1)(i); case plan review 180d federal floor; TPR 455d; ICPC 60 calendar days) — v1.1 #1668

texas-intake-screening.json

Statewide Intake screening per TFC Chapter 261 — screen-in/screen-out with P1 (24hr: immediate risk, sexual abuse of child <6, non-mobile infant injury, physical abuse of child <3) and P2 (72hr: all other accepted reports) priority assignment; Investigation vs Alternative Response track (a P2 intake with an alleged victim 6 or older, attested free of every CPS 2611.1 element, takes AR at 60d for neglect, medical neglect, emotional abuse and physical abuse without serious injury; everything else takes INV at 45d)

texas-placement-matching.json

Placement matching per CPS Handbook 4114 / 4400 / 6600 and 42 USC §671(a)(19)/(a)(31) — the five DFPS service levels (basic/moderate/specialized/intense/intense-plus), ICWA placement preferences (25 USC 1915), kinship verification, Residential Treatment Center placement for the Intense-Plus level only (40 TAC §700.2365), sibling joint placement, and proximity/school stability scoring

Verification

  1. cargo test -p craig-rules — runs 67 integration tests validating all 10 rule sets (5 Georgia + 5 Texas) against zen-engine

  2. cargo run -p craig-rules — service starts, connects to DB and RabbitMQ

  3. curl http://localhost:8001/healthz — returns {"status":"ok"}

  4. Obtain Keycloak token and call POST /v1/rules/evaluate with sample input

  5. Verify rule_evaluations table contains audit record

Phase 3 — Case Management Service

Status: Completed

Service: craig-cases

Property Value

Binary

services/craig-cases/

Port

8002

Database

craig_cases

Dependencies

Phase 1 + Phase 2

Key dependencies

workspace crates

Repository Structure

services/craig-cases/
  Cargo.toml
  src/
    main.rs
    api/
      mod.rs
      persons.rs
      referrals.rs
      investigations.rs
      cases.rs
      case_plans.rs
      contacts.rs
      court_orders.rs
      contact_attachments.rs
    store/
      mod.rs
      models.rs
      persons.rs
      referrals.rs
      investigations.rs
      cases.rs
      case_plans.rs
      contacts.rs
      court_orders.rs
      contact_attachments.rs
    events.rs
    transitions.rs
  migrations/
    20240201000000_create_case_tables.sql

Database Schema

-- Hotline intake / referral
CREATE TABLE referrals (
    id                UUID PRIMARY KEY DEFAULT uuidv7(),
    received_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
    reporter_type     TEXT NOT NULL,           -- mandated, professional, anonymous, self_report, law_enforcement, concerned_citizen
    reporter_first_name TEXT,
    reporter_last_name  TEXT,
    reporter_phone    TEXT,
    reporter_relation TEXT,
    county            TEXT NOT NULL,
    response_priority TEXT NOT NULL,           -- the {j}-response-priority roll-up token (#1746; UNDERIVED = pre-cutover backfill)
    response_priority_basis TEXT,              -- + _rule_set_name / _rule_set_revision / _evaluation_id: all-or-none provenance
    icwa_flag         BOOLEAN NOT NULL DEFAULT false,
    created_by        TEXT NOT NULL,
    created_at        TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_by        TEXT NOT NULL,
    updated_at        TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE allegations (
    id            UUID PRIMARY KEY DEFAULT uuidv7(),
    referral_id   UUID NOT NULL REFERENCES referrals(id),
    victim_id     UUID NOT NULL,             -- person ID (child)
    perpetrator_id UUID,                     -- person ID
    abuse_type    TEXT NOT NULL,             -- chk_allegations_abuse_type: physical_abuse, sexual_abuse, neglect,
                                             -- emotional_abuse, medical_neglect, sex_trafficking, labor_trafficking,
                                             -- sexual_exploitation (#1630)
    description   TEXT,
    disposition   TEXT                       -- chk_allegations_disposition (#648): substantiated, indicated,
                                             -- alternative_response_victim, alternative_response_nonvictim,
                                             -- unsubstantiated, unsubstantiated_false_report, closed_no_finding
);

-- Person registry (children, parents, caregivers, reporters)
CREATE TABLE persons (
    id             UUID PRIMARY KEY DEFAULT uuidv7(),
    first_name     TEXT NOT NULL,
    last_name      TEXT NOT NULL,
    date_of_birth  DATE,
    sex            TEXT,
    ssn_last_four  TEXT,
    created_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at     TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Demographics ledger (#1991, ADR-078 D1): race / ethnicity / tribal facts per window; rows are
-- never updated in place (only a CLOSE or a RETIRE) and never deleted (trigger refuse_fact_row_mutation)
CREATE TABLE person_demographic_facts (
    id                 UUID PRIMARY KEY,
    person_id          UUID NOT NULL REFERENCES persons(id) ON DELETE RESTRICT,
    effective_from     DATE NOT NULL,
    effective_until    DATE,                 -- NULL = the open row
    race_american_indian_or_alaska_native BOOLEAN,  -- the eight race_* columns: all-or-none
    race_asian         BOOLEAN,
    race_black_or_african_american BOOLEAN,
    race_native_hawaiian_or_other_pacific_islander BOOLEAN,
    race_white         BOOLEAN,
    race_unknown       BOOLEAN,
    race_abandoned     BOOLEAN,
    race_declined      BOOLEAN,
    ethnicity          TEXT,                 -- hispanic, non_hispanic, unknown, abandoned, declined
    tribal_member_or_eligible TEXT,          -- yes, no, unknown
    tribal_member      TEXT,                 -- yes, no, unknown
    tribal_affiliation TEXT,                 -- at most 255 characters
    recorded_at        TIMESTAMPTZ NOT NULL DEFAULT now(),
    recorded_by        UUID NOT NULL,
    supersedes_id      UUID REFERENCES person_demographic_facts(id) ON DELETE RESTRICT,
    retired_at         TIMESTAMPTZ,          -- live while NULL
    retired_reason     TEXT,                 -- corrected, retracted, order_corrected, order_deleted
    retired_note       TEXT,
    retired_by         UUID,                 -- the retiring worker; set with retired_at (#2016)
    closed_at          TIMESTAMPTZ,          -- set only by a closing UPDATE (#2016)
    closed_by          UUID,                 -- the closing worker; set with closed_at (#2016)
    CONSTRAINT excl_person_demographic_facts_window EXCLUDE USING gist
        (person_id WITH =, daterange(effective_from, effective_until, '[)') WITH &&)
        WHERE (retired_at IS NULL)
);

-- Investigation
CREATE TABLE investigations (
    id              UUID PRIMARY KEY DEFAULT uuidv7(),
    referral_id     UUID NOT NULL REFERENCES referrals(id),
    assigned_worker TEXT NOT NULL,
    assignment_area TEXT NOT NULL,
    status          TEXT NOT NULL DEFAULT 'open', -- open, pending_review, closed
    response_due_at TIMESTAMPTZ NOT NULL,          -- DERIVED at open from the referral token via {j}-response-window (#1747)
    response_priority TEXT,                        -- + response_due_basis / response_rule_set_name / _revision / response_evaluation_id (all-or-none)
    response_due_original TIMESTAMPTZ,             -- + response_due_overridden_at / _by / _reason / response_due_override_evaluation_id (#1748)
    first_contact_at TIMESTAMPTZ,
    closed_at       TIMESTAMPTZ,
    disposition     TEXT,                          -- substantiated, unsubstantiated
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Every investigation READ selects from v_investigations = investigations.* +
-- response_timeliness (on_track | overdue | met | met_late, computed at read time — #1747)

-- Safety assessment (completed during investigation)
CREATE TABLE safety_assessments (
    id                UUID PRIMARY KEY DEFAULT uuidv7(),
    investigation_id  UUID NOT NULL REFERENCES investigations(id),
    threats           JSONB NOT NULL DEFAULT '[]',
    protective_capacities JSONB NOT NULL DEFAULT '{}',
    rule_set_name     TEXT NOT NULL,
    rule_set_version  TEXT NOT NULL,
    engine_decision   TEXT NOT NULL,               -- SAFE, SAFE_WITH_PLAN, UNSAFE
    worker_override   TEXT,                        -- null if no override
    worker_override_reason TEXT,
    assessed_by       TEXT NOT NULL,
    assessed_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Case (opened after investigation substantiates)
CREATE TABLE cases (
    id               UUID PRIMARY KEY DEFAULT uuidv7(),
    case_number      TEXT NOT NULL UNIQUE,
    referral_id      UUID REFERENCES referrals(id),
    investigation_id UUID REFERENCES investigations(id),
    status           TEXT NOT NULL DEFAULT 'open',  -- open, closed, transferred
    stage            TEXT NOT NULL DEFAULT 'assessment', -- assessment, ongoing, permanency
    county           TEXT NOT NULL,
    assigned_worker  TEXT NOT NULL,
    supervisor       TEXT,
    opened_at        TIMESTAMPTZ NOT NULL DEFAULT now(),
    closed_at        TIMESTAMPTZ,
    closure_reason   TEXT,
    icwa_flag        BOOLEAN NOT NULL DEFAULT false,
    created_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Household members linked to a case
CREATE TABLE case_household (
    id          UUID PRIMARY KEY DEFAULT uuidv7(),
    case_id     UUID NOT NULL REFERENCES cases(id),
    person_id   UUID NOT NULL REFERENCES persons(id),
    role        TEXT NOT NULL,               -- child, parent, caregiver, sibling, other
    primary_caregiver BOOLEAN NOT NULL DEFAULT false,
    active      BOOLEAN NOT NULL DEFAULT true,
    added_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Case plan
CREATE TABLE case_plans (
    id              UUID PRIMARY KEY DEFAULT uuidv7(),
    case_id         UUID NOT NULL REFERENCES cases(id),
    strengths       TEXT,
    needs           TEXT,
    status          TEXT NOT NULL DEFAULT 'draft', -- draft, active, completed, superseded
    approved_by     TEXT,
    approved_at     TIMESTAMPTZ,
    review_due_at   TIMESTAMPTZ,
    created_by      TEXT NOT NULL,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Tasks within a case plan
CREATE TABLE case_plan_tasks (
    id           UUID PRIMARY KEY DEFAULT uuidv7(),
    case_plan_id UUID NOT NULL REFERENCES case_plans(id),
    description  TEXT NOT NULL,
    responsible  TEXT NOT NULL,               -- parent, agency, provider, other
    due_at       TIMESTAMPTZ,
    completed_at TIMESTAMPTZ,
    status       TEXT NOT NULL DEFAULT 'pending' -- pending, in_progress, completed
);

-- Contact / visitation log
CREATE TABLE contacts (
    id          UUID PRIMARY KEY DEFAULT uuidv7(),
    case_id     UUID NOT NULL REFERENCES cases(id),
    contact_type TEXT NOT NULL,              -- ContactType tokens; home_visit / office_visit / school_visit admit a visit
    contact_with TEXT NOT NULL,              -- who was contacted (person name or role)
    occurred_at TIMESTAMPTZ NOT NULL,
    duration_minutes INTEGER,
    narrative   TEXT,
    recorded_by TEXT NOT NULL,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    visited_child_id UUID REFERENCES persons(id), -- (f)(5) the child visited; set exactly when location is (#1995)
    location    TEXT                         -- (f)(6) childs_residence, other_location
);

-- Court orders and legal status
CREATE TABLE court_orders (
    id              UUID PRIMARY KEY DEFAULT uuidv7(),
    case_id         UUID NOT NULL REFERENCES cases(id),
    order_type      TEXT NOT NULL,           -- CourtOrderType tokens; review_hearing / permanency_hearing carry a hearing (#1995)
    court_name      TEXT,
    judge           TEXT,
    order_date      DATE NOT NULL,
    effective_date  DATE,
    findings        JSONB,                   -- contrary-to-welfare, reasonable-efforts, etc.
    next_hearing_date DATE,
    object_key      TEXT,                    -- object store key (renamed from document_url)
    recorded_by     TEXT NOT NULL,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Contact attachments (uploaded via craig-store)
CREATE TABLE contact_attachments (
    id           UUID PRIMARY KEY DEFAULT uuidv7(),
    contact_id   UUID NOT NULL REFERENCES contacts(id),
    filename     TEXT NOT NULL,
    content_type TEXT NOT NULL,
    size_bytes   BIGINT NOT NULL,
    object_key   TEXT NOT NULL,
    uploaded_by  TEXT NOT NULL,
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX idx_referrals_county ON referrals(county);
CREATE INDEX idx_investigations_worker ON investigations(assigned_worker);
CREATE INDEX idx_investigations_status ON investigations(status);
CREATE INDEX idx_cases_worker ON cases(assigned_worker);
CREATE INDEX idx_cases_status ON cases(status);
CREATE INDEX idx_case_household_case ON case_household(case_id);
CREATE INDEX idx_case_household_person ON case_household(person_id);
CREATE INDEX idx_contacts_case ON contacts(case_id);
CREATE INDEX idx_court_orders_case ON court_orders(case_id);

REST API (a curated subset; the full route list is Case Management API Reference)

Method Path Description Role

POST

/v1/cases/reports

Submit a report — the intake edge’s forward AND the staff (phone) entry path with the attested received_at (#1745; the birth of every referral)

caseworker+ (staff) / service (edge)

POST

/v1/cases/reports/{id}/screening-decisions

Record a screening decision; optional attested_response_priority (#1746) validated against the intake-screening output enum minus NONE

any role the {j}-intake-screening surface maps

POST

/v1/cases/reports/{id}/convert

Convert a screened report into a referral — the ONLY way a referral is born since #1746 (POST /v1/cases/referrals is a 405): the {j}-response-priority roll-up writes response_priority + provenance

caseworker+

GET

/v1/cases/referrals

List referrals (paginated, filterable by county; sort key response_priority)

caseworker+

GET

/v1/cases/referrals/{id}

Get referral detail with allegations

caseworker+

POST

/v1/cases/referrals/{id}/allegations

Add allegation to referral

caseworker+

POST

/v1/cases/investigations

Open investigation from referral — response_due_at is DERIVED (no caller field, deny_unknown_fields): the {j}-response-window consult + craig_common::deadline on the referral’s receipt (#1747)

caseworker+

GET

/v1/cases/investigations

List investigations (filterable by worker, status, timeliness band — served from v_investigations)

caseworker+

GET

/v1/cases/investigations/{id}

Get investigation detail

caseworker+

POST

/v1/cases/investigations/{id}/response-deadline

Override the response deadline — authz Update + attrs.operation = override_response_deadline (supervisor / county_director / regional_director / state_office operation rows, plus admin’s standing wildcard row; a caseworker is refused), then the {j}-response-deadline-override arm (GA / TX CLOSED) decides (#1748)

supervisor+ (operation-scoped)

PUT

/v1/cases/investigations/{id}

Update investigation status/disposition

caseworker+

POST

/v1/cases/investigations/{id}/safety-assessment

Submit safety assessment (calls Rules Engine)

caseworker+

POST

/v1/cases/cases

Open case from investigation

caseworker+

GET

/v1/cases/cases

List cases (filterable by worker, status, county)

caseworker+

GET

/v1/cases/cases/{id}

Get case detail

caseworker+

PUT

/v1/cases/cases/{id}

Update case (status, assignment, ICWA flag)

caseworker+

GET

/v1/cases/cases/{id}/household

Get household members

caseworker+

POST

/v1/cases/cases/{id}/household

Add household member

caseworker+

POST

/v1/cases/cases/{id}/children/{child_id}/{segment}

Record a complete statement on one of the five child-fact ledgers — {segment} = parenting-facts | prior-permanency-facts | assistance-facts | sibling-facts | icwa-facts (#1993); {child_id} must be or have been a child-role household member (400 child-not-in-case); refused on a closed case (409 case-closed) (#1992)

caseworker+ (human only)

POST

/v1/cases/cases/{id}/children/{child_id}/{segment}/{row_id}/corrections

Correct a live child-fact row (retire + successor) — admitted on a closed case

caseworker+ (human only)

POST

/v1/cases/cases/{id}/children/{child_id}/{segment}/{row_id}/retract

Retract a live child-fact row (with a note) — admitted on a closed case

caseworker+ (human only)

POST

/v1/cases/cases/{id}/children/{child_id}/{segment}/{row_id}/close

Close the open child-fact row — refused on a closed case

caseworker+ (human only)

GET

/v1/cases/cases/{id}/children/{child_id}/{segment}?as_of=

The child-fact row in force at a date (200, or 204 when none)

caseworker+ (human only)

GET

/v1/cases/cases/{id}/children/{child_id}/{segment}/history?from=&to=

Every live child-fact row in force during a period, newest first

caseworker+ (human only)

POST

/v1/cases/cases/{id}/children/{child_id}/parental-rights-actions

Record one parental-rights action (the first EVENT ledger, #1994) for a parent_person_id linked to the child (400 parent-not-linked); a court_order_id must be an active termination_of_parental_rights order of the case (400 parental-rights-order-invalid); an ICWA finding needs a yes_icwa_applies determination in force at terminated_on, else at effective_on when no termination date is stated (400 icwa-flags-without-determination); refused on a closed case (409 case-closed)

caseworker+ (human only)

POST

/v1/cases/cases/{id}/children/{child_id}/parental-rights-actions/{row_id}/corrections

Correct a live action (retire + successor; the body names the row’s parent) — admitted on a closed case

caseworker+ (human only)

POST

/v1/cases/cases/{id}/children/{child_id}/parental-rights-actions/{row_id}/retract

Retract a live action (with a note) — admitted on a closed case; there is no close

caseworker+ (human only)

GET

/v1/cases/cases/{id}/children/{child_id}/parental-rights-actions?as_of=

Without as_of: every live action, newest first by (recorded_at, id); with it: per parent, the action in force at the date (200 array)

caseworker+ (human only)

POST

/v1/cases/cases/{id}/children/{child_id}/permanency-plans

Establish one permanency plan for the child (EVENT ledger, #1995): plan + established_on (required on a new plan, on or before today); refused on a closed case (409 case-closed); publishes case.permanency_plan_established

caseworker+ (human only)

POST

/v1/cases/cases/{id}/children/{child_id}/permanency-plans/{row_id}/corrections

Correct a live plan (retire + successor; an omitted established_on is kept) — admitted on a closed case

caseworker+ (human only)

POST

/v1/cases/cases/{id}/children/{child_id}/permanency-plans/{row_id}/retract

Retract a live plan (with a note) — admitted on a closed case

caseworker+ (human only)

GET

/v1/cases/cases/{id}/children/{child_id}/permanency-plans?as_of=

Without as_of: every live plan, newest first by (established_on, recorded_at, id) (the first is CURRENT); with it: the plan in force at the date (200 array)

caseworker+ (human only)

GET

/v1/cases/cases/{id}/children/{child_id}/permanency-plans/current?as_of=

Service-to-service (#1996, plan D7, ADR-078 D4): the plan in force at as_of (REQUIRED, not capped at today) for craig-financial’s guardianship activation — 200 CurrentPermanencyPlan { event_id, plan, established_on } or 204 when none (an unknown case or a non-member child is 204, never 404 / 400); Cache-Control: no-store on both

service:craig-financial ONLY (require_service_caller allowlist; no per-row authz)

POST

/v1/cases/cases/{id}/children/{child_id}/review-events

Record an administrative periodic review or permanency hearing (kind + held_on); a body stating court_order_id is a 422 (only the court-order act writes it)

caseworker+ (human only)

POST

/v1/cases/cases/{id}/children/{child_id}/review-events/{row_id}/corrections

Correct a live review row (an omitted held_on and the court_order_id are kept) — admitted on a closed case

caseworker+ (human only)

POST

/v1/cases/cases/{id}/children/{child_id}/review-events/{row_id}/retract

Retract a live review row (with a note) — admitted on a closed case

caseworker+ (human only)

GET

/v1/cases/cases/{id}/children/{child_id}/review-events?as_of=

Without as_of: every live review row, newest first by (held_on, recorded_at, id); with it: the row in force at the date (200 array)

caseworker+ (human only)

POST

/v1/cases/cases/{id}/plans

Create case plan

caseworker+

GET

/v1/cases/cases/{id}/plans

List case plans

caseworker+

PUT

/v1/cases/plans/{id}

Update case plan

caseworker+

PUT

/v1/cases/plans/{id}/approve

Supervisor approval/countersign

supervisor+

POST

/v1/cases/plans/{id}/tasks

Add task to case plan

caseworker+

PUT

/v1/cases/tasks/{id}

Update task status

caseworker+

POST

/v1/cases/cases/{id}/contacts

Record contact/visitation; an optional visit: { visited_child_id, location } on a home_visit / office_visit / school_visit (any other type: typed 400 bad-request, field visit; a child not of the case: 400 child-not-in-case); the update’s visit is omitted = unchanged, null = clear, value = set (#1995)

caseworker+ (human only)

GET

/v1/cases/cases/{id}/contacts

List contacts

caseworker+

POST

/v1/cases/cases/{id}/court-orders

Record court order; a review_hearing / permanency_hearing order REQUIRES hearing: { held_on, children } (typed 400 court-order-hearing-required; on any other type court-order-hearing-not-admitted) and writes one child_review_events row per child; the update restating the hearing and the delete retire those rows (#1995)

caseworker+ (human only)

GET

/v1/cases/cases/{id}/court-orders

List court orders

caseworker+

POST

/v1/cases/contacts/{id}/attachments

Upload attachment to contact

caseworker+

GET

/v1/cases/contacts/{id}/attachments

List contact attachments

caseworker+

GET

/v1/cases/contacts/{id}/attachments/{aid}

Download attachment

caseworker+

DELETE

/v1/cases/contacts/{id}/attachments/{aid}

Delete attachment

caseworker+

GET

/v1/cases/persons

Search persons (name, DOB, SSN last-four)

caseworker+

POST

/v1/cases/persons

Create person record

caseworker+

GET

/v1/cases/persons/{id}

Get person detail

caseworker+

PUT

/v1/cases/persons/{id}

Update person record (a non-null race / ethnicity / tribal_affiliation is the typed 400 demographics-via-ledger, as on create)

caseworker+

POST

/v1/cases/persons/{id}/demographics

Record a complete demographics statement — a change (open-ended) or a backfill (with effective_until) (#1991)

caseworker+ (human only)

POST

/v1/cases/persons/{id}/demographics/{row_id}/corrections

Correct a live demographics row (retire + successor)

caseworker+ (human only)

POST

/v1/cases/persons/{id}/demographics/{row_id}/retract

Retract a live demographics row (with a note)

caseworker+ (human only)

POST

/v1/cases/persons/{id}/demographics/{row_id}/close

Close the open demographics row

caseworker+ (human only)

GET

/v1/cases/persons/{id}/demographics?as_of=

The demographics row in force at a date (200, or 204 when none)

caseworker+ (human only)

GET

/v1/cases/persons/{id}/demographics/history?from=&to=

Every live demographics row in force during a period, newest first (#1992)

caseworker+ (human only)

POST

/v1/cases/persons/{id}/siblings

Record a sibling link to sibling_person_id (stored as the ordered pair; a self-link is the 400 bad-request) (#1992)

caseworker+ (human only)

POST

/v1/cases/persons/{id}/siblings/{row_id}/corrections

Correct a live sibling link’s window (the path person on either side)

caseworker+ (human only)

POST

/v1/cases/persons/{id}/siblings/{row_id}/retract

Retract a live sibling link (with a note)

caseworker+ (human only)

POST

/v1/cases/persons/{id}/siblings/{row_id}/close

Close an open sibling link

caseworker+ (human only)

GET

/v1/cases/persons/{id}/siblings?as_of=

The sibling links in force at a date, on either side (200 array; empty when none)

caseworker+ (human only)

GET

/v1/cases/persons/{id}/siblings/history?from=&to=

Every live sibling link with the person on either side in force during a period, newest first (#1992)

caseworker+ (human only)

POST

/v1/cases/persons/{id}/parentage

Record a complete parentage statement of the child — parents_abandoned (required), sole_legal_parent (#1994)

caseworker+ (human only)

POST

/v1/cases/persons/{id}/parentage/{row_id}/corrections

Correct a live parentage row (retire + successor)

caseworker+ (human only)

POST

/v1/cases/persons/{id}/parentage/{row_id}/retract

Retract a live parentage row (with a note)

caseworker+ (human only)

POST

/v1/cases/persons/{id}/parentage/{row_id}/close

Close the open parentage row

caseworker+ (human only)

GET

/v1/cases/persons/{id}/parentage?as_of=

The parentage row in force at a date (200, or 204 when none)

caseworker+ (human only)

GET

/v1/cases/persons/{id}/parentage/history?from=&to=

Every live parentage row in force during a period, newest first

caseworker+ (human only)

POST

/v1/cases/persons/{id}/parents

Record a link from the child to parent_person_id with its role and legal_responsibility (a self-link is the 400 bad-request) (#1994)

caseworker+ (human only)

POST

/v1/cases/persons/{id}/parents/{row_id}/corrections

Correct a live parent link (the body names the row’s parent)

caseworker+ (human only)

POST

/v1/cases/persons/{id}/parents/{row_id}/retract

Retract a live parent link (with a note)

caseworker+ (human only)

POST

/v1/cases/persons/{id}/parents/{row_id}/close

Close an open parent link

caseworker+ (human only)

GET

/v1/cases/persons/{id}/parents?as_of=

The child’s parent links in force at a date, in the (c) parent order (200 array; empty when none)

caseworker+ (human only)

GET

/v1/cases/persons/{id}/parents/history?from=&to=

Every live parent link in force during a period, newest first

caseworker+ (human only)

GET

/v1/cases/ncands-export

Service-to-service (#651, paged by #1936): ONE referral-paged page of NCANDS Child File rows — ?ffy&as_of&after&limit (limit 1..=500, default 500; as_of REQUIRED — the FIXED cohort received_at ∈ [ffy) AND created_at ⇐ as_of, ordered (received_at, id)); returns WHOLE referrals with all their allegation rows; next = the opaque ExportCursor of the LAST SCANNED referral when the page is full (an all-unclassifiable page is zero rows + a non-null next), null on exhaustion; a malformed after / out-of-range limit is a typed 400 naming the parameter, an unknown query parameter the extractor’s value-free bad-request problem; each page rides the caller’s 8 s S2S hop budget (the whole-FFY Batch hop is gone)

service:craig-reporting ONLY (require_service_caller allowlist; no per-row authz)

RabbitMQ Events

Publishes:

Routing Key Payload

case.referral_created

{ referral_id, admin_unit, response_priority, icwa_flag, user_id } — user_id the converting worker, as on case.report_converted (#2277)

case.intake_created

{ investigation_id, referral_id, user_id } — user_id the acting worker (#2277); audit-only since #1670 (no consumer binds it; the intake-screening consult is the cases screening-decision act)

case.investigation_closed

{ investigation_id, disposition, user_id } — user_id the acting worker (#2277); disposition is one of the seven NCANDS outcome tokens (#648; inconclusive retired)

case.investigation_response_deadline_overridden

{ investigation_id, referral_id, user_id, actor_role, original_due_at, previous_due_at, new_due_at, reason, rule_set_revision, evaluation_id } — the audited response-deadline override (#1748); staged in the claimed override transaction; audit-only (craig-security: update / investigation, resource = investigation_id)

case.created

{ case_id, case_number, admin_unit, assigned_worker, supervisor, user_id } — supervisor is nullable (#1084); seeds the placement/financial case_assignments projections; user_id the acting worker (#2248)

case.updated

{ case_id, field, old_value, new_value, user_id } — user_id the acting worker (#2248)

case.closed

{ case_id, closure_reason, user_id } — user_id the acting worker (#2248)

case.assignment_changed

{ case_id, old_assigned_worker, new_assigned_worker, old_supervisor, new_supervisor, assignment_revision, admin_unit, user_id } — the cross-service assignment denormalization (Plan A §D6 / #1084); consumers apply strictly-greater assignment_revision (#1214). admin_unit (#1901, ADR-077 D6) is the case’s unit from the same CAS-locked row and is OPTIONAL at every consumer (absent on a retained pre-upgrade envelope = NULL, filled unit-only, COALESCE`d into the projection upsert), never an identity key. Bound by placement, financial, exchange (which ignores the unit); `user_id the reassigning worker, audit-only (#2248)

case.plan_created

{ case_plan_id, case_id, user_id } — permanency_goal left the payload with the column (#1995); the per-child plan rides case.permanency_plan_established; user_id the acting worker (#2248)

case.plan_approved

{ case_plan_id, case_id, approved_by } — supervisor countersign; promotes a draft plan to active (#821)

case.plan_superseded

{ case_plan_id, case_id, superseded_by, user_id } — the previously-active plan an approval displaced (#821); user_id the approving worker, as approved_by on case.plan_approved (#2248)

case.plan_updated

{ case_plan_id, case_id, status, user_id } (#821) — user_id the acting worker (#2248)

case.task_created

{ task_id, case_plan_id, responsible, user_id } (#821) — user_id the acting worker (#2248)

case.task_updated

{ task_id, case_plan_id, status, user_id } (#821) — user_id the acting worker (#2248)

case.task_deleted

{ task_id, case_plan_id, user_id } (#821) — user_id the acting worker (#2248)

case.person_created

{ person_id, user_id } — no PII in the payload (#821); user_id the acting worker (#2248)

case.person_updated

{ person_id, user_id } — no PII in the payload (#821); user_id the acting worker; null on the SOLQ verification flip, a service act (ADR-065 §D2) (#2248)

case.person_demographics_changed

{ person_id, row_id, act: recorded|corrected|retracted|closed, user_id } — one per committed demographics-ledger act (#1991 / ADR-078 D1); no fact value rides the event

case.person_residences_changed

{ person_id, row_id, act: recorded|corrected|retracted|closed, user_id } — one per committed residence-ledger act (#3192); ids and the act only, never the unit

case.person_siblings_changed

{ person_a, person_b, row_id, act: recorded|corrected|retracted|closed, user_id } — one per committed sibling-ledger act (#1992); ids and the act only

case.person_parents_changed

{ child_id, ledger: person_parentage_facts|child_parents, row_id, act: recorded|corrected|retracted|closed, user_id } — one per committed act on either parent person ledger (#1994); ids and the act only

case.child_facts_changed

{ case_id, child_id, ledger, row_id, act: recorded|corrected|retracted|closed, user_id } — one per committed act on any of the five child-fact ledgers, ledger = the table name (#1992; child_icwa_facts since #1993) — also one per committed parental_rights_actions act (recorded|corrected|retracted, #1994) and one per committed child_review_events act — recorded|corrected|retracted, plus order_corrected|order_deleted for each row a court-order update or delete retires (#1995); ids and the act only. On all five ledger keys user_id is the act’s acting worker (claims.acting_worker(); a court-order sweep’s rows carry the order act’s) — #2016

case.permanency_plan_established

{ event_id, person_id, case_id, action: established|corrected|retracted, plan, established_on, supersedes_id, act_id, act_at, current, user_id } — one per committed permanency_plans act (#1995, plan D6; strict contract craig_cases_contracts::events::PermanencyPlanEstablishedPayload); current = the child’s CURRENT plan after the act ({ event_id, plan, established_on }) or null; consumers apply the latest message per (person_id, case_id) by (act_at, act_id) — act_at is read after the per-case plan lock

case.person_identifier_recorded

{ identifier_id, person_id, kind, act: recorded, act_id, user_id } — one per committed external person-identifier record (#1806, plan custody-episodes-doe-slds D5; strict contract craig_cases_contracts::person_identifiers::PersonIdentifierEventPayload); ids, the kind token and the act only, never the value; user_id the acting worker; craig-exchange binds it through the GA DOE-SLDS matrix (#2343)

case.person_identifier_ended

{ identifier_id, person_id, kind, act: ended|retracted, act_id, user_id } — one per committed end or retraction of a live identifier, act saying which (PersonIdentifierAct::routing_key; same contract); ids, the kind token and the act only, never the value; user_id the acting worker; craig-exchange binds it through the GA DOE-SLDS matrix (#2343)

case.custody_opened

{ episode_id, child_id, case_id, row_id, act: recorded|corrected|retracted|episode_retracted, act_id, act_at, user_id } — an act that opens a custody episode: an open, or the first event of an until record (then case.custody_closed with the closing row’s id) (#2342, plan custody-episodes-doe-slds D3, ADR-081 D4; strict contract craig_cases_contracts::custody::CustodyEventPayload); ids, the act and its instant only, never a status token or a date; act_id / act_at are per act and shared by every event of the act; user_id the acting worker; a replay stages none; craig-exchange binds it through the GA DOE-SLDS matrix (#1821)

case.custody_closed

{ episode_id, child_id, case_id, row_id, act: recorded|corrected|retracted|episode_retracted, act_id, act_at, user_id } — an act that closes an episode: a close, or the second event of an until record (#2342, plan custody-episodes-doe-slds D3, ADR-081 D4; strict contract craig_cases_contracts::custody::CustodyEventPayload); ids, the act and its instant only, never a status token or a date; act_id / act_at are per act and shared by every event of the act; user_id the acting worker; a replay stages none; craig-exchange binds it through the GA DOE-SLDS matrix (#1821)

case.custody_retracted

{ episode_id, child_id, case_id, row_id, act: recorded|corrected|retracted|episode_retracted, act_id, act_at, user_id } — an episode retract, or the retraction of its last live in-custody row; row_id the episode’s latest live in-custody row (#2342, plan custody-episodes-doe-slds D3, ADR-081 D4; strict contract craig_cases_contracts::custody::CustodyEventPayload); ids, the act and its instant only, never a status token or a date; act_id / act_at are per act and shared by every event of the act; user_id the acting worker; a replay stages none; craig-exchange binds it through the GA DOE-SLDS matrix (#1821)

case.custody_close_corrected

{ episode_id, child_id, case_id, row_id, act: recorded|corrected|retracted|episode_retracted, act_id, act_at, user_id } — a correction or row retraction that changes a closed episode’s instants or closing token (#2342, plan custody-episodes-doe-slds D3, ADR-081 D4; strict contract craig_cases_contracts::custody::CustodyEventPayload); ids, the act and its instant only, never a status token or a date; act_id / act_at are per act and shared by every event of the act; user_id the acting worker; a replay stages none; craig-exchange binds it through the GA DOE-SLDS matrix (#1821)

case.legal_status_changed

{ episode_id, child_id, case_id, row_id, act: recorded|corrected|retracted|episode_retracted, act_id, act_at, user_id } — every other legal-status act (a change; a correction or row retraction on an open episode or of an unchanged closed one; any act on a history row, whose episode_id is null) (#2342, plan custody-episodes-doe-slds D3, ADR-081 D4; strict contract craig_cases_contracts::custody::CustodyEventPayload); ids, the act and its instant only, never a status token or a date; act_id / act_at are per act and shared by every event of the act; user_id the acting worker; a replay stages none; no consumer binds it

case.medicaid_application_submitted

{ application_id, child_id, case_id, episode_id, act: submitted|retracted, act_id, act_at, user_id } — one per committed Initial Medicaid Application submit (#1807, plan partner-auth-medicaid-application D7; strict contract craig_cases_contracts::medicaid_applications::MedicaidApplicationEventPayload); ids, the act and its instant only, never the citizenship status; act_id / act_at per act; user_id the acting worker; no consumer until TP-3’s IES bind (#1822), and no service may read the routes (deny_pure_service; TP-3 owes a service read); craig-security files it as a create of medicaid_application

case.medicaid_application_retracted

{ application_id, child_id, case_id, episode_id, act: submitted|retracted, act_id, act_at, user_id } — one per committed retract of a live application (#1807, plan partner-auth-medicaid-application D7; strict contract craig_cases_contracts::medicaid_applications::MedicaidApplicationEventPayload); ids, the act and its instant only, never the citizenship status; act_id / act_at per act; user_id the acting worker; no consumer until TP-3’s IES bind (#1822), and no service may read the routes (deny_pure_service; TP-3 owes a service read); craig-security files it as a update of medicaid_application

case.medicaid_application_report_received

{ report_id, application_id, child_id, case_id, kind: receipt|outcome, interface, exchange_transaction_id, received_at } — one per partner report stored on a Medicaid application (#3193; strict contract craig_cases_contracts::medicaid_application_reports::MedicaidApplicationReportReceivedPayload), staged in the transaction of POST /v1/cases/medicaid-applications/partner-reports; ids, the kind and the interface only, never the partner’s reference, case reference, program id or status; a replayed, unknown or withdrawn report stages none; craig-security files it as an update of medicaid_application by the posting service (service:craig-exchange)

case.person_pii_exported (consumed by craig-exchange’s outbound-trigger legs via the projection it audits)

{ person_ids, person_count, include_full_ssn, requestor, purpose } — the person-PII READ-audit (#1064 / ADR-051; its first emitter, the persons/federal-export route, was removed in P-C U1a, #1990); UUIDs only, no PII. The outbound-principals projection (#1827 / ADR-075) rides the SAME key discriminated by purpose = outbound_principals (include_full_ssn: false, requestor = craig-exchange, extended with { interface, correlation_id, stage_kind, stage_id } — one audit per decrypted release, correlated to the exchange job that read it, staged BEFORE the response). The SOLQ custody release (#1463 / ADR-065 §D2) rides the SAME key discriminated by purpose = ssa_solq_screening, extended with { screening_run_id, screening_member_id, requested_by }. The AFCARS persons export (#2121, plan afcars-pipeline-sources D5) rides the SAME key discriminated by purpose = afcars-2020 federal reporting (include_full_ssn: false, requestor = craig-reporting, extended with { date_of_birth_person_ids, from, to, as_of } — one audit per page that releases a person, staged in the handler’s transaction before the body; a not_found row releases nothing). A release to the jurisdiction’s person index (#3192) rides the SAME key discriminated by purpose = person_index_match, person_index_registration or person_index_participation (a one-element person_ids, include_full_ssn: false, no requestor, extended with { case_id, user_id } — one audit per call of the index, staged and committed BEFORE craig-exchange is called)

case.person_screening_release_refused

{ person_id, identifier_id, requestor, purpose: income_inquiry_screening, refusal_reason: identifier_stale, screening_run_id, screening_member_id, requested_by } — the screening identifier release’s categorical refusal audit (#3175 / ADR-065, renamed from case.person_ssn_release_refused); UUIDs + reason token only, never a value

case.person_ssn_admin_action

{ person_id, action: revoked|cleared, reason, user_id } — the revoke/clear reason’s durable audit sink (#1064 / ADR-051; worker-authored text, kept out of tracing); user_id the acting worker (#2248)

case.screening_cohort_changed

{ case_id, cohort_revision, change: household|screening_identifier } — the SSA-screening cohort signal (#1467 / ADR-065 D1); deliberately no person_id

case.household_member_added

{ id, case_id, user_id } — the household add’s act record (#2322), staged in the claimed add transaction beside the actor-less case.screening_cohort_changed; id the case_household row, user_id the acting worker (spec.actor); craig-security parses create on case_household; craig-reporting’s case.* binding no-ops on it

case.household_member_ended

{ id, case_id, ended_on, user_id } — the act record of ending a household membership (#2460), staged in the claimed end transaction beside the actor-less case.screening_cohort_changed; id the case_household row, ended_on the business date the worker stated, user_id the acting worker

case.screening_review_dismissed

{ item_id, case_id, user_id, latest_reason, dismissal_reason } — one per human dismissal of a screening-review item (#1557 / UD5)

case.report_submitted

{ report_id, partner_id, admin_unit } — partner_id is null for anonymous public submissions; cases owns the report lifecycle (ADR-017)

case.report_disposition_recorded

{ report_id, decision_id, user_id, actor_role, disposition_kind, supersedes_id, evaluation_ids } — one per recorded report disposition (ADR-017 Step 4, the screening endpoints; the strict contract is craig_cases_contracts::events::ReportDispositionRecordedPayload, #1672); ids + the actor_role (a {j}-intake-screening mapping token — cicc_intake …) / disposition_kind tokens, supersedes_id nullable, evaluation_ids the rules-side rule_evaluations ids of the per-subject consult — no narrative; user_id the acting worker (#2248)

case.report_attachment_uploaded

{ report_id, attachment_id, file_name, file_size, user_id } — user_id the attempt’s claimant, the uploading worker (#2277)

case.report_attachment_upload_failed

{ attempt_id, report_id, error } — keyed on the attempt: no entity row exists when an upload fails (#1249 / ADR-062 §U)

case.report_converted

{ report_id, referral_id, admin_unit, user_id, seed_case_id } — consumed by cases' own auto-link inbox (#1269 / ADR-062 §G4); user_id is the converting worker (#2211; was converted_by)

case.report_contact_revealed

{ report_id, admin_unit, user_id } — the audited reveal of an anonymous reporter’s contact details (#2209); ids and the unit, never the details

case.report_person_linked

the report_persons row (id, report_id, person_id, role, jsonb_index, user_id, linked_at, ruleset_name, ruleset_version) — user_id is the row’s linked_by (#2211; was linked_by on the wire); NULL = system auto-link (ADR-019)

case.report_persons_auto_linked

{ report_id, referral_id, count, skipped_due_to_ambiguity, ssn_promoted } — the per-convert auto-link batch (ADR-019; ssn_promoted is a COUNT, #1066)

case.report_person_unlinked

the deleted row’s provenance (id, report_id, person_id, role, jsonb_index, originally_linked_by, originally_linked_at, ruleset_name, ruleset_version) + user_id (the unlinking worker; #2211, was unlinked_by), unlinked_at (ADR-019)

case.contact_attachment_uploaded

{ attachment_id, contact_id, file_name, file_size, user_id } (platform-stab-2 §D4) — user_id the attempt’s claimant, the uploading worker (#2277)

case.contact_attachment_upload_failed

{ attempt_id, contact_id, error } (#1249 / ADR-062 §U)

case.court_order_document_uploaded

{ court_order_id, case_id, attempt_id, file_name, user_id } (#1296) — user_id the attempt’s claimant, the uploading worker (#2277)

case.court_order_document_upload_failed

{ court_order_id, case_id, error } — platform-stab-2 §D4 / ADR-062 §U; the one failed-upload event keyed on its entity ids (court_order_id, case_id) rather than attempt_id; ids + error only

case.ive_determination_invalidated

{ case_id, determination_revision } (#1313 U5b) — the LATEST determination’s witness run was invalidated; staged in the SAME tx as the cases-local marker, under the case row lock. The strict shared contract (craig-cases-contracts::events); financial’s invalidation SET converges both arrival orders

eligibility.evaluated

craig_cases_contracts::events::EligibilityEvaluatedPayload — { determination_id, determination_revision, case_id, child_id, ive_eligible, ffp_rate, business_date, user_id } (#1313 U6): ONE per witnessed child of a determination act, staged in the act tx with the child’s verdict row; user_id (#2323): the acting worker, the one defaulted field; ffp_rate is the U-FMAP bundle fraction (0.00 when ineligible) as a string; strict on both sides (deny_unknown_fields). PII-free.

Consumes:

Routing Key Action

case.report_converted

Run the report→person auto-link pass inside the inbox attempt transaction (ADR-062 §G4, #1269); the payload’s seed_case_id reproduces the request’s household seed

exchange.screening_run_invalidated

Mark the LATEST IV-E determination invalidated when its witness run is invalidated, under the case row lock, and stage case.ive_determination_invalidated in the same transaction (#1313 U5b / #1557)

(These two are the service’s ONLY bindings — craig-cases.events is declared with exactly this list and the dispatch refuses any other type. The design-era rows this table used to carry — rules.evaluated, placement.created, eligibility.evaluated — were never bound; ADR-003 § Amendment #1649.)

Rules Engine Integration

  • Safety assessment: When a caseworker submits a safety assessment, the service calls POST /v1/rules/evaluate with the safety assessment rule set. The engine decision (Safe / Safe with Plan / Unsafe) is stored alongside any worker override.

  • Investigation response (#895, ADR-072 § Amendment #895): three tier-1 consults, each as the acting worker under the S2S hop budget, fail-closed (rules down → 503, an absent ruleset or a drifted output → a named 500). {j}-response-priority at report conversion rolls the effective decision’s per-child response_priority tokens up to the referral’s ONE token (most-urgent-wins by first-hit order; a supervisor-attested priority counts where the arm says); {j}-response-window at investigation open turns that token into the window spec craig_common::deadline::derive_deadline resolves on the jurisdiction clock (Georgia: 24 h / 24 h / five weekdays to end of day); {j}-response-deadline-override judges the audited override (Georgia and Texas CLOSED). The BFF and CLI type no deadline and no priority anywhere.

  • Case routing: On case.referral_created, the Rules Engine can evaluate a complexity classification rule set to suggest assignment priority.

  • Relay auth (#1060): every cases→rules evaluate relay (safety-assessment submit, person-match suggestions + their ruleset-metadata fetch, conversion auto-link) forwards the inbound Authorization bearer AND the Plan E X-Craig-Actor header together via one RelayAuth value — so when craig-web mediates, rules scopes the RuleEvaluation × Create gate on the acting WORKER and rule_evaluations.evaluated_by names the worker, not the relay service. The auto-link consumer is the deliberate exception: it runs on a minted service bearer with no actor by construction, which is why the authz fixture’s rule_evaluation service create row stays (#786; see Rule Set Patterns and Domain Knowledge). The screening-SURFACE read (#1672 — the {j}-intake-screening metadata + schemas the act, conversion and follow-ups consult) does NOT forward the actor: it runs on the cases service principal inside one hop budget, and its client is a cross-request 60 s cache keyed by ruleset name, so per-worker credentials must not influence what it caches. The per-subject screening evaluates themselves ARE actor-relayed (context_type = 'screening-decision', context_id = report_id).

Verification

  1. cargo run -p craig-cases — service starts on port 8002

  2. Submit a report via POST /v1/cases/reports, record a screening decision, convert it via POST /v1/cases/reports/{id}/convert — verify the referral carries response_priority + its provenance (POST /v1/cases/referrals is a 405)

  3. Open investigation → submit safety assessment → verify Rules Engine evaluation recorded

  4. Open case → create case plan → verify the plan persists and supervisor approval countersigns it

  5. Verify RabbitMQ events published for each operation

Phase 4 — Placement and Foster Care Service

Status: Completed — core foster homes, placements, kinship, and matching, plus the later Phase 4 expansion (IV-E eligibility via the rules engine, educational enrollment, health records, and major-changes monitoring all landed; see the Roadmap Phase 4 checklist)

Service: craig-placement

Property Value

Binary

services/craig-placement/

Port

8003

Database

craig_placement

Dependencies

Phase 1 + Phase 2 + Phase 3

Key dependencies

workspace crates

Database Schema

-- Licensed foster home / provider
CREATE TABLE foster_homes (
    id               UUID PRIMARY KEY DEFAULT uuidv7(),
    name             TEXT NOT NULL,
    address          TEXT NOT NULL,
    county           TEXT NOT NULL,
    phone            TEXT,
    license_number   TEXT UNIQUE,
    license_status   TEXT NOT NULL DEFAULT 'pending',  -- pending, active, suspended, revoked, expired
    license_type     TEXT NOT NULL,                    -- foster, kinship, therapeutic, group
    licensed_at      DATE,
    license_expires  DATE,
    max_capacity     INTEGER NOT NULL DEFAULT 0,
    current_occupancy INTEGER NOT NULL DEFAULT 0,
    accepts_ages_min INTEGER DEFAULT 0,
    accepts_ages_max INTEGER DEFAULT 18,
    accepts_sibling_groups BOOLEAN NOT NULL DEFAULT false,
    icwa_compliant   BOOLEAN NOT NULL DEFAULT false,
    primary_contact  TEXT,
    created_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Training records for foster parents
CREATE TABLE foster_home_training (
    id             UUID PRIMARY KEY DEFAULT uuidv7(),
    foster_home_id UUID NOT NULL REFERENCES foster_homes(id),
    training_type  TEXT NOT NULL,            -- pre-service, in-service, CPR, first_aid, trauma_informed
    completed_at   DATE NOT NULL,
    expires_at     DATE,
    hours          NUMERIC(5,2) NOT NULL,
    verified_by    TEXT
);

-- #2018 (ADR-079 D2): one removal of a child under a case. Insert-only except the
-- current instants, a RETIRE and the admin_unit fill (refuse_episode_row_mutation);
-- the full constraint set, guards and deferred triggers are in
-- 20260925130000_removal_episodes_recut.sql and data-model-placement.adoc (Removal episodes).
CREATE TABLE removal_episodes (
    id             UUID PRIMARY KEY DEFAULT uuidv7(),
    child_id       UUID NOT NULL,
    case_id        UUID NOT NULL,
    admin_unit     TEXT,
    removal_at     TIMESTAMPTZ NOT NULL,     -- the live removal response's (ck_episode_current_instants, deferred)
    exit_at        TIMESTAMPTZ,              -- #2019: the live exit response's, NULL while in care; CHECK exit_at > removal_at
    recorded_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    recorded_by    UUID NOT NULL,
    retired_at     TIMESTAMPTZ,              -- RETIRE: retired_reason = 'retracted', retired_by paired
    retired_by     UUID,
    retired_reason TEXT,
    retired_note   TEXT,
    UNIQUE (id, child_id, case_id),
    EXCLUDE USING gist (child_id WITH =, tstzrange(removal_at, exit_at, '[)') WITH &&)
        WHERE (retired_at IS NULL)           -- a child's live episodes never overlap
);

-- #2018: the removal event ledger (FIRST_RECORDED; refuse_event_row_mutation)
CREATE TABLE removal_responses (
    id                UUID PRIMARY KEY DEFAULT uuidv7(),
    episode_id        UUID NOT NULL REFERENCES removal_episodes(id) ON DELETE RESTRICT,
    removal_at        TIMESTAMPTZ NOT NULL,
    removal_manner    TEXT NOT NULL,         -- voluntary_placement_agreement, court_ordered_removal
    recorded_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
    first_recorded_at TIMESTAMPTZ NOT NULL,  -- BEFORE INSERT trigger: own recorded_at, or the superseded row's
    recorded_by       UUID NOT NULL,
    supersedes_id     UUID REFERENCES removal_responses(id) ON DELETE RESTRICT,
    retired_at        TIMESTAMPTZ,           -- RETIRE: corrected, retracted
    retired_reason    TEXT,
    retired_note      TEXT,
    retired_by        UUID
);

-- #2019: the exit event ledger, the one home of AFCARS (g)(1)-(g)(4) (FIRST_RECORDED;
-- refuse_event_row_mutation; one live exit per episode); the full constraint set is in
-- 20260925150000_exit_responses.sql and data-model-placement.adoc (Removal episodes)
CREATE TABLE exit_responses (
    id                   UUID PRIMARY KEY DEFAULT uuidv7(),
    episode_id           UUID NOT NULL REFERENCES removal_episodes(id) ON DELETE RESTRICT,
    exit_at              TIMESTAMPTZ NOT NULL,  -- (g)(1)
    exit_reason          TEXT NOT NULL,         -- (g)(3): the 8 ExitReason tokens, never not_applicable
    transfer_agency_type TEXT,                  -- (g)(4): the 7 TransferAgencyType tokens; NOT NULL iff transfer_to_another_agency
    recorded_at          TIMESTAMPTZ NOT NULL DEFAULT now(),
    first_recorded_at    TIMESTAMPTZ NOT NULL,  -- (g)(2) BEFORE INSERT trigger: own recorded_at, or the superseded row's
    recorded_by          UUID NOT NULL,
    supersedes_id        UUID REFERENCES exit_responses(id) ON DELETE RESTRICT,
    retired_at           TIMESTAMPTZ,           -- RETIRE: corrected, retracted
    retired_reason       TEXT,
    retired_note         TEXT,
    retired_by           UUID
);

-- Child placement record: since #2018 a living arrangement inside one removal episode; a child's
-- activated arrangements never overlap (excl_placements_child_arrangement) and lie inside their
-- live episode (ck_arrangement_in_episode, deferred)
CREATE TABLE placements (
    id               UUID PRIMARY KEY DEFAULT uuidv7(),
    episode_id       UUID NOT NULL,           -- #2018: FK (episode_id, child_id, case_id) -> removal_episodes
    case_id          UUID NOT NULL,           -- references craig_cases.cases(id) cross-service; the episode's
    child_id         UUID NOT NULL,           -- references craig_cases.persons(id) cross-service; the episode's
    foster_home_id   UUID REFERENCES foster_homes(id),
    placement_type   TEXT NOT NULL,           -- #2056: foster_family_home or a federal (e)(4) token
                                              -- (group_home_*, residential_treatment_center, …, placed_at_home);
                                              -- family rows add six ffh_type_* flags and the generated
                                              -- foster_family_home ((e)(2))
    status           TEXT NOT NULL DEFAULT 'active', -- active, ended, planned, cancelled, retracted (#2020)
    started_at       TIMESTAMPTZ NOT NULL,
    ended_at         TIMESTAMPTZ,             -- CHECK ended_at > started_at
    activated_at     TIMESTAMPTZ,             -- #2018: write-once now() at activation (or at a #2020 historical
                                              -- record's birth); set iff active, ended or retracted
    cancelled_at     TIMESTAMPTZ,             -- #2018: the cancel trio, all set iff status = 'cancelled'
    cancelled_by     UUID,
    cancel_note      TEXT,
    retracted_at     TIMESTAMPTZ,             -- #2020: the retract trio, all set iff status = 'retracted'
    retracted_by     UUID,
    retract_note     TEXT,
    replaces_placement_id UUID REFERENCES placements(id) ON DELETE RESTRICT,
                                              -- #2020 R-B21: the retracted arrangement this row re-records (INSERT
                                              -- only); partial UNIQUE where status <> 'cancelled'
    end_reason       TEXT,                    -- transfer, disruption, runaway, left_care (#2019 added left_care;
                                              -- #2023 removed the six exit-like tokens)
    created_by       TEXT NOT NULL,
    created_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- #2023: the audit of the one sanctioned end-reason rewrite (append-only; the serving role never writes it); the full
-- definition is in 20260926120000_end_reason_narrowing.sql and data-model-placement.adoc (Removal episodes)
CREATE TABLE placement_end_reason_rewrites (
    placement_id     UUID PRIMARY KEY REFERENCES placements(id) ON DELETE RESTRICT,
    from_reason      TEXT NOT NULL,           -- CHECK chk_placement_end_reason_rewrites_from_reason: reunification,
                                              -- adoption, aging_out, guardianship, emancipation, death
    exit_response_id UUID NOT NULL REFERENCES exit_responses(id) ON DELETE RESTRICT,
    rewritten_at     TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Kinship / relative options evaluated during matching
CREATE TABLE kinship_options (
    id           UUID PRIMARY KEY DEFAULT uuidv7(),
    case_id      UUID NOT NULL,
    child_id     UUID NOT NULL,
    relative_name TEXT NOT NULL,
    relationship TEXT NOT NULL,
    evaluated    BOOLEAN NOT NULL DEFAULT false,
    approved     BOOLEAN,
    rejection_reason TEXT,
    evaluated_at TIMESTAMPTZ,
    recorded_by  TEXT NOT NULL
);

CREATE INDEX idx_placements_case ON placements(case_id);
CREATE INDEX idx_placements_episode ON placements(episode_id);
CREATE INDEX idx_placements_child ON placements(child_id);
CREATE INDEX idx_placements_foster_home ON placements(foster_home_id);
CREATE INDEX idx_placements_status ON placements(status);
CREATE INDEX idx_foster_homes_county ON foster_homes(county);
CREATE INDEX idx_foster_homes_status ON foster_homes(license_status);
CREATE INDEX idx_foster_home_training ON foster_home_training(foster_home_id);
CREATE INDEX idx_kinship_options_case ON kinship_options(case_id);

REST API (a curated subset; the full route list is Placement API Reference)

Method Path Description Role

GET

/v1/placement/homes

Search foster homes (county, capacity, type, age range)

caseworker+

GET

/v1/placement/homes/{id}

Get foster home detail with training records and per-type training evidence (#1642: training_evidence — six entries, state ∈ current | expired | undated | absent, the deciding row)

caseworker+

POST

/v1/placement/homes

Create foster home record

supervisor+

PUT

/v1/placement/homes/{id}

Update foster home (license status, capacity)

supervisor+

POST

/v1/placement/homes/{id}/training

Record training completion; #2075: 409 concurrent-modification when the home’s admin_unit moved since authorization (the PUT / DELETE /v1/placement/training/{id} writes answer the same)

caseworker+

POST

/v1/placement/episodes

#2018 (ADR-079 D2): open a removal episode — { client_request_id, child_id, case_id, removal_at, removal_manner } records the episode and its root removal response in one ADR-062 claimed transaction; the child is verified through craig-cases' placement-facts read (its refusals relayed, 503 when it does not answer); 400 ledger-instant-after-now, 409 episode-overlap; #2081: + the 43 removal-answer keys (required, nullable; null = unanswered; a missing key is 422 validation-failed; 400 structural-mismatch on an ungated (i)(1) answer).

caseworker+

POST

/v1/placement/episodes/{id}/removal/{row_id}/corrections

#2018: correct the live removal response — the complete corrected statement supersedes it and moves the episode’s removal_at; 400 response-after-recording, 404 ledger-row-not-found, 409 episode-retracted / episode-overlap / arrangement-outside-episode; #2081: + the 43 removal-answer keys (required, nullable; null = unanswered; a missing key is 422 validation-failed; 400 structural-mismatch on an ungated (i)(1) answer; the correction is the complete state, an answer sent as null is cleared).

caseworker+

POST

/v1/placement/episodes/{id}/retract

#2018: retract an episode entered in error (a note required) — its live removal response, its live exit response if any (#2019) and the episode are retired retracted; 409 episode-has-arrangements while a planned, active or ended arrangement references it, episode-retracted on a second retraction

caseworker+

POST

/v1/placement/episodes/{id}/exit

#2019 (ADR-079 D4): record the exit — { client_request_id, exit_at, exit_reason, transfer_agency_type } records the root exit response and sets the episode’s exit_at (200, the episode); 400 ledger-instant-after-now / exit-before-removal, 409 episode-retracted / episode-already-exited / episode-has-open-arrangement (a planned or active arrangement) / arrangement-outside-episode, 422 when transfer_agency_type is not given exactly for transfer_to_another_agency; #2083: + the 21 exit-answer keys (required, nullable; null = unanswered; a missing key is 422 validation-failed; an (h) key off an adoption / guardianship exit, an (i) key off an adoption, a count beside siblings_not_applicable or an ungated ICWA leaf is 400 structural-mismatch; a bad adoptive slot is 422; 503 while craig-cases is down on a fresh act naming one)

caseworker+

POST

/v1/placement/episodes/{id}/exit/{row_id}/corrections

#2019: correct the live exit response — the complete corrected statement supersedes it and moves the episode’s exit_at; 400 ledger-instant-after-now / response-after-recording / exit-before-removal, 404 ledger-row-not-found, 409 episode-retracted / episode-overlap / arrangement-outside-episode, 422 as on the record; #2083: + the 21 exit-answer keys (required, nullable; null = unanswered; a missing key is 422 validation-failed; an (h) key off an adoption / guardianship exit, an (i) key off an adoption, a count beside siblings_not_applicable or an ungated ICWA leaf is 400 structural-mismatch; a bad adoptive slot is 422; 503 while craig-cases is down on a fresh act naming one)

caseworker+

POST

/v1/placement/episodes/{id}/exit/{row_id}/retract

#2019: retract the live exit response entered in error (a note required) — it is retired retracted and the episode’s exit_at cleared, re-opening it; 404 ledger-row-not-found, 409 episode-retracted / later-episode-exists (the child has a later live episode the re-opened window would overlap)

caseworker+

POST

/v1/placement/episodes/historical

#2019: record an already-ended episode — { client_request_id, child_id, case_id, removal_at, removal_manner, exit_at, exit_reason, transfer_agency_type } records the episode, its root removal response and its root exit response in one ADR-062 claimed transaction (201, also on a replay); the child is verified as on the open; 400 ledger-instant-after-now / exit-before-removal, 409 episode-overlap, 422 as on the exit record; #2081: + the 43 removal-answer keys (required, nullable; null = unanswered; a missing key is 422 validation-failed; 400 structural-mismatch on an ungated (i)(1) answer); #2083: + the 21 exit-answer keys (required, nullable; null = unanswered; a missing key is 422 validation-failed; an (h) key off an adoption / guardianship exit, an (i) key off an adoption, a count beside siblings_not_applicable or an ungated ICWA leaf is 400 structural-mismatch; a bad adoptive slot is 422; 503 while craig-cases is down on a fresh act naming one).

caseworker+

GET

/v1/placement/children/{child_id}/episodes

#2018: the child’s live episodes, each with its live removal response and (#2019) its live exit response or null; per-row read check, an unreadable episode omitted

caseworker+

POST

/v1/placement/placements

Create placement — since #2018 an arrangement inside a removal episode: episode_id required, case_id / child_id derived from the episode (404 for an unknown one); 409 episode-retracted / episode-closed (the episode has a live exit); a birth-active create also answers 400 activation-start-out-of-range (a start outside [removal_at, now()]) and 409 arrangement-overlap / arrangement-outside-episode. #2020: optional replaces_placement_id (the retracted, not yet replaced arrangement of the same episode it re-records; 409 invalid-replacement otherwise). #2056: placement_type is foster_family_home or a federal (e)(4) token; ffh_types? (the applying (e)(3) categories) is required on foster_family_home and refused elsewhere; 400 required-field-missing (ffh_types absent on a family setting; a congregate setting without foster_home_id), structural-mismatch (ffh_types on another setting or repeated; a non-caregiving setting naming a home), setting-provider-mismatch (a home of the wrong provider kind). #2058: optional kinship_household on a home-less foster_family_home row — {"existing": <id>} or {"new": {"admin_unit"?}}; absent, a re-record reuses the replaced row’s household and anything else mints one with the episode’s unit; 400 structural-mismatch (a choice on another row; new.admin_unit beside an episode unit stamp), required-field-missing (no stamp and no new.admin_unit), 409 invalid-kinship-household (existing names no household), 403 (an unreadable household); #2080: + the 16 arrangement-fact keys (required, nullable; null = unanswered; a missing key is 422 validation-failed); 400 structural-mismatch on a fact its setting or a sibling fact does not admit (Arrangement facts)

caseworker+

POST

/v1/placement/placements/{id}/cancel

#2018: cancel a planned placement that never happened — { client_request_id, note }, ADR-062 claimed; planned → cancelled, emits placement.cancelled; 400 invalid-state-transition from any other status

caseworker+

POST

/v1/placement/placements/{id}/retract

#2020: retract an active or ended placement entered in error — { client_request_id, note } (1–1000 characters), ADR-062 claimed; → retracted (200 PlacementRetracted, retracted_from naming the origin), the row kept as the record and out of the effective set; emits placement.retracted; 400 invalid-state-transition from any other status; since #2058 no caregiver binding blocks it (a binding keys the kinship household)

caseworker+

POST

/v1/placement/placements/historical

#2020: record a missed past arrangement — { client_request_id, episode_id, placement_type, foster_home_id?, ffh_types?, started_at, ended_at, end_reason, replaces_placement_id?, + the 16 arrangement-fact keys (required, nullable) }, ADR-062 claimed; born ended with its facts set at birth (201 PlacementRecorded), never occupies, never bills; its one lifecycle event is placement.recorded (plus the #634 placement.field_written audit of its status); 400 when ended_at is not after started_at or ledger-instant-after-now, 404 episode or foster home, 409 episode-retracted / arrangement-overlap / arrangement-outside-episode / invalid-replacement; #2056: the same setting 400s as the create (required-field-missing, structural-mismatch, setting-provider-mismatch); #2058: the create’s optional kinship_household choice and its 400 / 409 / 403s; #2080: the create’s arrangement-fact keys, its 422 on a missing key and its 400 structural-mismatch refusals; the PlacementRecorded answer carries the sixteen keys

caseworker+

POST

/v1/placement/caregivers

#1848: bind a cases person to a caregiving unit (foster_home_id XOR kinship_household_id, #2058; was placement_id), effective-dated; ADR-062 claimed; 409 caregiver-binding-overlap (#2058: one person’s bindings on one unit never overlap)

caseworker+

GET

/v1/placement/caregivers?foster_home_id=|kinship_household_id=

#1848: a unit’s bindings with current, identity_enrolled, the newest open invitation (open_invitation: id, code prefix, expiry — the DELETE /v1/placement/invitations/{id} handle)

caseworker+

GET

/v1/placement/kinship-households/{id}

#2058 (plan afcars-placement-facts D4): one kinship household { id, admin_unit, created_at }; foster_home read on the household’s unit; 403 for a pure service principal, 404

caseworker+

GET

/v1/placement/kinship-households?person_id=&page=&per_page=

#2058: the households whose bindings name the person, under the foster-home list scope; person_id required (400 required-field-missing); 403 for a pure service principal

caseworker+

POST

/v1/placement/caregivers/{id}/end

#1848: end a binding (effective_from < ended_on ⇐ today); revokes its open invitations in the same transaction; #2053: 409 concurrent-modification when the home’s admin_unit moved since authorization

caseworker+

POST

/v1/placement/caregivers/{id}/invitations

#1848: issue a one-time enrollment code (returned ONCE; replay = 409 one-time-secret-already-issued); #2053: 409 concurrent-modification when the home’s admin_unit moved since authorization

caseworker+

DELETE

/v1/placement/invitations/{id}

#1848: revoke an open invitation; #2053: 409 concurrent-modification when the home’s admin_unit moved since authorization

caseworker+

DELETE

/v1/placement/caregivers/{id}/identity

#1848: revoke the caregiver’s live portal identity; #2053: the identity is person-wide, so the actor needs update on every unit the person holds an open (current or future) binding on (403 otherwise); 409 concurrent-modification when a unit moved or a binding was gained since authorization

caseworker+

GET

/v1/placement/field-proposals?decision=&page=&per_page=

#634 (ADR-037 §6): the propose-approve queue (decision defaults pending; craig_common::PageRequest) — rows FieldProposal { id, surface, unit_kind, unit_id, unit_name (home units), target_table, target_id, child_id?, placement_id?, child_display? (the cases arm, ≤ 50 ids, null on failure), field, proposed_value, previous_value?, proposed_at, decision, decided_at?, reason? }; NO proposed_by_sub / decided_by on the wire (attribution is the audit’s — staff never see the caregiver’s subject). Listed under auto_scope_list(FosterHome, List) exactly as the homes list — Denied is an empty page

list on foster homes (Georgia admin / supervisor / caseworker; Texas admin / caseworker — a Texas plain supervisor sees an empty page, and since #1904 so does a regional_director, rita.regional as a supervisor + regional dual holder included: the foster_home LIST resolves to the unit scope, and this queue has no admin_unit column, so its Units arm is the empty page — the in-unit foster_home proposals are still accepted by id)

POST

/v1/placement/field-proposals/{id}/accept

#634: apply a proposal — { client_request_id, reason? } → the decided FieldProposal. Action::Approve on the TARGET row’s own resource type; ADR-062 claimed; in ONE transaction: the proposal FOR UPDATE (already decided → 409 field-proposal-decided), the target FOR NO KEY UPDATE. The target is loaded BEFORE the check, existence-first (#1902, ADR-077 D5): an absent foster home answers 404 foster home, and an absent education / health record 404 education record / health record (#1909 b; a soft-deleted record still loads). Under the lock, a record whose admin_unit stamp moved since the check → 409 concurrent-modification (ADR-060), and so is a foster home whose admin_unit moved (#2075), and a soft-deleted record → 409 field-proposal-target-gone from the locked text read, the row staying pending, the live text compared to previous_value (moved → 409 concurrent-modification "the value changed since it was proposed — reject it or ask the caregiver again"; the row keeps the live value), the write under the lock (foster_homes bumps version, no If-Match), placement.education.updated / placement.health.updated where they exist, and placement.field_proposal_decided (ADR-022 outbox — the live write and its audit cannot diverge). A no-op accept (proposed == current) still marks the row accepted

approve on the target type — Georgia admin + supervisor; Texas (#1904, ADR-077 D7; #1909 (b)): admin + an IN-UNIT regional_director on all three (the unit CHECK row over the home’s attrs.admin_unit or the record’s creation-time stamp; out-of-unit or a NULL stamp → 403); a Texas plain supervisor’s approve row is i_supervises-gated and inert on these refs → 403; caseworkers denied. The Studio page stays {admin, supervisor}, so the in-unit regional_director accept is API-only (ruled 2026-10-06, #1927)

POST

/v1/placement/field-proposals/{id}/reject

#634: decline a proposal with an optional reason (≤ 500 — the caregiver reads it beside "Not accepted") — the same claim + proposal lock, then the target lock (#1909 b) with accept’s existence-first 404s and its stamp compare (a moved record stamp or home unit → 409 concurrent-modification, #2075); the ONLY drain for a stale proposal or one whose education / health target was soft-deleted; the caregiver may propose again afterwards

same as accept

POST

/v1/placement/portal/enrollment

#1848: the portal channel redeems a code into a live identity — uniform 404 for every code-side failure, per-IP + per-subject quota

portal channel + foster_parent subject

GET

/v1/placement/portal/units

#1851 (ADR-076 D4): the subject’s CURRENT caregiving units on the jurisdiction clock — { unit_id, kind: home | kinship_household, name (the home’s name only), role, effective_from } (#2058: kinship_household was placement); the LIST row’s custom scope decoded by craig_authz::PortalScope. The scope rule every portal route shares: zero current bindings (or a revoked identity) → 403 (the BFF ends the session); a unit outside the subject’s bindings → 404; ListScope::Denied → 403; a refused request stages no audit row

portal channel + foster_parent subject

GET

/v1/placement/portal/units/{unit}

#1851 (ruling R5): the unit’s ACTIVE placements — children[] { child_id, child_display ("First L." from the cases arm), started_at, caseworker_name (from the security arm) }, education[] { record_id, child_id, school_name, grade_level, enrollment_date }, health[] { record_id, child_id, record_type, provider_name, next_due_date }, names_unavailable (an arm did not answer ⇒ its names are null, never a guess — the rest still served); since #634 also the lock-state ride-along — field_permissions[] { field, access ∈ propose | read }, home_contact { foster_home_id, phone?, primary_contact? } (home units only) and proposals[] (pending + the last 30 days' decisions) — no extra call, no extra portal_read

portal channel + foster_parent subject

GET

/v1/placement/portal/units/{unit}/training

#1851: the home’s active training rows { training_type, completed_at, expires_at, hours } — never verified_by; a kinship household unit answers []

portal channel + foster_parent subject

GET

/v1/placement/portal/units/{unit}/documents

#1851: the home’s training_certificate documents ONLY — { id, filename, content_type, document_type, created_at } (no object key, uploader or description); a kinship unit answers []

portal channel + foster_parent subject

GET

/v1/placement/portal/units/{unit}/documents/{doc_id}/download

#1851: the certificate bytes (whole blob, Content-Disposition: attachment); a licence document, another home’s certificate, a deactivated row or a kinship unit → the uniform 404

portal channel + foster_parent subject

POST

/v1/placement/portal/units/{unit}/documents

#1851: multipart certificate upload (file, client_request_id, file_sha256 — ADR-062 §U; a byte-identical retry replays the SAME document); document_type is fixed server-side to training_certificate (a client-sent type is never read); binding + channel are checked BEFORE the body is parsed; the §U finalizer re-checks the binding under FOR NO KEY UPDATE OF b FOR UPDATE OF i — revoked in between ⇒ TargetGone: 404 upload target here, failed(target_gone) by the reconciler after the grace (#1886); a kinship unit → typed 422

portal channel + foster_parent subject

POST

/v1/placement/portal/units/{unit}/proposals

#634 (ADR-037 §6, ADR-076 D10): the bound caregiver proposes ONE new value for ONE shared field of ONE row of their own unit — { target_table ∈ education_records | health_records | foster_homes, target_id, field (the `table.column token), proposed_value, client_request_id }` → { proposal_id, field, proposed_at }. Admitted by the foster_portal create × projection == 'proposal' row, then by the owner MAP (shared only — a state-owned, unknown or wrong-table token, or a home column on a kinship unit, is 422 field-not-proposable); membership is checked BEFORE the field / value refusals, so a row outside the unit’s ACTIVE placements is the uniform 404; the value is validated + canonicalised per token kind (text trimmed / non-empty / ≤ the staff cap, dates YYYY-MM-DD; else 422 validation-failed on proposed_value; a proposal cannot clear a field); previous_value is read server-side inside the ADR-062 claimed tx; one open proposal per (target_id, field) (409 field-proposal-pending); stages placement.field_proposed in the tx and ONE portal_read (surface proposal) after it; the replay of a client_request_id returns the same receipt

portal channel + foster_parent subject

GET

/v1/placement/internal/caregiver-bindings?sub=

#1851 (ADR-076 D5): service-to-service — the subject’s CURRENT bindings on the jurisdiction clock WITH their unit ids { binding_id, foster_home_id?, placement_id?, person_id, role, effective_from, ended_on }; outside PORTAL_PATHS (a portal subject meets the fleet guard’s 403 first); unpaged; Cache-Control: no-store; craig-financial’s per-request authority (U9, #1852)

service caller craig-financial only (the scoped caregiver_bindings row, {j}-authz-foster_home_caregiver 1.1.0); a relayed (X-Craig-Actor) call is the 403 before the engine (#2339)

GET

/v1/placement/placements

List placements (filterable by case, child, home, status)

caseworker+

GET

/v1/placement/placements/{id}

Get placement detail

caseworker+

GET

/v1/placement/placements/{id}/subsidy-eligibility?as_of=

#1069 M2 S2S: the minimal projection financial’s subsidy enrollment reads (child_id, case_id, the assignment triple, placement_type, ffh_types (#2056: the family row’s applying (e)(3) categories, null otherwise; typed, serde-defaulted), status, dates, end_reason; permanency_goal left in P-C U6b #1997). #1851 (ADR-076 D8): the additive caregivers[] { person_id, role, effective_from, ended_on } — the intervals current on as_of (absent = the placement’s evidence date: the jurisdiction business date while planned/active, ended_on once ended, the served episode_exit.exit_on whenever episode_exit is non-null (#2022), never ahead of the business date; any past date accepted; more than one day ahead → 400 invalid-date); a homed placement’s caregivers are the home’s, a household-naming placement’s its kinship household’s (#2058); no unit ids on the items; no ruleset change (the subsidy_eligibility projection row keeps admitting). #2021 (ADR-079 D4): the additive episode_exit { exit_on, exit_reason } | null — non-null for the episode’s latest effective arrangement (by started_at, then id; activated, not retracted) or, since #2059, a placement whose residence run ends with it, with a live exit; exit_on is the jurisdiction’s business date of exit_at. #2059 (P-B2 D5): the additive residence { started_on, ended_on, arrangement_ids } | null — the placement’s residence run (date-adjacent effective arrangements of its episode, caregiving at both ends, one setting identity, non-caregiving rows only between), served for an effective caregiving placement only

service caller craig-financial only (the scoped subsidy_eligibility row)

PUT

/v1/placement/placements/{id}

Update placement — moves only planned → active and active → ended (#2018 removed planned → ended: cancel instead); started_at is accepted only on the activation; the removal, CTW and reasonable-efforts findings are gone (#2018), and so is permanency_goal (#2024); #2080: the optional arrangement_facts — absent or null = unchanged, present = the complete state of all sixteen keys, on a planned, active or ended row (else 400 invalid-state-transition); 400 structural-mismatch as on the create, against the row’s setting; 409 episode-retracted on a row of a retracted episode; no event and no field audit

caseworker+

GET

/v1/placement/placements/{id}/history

Placement history timeline for a child

caseworker+

POST

/v1/placement/kinship

Record kinship option evaluation

caseworker+

GET

/v1/placement/kinship?case_id={id}

List kinship options for a case

caseworker+

GET

/v1/placement/matching

Matching search FOR A CHILD — case_id + child_id required, the query CLOSED (identity-based, #972 / ADR-073; a stale child_age / icwa_required / sibling_group_size is a typed 400 structural-mismatch): the child’s facts (age at the business date, the ICWA person carrier — derived by cases through the federal ruleset federal-icwa-status over the case’s current child_icwa_facts row (#1993) — and the case flag, sibling-group size) come from craig-cases' placement-facts projection under the acting worker’s relayed credentials (cases' refusals relayed — 400 child-not-in-case / placement-facts-clock-drift, 422 child-dob-missing, 409 case-closed (a closed or transferred case, #2029), 403, 404; an outage is the typed 503 matching-facts-unavailable within 4 s, never a match on unverified facts); ONE merged consult of {j}-placement-eligibility (context_type placement-matching-criteria, context_id = the child) answers the candidate scope (matching-scope, #1721) AND the v1.4 child_criteria, bound mechanically by the SQL (require ⇒ a WHERE arm, prefer ⇒ a rank prefix ahead of the kinship / free-bed order, ignore ⇒ neither; a child_refusal_reason ⇒ 409 child-not-matchable before any scan); since #1641 every DISTINCT eligibility facts tuple of the candidate set is consulted (relayed as the acting worker) and the page is cut from the ADMITTED set: the typed envelope carries total = the admitted count plus excluded_by_policy / truncated; per_page caps at 50 (per_page=0 = an empty page, no cases call, no consult); a role without rule_evaluation create (readonly) is refused 403 rules-consult-denied

caseworker+

POST

/v1/placement/expiry-sweep/run

ENQUEUE one license/training-expiry notice sweep as a background job (#1641; since #1933 the body is the REQUIRED { client_request_id } — a forged field is 422 validation-failed; answers 202 + Location: /v1/placement/jobs/{id} + the JobView; the same id replays the same job, a fresh id while one is queued/running is 409 job-already-active; a peer-held engine lease is waiting_for_lease, no longer a 409; the pass report is the job’s result once succeeded)

approve on foster homes — Georgia admin + supervisor

GET

/v1/placement/jobs/{id}

Poll a background job (#1933, plan background-jobs D5): state / attempt ledger / progress / result / closed error token; Cache-Control: no-store; never writes

read on background_job — admin, or the creator (human or service principal); an unknown id is 404 BEFORE the check

RabbitMQ Events

Publishes:

Routing Key Payload

placement.created

{ placement_id, case_id, child_id, foster_home_id?, placement_type, status, started_at, user_id } — a placement ROW exists (any status); lifecycle/audit signal, NOT the billing trigger (#979); user_id the row’s created_by (#2248)

placement.activated

craig_placement_contracts::events::PlacementActivatedPayload — { placement_id, case_id, child_id, foster_home_id?, placement_type, ffh_types?, started_at, assigned_worker_sub?, supervisor_sub?, assignment_revision, user_id? } (#1632: the row’s assignment triple, additive/defaulted); #2277: user_id the acting worker — the creator on a born-active row, the activating worker on planned → active; additive/defaulted like the #1632 triple; #2056: placement_type is the typed federal setting and ffh_types the family row’s applying (e)(3) categories (absent otherwise); emitted when a placement becomes financially active (created active, or planned → active). #2020: an optional field replaces_placement_id names the retracted arrangement the activated row re-records (omitted when absent, so a plain activation carries no such key). Shared typed contract compiled by producer AND the craig-financial consumer (#979)

placement.ended

craig_placement_contracts::events::PlacementEndedPayload — { placement_id, end_reason?, ended_at?, user_id? } (#2277: user_id the ending worker, additive/defaulted); emitted when a placement transitions to ended. #1123: ended_at is the ROW’s business end instant (operators record endings after the fact, so the envelope’s staging timestamp differs on every backdated end — the event record itself now carries the terminal fact); present-only, so pre-#1123 envelopes degrade, never fail. Shared typed contract compiled by producer AND the craig-financial consumer since #1070 F9 (it replaced an ad-hoc producer-side json! whose end_reason the consumer silently dropped); end_reason is OMITTED when the row has none, and a consumer reading an older envelope degrades to reason-blind behavior, never a deserialization failure

placement.episode_facts_changed

#2018 (ADR-079 D2): craig_placement_contracts::events::EpisodeFactsChangedPayload — { episode_id, child_id, case_id, ledger ∈ removal_episodes | removal_responses | exit_responses | episode_trafficking_statements | trafficking_law_enforcement_reports, row_id, act ∈ recorded | corrected | retracted, user_id }; ONE per episode, exit or (#2082) trafficking act, staged in its transaction (the open and the episode retraction name the episode, a correction its successor response, an exit record its root exit response, an exit retraction the retired exit response, a trafficking record / correction / retraction the new / successor / retired statement or report; an episode retraction that also retires a live exit or live trafficking rows still stages one), except #2019’s historical episode, which stages TWO (removal_episodes / recorded naming the episode, then exit_responses / recorded naming its exit response); strict (deny_unknown_fields), ids and tokens only — never a removal, exit or trafficking fact; user_id = the acting worker, the attribution key

placement.cancelled

#2018: craig_placement_contracts::events::PlacementCancelledPayload — { placement_id, episode_id, child_id, case_id, user_id }; staged in the cancel transaction; strict, ids only (the note stays on the row); user_id = the acting worker, the attribution key

placement.retracted

#2020: craig_placement_contracts::events::PlacementRetractedPayload — { placement_id, episode_id, child_id, case_id, retracted_from ∈ active | ended, user_id }; staged in the retract transaction; strict, ids and the closed origin token only (the note stays on the row); user_id = the acting worker, the attribution key. craig-financial voids the placement’s undisbursed payments on it

placement.recorded

#2020: craig_placement_contracts::events::PlacementRecordedPayload — { placement_id, episode_id, child_id, case_id, started_at, placement_type, ffh_types?, replaces_placement_id?, user_id }; #2056 adds placement_type (the federal setting) and ffh_types (absent on a non-family row); the historical record’s one lifecycle event (no placement.created / activated / ended; the #634 placement.field_written audit of its status is also staged), staged in its transaction; strict; started_at is the business start instant (financial derives a pending re-anchor’s jurisdiction date from it)

placement.episode_exited

#2021 (ADR-079 D4): craig_placement_contracts::events::EpisodeExitedPayload — { episode_id, child_id, case_id, arrangement_ids, current: { exit_on, exit_reason } | null, act_id, act_at, user_id }; ONE per exit record, correction and retraction and one from the historical episode (an episode retraction publishes none), staged in the act’s transaction after its placement.episode_facts_changed; strict at its top level (current is the lenient EpisodeExit the subsidy-eligibility read serves); current = the episode’s live exit after the act on the jurisdiction calendar (null after a retraction); arrangement_ids = every live arrangement (planned, active, ended, by started_at then id; empty for a historical episode); act_at = the act’s clock_timestamp() under the episode lock, act_id a v7 minted per act (a consumer orders an episode’s messages by act_at, act_id); the exit’s date and reason are fleet vocabulary, not PII; user_id = the acting worker, the attribution key. craig-financial runs the #1070 guardianship WARN arms from it (log-only)

placement.education.created

{ education_record_id, child_id, user_id } — child education-record lifecycle (Phase 3/4 feature completion, the archived case-placement-completion plan; commit 914e6a76, pre-issue-numbered); ids only, no record content; user_id the acting worker (#2248)

placement.education.updated

{ education_record_id, user_id } — ids only; user_id the acting worker; on a proposal accept, the deciding staff member (#2248)

placement.education_report_received

#3188: craig_placement_contracts::education_reports::EducationReportReceivedPayload — { report_id, child_id, listing_id, interface, as_of }, strict; a partner’s report became, or was confirmed as, the child’s partner-reported education record. Staged in the write’s transaction; the audit header names the posting service (service:craig-exchange), create for a new row and update when the report moved a held row to a later day. Never the school, district or grade

placement.education_report_withdrawn

#3188: EducationReportWithdrawnPayload — { report_id, child_id, listing_id, interface, reason ∈ superseded | listing_ended }, strict; the row stopped being the child’s live report. The audit header’s actor is the posting service when its report superseded the row, the system when the row’s listing ended

placement.health.created

{ health_record_id, child_id, user_id } — child health-record lifecycle (same provenance); ids only, no clinical content; user_id the acting worker (#2248)

placement.health.updated

{ health_record_id, user_id } — ids only; user_id the acting worker; on a proposal accept, the deciding staff member (#2248)

placement.home_document_uploaded

{ document_id, home_id, file_name, file_size, created_by, document_type } — staged in the finalize transaction (#1251 / ADR-062 §U); #1851 added created_by (the uploader’s sub — a caregiver’s on the portal path, the staff sub otherwise; the key security’s actor walk attributes the row to, instead of system) and document_type, both additive

placement.home_document_upload_failed

{ attempt_id, home_id, file_name, error } — keyed on the attempt; carries the sanitized file name so reap-path failures name the file (#1251)

foster_home.license_expiring

craig_placement_contracts::expiry::FosterHomeLicenseNoticePayload — { notice_id, foster_home_id, expires_on, days, created_by }; raised by the expiry sweep (#1641) when a stored-active home’s license_expires lies within EXPIRY_SWEEP__LEAD_DAYS (days = days UNTIL, >= 0), staged in the notice transaction exactly once per (home, kind, expires_on); created_by = system or the triggering worker’s sub

foster_home.license_expired

same payload; raised when license_expires < today while the stored status is still active (days = days PAST, >= 1)

foster_home.training_expiring

craig_placement_contracts::expiry::FosterHomeTrainingNoticePayload — { notice_id, foster_home_id, training_type, expires_on, days, created_by }; raised by the same sweep (#1642) when a stored-active home’s EFFECTIVE certificate for one training type (max(expires_at) over the type’s active, dated rows with completed_at ⇐ today) lies within EXPIRY_SWEEP__LEAD_DAYS (days = days UNTIL, >= 0); independent of the license window — a home with no license_expires still notices; exactly once per (home, kind, training_type, expires_on)

foster_home.training_expired

same payload; raised when the type’s effective certificate is < today while the stored status is still active (days = days PAST, >= 1); an undated-only type raises NO notice (it reads undated to the gate, where Georgia’s arm refuses cpr_first_aid only), a type never recorded raises nothing

placement.caregiver_bound / placement.caregiver_ended

#1848: binding_id, unit ids, person_id, role, effective_from, ended_on, created_by (the acting staff sub — the audit attribution key)

placement.portal_invitation_issued / placement.portal_invitation_revoked

#1848: invitation_id, binding_id, expires_at, created_by — never the code or its hash

placement.caregiver_identity_enrolled

#1848: identity_id, sub (the caregiver’s own subject — the attribution key; there is no created_by), person_id, invitation_id, binding_id

placement.caregiver_identity_revoked

#1848: identity_id, sub, person_id, binding_id, created_by (the revoking staff sub)

placement.portal_read

#1851 (ADR-076 D4, ruling R4): craig_placement_contracts::portal::PortalReadPayload — { sub, role, jurisdiction, surface ∈ units | unit | training | documents | document_download | document_upload, unit_id? }; ONE per ADMITTED portal request (a refused 403 / 404 emits nothing), staged in its own transaction after the data read; sub = the caregiver — the attribution key, there is no created_by; ids and tokens only. Security records it as action portal_read, resource_type foster_portal, resource_id = unit_id (NULL on the units list; #2249). Volume: one outbox row (30 d) + one audit_log row (90 d hot) per portal request

placement.afcars_released

P-B1 U2 (#2017, plan D6 / R-B11): craig_placement_contracts::events::PlacementAfcarsReleasedPayload — { requestor ∈ craig-reporting, purpose ∈ afcars-2020 federal reporting, child_ids, child_count, from, to, as_of }, strict (deny_unknown_fields, each token set closed at one member); the AFCARS release audit — one per non-empty page of the service-only GET /v1/placement/afcars-export (#2119, P-D1 of #1965), staged in the page’s read transaction before it answers no-store. The producer is events::publish_afcars_released. Security records it as (read, placement), no resource id (children travel as a list), actor service:craig-reporting, the calling service (#3116)

placement.field_proposed

#634 (ADR-037 §6 — the propose act’s FIELD audit; its portal_read is the access trail): craig_placement_contracts::field_ownership::FieldProposedPayload — { proposal_id, surface, unit_kind, unit_id, target_table, target_id, field, field_owner, old_value?, new_value, sub, role, jurisdiction }; staged in the claimed propose transaction; sub = the caregiver — the attribution key, NO staff key; old_value = the stored text read in that transaction (null = was unset). Governed values only (a school name, a grade, a visit date, the home’s phone / primary contact) — never a DOB / SSN column (pinned in the contracts crate)

placement.field_proposal_decided

#634: FieldProposalDecidedPayload — { proposal_id, decision ∈ accepted | rejected, surface, unit_kind, unit_id, target_table, target_id, field, field_owner, old_value?, new_value, proposed_by_sub, approved_by, roles, jurisdiction, reason? }; staged in the ONE accept / reject transaction beside the live write; approved_by = the deciding staff member — the attribution key (on a reject as much as an accept); the caregiver rides as proposed_by_sub, deliberately NOT sub, so the row lands on staff

placement.field_written

#634 (plan portals decision 12): FieldWrittenPayload — { surface, target_table, target_id, field, field_owner, old_value?, new_value?, user_id, roles, jurisdiction }; ONE per governed token whose TEXT changed on a LIVE staff write (the four PUTs and the four creates, plus since #2020 the historical record — old_value null on a create, new_value null when a PATCH clears a tri-state field), staged in the write’s transaction from the LOCKED before-image; user_id = the acting worker (claims.acting_worker() — the WORKER’s roles under a BFF token, never the service’s). Since #2330 security records all three keys under their own action tokens, which the audit header states (#2314): a proposal and its decision under field_proposal (proposal_id), a write under the record type of its target_table (education_record / health_record / foster_home / placement; governed_record for any other table) with target_id — the generic split’s placement / NULL before; { field, old_value, new_value } is the case.updated key shape

The matching endpoint (GET /v1/placement/matching) is a read-only, attribute-based search and publishes nothing (#837 removed a dead placement.requested emission that reused child_id as a case_id placeholder). #971 retired the consumer half too — the Rules Engine no longer binds placement.requested and craig-security no longer names it; the routing key is gone from the ADR-003 catalog (see its § Amendment #971). A real producer would be new product behaviour, to be raised if placement requests ever become a workflow.

Consumes:

Routing Key Action

case.created

Seed the case_assignments projection (revision 0; #1084: the supervisor half rides along) the create handlers derive assigned_worker_sub from, and heal rows born while the case was unknown (#1213). #1901: the per-case advisory lock FIRST; the seed’s conflict arm fills a still-NULL admin_unit (pair and revision untouched); the unit-only heals (placements → kinship_options) run after the seed and BEFORE the pair heals

case.assignment_changed

Upsert case_assignments (full (worker, supervisor) pair snapshot, #1084) and reassign the denormalized assigned_worker_sub on placements/kinship_options under the #1214 revision guard. #1901: the per-case advisory lock FIRST; admin_unit rides the upsert as COALESCE(EXCLUDED.admin_unit, admin_unit); the unit-only heals run LAST

exchange.listing_ended

#3188: record the ended listing in ended_partner_listings and withdraw the live partner reports admitted under it, under the write’s child and listing locks, staging placement.education_report_withdrawn for each; a later report naming the listing is refused (Partner-reported education records)

Rules Engine Integration

  • License expiration (#1641, ruled in scope 2026-09-02 on #1639): every FosterHome read DERIVES effective_license_status (expired when stored active and license_expires < the jurisdiction business date — strict, never written back); both activation sites and matching consult the jurisdiction’s {j}-placement-eligibility ruleset (license_gate v1.0 — inputs license_status_effective + days_past_license_expiry; a derived expiry refuses 409 foster-home-license-expired, stored non-active keeps foster-home-license-not-active), with the verdict bound to facts re-derived under the home row lock; the expiry sweep raises foster_home.license_expiring / license_expired once per key. Training expiration (#1642): the SAME consult carries training.<type>.{state, days_past_expiry} for all six types — per (home, type) currency DERIVED from the active rows with completed_at ⇐ today (dated rows by max(expires_at); only undated ⇒ undated; none ⇒ absent; a household proxy, #1722) — and v1.1’s training_gate answers training_admits_matching / training_admits_activation / training_refusal_reason (Georgia: an expired or undated cpr_first_aid refuses 409 foster-home-training-expired / foster-home-training-unverifiable; every other type admits); the sweep’s training leg raises foster_home.training_expiring / training_expired. Order of refusal: license, training, then the untyped capacity 400. v1.2 (#1721): the candidate scope itself is the ruleset’s matching-scope row (Georgia: active only), bound in SQL — no status is hard-coded in placement

  • CTW timeliness: Monitors the CRAIG 60-day monitoring window (borrowed from Policy 9.5’s reasonable-efforts-to-prevent-removal deadline, #1662) for the contrary-to-welfare / best-interest finding; the IV-E first-order test is georgia-ive-eligibility’s `ctw_in_first_order (#1659)

  • Placement matching (#972 / ADR-073): a search FOR A CHILD — the age, ICWA and sibling-group facts come from craig-cases' placement-facts projection under the acting worker’s relayed credentials (never from the client) and the v1.4 child_criteria tables of {j}-placement-eligibility decide per request which are required (a WHERE arm), preferred (a rank prefix) or ignored; both activation sites prove the same facts for the placement’s own (case_id, child_id) — with or without a home — and refuse 409 child-not-matchable / child-criteria-violated after license and training, before capacity

Verification

  1. Create foster home → verify capacity tracking

  2. Create placement → verify placement.created event published (and placement.activated when created active / on planned → active)

  3. Verify CTW timeliness monitoring warns past day 45 and reads OVERDUE past day 60 (the monitoring window, not the IV-E first-order test)

  4. Verify the matching endpoint, given a case and its child, returns the in-scope homes with a free bed that pass the child’s required criteria (sibling-capable homes first for a 2-child case) and refuses a stale child_age= with a typed 400

  5. Lapse a stored-active home’s license_expires → its reads answer effective_license_status = expired, matching omits it (excluded_by_policy counts it), activation answers 409 foster-home-license-expired, and POST /v1/placement/expiry-sweep/run { client_request_id } → 202, polled to succeeded, raises one foster_home.license_expired (#1641 / #1933)

Phase 5 — Data Exchange Service

Status: Completed

Service: craig-exchange

Property Value

Binary

services/craig-exchange/

Port

8004

Database

craig_exchange

Dependencies

Phase 1 + Phase 2

Key dependencies

reqwest, workspace crates

Database Schema

-- Data exchange partner configuration
CREATE TABLE exchange_partners (
    id               UUID PRIMARY KEY DEFAULT uuidv7(),
    partner_name     TEXT NOT NULL UNIQUE,
    partner_type     TEXT NOT NULL,           -- cwca, financial, medicaid, can, tanf, child_support, external, court, education, health, tribal
    direction        TEXT NOT NULL,           -- inbound, outbound, bidirectional
    endpoint_url     TEXT,
    auth_type        TEXT,                    -- oauth2, api_key, certificate, none
    auth_config      JSONB,                  -- reserved for outbound auth (unimplemented, deferred); stored write-only, never returned in API responses (#757); store a secret reference (not plaintext) when wired
    exchange_format  TEXT NOT NULL DEFAULT 'json', -- json, xml, flat_file, hl7
    active           BOOLEAN NOT NULL DEFAULT true,
    data_sharing_agreement_id UUID,
    created_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Data sharing agreements (per ACF Technical Bulletin #8)
CREATE TABLE data_sharing_agreements (
    id               UUID PRIMARY KEY DEFAULT uuidv7(),
    partner_id       UUID NOT NULL REFERENCES exchange_partners(id),
    agreement_title  TEXT NOT NULL,
    effective_date   DATE NOT NULL,
    expiration_date  DATE,
    data_elements    JSONB NOT NULL,          -- list of data elements shared
    legal_authority  TEXT,                    -- CFR section or state statute
    status           TEXT NOT NULL DEFAULT 'draft', -- draft, active, expired, terminated
    object_key       TEXT,                    -- object store key (renamed from document_url)
    approved_by      TEXT,
    approved_at      TIMESTAMPTZ,
    created_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Exchange transaction log (audit trail)
CREATE TABLE exchange_transactions (
    id               UUID PRIMARY KEY DEFAULT uuidv7(),
    partner_id       UUID NOT NULL REFERENCES exchange_partners(id),
    direction        TEXT NOT NULL,           -- inbound, outbound
    exchange_type    TEXT NOT NULL,           -- e.g. "medicaid_eligibility", "court_order", "afcars"
    status           TEXT NOT NULL DEFAULT 'pending', -- pending, success, failed, retry
    request_payload  JSONB,
    response_payload JSONB,
    error_message    TEXT,
    record_count     INTEGER,
    initiated_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
    completed_at     TIMESTAMPTZ,
    initiated_by     TEXT NOT NULL
);

-- ICPC (Interstate Compact on the Placement of Children) requests
CREATE TABLE icpc_requests (
    id              UUID PRIMARY KEY,
    case_id         UUID NOT NULL,
    child_id        UUID NOT NULL,
    direction       TEXT NOT NULL,             -- outgoing, incoming
    sending_state   TEXT NOT NULL,
    receiving_state TEXT NOT NULL,
    request_type    TEXT NOT NULL,             -- foster_care, adoption, residential, parent
    status          TEXT NOT NULL DEFAULT 'draft', -- draft, submitted, home_study_requested, home_study_completed, approved, denied, placed, closed
    submitted_at    TIMESTAMPTZ,
    deadline_at     TIMESTAMPTZ,
    completed_at    TIMESTAMPTZ,
    created_by      TEXT NOT NULL,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- ICPC home studies (one per request)
CREATE TABLE icpc_home_studies (
    id                      UUID PRIMARY KEY,
    icpc_request_id         UUID NOT NULL REFERENCES icpc_requests(id),
    home_safety             TEXT NOT NULL DEFAULT 'pending',
    background_checks       TEXT NOT NULL DEFAULT 'pending',
    references_check        TEXT NOT NULL DEFAULT 'pending',
    space_capacity          TEXT NOT NULL DEFAULT 'pending',
    support_systems         TEXT NOT NULL DEFAULT 'pending',
    education_access        TEXT NOT NULL DEFAULT 'pending',
    medical_access          TEXT NOT NULL DEFAULT 'pending',
    rules_recommendation    TEXT,
    coordinator_decision    TEXT,
    override_justification  TEXT,
    completed_at            TIMESTAMPTZ,
    assessed_by             TEXT
);

-- ICPC attachments (100A forms, medical records, etc.)
CREATE TABLE icpc_attachments (
    id               UUID PRIMARY KEY,
    icpc_request_id  UUID NOT NULL REFERENCES icpc_requests(id),
    attachment_type  TEXT NOT NULL,
    object_key       TEXT NOT NULL,            -- object store key (via craig-store)
    uploaded_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    uploaded_by      TEXT NOT NULL
);

CREATE INDEX idx_exchange_partners_type ON exchange_partners(partner_type);
CREATE INDEX idx_exchange_partners_active ON exchange_partners(active);
CREATE INDEX idx_agreements_partner ON data_sharing_agreements(partner_id);
CREATE INDEX idx_agreements_status ON data_sharing_agreements(status);
CREATE INDEX idx_exchange_transactions_partner ON exchange_transactions(partner_id);
CREATE INDEX idx_exchange_transactions_status ON exchange_transactions(status);
CREATE INDEX idx_icpc_requests_case ON icpc_requests(case_id);
CREATE INDEX idx_icpc_requests_status ON icpc_requests(status);

REST API (a curated subset; the full route list is Data Exchange & ICPC API Reference)

Method Path Description Role

GET

/v1/exchange/partners

List exchange partners

admin

POST

/v1/exchange/partners

Configure exchange partner

admin

PUT

/v1/exchange/partners/{id}

Update partner configuration

admin

POST

/v1/exchange/partners/{id}/test

Test connectivity to partner

admin

GET

/v1/exchange/agreements

List data sharing agreements

admin

POST

/v1/exchange/agreements

Create data sharing agreement

admin

PUT

/v1/exchange/agreements/{id}

Update agreement

admin

POST

/v1/exchange/send

Trigger outbound exchange

caseworker+

GET

/v1/exchange/transactions

List exchange transactions (filterable)

supervisor+

GET

/v1/exchange/transactions/{id}

Get transaction detail with payloads

supervisor+

POST

/v1/exchange/transactions/{id}/retry

Retry failed transaction

admin

POST

/v1/exchange/collections/run

Enqueue one collection run as a background job (#3188, #3190): the body is \{ client_request_id, interface, leg }; answers 202 + Location: /v1/exchange/jobs/{id} + the job; the same id replays the same job, a fresh id while a run is queued or running is 409 job-already-active; the recorded run (transaction, status, counts) is the job’s result once succeeded

a human admin on their own bearer (no service, no relay)

GET

/v1/exchange/jobs/{id}

Poll a background job (#3190): state, attempt ledger, progress, result, the closed error token; Cache-Control: no-store; never writes

read on background_job: admin, or the creator; an unknown id is 404 before the check

GET

/v1/exchange/icpc

List ICPC requests

icpc_coordinator+

POST

/v1/exchange/icpc

Create ICPC request

icpc_coordinator+

GET

/v1/exchange/icpc/{id}

Get ICPC request detail

icpc_coordinator+

PUT

/v1/exchange/icpc/{id}

Update ICPC request (status transitions)

icpc_coordinator+

POST

/v1/exchange/icpc/{id}/home-study

Submit home study results

icpc_coordinator+

GET

/v1/exchange/icpc/{id}/home-study

Get home study detail

icpc_coordinator+

POST

/v1/exchange/icpc/{id}/attachments

Upload attachment (100A, medical records)

icpc_coordinator+

GET

/v1/exchange/icpc/{id}/attachments

List attachments

icpc_coordinator+

GET

/v1/exchange/icpc/{id}/attachments/{aid}

Download attachment

icpc_coordinator+

Adapter Pattern

Each of the 11 mandatory exchange types (45 CFR § 1355.52(e-f)) is implemented as an adapter module:

Adapter Exchange Partner Requirement

cwca

Child Welfare Contributing Agencies

§ 1355.52(e)(1) — mandatory

financial

Title IV-B / IV-E payment systems

§ 1355.52(e)(2) — mandatory

medicaid

Medicaid eligibility systems

§ 1355.52(e)(3) — mandatory

can

Child Abuse and Neglect systems

§ 1355.52(e)(4) — mandatory if applicable

tanf

Title IV-A TANF systems

§ 1355.52(e)(5) — mandatory if applicable

child_support

Title IV-D child support systems

§ 1355.52(e)(6) — mandatory if applicable

external

External data collection systems

§ 1355.52(e)(7) — mandatory if applicable

court

Court systems

§ 1355.52(f)(1) — to the extent practicable

education

Education systems

§ 1355.52(f)(2) — to the extent practicable

health

Health agency systems

§ 1355.52(f)(3) — to the extent practicable

tribal

Tribal entities

§ 1355.54 — optional

All adapters implement a common ExchangeAdapter trait and use the jurisdiction’s single unified data exchange standard per § 1355.52(f).

RabbitMQ Events

Publishes:

Routing Key Payload

exchange.sent

{ transaction_id, partner_id }

exchange.failed

{ transaction_id, partner_id, error }

exchange.send_requested

{ transaction_id, partner_id, correlation_id, user_id } — user_id the requesting worker on a send or retry, JSON null on a trigger dispatch (#2277); staged with the transaction’s send claim (platform-stab-2 §D5); audit-only, no consumer by design — emitted for the audit log, no service binds it (ADR-003 § Amendment #1652)

icpc.created

{ icpc_request_id, case_id, user_id } — user_id the acting worker (#2277)

icpc.status_changed

{ icpc_request_id, from_status, to_status, user_id } — user_id the acting worker (#2277)

icpc.attachment_uploaded

{ attachment_id, icpc_request_id, attachment_type, user_id } (#1250 / ADR-062 §U) — user_id the uploading worker (#2277)

icpc.attachment_upload_failed

{ attempt_id, icpc_request_id, error } — keyed on the attempt (#1250)

exchange.screening_run_invalidated

{ run_id, case_id, reason: cohort_changed|operator_cancelled|freshness_expired, superseded_by_run_id?, user_id? } — present-only optionals; user_id only on operator_cancelled (#1467 / ADR-065/066)

exchange.screening_run_staged

{ run_id, case_id, user_id } — the run start’s act record (#2322), staged on every fresh run start (a replay stages none); user_id the relayed requested_by (craig-cases relays under its own bearer with no X-Craig-Actor); craig-security parses create on ssa_screening_run

exchange.screening_hold_set, exchange.screening_hold_cleared

{ run_id, case_id, user_id, reason } — one event per genuine legal-hold TRANSITION (#1566 / UD10)

ssa.jobs_resumed

{ user_id, reason_filter?, run_id?, jobs: [{ job_id, pre_reset_attempts }], count } — one per operator resume act (#1469 / ADR-066 fork 6)

exchange.partner_created, exchange.partner_updated, exchange.partner_deactivated, exchange.agreement_created, exchange.agreement_updated, exchange.agreement_deleted

{ id, user_id, fields? } — one per partner or agreement write, in its transaction (#2496); fields the updated field NAMES, never a value

exchange.trigger_admissions_released

{ user_id, interface, held_reason?, released_ids, still_held } — one per release pass that wrote a row (#2496)

exchange.trigger_records_restaged

{ user_id, interface, record_class, restaged_job_ids, refused } — one per record-arm pass that re-staged a job (#2496)

exchange.trigger_admissions_dismissed

{ user_id, interface, admission_ids } — one per dismiss pass that retired a row (#2496)

exchange.trigger_stages_caught_up

{ run_id, user_id, interface, stage_kind, status } — one per catch-up walk that opened its run row, staged with the run’s close (status completed | failed); user_id the walking admin (#3001)

exchange.collection_completed

{ transaction_id, partner_id, user_id, interface, leg, status, applied, stale, not_listed, unattributable, failed } — one per collection run that resolved its partner, staged with the run’s transaction (status completed | failed); user_id the admin who ran it, absent with its key on a run the collection schedule started (#3190); counts only, no reported value (#3188)

exchange.return_completed

{ transaction_id, partner_id, caller_partner_id, certificate_id, fingerprint, interface, leg, status, applied, replayed, unknown, withdrawn, failed, unread } — one per partner call the return listener read and handed on (#3193, ADR-091), staged with the call’s transaction (status completed | failed). fingerprint is the SHA-256 of the caller’s certificate; the audit row is filed under client-certificate:<fingerprint>. Nothing the partner reported is in it

exchange.return_refused

{ fingerprint, class, interface?, leg?, certificate_id?, caller_partner_id?, partner_id? } — one per call that completed the listener’s handshake and was not applied. class is lookup-unavailable, unknown-caller, not-callers-interface, agreement-does-not-admit, no-consent, no-leg, unread, store-unavailable, malformed, too-large or busy. Each later key is absent when the call was refused before it was learned; interface and leg are the deployment’s own tokens, never the path’s text. The audit row is a deny under client-certificate:<fingerprint>

exchange.listing_ended

{ listing_id, interface, person_id } (craig_placement_contracts::partner_listings::ListingEndedPayload, strict) — one per stamp that ends a recipient row’s listing (closure staged, or recipient removed), staged in that transaction by the ledger’s own writers, so no pass ends a listing without it; the system’s act on the person. craig-placement withdraws the partner reports admitted under the listing (#3188)

(The design-era exchange.received row this table used to carry was retired producer-less by #1652 — no emitter has ever existed; a stray headerless envelope is filed by the split of its event type, as received/exchange. It returns with the producer when inbound exchange is built; ADR-003 § Amendment #1652.)

Consumes:

Routing Key Action

case.created

No projection; the outbound-trigger matrix decides what it admits (#1828)

placement.created

Bound ahead of its own leg (ADR-075 D17, consumers before producers); no projection

case.assignment_changed

Reassign the worker denorms on exchange rows under the #1214 revision guard (supervisor columns are #1367)

case.screening_cohort_changed

Watermark GREATEST-upsert → strict < invalidation of open screening runs → sweep (#1466 B5-U3 / #1467 / ADR-066)

every event key the jurisdiction’s outbound-trigger matrix declares

No projection; admitted to the outbound-trigger path (#1829 CPRS stages and principals, #2343 DOE-SLDS custody and GTID; Georgia’s matrix: the georgia layer’s bundle/outbound_triggers.toml)

(craig-exchange.events binds the four keys above plus the matrix’s event keys — inbox_routing_keys in services/craig-exchange/src/lib.rs. Every one runs outbound-trigger admission after its own handler; an event with no matrix row admits nothing. The eligibility.evaluated row this table once carried was never bound and is removed; ADR-003 § Amendment #1649.)

Verification

  1. Configure a test exchange partner → verify connectivity test endpoint

  2. Trigger outbound exchange → verify transaction logged with payload

  3. Simulate inbound exchange → verify event published to RabbitMQ

  4. Retry failed transaction → verify status updated

Hardening — Seed Data, Tests & Documentation

Status: Complete — Sessions 1-5 complete (seed data, e2e tests, data model docs, developer guides, e2e manifest integration)

This phase is intentionally positioned before Phase 6 (Financial). The goal is to harden the existing platform so that new feature services can be built on a well-tested, well-documented foundation.

1. Seed Data Generator (craig-seed)

The original static SQL seed files (devstack/seed/sql/*.sql) were replaced with a scalable, optionally deterministic seed data generator. The craig-seed Rust binary (in tools/craig-seed/) generates realistic, cross-service seed data at arbitrary scale.

Key Features

  • Random by default — different data each run when no seed is specified

  • Deterministic via --seed N — identical output for the same seed + families combination

  • Scalable via --families N — each family generates a cascade of referrals, investigations, cases, placements, and exchange entities

  • Cross-service FK integrity — all foreign key references valid across craig_cases, craig_placement, and craig_exchange databases

  • Deterministic UUIDv7s — custom generator using monotonic counter + seeded RNG for reproducible, time-ordered UUIDs

  • 21 tests — determinism, FK consistency, scale (1/100/1000 families), UUID validity, SQL structure

Docker Integration

The craig-seed binary is built in the main Dockerfile (target: craig-seed) and invoked by devstack/seed/seed.sh. Environment variables CRAIG_SEED (empty = random) and CRAIG_FAMILIES (default 12 in devstack) are passed through docker-compose.yml.

Usage

# Random seed, default 9 families
cargo xtask dev restart

# Deterministic, scaled up
CRAIG_SEED=42 CRAIG_FAMILIES=500 cargo xtask dev restart

# Local generation (without Docker)
cargo run -p craig-seed -- --seed 42 --families 9 --output-dir /tmp/seed

See the craig-seed design plan for full architecture details.

2. Test Audit

E2E Assertion Hardening

Review all existing e2e tests and strengthen assertions:

  • Replace toBeVisible() checks on flash messages with toContainText('specific value')

  • After form submissions, verify the created/updated entity appears in the list/detail view

  • After state transitions, verify the new status badge text matches expected value

  • After delete operations, verify the entity is removed from the list

Negative and Error Path Tests

Add e2e tests for error conditions:

  • Authentication: Visit protected pages without login → verify redirect to Keycloak

  • Authorization: Attempt supervisor-only actions (close investigation) as caseworker → verify 403 or appropriate error

  • Not Found: Navigate to /cases/00000000-0000-0000-0000-000000000000 → verify 404 page

  • Form Validation: Submit forms with missing required fields → verify inline validation errors

  • State Machine Guards: Attempt invalid transitions (e.g. close an already-closed case) → verify error message

API Integration Test Gaps

Review and add integration tests for:

  • Pagination edge cases (empty results, last page, invalid page number)

  • Soft-delete behavior (deleted entities hidden from LIST; since #1579 the GET-by-id paths 404 tombstones — the #1215 posture)

  • Concurrent modification (optimistic locking if implemented)

  • Cross-service event publishing (verify RabbitMQ messages published after mutations)

3. Data Model Documentation

ER Diagrams

Create Mermaid ER diagrams for each service database:

  • docs/modules/ROOT/pages/data-model-cases.adoc — persons, referrals, allegations, investigations, cases, household_members, case_plans, plan_tasks, contacts, court_orders

  • docs/modules/ROOT/pages/data-model-placement.adoc — foster_homes, placements, kinship_assessments

  • docs/modules/ROOT/pages/data-model-exchange.adoc — exchange_partners, agreements, icpc_requests, transactions, home_studies

  • docs/modules/ROOT/pages/data-model-rules.adoc — rule_sets, rule_evaluations

Each diagram should include column names, types, and foreign key relationships.

State Machine Diagrams

Create Mermaid state diagrams for all entities with status fields:

  • Referral: new → screening → accepted / rejected

  • Investigation: open → pending_review → closed

  • Case: open → plan_active → closed

  • Case Plan: draft → active → approved → closed

  • Placement: active → ended

  • Agreement: draft → active → expired / terminated

  • ICPC Request: requested → accepted / denied → placed → closed

  • Exchange Transaction: pending → sent → acknowledged / failed

Domain Glossary

Create docs/modules/ROOT/pages/glossary.adoc with authoritative definitions for all domain terms: allegation, case plan, CCWIS, contact, court order, disposition, foster home, household member, ICPC, investigation, kinship, permanency goal, placement, referral, rule set, safety assessment, etc.

4. Developer Onboarding Guide

Create docs/modules/ROOT/pages/developer-guide.adoc covering:

  • Getting started — prerequisites, clone, devstack startup, running tests

  • How to add an API endpoint — step-by-step walkthrough (model, migration, handler, route registration, OpenAPI, test)

  • How to add a new service — workspace member, Dockerfile, docker-compose entry, shared crate usage

  • How to add a web UI page — Askama template, route, middleware, htmx patterns, Alpine.js conventions

  • How to add a CLI command — clap subcommand, cmd::* module, API client method, integration test

  • How to add a JDM rule set — file format, jurisdiction naming, evaluation test, import via API

  • Testing guide — unit vs integration vs e2e, craig-test-lib usage, running specific test suites

  • Architecture overview — service communication patterns, authentication flow, event bus topology

Architecture Decision Records

Create docs/modules/ROOT/pages/adrs/ directory with ADR files:

  • adr-001-rust-monorepo.adoc — why Rust, why monorepo, why Cargo workspace

  • adr-002-uuid-v7.adoc — why UUID v7 over auto-increment or UUID v4

  • adr-003-rabbitmq-topology.adoc — topic exchange, routing key conventions, competing vs exclusive consumers

  • adr-004-bff-pattern.adoc — why server-side rendering with BFF vs SPA

  • adr-005-keycloak-oidc.adoc — why Keycloak, realm structure, role model

  • adr-006-rules-engine.adoc — why zen-engine/JDM, jurisdiction configurability

5. Deployment and Operations Guide

Create docs/modules/ROOT/pages/deployment-guide.adoc covering:

  • Environment variables reference — complete list of all CRAIG_* env vars across all services with descriptions and defaults

  • Container deployment — Docker image builds, container registry, health checks

  • Database setup — PostgreSQL requirements, migration execution, backup strategy

  • RabbitMQ configuration — exchange/queue topology, user setup, HA considerations

  • Keycloak configuration — realm import, client setup, role mapping, OIDC endpoints

  • Monitoring — structured logging format, health check endpoints, readiness vs liveness probes

  • Scaling — horizontal scaling guidelines, connection pool sizing, stateless service guarantees

Verification

  1. Devstack starts cleanly with expanded seed data — all services healthy

  2. All existing e2e tests still pass with new seed data

  3. New negative/error e2e tests pass

  4. ER diagrams render correctly in Antora site

  5. Developer guide is sufficient for a new contributor to add an endpoint end-to-end

  6. Deployment guide covers all configuration needed for a fresh installation

Phase 6 — Financial and Claims Service

Status: Complete

Service: craig-financial

Property Value

Binary

services/craig-financial/

Port

8005

Database

craig_financial

Dependencies

Phase 1 + Phase 2 + Phase 3 + Phase 4

Key dependencies

workspace crates

Database Schema

-- Payment rate tables (jurisdiction-specific)
CREATE TABLE rate_tables (
    id             UUID PRIMARY KEY DEFAULT uuidv7(),
    jurisdiction   TEXT NOT NULL,
    payment_type   TEXT NOT NULL,            -- foster_care, adoption_assistance, guardianship_assistance
    age_min        INTEGER NOT NULL,
    age_max        INTEGER NOT NULL,
    daily_rate     NUMERIC(10,2) NOT NULL,
    effective_date DATE NOT NULL,
    end_date       DATE,
    created_at     TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Payment records
CREATE TABLE payments (
    id               UUID PRIMARY KEY DEFAULT uuidv7(),
    case_id          UUID NOT NULL,
    child_id         UUID NOT NULL,
    placement_id     UUID NOT NULL,
    foster_home_id   UUID NOT NULL,
    payment_type     TEXT NOT NULL,           -- foster_care, adoption_assistance, guardianship_assistance
    period_start     DATE NOT NULL,
    period_end       DATE NOT NULL,
    daily_rate       NUMERIC(10,2) NOT NULL,
    day_count        INTEGER NOT NULL,
    gross_amount     NUMERIC(10,2) NOT NULL,
    adjustments      NUMERIC(10,2) NOT NULL DEFAULT 0,
    net_amount       NUMERIC(10,2) NOT NULL,
    ive_eligible     BOOLEAN NOT NULL DEFAULT false,
    ffp_rate         NUMERIC(5,4) NOT NULL DEFAULT 0,  -- e.g. 0.5000 for 50%
    ffp_amount       NUMERIC(10,2) NOT NULL DEFAULT 0,
    status           TEXT NOT NULL DEFAULT 'pending',  -- pending, approved, issued, cleared, voided
    approved_by      TEXT,
    approved_at      TIMESTAMPTZ,
    issued_at        TIMESTAMPTZ,
    created_by       TEXT NOT NULL,
    created_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Payment adjustments
CREATE TABLE payment_adjustments (
    id           UUID PRIMARY KEY DEFAULT uuidv7(),
    payment_id   UUID NOT NULL REFERENCES payments(id),
    reason       TEXT NOT NULL,
    amount       NUMERIC(10,2) NOT NULL,
    requested_by TEXT NOT NULL,
    approved_by  TEXT,
    approved_at  TIMESTAMPTZ,
    status       TEXT NOT NULL DEFAULT 'pending', -- pending, approved, denied
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- IV-E claiming records (for CFS-2 submission)
CREATE TABLE claiming_records (
    id               UUID PRIMARY KEY DEFAULT uuidv7(),
    claiming_period  TEXT NOT NULL,           -- e.g. "2025-Q1"
    payment_type     TEXT NOT NULL,
    total_expenditure NUMERIC(12,2) NOT NULL,
    ive_eligible_amount NUMERIC(12,2) NOT NULL,
    ffp_claimed      NUMERIC(12,2) NOT NULL,
    non_ive_amount   NUMERIC(12,2) NOT NULL,
    ccwis_operations_cost NUMERIC(12,2) NOT NULL DEFAULT 0,
    status           TEXT NOT NULL DEFAULT 'draft', -- draft, submitted, accepted
    submitted_at     TIMESTAMPTZ,
    created_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX idx_payments_case ON payments(case_id);
CREATE INDEX idx_payments_child ON payments(child_id);
CREATE INDEX idx_payments_foster_home ON payments(foster_home_id);
CREATE INDEX idx_payments_status ON payments(status);
CREATE INDEX idx_payments_period ON payments(period_start, period_end);
CREATE INDEX idx_claiming_period ON claiming_records(claiming_period);

REST API (a curated subset; the full route list is Financial & Claims API Reference)

Method Path Description Role

GET

/v1/financial/payments

List payments (filterable by case, home, status, period)

eligibility_worker+

GET

/v1/financial/payments/{id}

Get payment detail with rate breakdown

eligibility_worker+

POST

/v1/financial/payments/calculate

Calculate payment for placement period

eligibility_worker+

PUT

/v1/financial/payments/{id}/approve

Approve payment for issuance

supervisor+

PUT

/v1/financial/payments/{id}/issue

Record disbursement (approved → issued)

supervisor+

PUT

/v1/financial/payments/{id}/clear

Record reconciliation clearance (issued → cleared)

supervisor+

PUT

/v1/financial/payments/{id}/void

Deliberate manual void of an UNDISBURSED payment (pending/approved → voided; mandatory row-only reason; issued/cleared → typed 400 disbursed-payment-void — disbursed money is corrected by adjustment, never clawed back, #1028)

supervisor+

POST

/v1/financial/payments/{id}/adjustments

Request payment adjustment

eligibility_worker+

PUT

/v1/financial/adjustments/{id}/approve

Approve/deny adjustment

supervisor+

POST

/v1/financial/subsidy-payments/generate

ENQUEUE one month’s subsidy payment generation as a background job (#1068 / ADR-053; since #1937 the body is { client_request_id (REQUIRED), month? } — a forged field is 422 validation-failed; month resolves at enqueue to [current − 12, current] on the Eastern business clock, else typed 400; answers 202 + Location: /v1/financial/jobs/{id} + the JobView; the same id replays the same job, a fresh id while that month is queued/running is 409 job-already-active; every month shares the subsidy-gen lease key — one running month per instance, the rest queued; a scheduled tick holding the engine lease is waiting_for_lease, no longer a 409; the GenerationReport is the job’s result once succeeded — errors > 0 is still partial success; ONE subsidy_generation_runs row per attempt with job_id / attempt set)

approve on subsidy agreements (nil-id, realm-flat) — Georgia admin + supervisor; other jurisdictions typed 400 unsupported-jurisdiction

POST

/v1/financial/subsidy-imports/{id}/finalize

ENQUEUE the conversion-import finalize — the single money-consent act (#1071 / ADR-057 D12) — as a CONSENT background job (#1938; the body is the REQUIRED { client_request_id } — a forged field is 422 validation-failed; the import knob, authz, the Georgia gate and the state-floor ImportHistory proof stay synchronous BEFORE the claim, the manifest gate / batch-state refusal run INSIDE the claim transaction and abort it — 409 with the four numbers / 404, nothing enqueued; answers 202 + Location: /v1/financial/jobs/{id} + the JobView with resource = the batch; the same id replays the same job, a fresh id while that batch is queued/running is 409 job-already-active; lease_key = import:<batch_id> — different batches finalize in parallel; a peer-held engine lease is waiting_for_lease, no longer a 409; the LAST pass’s FinalizeReport is the job’s result once succeeded — finalized, or staging on live rejections; a crash / lost_proof / interrupted attempt ends the job failed with the batch left finalizing — a fresh-id re-POST resumes per record exactly once; three passes that moved nothing are failed(no_progress) with remaining_staged / passes in error.detail)

update (operation finalize) on subsidy_import — the explicit-admin ruleset — AND the state_office office floor of ADR-074’s ImportHistory (a session below it is 400 naming the floor; Georgia only)

POST

/v1/financial/backpay/batches/{id}/finalize

ENQUEUE the below-floor backpay finalize — the per-batch money-consent act (#1115, G-B ruling 2026-10-08) — as a CONSENT background job (#2225; the body is { client_request_id (REQUIRED), content_checksum }, deny_unknown_fields — a forged field is 422 validation-failed, a checksum that is not 64 characters is 422 validation-failed, and a 64-character checksum that is not lowercase hex is 400; the backpay knob (403 feature-disabled), authz, the subsidy-writes gate and the BackpayFinalize office proof stay synchronous BEFORE the claim; INSIDE the claim transaction the consent gate — 409 backpay-finalizer-staged (the finalizer staged a staged or materialized record of the batch), 409 manifest-mismatch (the leg named), 409 batch-state on an aborted batch, 404 — aborts the claim, nothing enqueued; answers 202 + Location: /v1/financial/jobs/{id} + the JobView with resource = the batch; the same id replays the same job, a fresh id while that batch is queued/running is 409 job-already-active; lease_key = backpay:<batch_id>; the LAST pass’s BackpayFinalizeReport is the job’s result once succeeded — finalized, or staging when a record diverged or a manifest key is not materialized; a crash / lost_proof / interrupted attempt ends the job failed with the batch left finalizing — a fresh-id re-POST resumes per record exactly once; three passes that moved nothing are failed(no_progress))

subsidy_backpay_batch with operation = finalize (admin-only as shipped, no unit) AND the jurisdiction’s ADR-074 BackpayFinalize floor (Georgia: state office)

POST

/v1/financial/subsidy-reviews/sweep/preview

ENQUEUE a review-sweep preview as a background job (#1096 / ADR-054 U4; since #1939 the body { client_request_id } is deny_unknown_fields — a forged field is 422 validation-failed; answers 202 + Location: /v1/financial/jobs/{id} + the JobView; the attempt collects the actionable sets as of the jurisdiction’s business today and pins them into a previewed run row in the SAME transaction that completes the job — result = PreviewSweepResult with token_state: available, NO token; resource = the run (/v1/financial/subsidy-reviews/sweep/runs/{id}); the same id replays the same job, a fresh id while a preview is queued/running in the jurisdiction is 409 job-already-active)

update on subsidy agreements with operation = review_sweep (nil-id) — Georgia supervisor+; other jurisdictions typed 400 unsupported-jurisdiction

POST

/v1/financial/subsidy-reviews/sweep/runs/{run_id}/token

Issue a previewed run’s single-use execute token — exactly once (#1939, plan background-jobs D6 / R4; no body): ONE guarded UPDATE (previewed, token_issued_at IS NULL, inside 15 min of the run’s started_at) mints + hashes the token AT issuance and answers 200 SweepTokenResponse { run_id, execute_token, expires_at } under Cache-Control: no-store — only the SHA-256 digest and token_issued_at persist; a second POST is 409 sweep-token-issued, an aged preview 409 sweep-preview-expired (the run stamped expired in place), any other state — or a run no preview job wrote — 409 sweep-run-state, an unknown run 404

the review_sweep row AND read on the preview background_job — the previewer or an admin; Georgia only

POST

/v1/financial/subsidy-reviews/sweep/{run_id}/execute

ENQUEUE the sweep execute as a CONSENT background job (#1939; body { client_request_id (REQUIRED), execute_token, acknowledged_suspend, acknowledged_terminate, acknowledged_handoff }, deny_unknown_fields; the token’s wire shape (400), authz, the Georgia gate and the regional SweepExecute office proof stay synchronous BEFORE the claim; an aged preview is stamped expired in its own pre-claim statement — 409 sweep-preview-expired; INSIDE the claim transaction the consent act — the token digest (400), the acknowledged counts against the pinned sets (409 sweep-preview-stale), the previewed → consented flip (a replay or a concurrent execute is 409 sweep-run-state naming the state) — a refusal aborts the claim and the run stays previewed; answers 202 + Location: /v1/financial/jobs/{id} + the JobView with resource = the run; the attempt takes the subsidy-sweep lease (a scheduled pass holding it is waiting_for_lease), re-checks the proof, moves consented → executing and commits the counters after every agreement; result = the SweepReport; a crash / lost_proof / interrupted attempt ends the job failed with the run failed and its counters preserved — a fresh preview is the remedy)

the review_sweep row + the regional SweepExecute office proof (ADR-074 family); Georgia only

GET

/v1/financial/jobs/{id}

Poll a background job (#1937 / #1938 / #1939 / #2225, plan background-jobs D5): state / attempt ledger / progress / result (the kind’s — GenerationReport, FinalizeReport, PreviewSweepResult, SweepReport, BackpayFinalizeReport) / closed error token / resource (the import batch for import_finalize; the backpay batch for backpay_finalize; the sweep run for sweep_preview / sweep_execute); Cache-Control: no-store; never writes

read on background_job — admin, or the creator (human or service principal); an unknown id is 404 BEFORE the check

GET

/v1/financial/rates

Get current rate table

eligibility_worker+

POST

/v1/financial/rates

Create/update rate table

admin

GET

/v1/financial/claims

List claiming records

eligibility_worker+

POST

/v1/financial/claims/generate

Generate claiming report for period

supervisor+

GET

/v1/financial/claims/{id}

Get claiming detail with cost allocation

eligibility_worker+

PUT

/v1/financial/claims/{id}/submit

Submit claiming report

admin

GET

/v1/financial/portal/units/{unit}/payments

#1852 (ADR-076 D5): the unit’s payments as the caregiver may see them — PageResponse<PortalPayment> rows of EXACTLY { payment_id, child_id, payment_type, period_start, period_end, day_count, net_amount, status, issued_at } (no ive_eligible / FFP figures / uas_code / case_id / agreement or term ids / *_by / *_sub / void_reason), newest period first; per-diem rows follow the UNIT (by home, or by placement for a home-less kinship unit), subsidy rows the BOUND PERSON(S) via subsidy_agreement_parties (a home unit: the persons' whole subsidy set; a kinship unit: only agreements anchored on it). The unit is resolved against placement’s GET /v1/placement/internal/caregiver-bindings?sub= on EVERY request (financial’s own principal, 4 s budget, no cache): zero current bindings → 403, a unit outside them → 404, placement not answering → typed 503 portal-bindings-unavailable, a placement 403 (the missing {j}-authz-foster_home_caregiver 1.1.0 row) → named 500 with the remedy; a refused request stages no audit row

portal channel + foster_parent subject

RabbitMQ Events

Publishes:

Routing Key Payload

financial.payment_created

{ payment_id, case_id?, child_id, amount, ive_eligible } (case_id OMITTED — not null — when the payment has no case: post-case subsidy rows, #1068; craig-security’s resource extraction is presence-based, #1090)

financial.payment_approved

{ payment_id, case_id, child_id, amount, ive_eligible, user_id } — staged in the approval transaction (#978); user_id is the acting worker’s sub

financial.payment_issued

{ payment_id, case_id, child_id, amount, ive_eligible, user_id } — staged in the issue (disbursement) transaction (#978)

financial.payment_cleared

{ payment_id, case_id, child_id, amount, ive_eligible, user_id } — staged in the clearance transaction (#978)

financial.payments_voided

{ payment_ids, count, cause, placement_id?, agreement_id?, month? } — one bulk event per set-based void (#953), reshaped by #1068: cause is placement_ended or, since #2020, placement_retracted (scope: placement_id), or subsidy_reconciliation (scope: agreement_id + month — an ISO DATE, the month’s first day; the run-level subsidy_generation_completed.month is the YYYY-MM token — two deliberate encodings: row-level events carry the DB key, run-level the operator token); emitted only when the void changed rows. #1029: craig-security parses it explicitly as one update on payment per void pass (the event’s own grain; resource id per the #1090 payment family — placement_id for the placement causes, none for the reconcile cause; previously the unknown-key fallback recorded a raw payments_voided/financial split), and craig-reporting deliberately routes it (and every non-payment-lifecycle financial type) past the payment-shape validator

financial.payment_period_shortened

{ payment_id, placement_id, child_id, case_id, period_start, period_end, previous_period_end, day_count, previous_day_count, returned_to_pending, cause } — one per per-diem that a placement’s end cut back to the last paid day (#3189), staged in the transaction that shortened it; cause is placement_ended, and returned_to_pending says the row was approved and went back to pending. Ids, dates and day counts, no money. Its audit header states the system’s update of that payment (the worker who ended the placement is named on placement.ended); craig-reporting routes it past the payment-shape validator

financial.payment_voided

{ payment_id, case_id?, child_id, created_by } — ONE attributed event per deliberate manual void (#1028; the system bulk voids keep payments_voided above). Ids + actor only: no money (the #1078 convention) and deliberately NO reason text — the operator’s mandatory free-text reason is protected-note class and lives on the payment row (void_reason), never the wire (#1095 doctrine). created_by is the acting worker’s sub. Its audit header states update on payment, the payment and that worker; craig-reporting routes it past the payment-shape validator (ids-only)

financial.payment_generation_skipped

{ placement_id, case_id, child_id, reason } — a placement.activated no-payment fail-safe fired (#1058; the #979 conditions): reason is missing_dob | unknown_person | missing_foster_home | dob_after_start | no_applicable_rate (#1359 extended the #1058 set: the DOB-after-start record defect and the no-rate-band CONFIG gap were the last two silent-zero-payment paths). A placement.activated in a non-caregiving setting (plan afcars-placement-facts D3, #2057) is not a fail-safe and stages nothing. Staged on the attempt tx (exactly once per consumed activation envelope). craig-reporting ingests it into data_quality_issues (issue_type no_payment_activation, severity warning, anchored on the placement; no_applicable_rate maps to field rate_configuration so the queue separates record fixes from rate-table provisioning — unknown future tokens still land fail-open with the token as the field); craig-security parses create on quality_issue (the payment family resolves the denormalized case_id — no payment exists)

financial.claim_submitted

{ claiming_record_id, period, ffp_claimed, user_id } — user_id the submitting worker (#2277)

financial.claim_accepted

{ claiming_record_id, period, created_by } — federal acceptance recorded on a IV-E claiming record (#1079): ids/period/actor only, no money (the claim’s figures were announced at submit; acceptance records the federal decision). created_by is the acting worker’s sub (#1095), whom the audit header states as the actor. Both claim types name claiming_record_id as their audit record (#1079)

financial.claim_generated

{ claiming_record_id, period, payment_type, user_id } — a fresh claiming record built, in the claimed build transaction; a replay stages none, and no money rides it (#3001); user_id the generating worker

financial.adjustment_created

{ adjustment_id, payment_id, created_by } — a payment correction was requested (#1078; pre-#1078 adjustments staged NO events, so corrections were invisible to the audit tier). Staged in the same ADR-062 claim transaction as the insert — a replay stages nothing. The free-text reason (PII risk) and amount (money) deliberately never ride the bus. craig-security parses create on payment_adjustment, resolving adjustment_id BEFORE the denormalized payment_id (the adjustment id family)

financial.adjustment_deleted

{ adjustment_id, payment_id, user_id } — a pending adjustment withdrawn (hard-deleted), staged in the delete’s transaction (#2496); user_id the withdrawing worker

financial.adjustment_resolved

{ adjustment_id, payment_id, resolution, created_by } — one per terminal transition (#1078): resolution is approved | denied, created_by the RESOLVING worker’s sub. Both terminal paths stage it on the ADR-062 §G3 status-pinned row (approve additionally under the F-015 payment lock), so a concurrent double-resolve stages exactly one. Parsed as update on payment_adjustment

financial.rate_created, financial.rate_updated, financial.rate_deleted

{ id, user_id, fields? } — one per rate-table write, in its transaction (#3001); fields the updated field NAMES, never a rate or a date; a create replay, a stale If-Match or a repeat delete stages none

financial.subsidy_generation_completed

{ run_id, month, initiator, generated, already_existed, derivation_mismatch, skipped_exclusivity, skipped_multi_program, skipped_superseded, skipped_not_active, skipped_before_payments_begin, skipped_before_cutover, errors, voided_stale, queue_drained, queue_retired_below_floor, user_id } — one per generation run (#1068/ADR-053); counters and the actor only, no PII; initiator is scheduled | manual; user_id the initiating worker’s sub, system on the scheduled tick (#2248). #1069 M1 adds skipped_superseded (birth-month claims demoted by an incumbent); #1070 F2 adds skipped_before_payments_begin (months before a guardianship agreement’s stored money boundary); #1071 D5 adds skipped_before_cutover (months before an imported agreement’s payment_cutover_month — SHINES owns them); #1105 adds queue_drained (the #1081 reconcile-queue pairs repaired this run — the report carried it from ADR-054 U1 but the event omitted it); #2228 adds queue_retired_below_floor (pairs settled unrepaired because their month fell below the reconcile floor). All additive, so older consumers are unaffected; the payload is test-pinned as a superset of the serialized GenerationReport (it additionally carries initiator and user_id), so future report counters must land on the event in the same change

financial.subsidy_agreement_created

{ agreement_id, program, effective_from, initial_status, created_by, approval_level, client_request_id, authority_revision? } — authority_revision (#1788, ADR-074 decision 8) is the administrative-authority family revision that answered the consenting proof’s floor, present iff the proof was resolved (omitted, never null, otherwise); native enrollment (#1069 M2, generalized by #1070/ADR-056): #1070 adds the ADDITIVE initial_status key (active for the one-shot ERR arm, pending for the two-step guardianship arms — additive for every decoder) and makes effective_from arm-specific (ERR: the coverage start; guardianship: the signing date). its audit header states a create on subsidy_agreement with agreement_id as the record (never client_request_id: the audit row names the enrollment, never the idempotency key); no money and no evidence keys in the payload. No deployment ordering: the event carries its own audit columns (#2314)

financial.subsidy_agreement_transitioned

{ agreement_id, interval_id, from_status, to_status, business_date, created_by, reason_code? } — one per status transition (#1095/ADR-054 U2): the NEW head interval’s identity + the from/to status tokens + the business date; ids/tokens/dates only, the interval’s protected note never rides. reason_code is present-only (#1090). TWO emitters share the type: the human mutation surface (created_by = the acting worker’s sub) and the #1096 sweep’s enforcement legs, which ADD run_id (run correlation) and — leg-1 suspensions — trigger_review_id (deliberately NOT review_id: attribution stays in the agreement id family, the trigger is correlation-only; created_by = system for scheduled legs or the executor’s sub). craig-security parses update on subsidy_agreement, resolving agreement_id

financial.subsidy_terms_amended

{ term_id, agreement_id, previous_term_id, effective_from, created_by } — one per appended terms revision (#1095): term_id IS the new revision and craig-security’s subsidy id family resolves it BEFORE agreement_id, so the audit row names the revision, not its parent; previous_term_id carries the closed predecessor for lineage. No money fields ride the bus. Parsed as update on subsidy_agreement

financial.subsidy_anchor_replaced

#2020: { agreement_id, from_placement_id, to_placement_id, agreement_status, created_by: "system", previous_started_on?, placement_started_on? } — one per agreement the re-anchor moves off a retracted placement onto its replacement (R-B21), staged in the consuming placement.activated / placement.recorded attempt transaction; the two dates are present only when a pending SG / NRSG agreement’s placement_started_on snapshot was re-snapshotted (omitted, never null); coverage never moves. craig-security parses update on subsidy_agreement, resolving agreement_id

financial.subsidy_review_scheduled

{ review_id, agreement_id, review_type, cycle, due_on, created_by } — one per NEW open review slot (#1095): chain identity (type + cycle) + the statutory due date. Parsed as create on subsidy_review, resolving review_id

financial.subsidy_review_completed

{ review_id, agreement_id, review_type, outcome, completed_on, created_by, resulting_term_id?, resulting_interval_id? } — one per completed review (#1095); the resulting_* linkage ids are present-only (a continued paper review links nothing). Parsed as update on subsidy_review

financial.subsidy_review_rescheduled

{ review_id, successor_review_id, agreement_id, review_type, cycle, new_due_on, reason, created_by } — one per supersession (#1095): review_id is the SUPERSEDED slot (the audited resource, resolved first), successor_review_id its same-cycle replacement carrying new_due_on; reason is the audited supersession reason (operational text, never case narrative). Parsed as update on subsidy_review

financial.subsidy_review_sweep_completed

{ run_id, as_of, state, initiated, mode_materialize, mode_auto_suspend, mode_auto_terminate, mode_per_diem_handoff, leg1_actionable, leg2_actionable, leg3_actionable, materialized, suspended, terminated, handoff_terminated, leg3_moved_children, skipped_drift, errors, user_id } — one per finished sweep run (#1096/ADR-054 U4); counters and the actor only, no PII, no agreement identities (craig-security resolves NO resource id — the generation-completed shape). #1069 M3 adds mode_per_diem_handoff, leg3_actionable, handoff_terminated, leg3_moved_children (serde-defaulted for pre-leg consumers). Leg-3 ENFORCEMENT terminations ride the financial.subsidy_agreement_transitioned row above with run_id for run correlation — attribution stays on the agreement. user_id the executing worker’s sub on a manual execute, system on a scheduled pass (#2248)

financial.subsidy_agreement_imported

{ agreement_id, child_id, program, head_status, reviews_materialized, import_batch_id, cutover_month, created_by, approval_level, authority_revision? } — authority_revision (#1787, ADR-074 decision 8) is the administrative-authority family revision that answered the finalizing proof’s floor, present iff the proof was resolved (omitted, never null, otherwise); — ONE per record MATERIALIZED at batch finalize (#1071/ADR-057 D11); created_by is the FINALIZING operator; NO external_reference (unclassified source id — DB-only), no notes, no money. its audit header states an import on subsidy_agreement, the agreement as the record

financial.subsidy_import_batch_finalized

{ batch_id, expected_count, materialized, superseded, user_id } — one summary per FINALIZED batch (#1071 D11), counts plus user_id, the finalizing operator (#2248), staged in the same transaction that flips the batch finalized; its audit header states system on subsidy_import with NO record (the generation-completed shape)

financial.subsidy_backpay_batch_finalized

{ batch_id, expected_count, materialized, superseded, user_id } — one summary per FINALIZED backpay batch (#2224, plan backpay-import-path U2), counts plus user_id, the finalizing operator (#2248), staged in the transaction that flips the batch finalized (every manifest key materialized); its audit header states system on subsidy_backpay_batch with NO record. Nothing emits it until U-AUTHZ (#2225) wires the backpay_finalize job

financial.subsidy_import_batch_aborted, financial.subsidy_backpay_batch_aborted

{ batch_id, user_id } — a staging batch aborted, staged in the abort’s transaction by the call that flipped it; a replay of an aborted batch or a refused abort stages none (#3001); user_id the aborting worker

financial.portal_read

#1852 (ADR-076 D5): craig_financial_contracts::portal::FinancialPortalReadPayload — { sub, role, jurisdiction, surface ∈ payments, unit_id? } (the surface enum is financial’s own, closed — never placement’s); ONE per ADMITTED portal request (a refused 403 / 404 / 503 emits nothing), staged in its own transaction after the data read; sub = the caregiver — the attribution key, there is no created_by; ids and tokens only, no money. Security records it as portal_read on foster_portal with unit_id (an exact family), the placement.portal_read twin, since #2330 — the generic split’s financial / NULL before. Volume: one outbox row (30 d) + one audit_log row (90 d hot) per portal request

Consumes:

Routing Key Action

placement.activated

Generate the first-period payment (#979): prorated from the placement’s started_at, age-band rate from the child’s authoritative craig-cases DOB as of that date; missing foster home / missing DOB = logged no-op. Planned placements do not bill (placement.created is no longer consumed). #3189: an activation consumed after the placement’s end bills the days in care, from the start through the last paid day the termination tombstone’s ended_at gives, and nothing for a retraction, an end with no ended_at or an end that leaves no paid day (Data Model: Financial & Claims). #2020: when the payload carries replaces_placement_id, the re-anchor then runs LAST, on every billing outcome (home-less, replay, tombstone, age skip, rate gap): every subsidy agreement on the retracted placement moves to the activated one (a pending SG / NRSG with a snapshot also re-snapshots placement_started_on), one financial.subsidy_anchor_replaced each; an active or suspended agreement’s coverage is not moved (WARN)

placement.ended

Settle the placement’s undisbursed per-diems to the days in care (#3189; decoded via the shared PlacementEndedPayload since #1070 F9): a row wholly in care is kept, a row that runs past the last paid day is shortened to it (financial.payment_period_shortened), and a row with no day in care is voided; an end with no ended_at voids them all (Data Model: Financial & Claims). #2021 (ADR-079 D4): only the reason-blind and non-guardianship WARN arms (#1070, WARN-only — automation is #1113) stay here — a stranded active ERR, and a pending SG/NRSG whose basis is gone (withdraw/decline), over the agreements anchored on the ended placement; an absent or unknown end_reason degrades to these reason-blind arms. A left_care ending raises none (since #2023 no arrangement ends guardianship; the exit’s arm owns it)

placement.retracted

#2020: void every undisbursed payment of the placement, under the locks and the tombstone placement.ended takes (lifecycle lock, termination tombstone, payments_voided with cause placement_retracted), with no branch on retracted_from and no end-reason arm; then one WARN per pending / active / suspended subsidy agreement still anchored to the retracted placement (record its replacement). Issued payments stay

placement.recorded

#2020: with replaces_placement_id, the re-anchor (as on placement.activated, the started-on date derived from started_at in the jurisdiction’s business clock); otherwise a log line only. It never bills

placement.episode_exited

#2021 (ADR-079 D4): the #1070 guardianship WARN arms, judged over the payload child’s pending / active / suspended ERR, SG and NRSG agreements anchored on any of its arrangement_ids (a historical episode names none, so it reads nothing). A guardianship exit raises A (the handoff steps for an active ERR), D (a pending SG/NRSG ready to activate) and C (the support gap, when no SG/NRSG is pending, active or suspended); any other exit raises B′ / E′ (the stranded active ERR, the pending SG/NRSG whose basis is gone); any non-guardianship current, a null one after a retraction included, raises G per active or suspended SG/NRSG (the episode’s exit is not guardianship, so the agreement’s guardianship basis is gone). Log-only: nothing is written, so the inbox claim alone dedups a redelivery

eligibility.evaluated

Apply the per-child verdict to ive_child_verdicts via revision-CAS (#1313 U5); when applied, reprice pending/approved per-diem rows + stamp payments.ive_revision

case.ive_determination_invalidated

Record the (case, revision) pair in ive_invalidated_revisions and flag standing verdict rows (#1313 U5 — arrival-order-independent)

rules.evaluated (context_type=rate)

Bound and parsed (handle_rules_evaluated): non-rate evaluations are ignored, and the rate-related arm is a log-only stub — "rate updates via events not yet implemented". The age-bracket rate change this row used to describe is unbuilt

case.created

Seed financial’s own case_assignments projection (revision 0, worker + supervisor) that per-diem birth reads FOR SHARE, and heal revision-0 rows (#1084 / #1632). #1901: the seed’s conflict arm fills a still-NULL admin_unit; then, one table at a time parents first (subsidy_agreements → payments → payment_adjustments via the payments JOIN, #1922), the table’s unit-only heal and then its pair heal. #2042: first the pay-exclusion lock of every child with an agreement on the case, child id ascending, then the per-case lock

case.assignment_changed

Advance the projection as the attempt’s first write (after the #2042 child locks and the per-case lock), then reassign the (assigned_worker_sub, supervisor_sub) pair on subsidy_agreements, payments and payment_adjustments — in that order, parents first (#1922) — under the #1214 monotonic-revision guard (#1083 / #1312). #1901: admin_unit rides the upsert as COALESCE(EXCLUDED.admin_unit, admin_unit); each table’s unit-only heal runs right after that table’s reassign

Rules Engine Integration

  • Rate calculation: When a placement is created, the Rules Engine determines the applicable daily rate based on the child’s age, placement type, and jurisdiction rate table.

  • Age bracket transitions: The Rules Engine monitors child birthdays and triggers rate recalculations when a child ages into a new bracket.

  • Cost allocation: Claiming report generation invokes the Rules Engine to classify expenditures per the jurisdiction’s approved APD methodology (§ 1355.57).

Verification

  1. Create rate table → create placement → verify payment auto-calculated

  2. Approve and issue payment → verify event published

  3. Generate claiming report → verify IV-E and non-IV-E amounts computed

  4. Verify FFP rate applied correctly (50% for eligible)

Phase 7 — Reporting and Data Quality Service

Status: Complete

Service: craig-reporting

Property Value

Binary

services/craig-reporting/

Port

8006

Database

craig_reporting

Dependencies

Phase 1 + Phase 2 + Phase 3

Key dependencies

workspace crates

Database Schema

-- Data quality issues detected by automated monitoring
CREATE TABLE data_quality_issues (
    id               UUID PRIMARY KEY DEFAULT uuidv7(),
    source_service   TEXT NOT NULL,          -- craig-cases, craig-placement, etc.
    source_record_id UUID NOT NULL,
    issue_type       TEXT NOT NULL,          -- missing_field, invalid_value, timeliness, consistency
    field_name       TEXT NOT NULL,
    description      TEXT NOT NULL,
    severity         TEXT NOT NULL,          -- critical, warning, info
    resolved         BOOLEAN NOT NULL DEFAULT false,
    resolved_at      TIMESTAMPTZ,
    resolved_by      TEXT,
    detected_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- AFCARS submission records
CREATE TABLE afcars_submissions (
    id               UUID PRIMARY KEY DEFAULT uuidv7(),
    reporting_period TEXT NOT NULL,          -- e.g. "2025-Q1"
    record_count     INTEGER NOT NULL,
    validation_errors INTEGER NOT NULL DEFAULT 0,
    status           TEXT NOT NULL DEFAULT 'draft', -- draft, validated, validated_with_errors, reviewed, approved, ready_for_transmission (#2179), transmitted (delivery only, #1967)
    validated_at     TIMESTAMPTZ,
    reviewed_by      TEXT,
    reviewed_at      TIMESTAMPTZ,
    approved_by      TEXT,
    approved_at      TIMESTAMPTZ,
    transmitted_at   TIMESTAMPTZ,
    acf_acknowledgment TEXT,
    object_key       TEXT,                  -- object store key for generated flat file (via craig-store)
    created_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- NCANDS submission records
CREATE TABLE ncands_submissions (
    id               UUID PRIMARY KEY DEFAULT uuidv7(),
    reporting_year   INTEGER NOT NULL,       -- federal fiscal year (ending Sept 30)
    record_count     INTEGER NOT NULL,
    validation_errors INTEGER NOT NULL DEFAULT 0,
    child_fatalities INTEGER NOT NULL DEFAULT 0,
    status           TEXT NOT NULL DEFAULT 'draft', -- draft, validated, validated_with_errors, reviewed, approved; transmitted has no writer (#2130)
    transmitted_at   TIMESTAMPTZ,            -- no writer since the transmit route retired (#2130)
    acf_acknowledgment TEXT,
    object_key       TEXT,                  -- object store key for generated flat file (via craig-store)
    created_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Data quality metrics (tracked over time for trend analysis)
CREATE TABLE data_quality_metrics (
    id               UUID PRIMARY KEY DEFAULT uuidv7(),
    measured_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    metric_type      TEXT NOT NULL,          -- afcars_readiness, ncands_readiness, field_completeness
    metric_value     NUMERIC(5,2) NOT NULL,  -- percentage
    details          JSONB                   -- breakdown by field/category
);

CREATE INDEX idx_dq_issues_source ON data_quality_issues(source_service, source_record_id);
CREATE INDEX idx_dq_issues_type ON data_quality_issues(issue_type);
CREATE INDEX idx_dq_issues_unresolved ON data_quality_issues(resolved) WHERE resolved = false;
CREATE INDEX idx_afcars_period ON afcars_submissions(reporting_period);
CREATE INDEX idx_ncands_year ON ncands_submissions(reporting_year);
CREATE INDEX idx_dq_metrics_type ON data_quality_metrics(metric_type, measured_at);

REST API (a curated subset; the full route list is Reporting & Data Quality API Reference)

Method Path Description Role

GET

/v1/reporting/quality/dashboard

Data quality dashboard (metrics, trends, critical errors)

supervisor+

GET

/v1/reporting/quality/issues

List data quality issues (filterable)

caseworker+

PUT

/v1/reporting/quality/issues/{id}/resolve

Mark issue as resolved

caseworker+

POST

/v1/reporting/afcars/generate

Generate AFCARS submission for period

admin, or supervisor per the jurisdiction ruleset (authz Create)

GET

/v1/reporting/afcars

List AFCARS submissions

supervisor+

GET

/v1/reporting/afcars/{id}

Get submission detail with validation results

supervisor+

PUT

/v1/reporting/afcars/{id}/approve

Approve for transmission

admin, or supervisor per the jurisdiction ruleset (authz Approve)

POST

/v1/reporting/afcars/{id}/export

Export the flat file, sealed at rest under the reporting column key when the deployment has one (#2177); 409 afcars-artifact-frozen once ready for transmission

admin, or supervisor per the jurisdiction ruleset (authz Update)

GET

/v1/reporting/afcars/{id}/export/download

Download the decrypted file (#2177)

supervisor+

PUT

/v1/reporting/afcars/{id}/ready-for-transmission

Mark ready for transmission: re-verify the current export, then freeze it (#2179; delivery is #1967)

admin, or supervisor per the jurisdiction ruleset (authz Approve)

POST

/v1/reporting/ncands/generate

ENQUEUE one NCANDS Child File generation for a Federal Fiscal Year as a background job (#651; since #1936 the body is { client_request_id (REQUIRED), reporting_year } — a forged field is 422 validation-failed; answers 202 + Location: /v1/reporting/jobs/{id} + the JobView; the same id replays the same job, a fresh id while that year is queued/running is 409 job-already-active; the job’s input carries as_of = the enqueue instant — the FIXED cohort the paged cases walk reads under on every attempt; the finalized submission (the former 200 body, its id == the job id) is the job’s result once succeeded, committed in ONE transaction with the job’s terminal state; a cases page past the 8 s hop budget fails the attempt engine_failed with zero rows written — TERMINAL (an engine failure never re-queues; a crash / interrupted attempt re-queues up to 3); resource is empty — no submission GET exists)

admin, or supervisor per the jurisdiction ruleset (authz Create)

GET

/v1/reporting/jobs/{id}

Poll a background job (#1936, plan background-jobs D5): state / attempt ledger / progress / result / closed error token; Cache-Control: no-store; never writes

read on background_job — admin, or the creator (human or service principal); an unknown id is 404 BEFORE the check

GET

/v1/reporting/ncands

List NCANDS submissions

supervisor+

PUT

/v1/reporting/ncands/{id}/approve

Approve; the last NCANDS state (no route marks a submission transmitted, #2130)

admin, or supervisor per the jurisdiction ruleset (authz Approve)

RabbitMQ Events

Consumes:

Routing Key Action

case.*

Validate case data against federal quality standards

placement.*

Validate placement data for AFCARS completeness

eligibility.*

Validate eligibility determination data

financial.*

Validate financial data for claiming accuracy

Publishes:

Routing Key Payload

reporting.quality_issue_detected

{ issue_id, source_service, source_record_id, severity }

reporting.afcars_ready_for_transmission

{ submission_id, reporting_period, export_generation, export_sha256, user_id }

reporting.afcars_export_generated, reporting.ncands_export_generated

{ submission_id, attempt_id, export_sha256, export_generation, file_name, user_id } — user_id the attempt’s claimant, the generating worker (#2277); the fenced pointer flip on the submissions row, atomic with the promotion CAS (#1252 / ADR-062 §U)

reporting.afcars_export_failed, reporting.ncands_export_failed

{ attempt_id, submission_id, file_name, error } — keyed on the attempt; the reconciler reaps it (#1252)

Rules Engine Integration

  • Continuous data quality monitoring: The Rules Engine evaluates incoming data events against federal and state data quality standards, generating data_quality_issues records for any violations.

  • AFCARS field validation: Before generating a submission, the Rules Engine validates every record against AFCARS data element requirements.

  • Timeliness compliance: Monitors federal reporting deadlines (quarterly AFCARS, annual NCANDS by September 30).

Verification

  1. Create case and placement data → verify data quality monitoring detects missing fields

  2. Generate AFCARS submission → verify record count and validation errors

  3. Approve, export and mark ready for transmission → verify ready_for_transmission and the afcars_ready_for_transmission event (not reachable yet: every generated file stays validated_with_errors until P-D5, and devstack’s AFCARS surface stays unverified until #1987, so the act answers 503 afcars-surface-not-ready)

  4. Check data quality dashboard → verify metrics and trends

Phase 8 — Security and Compliance Service

Status: Complete

Service: craig-security

Property Value

Binary

services/craig-security/

Port

8007

Database

craig_security

Dependencies

Phase 1

Key dependencies

workspace crates

Database Schema

-- Audit log for all data access and modifications across services
CREATE TABLE audit_log (
    id             UUID PRIMARY KEY DEFAULT uuidv7(),
    timestamp      TIMESTAMPTZ NOT NULL DEFAULT now(),
    user_id        TEXT NOT NULL,
    user_role      TEXT NOT NULL,
    service        TEXT NOT NULL,           -- source service name
    action         TEXT NOT NULL,           -- create, read, update, delete
    resource_type  TEXT NOT NULL,           -- case, placement, payment, etc.
    resource_id    UUID,
    details        JSONB,                  -- changed fields, query parameters, etc.
    ip_address     TEXT,
    success        BOOLEAN NOT NULL DEFAULT true
);

-- Biennial security review tracking (45 CFR § 95.621(f))
CREATE TABLE security_reviews (
    id               UUID PRIMARY KEY DEFAULT uuidv7(),
    review_type      TEXT NOT NULL,         -- biennial, incident, ad_hoc
    scheduled_date   DATE NOT NULL,
    completed_date   DATE,
    reviewer         TEXT NOT NULL,
    findings         JSONB,
    remediation_plan JSONB,
    status           TEXT NOT NULL DEFAULT 'scheduled', -- scheduled, in_progress, completed, overdue
    created_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Archive-batch ledger (2 CFR § 200.334; #1129/ADR-058: one row per
-- archived batch, written inside the prune transaction — retention_until
-- is NULL until DFCS names a schedule, and the D14 purge predicate
-- (named+passed date, no legal_hold) guards every destructive statement)
CREATE TABLE archive_records (
    id               UUID PRIMARY KEY DEFAULT uuidv7(),
    source_service   TEXT NOT NULL,
    source_table     TEXT NOT NULL,
    record_count     INTEGER NOT NULL,
    archived_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    retention_until  DATE,
    purge_eligible   BOOLEAN NOT NULL DEFAULT false,
    purged_at        TIMESTAMPTZ,
    purged_by        TEXT,
    archived_by      TEXT NOT NULL,
    legal_hold       BOOLEAN NOT NULL DEFAULT false,
    data_key         TEXT,      -- + manifest_key, data_sha256, store identity,
    first_record_id  UUID,      --   [min,max] id/time range, hot_window_days
    last_record_id   UUID       --   (see data-model-security.adoc for the full shape)
);

-- NIST SP 800-53 control mapping
CREATE TABLE nist_controls (
    id               UUID PRIMARY KEY DEFAULT uuidv7(),
    control_id       TEXT NOT NULL UNIQUE,   -- e.g. "AC-2", "AU-3"
    control_family   TEXT NOT NULL,          -- Access Control, Audit, etc.
    control_name     TEXT NOT NULL,
    implementation_status TEXT NOT NULL DEFAULT 'planned', -- planned, implemented, partial, not_applicable
    implementation_notes TEXT,
    evidence_key     TEXT,                  -- object store key for evidence artifacts (via craig-store)
    last_assessed    DATE,
    assessed_by      TEXT
);

CREATE INDEX idx_audit_log_user ON audit_log(user_id);
CREATE INDEX idx_audit_log_resource ON audit_log(resource_type, resource_id);
CREATE INDEX idx_audit_log_timestamp ON audit_log(timestamp);
CREATE INDEX idx_audit_log_service ON audit_log(service);

REST API (a curated subset; the full route list is Security & Compliance API Reference)

Method Path Description Role

GET

/v1/security/audit

Query audit log (filterable by user, resource, date range)

admin

GET

/v1/security/audit/user/{user_id}

Audit trail for specific user

admin

GET

/v1/security/audit/resource/{type}/{id}

Audit trail for specific resource

supervisor+

GET

/v1/security/reviews

List security reviews

admin

POST

/v1/security/reviews

Schedule security review

admin

PUT

/v1/security/reviews/{id}

Update review status and findings

admin

GET

/v1/security/archive

List archive records

admin

POST

/v1/security/archive/run

ENQUEUE one archive-then-prune run as a background job (#1129 consent: the typed 403 while RETENTION_ARCHIVE__ENABLED=false stays synchronous at enqueue AND the job re-checks the knob at attempt start — failed(refused_at_start); since #1934 the body is the REQUIRED { client_request_id } — a forged field is 422 validation-failed; answers 202 + Location: /v1/security/jobs/{id} + the JobView; the same id replays the same job, a fresh id while a run is queued/running is 409 job-already-active; the job holds the retention-archive lease for its life — a scheduled pass holding it reads waiting_for_lease; the cumulative per-table report + more is the job’s result once succeeded — a D13-isolated table’s per_table[].error sits in the result, not a failure; zero batches archived while more stays true is failed(no_progress))

admin

POST

/v1/security/archive/purge

Destroy expired archives in bounded slices (?limit=, 1..=100; D14 predicate; consent-gated; Standard ceiling since #1934 — R6, request and response unchanged)

admin

GET

/v1/security/jobs/{id}

Poll a background job (#1934, plan background-jobs D5): state / attempt ledger / progress / result / closed error token; Cache-Control: no-store; never writes

read on background_job — admin, or the creator (human or service principal); an unknown id is 404 BEFORE the check

GET

/v1/security/nist

List NIST control mappings

admin

PUT

/v1/security/nist/{control_id}

Update control implementation status

admin

POST

/v1/security/worker-identities/contacts

#1857: batched worker contact cards for the foster-parent portal — { subs ≤ 50 } → { sub → { display_name, contact_phone } }, unknown subs omitted, Cache-Control: no-store; it replaced the #1850 display-names arm, retired by #2525 (404)

service caller craig-placement only (the scoped contact row); a relayed (X-Craig-Actor) call is the 403 before the engine (#2339)

RabbitMQ Events

Consumes:

All services publish events; the security service subscribes to # (all routing keys) to populate the audit log. An event that carries an audit header (#2314) is filed from it: the publisher states the action, the record, the actor and the outcome where it stages the event, and the payload is not read (data model § audit_log). An event with no header still lands a row, attributed to system with no record and its payload unread: deny on authz_decision with success = false for authz.access_denied, system on security for any other security.* type, and the two halves of the event type otherwise. It increments audit_headerless_events_total and logs audit event carries no header. No publisher in the workspace can stage one, so it is an outbox row from a build that stated no header, a replay of one, or a foreign publisher (ADR-003 § Amendment #2314).

Staging an event with its header. Every staged event states its header: a domain_event! wrapper without the clause does not compile, EventEnvelope::new and stage_json_event take the header as their last argument, and staging refuses an envelope that has none (Unpublishable::MissingAuditHeader). In a domain_event! wrapper, the clause follows the routing key:

craig_mq::domain_event! {
    publish_payment_created(payment_id: Uuid, user_id: Uuid),
    "financial.payment_created",
    audit = (Create, Payment, Some(payment_id), Sub(user_id)),
    { "payment_id": payment_id, "user_id": user_id }
}

The four parts are an AuditAction variant, an AuditResource variant, the record’s Option<Uuid> and the actor: Sub(user_id) for a worker, user_id.map_or(AuditActor::System, AuditActor::Sub) for an optional one, AuditActor::named(text) for an actor held as text (a service principal, a system pass). A hand-written site builds AuditMeta::new(action, resource, id, actor) (with .refused() and .with_roles(..) for a denial) and passes it to stage_json_event or EventEnvelope::new. A test that builds an envelope and does not read its audit row passes craig_test_lib::audit::plain(); a test of the headerless path decodes a JSON envelope with no audit key. craig-security’s header census (audit_header_census_tests.rs) reads every crate but craig-mq: it fails on an envelope built round the constructor (a struct literal, a write to .audit) holds each system actor or recordless act to a stated reason in a table that only shrinks (SYSTEM_OR_RECORDLESS, its length capped by SYSTEM_OR_RECORDLESS_CEILING), and holds every case.person_* event to the Person resource.

Publishes:

Routing Key Payload

security.review_due

{ review_id, review_type, scheduled_date, user_id } — audited as create / security_review with the review as the resource (#2211); user_id the acting worker (#2248)

security.archive_completed

the archive manifest facts (archive_id, source_service, source_table, record_count, data_key, manifest_key, data_sha256, store_endpoint, store_bucket, first/last_record_id, first/last_record_at, hot_window_days) + archived_by — REDEFINED by #1129 / ADR-058: one REAL archive-and-prune batch, staged inside the prune transaction

security.archive_purged

{ archive_id, user_id } — one expired archive destroyed (#1129 D15); user_id is the purging operator (#2211; was purged_by)

security.major_change.recorded

{ change_id, change_type, affected_scope, user_id } — a major-change monitoring entry recorded (commit 914e6a76, pre-issue-numbered; the create is claim-fenced since #1261); ids + tokens only; audited as create / major_change with the change as the resource (#2211); user_id the acting worker (#2248)

security.major_change.reported

{ change_id, reported_date, user_id } — the entry marked reported; id + date only; audited as update / major_change with the change as the resource (#2211); user_id the acting worker (#2248)

security.nist_control.created, security.nist_control.updated

{ id, control_id, implementation_status, user_id } — a NIST control mapped or its assessment updated, staged in the write’s transaction (#2496); implementation_status the resulting status, user_id the acting worker (never the body’s assessed_by)

security.nist_control.deleted

{ id, control_id, user_id } — a live control soft-deleted (#2496)

security.admin_unit.created, security.admin_unit.updated, security.admin_unit.deleted

{ id, user_id } — an admin unit registered, rewritten under its version CAS, or deactivated, staged in the write’s transaction (#3001); a replay, a lost CAS or a bound row stages none

security.detection_rule.created, security.detection_rule.updated, security.detection_rule.deleted

{ id, user_id, fields? } — one per detection-rule write, in its transaction (#3001); fields the field NAMES an update set, never a value

security.partner.updated, security.partner.deleted

{ id, user_id, fields? } — a partner’s details or status updated, or the partner soft-deleted (#3001); fields never names version

security.review.updated, security.review.deleted

{ id, user_id, fields? } — a review moved through an allowed transition (fields always names status), or soft-deleted (#3001); a finding never rides the bus

security.major_change.updated, security.major_change.deleted

{ change_id, user_id, fields? } — every major-change update (beside reported on the completing write) and the soft delete (#3001)

security.alert.created

{ alert_id, rule_name, severity } — a breach-detection rule fired (commit 0a1e6748, the detection system); id + rule name + severity token, none of the matched data; audited as create / security_alert with the alert as the resource (#2211)

security.alert.acknowledged

{ alert_id, user_id } — the operator acknowledgement; user_id is the acting worker (was acknowledged_by before #1913); audited as update / security_alert with the alert as the resource

security.dlq.threshold_exceeded

{ event_type, count, threshold, window } — staged exactly at the per-event_type hourly crossing, under an advisory lock (ADR-022 §D3); audited as system / dead_letter, no resource (#2211)

security.partner.created

{ partner_id, kind, created_by } (ADR-018); resource = the partner (#2211)

security.partner.key_issued, security.partner.key_revoked

{ partner_id, key_id, created_by | user_id } — a revocation’s actor rides user_id (#1913; was revoked_by); resource = the key (#2211)

security.worker_admin_unit.assigned, security.worker_admin_unit.revoked

{ binding_id, worker_sub, admin_unit_id, unit_name, jurisdiction, created_by } / { binding_id, worker_sub, unit_name, jurisdiction, user_id } — the worker→admin-unit registry’s audited acts (#1899, ADR-077 D1); resource = binding_id

security.worker_identity.contact_changed

{ worker_sub, contact_phone, user_id } — an admin set or cleared a caseworker’s agency work line (#1857, PUT /v1/security/admin/workers/{sub}/contact); contact_phone is the new E.164 value or null (an agency business line, not client PII); an unchanged value stages nothing; audited as update / worker_identity with worker_sub as the resource; user_id the acting admin

security.partner.signer_key_registered, security.partner.signer_key_approved, security.partner.signer_key_revoked

{ partner_id, signer_key_id, kid, created_by | approved_by | user_id } — a revocation’s actor rides user_id (#1913; was revoked_by); resource = the signer key (#2211)

(security.breach_detected, listed here since the design era, has never had a producer or a parser arm — removed by the #1649 census. The four major_change. / alert. keys are the DOTTED form the emitters have always used; ADR-003’s catalog carried an underscore spelling until #1649.)

Verification

  1. Perform operations in other services → verify audit log entries appear

  2. Schedule security review → verify reminder events

  3. Execute archiving → verify records archived and purge eligibility tracked

  4. Query audit log by user/resource → verify correct filtering

Phase 9 — CLI Client (craig)

Status: Complete

Binary: craig-cli

Property Value

Binary

services/craig-cli/

Dependencies

Phase 1 + any service APIs

Key dependencies

clap 4, reqwest, tabled, serde_json, dirs

Command Structure

The CLI follows the craig <service> <action> [args] pattern, modeled after the openstack CLI:

craig login                          # authenticate and cache token
craig token show                     # display current token info

craig rules list                     # list rule sets
craig rules get <id>                 # get rule set
craig rules import <file>            # import JDM file
craig rules evaluate <name> <json>   # evaluate against rule set

craig person search --name <name>    # search persons
craig referral list                  # list referrals
craig investigation create <json>    # open investigation
craig case list                      # list cases
craig case get <id>                  # get case detail
craig case create <json>             # create case
craig plan create <case-id> <json>   # create case plan

craig home list                      # list foster homes
craig placement list                 # list placements
craig placement match --case-id <case-id> --child-id <child-id>   # find matching homes for a child of a case
craig kinship list --case <id>       # list kinship options

craig exchange list                  # list exchange partners
craig agreement list                 # list data sharing agreements
craig icpc list                      # list ICPC requests

craig financial payments             # list payments
craig adjustment list                # list payment adjustments
craig claim list                     # list claiming records

craig reporting quality              # data quality dashboard
craig reporting afcars list          # list AFCARS submissions
craig reporting ncands list          # list NCANDS submissions

craig completion bash                # generate shell completion

Features

  • Output formats: --format table (default), --format json

  • Profiles: ~/.config/craig/profiles.toml for multi-jurisdiction deployments (different API URLs, Keycloak realms)

  • Shell completion: generated via clap_complete for bash, zsh, fish

  • Token caching: Keycloak tokens cached in ~/.config/craig/token.json, auto-refreshed on expiry

  • Pagination: --page, --per-page, --all flags for list commands

Testing

The CLI has 31 unit tests (config, output, token handling) and 43 integration tests across 13 modules that exercise every command against the devstack APIs. Tests use craig-test-lib (TestHarness, builders, typed clients) and call cmd::*::run() at the library level — no subprocess spawning.

Module Tests

rules.rs — create, list, get, update, delete, evaluate

6

person.rs — create+get, search, update, ICWA flag

4

referral.rs — create+get, list, add allegation

3

investigation.rs — create, update status, safety assessment

3

case.rs — create+get, list, update, household, contact+court order

5

plan.rs — create plan, approve (supervisor), add+update task

3

home.rs — create+get, list, record training

3

placement.rs — create, update, history

3

exchange.rs — create+list partners, send, list transactions

3

agreement.rs — create, update (draft→active)

2

icpc.rs — create, home study, attach+list

3

auth.rs — RBAC: caseworker create/delete rules, supervisor/caseworker approve plan

4

workflow.rs — full lifecycle: persons→referral→allegation→investigation→case→household→plan→approve

1

Total

43

Verification

  1. cargo build -p craig-cli — compiles

  2. cargo test -p craig-cli --lib — 28 unit tests pass

  3. cargo test -p craig-cli --test cli — 43 integration tests pass (requires devstack)

  4. cargo clippy -p craig-cli --tests — -D warnings — clean

  5. craig login → verify token obtained and cached

  6. craig rules list --format json → verify JSON output

  7. Tab completion works for subcommands

Phase 10 — Caseworker Web UI

Status: Complete — BFF with OIDC auth, 25+ pages across 8 modules (intake, cases, placement, exchange, financial, rules, dashboard, login/error), write forms on all modules, WCAG accessibility, Georgia Orchard theming. The dashboard fans out live stats via parallel API calls (cases, open investigations, active placements, pending reviews) plus the ADR-035 composed panels; i18n remains deferred (#1332/#1487).

Application: craig-web

Property Value

Application

services/craig-web/

Framework

Axum + Askama (server-side HTML) + htmx + Alpine.js (BFF pattern)

Dependencies

Phase 1 shared crates + all service REST APIs

Key dependencies

axum 0.8, askama 0.13, tower-sessions 0.14, reqwest 0.12

Architecture

The web UI follows the Backend-for-Frontend (BFF) pattern (similar to OpenStack Horizon). The Axum server handles OIDC authentication, stores JWTs server-side in cookie sessions, proxies API calls to backend services, and renders HTML via Askama templates. Client-side interactivity uses htmx for partial page updates and Alpine.js for in-page state (inline forms, toggles).

craig-web/
  src/
    main.rs              # Axum server entry, router setup, middleware
    config.rs            # CRAIG_WEB__* env var configuration
    state.rs             # AppState: config + shared reqwest::Client
    auth.rs              # Keycloak OIDC code+PKCE flow, session management
    clients/             # Typed service clients (cases, placement, exchange, financial, rules, reporting, security, composition) over one transport
    i18n.rs              # Fluent catalogs (locales/<lang>/*.ftl) and per-request translation
    routes/
      mod.rs             # Shared: error pages, flash messages, breadcrumbs, PageContext
      login.rs           # Login/logout/callback (OIDC)
      dashboard.rs       # Caseworker dashboard: live stat tiles (open cases, active placements, pending reviews)
      intake/            # Referrals, persons, investigations, safety assessments
      cases/             # Cases, household, plans, tasks, contacts, court orders, federal facts
      placement/         # Foster homes, training, placements, matching
      exchange/          # Exchange partners, agreements, ICPC requests, transactions
      financial/         # Payments, rates, claims, adjustments, subsidies
      reporting/         # Data quality dashboard, AFCARS and NCANDS submissions
      security/          # Audit log, NIST controls, archive, alerts, partners, reviews
      studio/            # Layout composition and worker admin-unit management
      rules.rs           # Rule set management (admin)
      jobs.rs            # Background-job polling fragments
      upload.rs          # File uploads
      download.rs        # Streamed file downloads
  templates/
    base.html            # Layout shell: nav sidebar, header, breadcrumbs, flash messages
    login.html           # Login page
    dashboard.html       # Dashboard tiles (role-based layout)
    error.html           # 404/error page
    intake/              # Referral list, detail, investigation detail
    cases/               # Case list, detail, household, plan detail, contact forms
    placement/           # Foster home list/detail, placement list/detail
    exchange/            # Partner list/detail, ICPC detail, agreement detail
    financial/           # Payment list/detail, rate list/new, claim list/detail
    reporting/           # Quality dashboard, AFCARS/NCANDS lists and details
    security/            # Audit log, NIST controls, archive records
    studio/              # Layout composition, worker admin-unit mapping
    rules/               # Rule set list, detail, evaluation
  static/
    themes/              # CSS custom properties, per-deployment overrides

Key Design Decisions

  • BFF pattern — server-side rendering, no client-side routing or WASM

  • Built entirely on the public REST APIs — no privileged backend access

  • Keycloak OIDC with PKCE flow for authentication (public craig-ui client)

  • Server-side JWT storage — browser receives only an opaque session cookie

  • Role-based navigation and content — UI elements hidden based on session user roles

  • Flash messages for post-redirect-get feedback (success/error/info)

  • CSS theming via custom properties (tokens.css) with per-deployment overrides

  • Inline form pattern: Alpine.js x-data toggles for sub-resource creation on detail pages

Remaining Work

Open craig-web work is tracked in GitLab (the craig-web label), not here: the dashboard tiles, the Fluent catalogs and the reporting pages listed here before have shipped.

Verification

  1. cargo build -p craig-web — compiles

  2. Login via Keycloak → verify session created, redirect to dashboard

  3. Navigate all CRUD pages → verify data loads from REST APIs

  4. Create/update records via forms → verify flash messages and redirects

  5. Verify role-based navigation (admin features hidden for caseworker)

  6. 404 page renders for invalid routes

Phase 11 — Constituent and Provider Portals

Status: In progress — the foster parent and kinship caregiver portal is complete (2026-09-15; Constituent & Provider Portals plan, ADR-076); the family (constituent) and CWCA provider portals are planned (Roadmap Phase 11).

Application: craig-portal

Property Value

Application

services/craig-portal/

Framework

Axum + Askama (server-side HTML) — a stateless BFF beside craig-web: no database, no message bus

Dependencies

Phase 10 (craig-web, whose BFF substrate craig-bff the portal shares); the craig-placement and craig-financial portal endpoints

Key dependencies

axum, askama, tower-cookies, craig-bff

Portal Types

Portal Functionality Data Scope

Family Portal

Case plan tasks (responsible=family), caseworker contact, messaging, provider finder, document upload

Single family’s case only

Foster Parent Portal

Placed child info (medical, school, visitation, emergency), payment summary, training alerts

Only children placed in their home

Provider Portal

Contracted cases, service record submission, overdue report alerts, structured data exchange (CCWIS partners)

Only contracted cases

Built: the Foster Parent Portal, serving foster parents and kinship caregivers (Caregiver Portal Guide); its as-built scope is the guide; the table is the planned scope. The Family and Provider rows are not yet built.

Component Architecture

The crate is services/craig-portal/. src/main.rs holds the module list and the router; pages render from templates/ with strings from locales/{en,es}/.

Key Design Decisions

  • Axum + Askama BFF — the Phase 10 pattern (settled by the portals plan; ADR-076 D6)

  • The subject-token channel: the caregiver’s own IdP token rides X-Craig-Subject under the portal’s service bearer; the BFF mints no actor and ends the session on any refresh failure (ADR-076 D2/D6)

  • Portal roles are craig_auth::PORTAL_REALM_ROLES (foster_parent, family, provider), disjoint per account from worker roles (ADR-076 D1); foster_parent is the one served today

  • Data scoping enforced server-side against the caregiver binding ledger (ADR-076 D4/D5) — dedicated, data-minimised portal endpoints, never the staff handlers

  • Prevents duplicate data entry per § 1355.52 — provider service records feed directly into the case record

Verification

  1. Login as family user → verify only assigned case visible

  2. Login as foster parent → verify only placed children visible

  3. Login as provider → verify only contracted cases visible

  4. Submit service record → verify it appears in caseworker’s case view

  5. Accessibility audit (Section 508 / WCAG 2.1 AA)

Phase 12 — Public Intake Service

Status: Complete (Phase 1 + Phase 2 field expansion) — Public-facing child abuse reporting with web form, partner REST API, SDK, and caseworker review workflow. See Public Child Abuse Reporting plan for full design.

Components

Component Details

Service

craig-intake (port 8008; stateless edge — no database, per ADR-017)

Public Web Form

Single-page Alpine.js form (/report) — reporter info, incident details, children/adults arrays, conditional sections

Partner API

/partner/v1/ with API key authentication for third-party system integration

SDK (Rust)

craig-intake-sdk crate (AGPL-3.0) — typed client with builder pattern, retry logic, optional JWS signing

SDK (TypeScript)

@craig/intake-sdk npm package — typed client with builder, JWS signing via jose

SDK (Python)

craig-intake-sdk PyPI package — async client (httpx), JWS signing via joserfc

Browser signing

craig-sign.js ES module — WebCrypto ECDSA P-256 key generation and JWS signing (zero dependencies), in craig-web. The standalone intake pages sign with a passkey instead (ADR-082)

JWS Verification

Detached ES256 signature verification on partner submissions, CRAIG-hosted signer key registry (ADR-010)

Web BFF

/report routes (public, no auth) + /intake routes (authenticated caseworker review) + /report/keys (key registration)

CLI

craig intake command group (8 subcommands)

Database

Table Description

public_reports

Submitted reports with reporter info, concern details, children/adults JSONB, narrative JSONB, review status, optional JWS signature

api_keys

Partner API keys with name, hashed key, active flag

report_attachments

File metadata (name, type, size, object key) linked to reports

signer_keys

ECDSA P-256 public keys for JWS integrity verification (pending/approved/revoked)

Endpoints

20 total endpoints:

  • Public (no auth): POST report, GET status, POST/GET attachments, POST/GET signer keys

  • Partner (API key): POST report (optional JWS verification), GET status

  • Authenticated (JWT): list/detail/claim/convert/screen-out reports, list/create/revoke API keys, list/approve/revoke signer keys, verify report signature

Phase 2: 3rd Party Field Expansion

Phase 2 expands the data model for comprehensive 3rd party reporting, broken into 4 sub-phases:

  • Phase 2a (complete): 7 new reference enums, typed JSONB structs (ChildEntry, AdultEntry, Narrative), 15+ new columns on public_reports, CreateReportInput struct

  • Phase 2b (complete): Typed enum validation for JSONB arrays, conditional logic (military branch, maltreater relationship), file upload endpoint with craig-store, SDK expansion

  • Phase 2c (complete): Single-page Alpine.js form with conditional reporter fields, dynamic children/adults arrays, max-10 enforcement, validation error display

  • Phase 2d (complete): 9 expanded-field integration tests, 7 attachment integration tests, 11 Playwright E2E tests, services.md + CHANGELOG updated

  • Phase 2e (complete): JWS integrity verification — signer key registry (signer_keys table), detached ES256 verification on partner submissions, verification audit endpoint, key management web page, browser signing library. See JWS & Multi-Language SDKs plan and ADR-010.

  • Phase 2f (complete): Multi-language SDKs — TypeScript (@craig/intake-sdk), Python (craig-intake-sdk), Rust SDK signing support, shared canonicalization test vectors

Verification

  1. Submit a public report via form, verify conditional fields and confirmation code

  2. Submit via partner API, verify all Phase 2 fields stored and returned

  3. Upload attachments to a report, verify file stored and listed

  4. Claim and convert a report to referral, verify cross-service call

  5. Screen out a report, verify status transition and reason

  6. Verify SDK builder creates valid requests with Phase 2 fields

Phase 13 — Mobile & Offline-Capable Client

Status: Planning — Architecture decision pending (ADR-009). See Mobile & Offline Client plan.

Overview

A field-ready client application for caseworkers operating in rural areas and other low-connectivity environments. Built with Tauri 2.0 (recommended), sharing Rust code with the CRAIG workspace. Encrypted local storage via SQLCipher, bidirectional sync with the CRAIG backend, and offline authentication.

Components

Component Details

craig-client

Tauri 2.0 application — desktop (Windows, macOS, Linux) + mobile (iOS, Android)

craig-sync

Shared crate — sync engine, conflict resolution, offline queue

Local DB

SQLCipher (AES-256 encrypted SQLite) — stores working set of assigned cases

Frontend

Web tech (Alpine.js or lightweight framework) rendered in Tauri WebView

Offline Data Scope

Data Offline Access Sync Direction

Assigned cases (summary)

Read

Pull only

Persons on assigned cases

Read

Pull only

Contact notes

Read + Write

Bidirectional

Safety assessments

Read + Write

Bidirectional

Case plan tasks

Read + Write

Bidirectional

Court orders

Read only

Pull only

Placement info

Read only

Pull only

Reference data (enums, admin units)

Read only

Pull only (infrequent)

Attachments/documents

Cached on demand

Pull only

Key Design Decisions

  • Sync strategy: Per-entity version column + updated_at cursor. Pull changes since last sync, push local modifications, field-level three-way merge for conflicts.

  • Security: SQLCipher AES-256 encryption at rest. Keycloak OIDC with cached tokens (72-hour offline expiry). Biometric/PIN device lock.

  • Conflict resolution: Auto-merge non-overlapping field changes. Safety-critical fields (safety assessments, immediate danger) always require manual review.

Server-Side Requirements

  • Sync endpoints on craig-cases, craig-placement: GET /v1/{entity}?updated_since={cursor}

  • version column (monotonic counter) on synced tables

  • Batch sync endpoint for efficient pull of multiple entity types

Verification

  1. Create contact note offline, reconnect, verify sync to server

  2. Modify same case from web UI and client simultaneously, verify conflict resolution

  3. Verify SQLCipher encryption — local DB unreadable without key

  4. Verify 72-hour offline token expiry forces re-authentication

  5. Verify biometric unlock on mobile

Phase Dependencies

The following diagram shows the dependency chain between phases:

Phase 1 (Foundation)
  └── Phase 2 (Rules Engine)
        ├── Phase 3 (Cases)
        │     ├── Phase 4 (Placement)
        │     │     └── Phase 6 (Financial)
        │     └── Phase 7 (Reporting)
        └── Phase 5 (Data Exchange)
  └── Phase 8 (Security)
  └── Phase 9 (CLI) ← can start after any service exists
  └── Phase 10 (Web UI) ← can start after any service exists
        └── Phase 11 (Portals)
  └── Phase 12 (Public Intake) ← depends on Phase 1; Phase 2c depends on Phase 10 (Web UI)
  └── Phase 13 (Mobile & Offline Client) ← depends on Phase 3 (Cases), Phase 4 (Placement); shares crates with Phase 1

Testing Infrastructure  ← cross-cutting, can start after Phase 1; grows with each service phase
Performance Testing     ← cross-cutting, can start after Testing Infrastructure; grows with each service phase
Object Storage          ← cross-cutting, no service dependencies; adopted by services incrementally

Phases 5, 8, and 9 can begin as soon as Phase 1+2 are complete. Phases 3 and 4 are the critical path for most downstream functionality. Testing Infrastructure is cross-cutting — it spans all service phases and grows incrementally as new services are added. Performance Testing builds on top of Testing Infrastructure and can begin as soon as any service has integration tests. Object Storage is cross-cutting — the craig-store crate and Garage devstack container can be built independently. Services adopt it incrementally by adding a craig-store dependency and wiring upload/download endpoints.

Edit this page · latest