Cross-phase · Architecture Core

AIB Application Build PRD

Version: 1.0 | Status: Draft | Date: 2026-06-11 Owner: Chief Architect | Reviewers: CTO, CRO, CCO | Parent: Architecture Vision, AI & Model Risk Charter


0. Purpose & Scope

This document scopes the work to turn the AIB reference architecture (66 TOGAF artifacts, 14 screen specs, 8 service APIs, a 387-table D1 schema with seed data) into a real, working application — one that reads live data, writes through governed approval flows, and runs OpenRouter-driven agents under the "agents propose, humans dispose" model (Principle P11).

It is a scope document, not an implementation. It defines architecture, phasing, and verification gates. No code is produced here.

In scope: the runnable web application at ai.wait-what.co/aib, its edge write API, the agent runtime, the audit/immutability layer, and the AuthZ model that maps Cloudflare Access identity to AIB roles.

Out of scope: see §10 (Non-Goals). The reference documentation itself (artifacts, processes, governance charters) is complete and is treated as a fixed input, not a build target.

Current State

AssetState
Next.js static-export site under /aib (basePath, output: "export", trailingSlash)Live behind Cloudflare Access
D1 binding AIB_DB (aib-architecture-db, id 44255067…)Provisioned, seeded
Schema: db/migrations/0001_initial.sql, 0002_add_recon_break.sql, climate migration 0003, reporting migration 0005, schema_d1.sql; 298 tables; seed under db/seed/Loaded
Read-only edge API functions/aib/api/db.jsLive — generic table reader, GET only, no auth, no scoping
Data Browser page + D1 snapshot fallback (data/d1-snapshot.json)Live
Automated testsZero. Called out as the single biggest gap — see §7.

The existing db.js is the seed of the write API layer but is currently an unauthenticated, unscoped, read-only table dump. Everything in §1–§4 below is net-new on top of it.


1. Architecture — Adding WRITE to a Static-Export Site

The page bundle is static (output: "export"). Static HTML/JS cannot hold a write path. The write path lives entirely in Cloudflare Pages Functions under /aib/api/*, which run at the edge with the AIB_DB D1 binding. The browser bundle is a pure client of that API.

Read path

  • GET /aib/api/q/{resource} — typed, per-screen query endpoints. Replaces the generic db.js table dump for application use. Each endpoint returns only the columns the caller's role is entitled to (the screen CRUD matrices define this).
  • The generic GET /aib/api/db stays for the read-only Data Browser dev/inspection page, but is not used by operational screens and must be brought under the same Access-JWT + role gate as everything else (it is currently open — a known defect to close in Phase 1).
  • Read responses are cached only where the screen spec tolerates staleness (reference/list data, e.g. sanctions list versions); operational queues (alert triage, payment queue) are always live.

Write path

  • All mutations go through command endpoints: POST /aib/api/cmd/{command} (and PATCH for state transitions). There are no generic INSERT/UPDATE endpoints — every command is named after a business action from the screen specs (e.g. aml.alert.triage, pay.tx.authorize, str.file).
  • Each command handler:
    1. Verifies the Access JWT and resolves the AIB role(s) (§2).
    2. Authorizes the command against the screen CRUD matrix + segregation-of-duties rules (§2).
    3. Validates the payload against the table CHECK constraints transcribed from the screen specs (§7 unit tests own these).
    4. Executes inside a D1 transaction (db.batch([...])) that performs the business write and the audit_log append atomically (§4). If the audit write cannot be batched, it is the first statement after the business write in the same batch() — never a separate request.
    5. Returns the new state + audit id.

D1 transaction note

D1 exposes atomic multi-statement writes via db.batch([stmt, ...]) (single implicit transaction, all-or-nothing). Interactive BEGIN…COMMIT across awaits is not available at the edge. Therefore: a command's business write + audit append + any state-machine guard must be expressible as one batch(). Commands that genuinely need read-modify-write under contention (e.g. "second authorizer must differ from first") use a conditional UPDATE (UPDATE … WHERE auth_1_by IS NOT NULL AND auth_1_by <> ?) and check meta.changes === 1, rather than read-then-write. This is the dominant concurrency pattern for the dual-auth and 4-eyes gates.


2. AuthN / AuthZ — Cloudflare Access → AIB Roles

Authentication

Cloudflare Access already fronts the site. Every request to a Pages Function carries the signed CF-Access-JWT-Assertion header. The API layer:

  1. Fetches the Access public keys from the team certs endpoint (cached in KV with TTL).
  2. Verifies the JWT signature, aud (the Access application AUD tag), and expiry. Never trust the header without verifying the signature — a Function can be reached directly if the Access policy is misconfigured, so the JWT check is the real gate, not the presence of the header.
  3. Extracts the verified identity (email, identity_nonce, groups/SAML claims if present).

Identity → AIB role mapping

AIB roles come from the governance docs: CCO, CRO, DPO, COO, CFO, CIO, Compliance Officer, Payments Officer, FX/Treasury Officer, Head of Operations, Settlement & Custody Officer, RM, Internal Audit, Senior Management (Role Definitions, Agent Register).

A role-binding table in D1 (app_user_role) maps verified Access identity → one or more AIB roles. This is the single source of truth for AuthZ, kept in D1 (not in Access groups) so role changes are auditable, versioned, and testable without touching the Access dashboard. Access remains the identity provider; D1 holds the role grants.

app_user_role(user_email, role_code, granted_by, granted_at, revoked_at, active)

Role grants are themselves mutations → audit-logged. A user with no active grant gets 403 on every command (default-deny).

Per-table CRUD enforcement

The screen specs already carry CRUD matrices per table per role (e.g. SCR-PAY-001: agent C R U on bank_transaction; Payments Officer R U; Head of Operations R U + cancel). These matrices are transcribed into a machine-readable policy map (one entry per (command, role) → allowed) that the API layer consults. The policy map is generated/checked against the screen-spec tables so the two cannot drift (a CI lint compares them).

Default-deny: a command with no matching (command, role) entry is rejected. Field-level scoping (e.g. STR linkage fields hidden from client-facing roles per SPG Art. 16) is enforced at the query layer, not just the UI — these columns are stripped from the SELECT for unentitled roles.

Segregation of duties (initiator ≠ authorizer)

SoD is enforced at the API layer inside the command, never in the UI alone. The binding cases from the screen specs:

ControlRuleEnforcement
Payment dual auth (BankG Art. 35, SCR-PAY-001)auth_2_by ≠ auth_1_by; initiating RM ≠ either authorizerConditional UPDATE WHERE auth_1_by <> ?; reject if changes ≠ 1
STR file (SPG Art. 17, SCR-AML-003)str.filed_by must be the CCO; drafter ≠ filerRole check (role = CCO) + drafter-id comparison
AML case closure 4-eyes (SCR-AML-002)decision_by ≠ closure_review_byCommand rejects equal ids
Sanctions freeze (SPG Art. 18, SCR-AML-004)freeze authoriser (CCO) ≠ executorTwo distinct commands, two distinct roles, id comparison
Recon write-off (SCR-PAY-004)only Head of Operations; SLA-breach flag agent-set, never human-clearedRole check + immutable flag
SSI activation (SCR-PAY-005)out-of-band validation; agent can never activateCommand unavailable to agent identity

The tip-off hard exclusion (SPG Art. 16) is the sharpest case: str and all STR-linkage fields are excluded from every client-facing role's data scope at the query layer, and str.tipped_off carries a DB-level CHECK(tipped_off = 0) — any write attempt fails at D1 and raises a critical audit event.


3. Agent Runtime

Where agents run

Agents do not run inside the request-path Pages Functions. They run in a separate Cloudflare Worker (aib-agents) driven by:

  • Cron triggers for scheduled work (overnight nostro ingest + auto-match, batch rescreen after a new sanctions list version, daily SLA-clock sweeps, periodic-review queue generation).
  • Cloudflare Queues for event-driven work (a payment created → enqueue AML pre-screen; a new alert → enqueue scoring + draft triage).

This keeps OpenRouter latency (seconds) out of the synchronous request path (§8). The user-facing API stays fast; agents work asynchronously and deposit proposals.

How agents call OpenRouter

  • All inference is OpenRouter only, model minimax/minimax-m3, reasoning disabled for structured output (per project standard — not negotiable, do not propose alternatives).
  • OPENROUTER_API_KEY is a wrangler secret on the aib-agents worker (Keychain → wrangler secret put), never in .env, never in the client bundle.
  • Agents request structured JSON outputs (draft narrative, proposed disposition, classification + rationale). Outputs are validated against a schema before being written as a pending record. A malformed/over-budget response is discarded and retried per the model-risk kill-switch (AI & Model Risk Charter §1, P-A).

"Agent proposes" → pending record + approval inbox

Per P11 and the Agent Register, no agent holds a standing direct-write credential to operational data. The mechanism:

  1. Agent computes a proposal (e.g. aml_alert with proposed decision, or a draft str.suspicion_narrative, or a sanctions_freeze_action instruction).
  2. Agent writes a pending proposal row — either the operational row in a non-committed state (status = 'open'/'draft'/'pending_validation') or, for sensitive commands, a row in a dedicated agent_proposal inbox table (proposal_id, agent_id, command, target_table, payload_json, status, created_at).
  3. The proposal surfaces as an inbox item to the named human owner (Agent Register column) with approve / reject / escalate affordances (AI & Model Risk Charter §3).
  4. Every proposal, decision, and actor is audit-logged.

The agent worker authenticates to the API with a distinct agent identity (service token), which the role resolver maps to the agent's access tier (Read-only / Propose / query-only / Approval-gated). The policy map denies agents any committing command — agents can stage everything but the signature. This is enforced at the data layer, not by prompt instruction (P11 implication).

"Human disposes" → commit

The human owner acts in the relevant SCR-* screen. Approve invokes the committing command (/aib/api/cmd/...) under the human's verified Access identity and role, runs the full AuthZ + SoD + validation chain (§2), executes the D1 batch, and writes audit. Reject/escalate are logged and the pending row is discarded or routed per the Escalation SOP.

Agent personas (from the Register)

Phase 4 wires concrete personas: agent:aib-aml (alert scoring, STR drafting, sanctions rescreen, rule-effectiveness stats), agent:aib-compliance (sanctions screen runs), agent:aib-operations (payment creation + AML pre-screen request, SWIFT message generation post-auth, nostro ingest/auto-match, break classification). Each has a named human owner, an access tier, and an escalation path already defined in the Agent Register — the build wires those rows, it does not invent them.


4. Audit & Immutability

aib-audit owns audit_log (append-only, immutable, 10-year retention; R/A = aib-audit in the Data Ownership Matrix).

Coverage

Every write command appends to audit_log in the same D1 batch() as the business write (§1). No mutation path exists that bypasses audit — this is enforced by routing all writes through the command layer and code-reviewing that each command's handler includes the audit statement. The audit row records entity_type, entity_id, mutation_type (INSERT|UPDATE|DELETE), before_values, after_values, actor_id, timestamp, plus actor_kind (human|agent) and the command name.

Immutability

  • audit_log is write-only at the application layer: no command issues UPDATE or DELETE against it.
  • Application-level enforcement is primary (D1 has no row-level grant model); a CI check asserts no SQL in the codebase mutates audit_log except INSERT.

Each audit_log row stores prev_hash and row_hash = SHA-256(canonical(row) || prev_hash), chaining per entity (or globally). This makes silent tampering detectable: a verifier recomputes the chain and flags any break. Recommended at minimum for str, sanctions_freeze_action, and bank_transaction authorization events. SHA-256 is available in the Workers runtime (crypto.subtle). Scoped as a Phase-3 deliverable, not Phase 1.

Critical-event audit

Specific events raise critical audit entries beyond the normal trail: any attempt to set str.tipped_off ≠ 0 (SPG Art. 16), any sanctions_freeze_action unfreeze, any app_user_role grant/revoke, any SoD-violation rejection. The audit service exposes the verification endpoints already specified (/audit-log/str/{id}/tipped-off-checks, /audit-log/sanctions-freeze/{id}/unfreeze-audit).


5. Data Model — Service → Table Ownership

The 387-table schema already exists and is seeded. Ownership is not re-designed here; it is governed by aib-data-ownership-matrix.md (RACI per table, SLA per owner). The build wires the API command layer to that ownership: a command may only write a table where its owning service is R/A.

Summary of the 8 services to primary-table ownership (full matrix is authoritative):

ServicePrimary owned tables (R/A)Screens served
aib-complianceclient, ubo, document, kyc_review, pep_record, sanctions_screenSCR-KYC, SCR-AML (screening), SCR-CLM
aib-identityclient_contact, account, authorized_signatory, consent_record, dsr_requestSCR-CLM, SCR-PRV
aib-amlaml_alert, aml_investigation_case, str, fiu_feedback, aml_typology_rule, sanctions_list_*SCR-AML
aib-tradingorder_, trade, settlement, positionSCR-TRD
aib-operationsbank_transaction, account_balance, fee_invoice, nostro_account, nostro_reconciliation, recon_break, swift_message_log, standing_settlement_instructionSCR-PAY, SCR-FEE
aib-reportingqir, emir_trade_report, fatca_account_report, crs_account_reportSCR-REP
aib-riskkri_reading, rcsa_risk_event, rcsa_control, credit_assessmentSCR-RSK, SCR-CRD, SCR-TRY
aib-auditaudit_logSCR-AUD (read), all (write-listener)

Cross-service reads (C/I in the matrix) are allowed; cross-service writes are forbidden — enforced by the policy map. The 14 SCR-* specs are the binding source for which tables each screen touches and at what CRUD level per role.


6. Build Phases

Each phase has a single deliverable theme and a verification gate that must pass before the next phase starts (DISCOVER → PLAN → EXECUTE → VERIFY → ITERATE).

Phase 0 — Foundations (enabler)

Deliverable. Access-JWT verification middleware; D1 role resolver + app_user_role table; the command-layer skeleton (/aib/api/cmd/* routing, AuthZ policy map, audit-batch wrapper); first unit-test harness (the project currently has zero tests — this phase establishes the harness). Gate. A trivial guarded command (e.g. a no-op echo behind role check) returns 200 for an entitled role, 403 for an unentitled one, with a verified Access JWT in wrangler dev; one passing unit test exists.

Phase 1 — One Vertical Slice (recommend Payment Dual-Auth, SCR-PAY-001/002)

Why payment dual-auth. It exercises the entire hard core in one screen: live D1 write, the conditional-UPDATE concurrency pattern, the SoD gate (auth_2_by ≠ auth_1_by, initiator ≠ authorizer), the AML-clear precondition, the atomic audit append, and a state machine (pending → awaiting_dual_auth → processing → completed). It is self-contained and its correctness is binary and testable. (Alternative slice: AML alert triage → STR draft, SCR-AML-001/003 — richer agent story but heavier tip-off/exclusion surface. Recommend PAY first, AML second.) Deliverable. SCR-PAY-001 Payment Queue + SCR-PAY-002 Transaction Detail, fully live: read the queue from D1, authorize through the command layer with the dual-auth gate, write bank_transaction + audit_log atomically, render SWIFT-trace read view. Gate. Integration tests (API + D1 via wrangler dev) prove: (a) same-user second auth is rejected, (b) initiator cannot authorize, (c) AML-blocked payment cannot be authorized, (d) every state transition writes exactly one audit row, (e) /qa or /browse confirms the screen works end-to-end behind Access.

Phase 2 — Remaining Read Screens

Deliverable. All 14 SCR-* screens rendering live read views from typed /api/q/* endpoints with role-scoped columns (field-level exclusion enforced for SPG Art. 16). No new write paths beyond Phase 1. Gate. Each screen loads live data for an entitled role; an unentitled role sees 403 or scoped-out columns; tip-off fields provably absent from client-facing role responses (integration test asserts the column is not in the payload).

Phase 3 — Write + Approval Across Screens

Deliverable. Committing commands for the remaining write-bearing screens (KYC approval 4-eyes, sanctions freeze authorise/execute split, STR draft→file, recon break resolution/write-off, SSI activation). The agent_proposal inbox table + approve/reject/escalate UI. Hash-chaining for the regulated subset (§4). Gate. For each SoD control in §2, an integration test proves the gate holds at the API layer (not just UI). Tip-off CHECK(tipped_off = 0) write attempt fails at D1 and raises a critical audit event. Audit chain verifies for the regulated subset.

Phase 4 — Agent Automation

Deliverable. The aib-agents Worker: cron + queue triggers, OpenRouter (minimax/minimax-m3, reasoning off) structured-output calls, pending-proposal writes under the agent service identity, inbox population. Wire the concrete personas (agent:aib-aml, agent:aib-compliance, agent:aib-operations) per the Agent Register. Gate. An agent produces a proposal (e.g. AML alert score + draft triage, or nostro auto-match + break classification) that lands in the human inbox; the human approve action commits via the Phase-3 command path with full audit; the agent provably cannot commit directly (its identity is denied the committing command). Model-risk sign-off recorded per AI & Model Risk Charter §1.


7. Testing Strategy

The application currently has ZERO automated tests. This is the single largest delivery risk. Phase 0 must stand up the harness before any feature work. No phase gate passes on "it should work."

LayerWhat it coversToolingGate
UnitCHECK-constraint + payload validation transcribed from screen specs (e.g. aml_alert.alert_type enum, bank_transaction.aml_status must be cleared before auth, tx_type 17-value enum); policy-map (command, role) decisions; SoD comparison logic; hash-chain computationVitest (Workers-compatible)Every command has validation + AuthZ unit tests; runs in CI
IntegrationAPI + real D1 via wrangler dev (or Vitest + @cloudflare/vitest-pool-workers with a Miniflare D1) — full command path: JWT → role → AuthZ → validate → batch write → audit append. Concurrency: two simultaneous authorizations, one must losewrangler dev + local D1 seeded from db/seed/Each write command has an integration test proving its gate; audit row count asserted per transition
E2EScreen-level flows behind Cloudflare Access/browse skill (gstack) / /qaPhase gate per §6: confirmed working in browser for entitled + unentitled roles
Policy driftScreen-spec CRUD matrices vs the machine-readable policy mapCI lint comparing the twoBuild fails if they diverge

Test data uses the existing db/seed/ fixtures against a local D1; never against the production aib-architecture-db.


8. Risks & Open Questions

#Risk / QuestionNotes / Mitigation
R1Access role granularity. Access gives identity, not fine-grained AIB roles.Resolved by D1 app_user_role mapping (§2) — roles live in D1, auditable. Open: who administers grants, and is there a bootstrap super-role? Recommend a single CTO-held break-glass role, itself audit-logged.
R2D1 write limits & transactions. No interactive BEGIN…COMMIT; only batch(). Read-modify-write under contention needs care.Conditional-UPDATE pattern (§1, §2). Open: D1 per-database write throughput vs the SEPA-Instant 10s / 50k-screen/sec SLAs in the API specs — those throughput numbers are reference targets and are not achievable on D1; treat them as documentation aspirations, not Phase-1 acceptance criteria.
R3OpenRouter latency in the request path. Inference is seconds; request budgets are 50–200ms.Architecturally resolved: agents run async (Workers cron + queue), never in the synchronous API path (§3). No screen blocks on inference.
R4Cost. OpenRouter per-call cost × alert/screen volume.Agents are batch/queue-driven, not per-keystroke. Open: budget cap + per-agent rate limit; kill-switch already mandated by the Model Risk Charter.
R5D1 as a regulated system of record. 10-year retention, immutability, BCBS 239.D1/SQLite is fine for this reference-app scope; hash-chaining (§4) adds tamper-evidence. Open question for any production posture: is D1 the system of record, or a projection of one? Out of scope to decide here.
R6Access JWT verification correctness. A misconfigured Access policy could expose Functions directly.Always verify signature + aud server-side (§2); never trust header presence. Add a test that an unsigned/forged token is rejected.
R7Generic db.js is currently open + read-only.Bring under the Access-JWT + role gate in Phase 1; restrict to the Data Browser dev page; never used by operational screens.
R8Schema drift vs screen specs. Specs cite CHECK constraints; the live schema must match.Phase 0 reconciles spec-quoted constraints against schema_d1.sql; discrepancies are ADRs, not silent edits.
Q1Agent identity mechanism — Access service token vs. a signed internal credential for the aib-agents worker→API call?Recommend Access service token so the same JWT-verify path applies; confirm in Phase 4 design.
Q2Where does the approval inbox live — per-screen panels or a unified inbox?Recommend a unified inbox surface (AI & Model Risk Charter §3) with deep links into the originating screen.

9. Verification Gate Summary

PhaseGate (must pass to proceed)
0Guarded no-op command: 200 entitled / 403 unentitled with verified JWT; harness + 1 passing test
1PAY dual-auth: 4 SoD/precondition integration tests green + audit-per-transition + browser E2E
2All 14 screens read-live, role-scoped; tip-off fields provably absent for client roles
3Every §2 SoD control proven at API layer; tipped_off write fails at DB + critical audit; chain verifies
4Agent proposal → human commit with full audit; agent cannot commit directly; model-risk sign-off recorded

10. Non-Goals / What Stays Mock

  • No new database design. The 387-table schema and ownership matrix are fixed inputs.
  • No external integrations. SWIFT/gpi, FIU-LI SFTI platform, sanctions-list feeds (EU/UN/OFAC/UK/SECO), MT940/MT950 nostro statements, RT1/TIPS — all mocked / seeded. The app generates and ingests representations of these messages into D1; it does not connect to real networks.
  • No real money movement, no real STR filing, no real freeze. Every "filed", "frozen", "settled" state is a record in D1. This is a reference application demonstrating the governed architecture, not a licensed bank system.
  • The reference SLA throughput numbers in the service-API specs (50k screen/sec, sub-ms audit, P95 budgets) are documentation targets, not acceptance criteria for this build (R2).
  • No alternative LLM provider, no alternative hosting. OpenRouter only; Cloudflare Pages/Functions/Workers/D1 only; deploy via wrangler + Keychain, manual, DEPLOY_CONFIRMED gate; no GitHub-Actions deploy.
  • No client-facing portal. All 14 screens are internal oversight screens for AIB roles; the client portal (PROC-011) is out of scope.
  • Authentication provider is not built. Cloudflare Access is the IdP as-is; we map its identity, we do not replace it.

11. Cross-References

References

Referenced by