openapi: 3.1.0

info:
  title: Veyndi AML API
  version: 0.3.0
  description: |
    Veyndi AML — AML/CFT compliance platform for the Nigerian financial sector.

    This document is the source of truth for the HTTP surface. `make gen` generates
    TypeScript API types and sqlc database queries. Go HTTP handlers and the web fetch
    wrapper are handwritten; contract tests check routes, permissions and response schemas.

    **Authorization is declared here.** Every operation carries `x-permission`, and the
    router registers each route with the permission named in this file. A route with no
    declared permission fails a test rather than defaulting to open, which is the mechanism
    behind "authz enforced server-side on every endpoint" in the definition of done.
    See ADR-0012.

    **Phase 1 scope.** Tenancy, IAM, configuration, approvals, content packs and audit,
    plus the AML domain: customers, screening, the monitoring rule library, alerts, cases
    and regulatory reporting.

    **Money is always an integer of minor units** with an explicit currency code. There is
    no decimal, no string amount and no float anywhere in this contract, because a rounding
    error in a threshold comparison is a missed filing.

    **Reports generated against a placeholder schema cannot be submitted.** The goAML
    format has not been validated against an authoritative source (see Q1 in
    `docs/open-questions.md`); every report carries `schema_authoritative`, and submission
    is refused at the handler, the service and a database CHECK while it is false.
  contact:
    name: Veyndi
    email: support@veyndi.com
    url: https://aml.veyndi.com

servers:
  - url: https://aml.veyndi.com/api
    description: Production API
  - url: https://{tenant}.aml.veyndi.com
    description: SaaS, tenant resolved from the subdomain
    variables:
      tenant:
        default: demo
  - url: http://localhost:8080
    description: Local development

security:
  - bearerAuth: []

tags:
  - name: Identity
    description: Who the caller is and what they may do
  - name: IAM
    description: Users, roles and the permission catalogue
  - name: Configuration
    description: The no-code configuration surface required by BRD §7.2
  - name: Approvals
    description: Maker-checker, the four-eyes primitive of BRD §8.5
  - name: Content packs
    description: Versioned regulatory content (BRD §10)
  - name: Audit
    description: The tamper-evident trail of BRD §8.9
  - name: Customers
    description: The party model and customer due diligence of BRD §8.1
  - name: Privacy
    description: |
      Data-subject requests, authority intake, legal holds and neutral evidence manifests.
      NEEDS-COMPLIANCE-VALIDATION (Q5): erasure records do not decide the retention boundary.
      NEEDS-COMPLIANCE-VALIDATION (Q34): authority records do not claim an external submission.
  - name: Screening
    description: Sanctions, PEP and adverse-media screening (BRD §8.4)
  - name: Monitoring
    description: The rule library behind transaction monitoring (BRD §8.3)
  - name: Alerts
    description: The triage queue produced by monitoring
  - name: Cases
    description: Investigation workspaces (BRD §8.5)
  - name: Reporting
    description: Regulatory filings — CTR, STR and board reporting (BRD §8.6)
  - name: Report distribution
    description: |
      Scheduled internal compliance and board aggregate packs (BRD §8.8). These artifacts
      use the disclosure-controlled analytics read model and are not regulatory filings,
      regulator submissions, acknowledgements or proof of delivery to a regulator.
  - name: Metrics
    description: |
      Aggregate compliance and board metrics (BRD §8.8, §13). Counts only: nothing on this
      surface resolves to a person, an account or a case, and every cell passes small-cell
      suppression inside the query (ADR-0027, Q18, Q29).
  - name: Watchlists
    description: |
      The institution's own blacklists and greylists, bulk import and export, and the schedule
      that refreshes externally-sourced lists (BRD §8.7, §8.4.4). No list content ships: Q6 has
      not established whether a commercial feed may be redistributed to an on-premise client.
  - name: Platform
    description: Veyndi operator endpoints
  - name: Health

paths:
  /v1/watchlists/lists/{listKey}/delta:
    get:
      operationId: getPublishedWatchlistDelta
      tags: [Watchlists]
      summary: Read the published version's immutable change counts
      x-permission: watchlists.list.read
      parameters:
        - { in: path, name: listKey, required: true, schema: { type: string } }
      responses:
        '200':
          description: Version identity, predecessor and added, changed and removed counts
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WatchlistVersionDelta' }
        default: { $ref: '#/components/responses/ProblemResponse' }
  /v1/watchlists/versions/{versionID}/delta:
    get:
      operationId: getWatchlistVersionDelta
      tags: [Watchlists]
      summary: Read an immutable historical version's change counts
      x-permission: watchlists.list.read
      parameters:
        - { in: path, name: versionID, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: Immutable publication delta, including superseded versions
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WatchlistVersionDelta' }
        default: { $ref: '#/components/responses/ProblemResponse' }
  /v1/approvals/export:
    get:
      operationId: exportApprovalsRegister
      tags: [Metrics]
      summary: Export the complete filtered metadata register as CSV or Excel
      description: |
        Reuses the current authorized list reader in one repeatable-read transaction.
        Starts at the first matching row, walks every cursor, and refuses cursor input.
        Maximum 10,000 rows/32 MiB; an oversized result fails without a partial file.
        The digest/row count are audited before bytes leave; CSV formulas are escaped
        and Excel cells are text. Only the declared metadata columns are exported;
        private payloads, rationales, assessment text and recipient identifiers are excluded.
        Columns: id, action_key, subject_type, status, payload_digest, proposed_at, sla_due_at, decided_at, escalated_at.
      x-permission: workflow.approval.read
      parameters:
        - name: format
          in: query
          required: true
          schema: { type: string, enum: [csv, xlsx] }
        - { name: status, in: query, schema: { type: string } }
        - { name: action, in: query, schema: { type: string } }
        - name: sort
          in: query
          schema: { type: string, enum: [proposed_at_desc, proposed_at_asc], default: proposed_at_desc }
      responses:
        "200":
          description: Complete matching metadata with audited SHA-256 digest and download disposition
          content:
            text/csv:
              schema: { type: string }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "503": { $ref: "#/components/responses/Unavailable" }
  /v1/kyc-reviews/export:
    get:
      operationId: exportKycReviewsRegister
      tags: [Metrics]
      summary: Export the complete filtered metadata register as CSV or Excel
      description: |
        Reuses the current authorized list reader in one repeatable-read transaction.
        Starts at the first matching row, walks every cursor, and refuses cursor input.
        Maximum 10,000 rows/32 MiB; an oversized result fails without a partial file.
        The digest/row count are audited before bytes leave; CSV formulas are escaped
        and Excel cells are text. Only the declared metadata columns are exported;
        private payloads, rationales, assessment text and recipient identifiers are excluded.
        Columns: id, customer_id, due_on, reason, status, started_at, completed_at, outcome.
      x-permission: onboarding.customer.read
      parameters:
        - name: format
          in: query
          required: true
          schema: { type: string, enum: [csv, xlsx] }
        - { name: status, in: query, schema: { type: string } }
        - { name: customer_id, in: query, schema: { type: string, format: uuid } }
        - name: sort
          in: query
          schema: { type: string, enum: [due_on_asc, due_on_desc], default: due_on_asc }
      responses:
        "200":
          description: Complete matching metadata with audited SHA-256 digest and download disposition
          content:
            text/csv:
              schema: { type: string }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "503": { $ref: "#/components/responses/Unavailable" }
  /v1/report-schedules/export:
    get:
      operationId: exportReportSchedulesRegister
      tags: [Metrics]
      summary: Export the complete filtered metadata register as CSV or Excel
      description: |
        Reuses the current authorized list reader in one repeatable-read transaction.
        Starts at the first matching row, walks every cursor, and refuses cursor input.
        Maximum 10,000 rows/32 MiB; an oversized result fails without a partial file.
        The digest/row count are audited before bytes leave; CSV formulas are escaped
        and Excel cells are text. Only the declared metadata columns are exported;
        private payloads, rationales, assessment text and recipient identifiers are excluded.
        Columns: id, name, report_kind, format, layout_key, state, next_run_at, created_at, updated_at.
      x-permission: distribution.schedule.read
      parameters:
        - name: format
          in: query
          required: true
          schema: { type: string, enum: [csv, xlsx] }
        - { name: include_retired, in: query, schema: { type: boolean, default: false } }
        - name: sort
          in: query
          schema: { type: string, enum: [created_at_desc, created_at_asc], default: created_at_desc }
      responses:
        "200":
          description: Complete matching metadata with audited SHA-256 digest and download disposition
          content:
            text/csv:
              schema: { type: string }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "503": { $ref: "#/components/responses/Unavailable" }
  /v1/transactions/batches/export:
    get:
      operationId: exportIngestBatchesRegister
      tags: [Data operations]
      summary: Export complete filtered operational metadata as CSV or Excel
      description: |
        Uses the current authorized tenant list reader in one repeatable-read transaction.
        Starts at the first matching row and refuses cursor positions. Existing10,000-row
        and32MiB bounds apply; oversized exports fail without a partial artifact. The digest
        and row count are audited before bytes leave. CSV formulas are escaped; Excel cells
        are text. Excludes filenames, raw source rows, error/provider diagnostics, private
        resource/actor identities, rejected document bytes and source row attempts.
        Columns: id, source, status, records_received, records_inserted, records_duplicate, records_quarantined, unresolved_quarantine, started_at, finished_at.
      x-permission: monitoring.data_operations.read
      parameters:
        - { name: format, in: query, required: true, schema: { type: string, enum: [csv, xlsx] } }
        - { name: source, in: query, schema: { type: string, maxLength: 120 } }
        - { name: status, in: query, schema: { type: string, enum: [running, completed, failed, partial] } }
        - { name: sort, in: query, schema: { type: string, enum: [started_at_desc, started_at_asc], default: started_at_desc } }
      responses:
        "200":
          description: Complete filtered metadata with audited SHA-256 digest and download disposition
          content:
            text/csv:
              schema: { type: string }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "503": { $ref: "#/components/responses/Unavailable" }
  /v1/transactions/source-manifests/export:
    get:
      operationId: exportSourceManifestsRegister
      tags: [Data operations]
      summary: Export complete filtered operational metadata as CSV or Excel
      description: |
        Uses the current authorized tenant list reader in one repeatable-read transaction.
        Starts at the first matching row and refuses cursor positions. Existing10,000-row
        and32MiB bounds apply; oversized exports fail without a partial artifact. The digest
        and row count are audited before bytes leave. CSV formulas are escaped; Excel cells
        are text. Excludes filenames, raw source rows, error/provider diagnostics, private
        resource/actor identities, rejected document bytes and source row attempts.
        Columns: id, source, window_from, window_to, expected_at, expected_count, source_sha256, batch_id, recorded_at.
      x-permission: monitoring.data_operations.read
      parameters:
        - { name: format, in: query, required: true, schema: { type: string, enum: [csv, xlsx] } }
        - { name: source, in: query, schema: { type: string, maxLength: 120 } }
        - { name: batch_id, in: query, schema: { type: string, format: uuid } }
        - { name: sort, in: query, schema: { type: string, enum: [recorded_at_desc, recorded_at_asc], default: recorded_at_desc } }
      responses:
        "200":
          description: Complete filtered metadata with audited SHA-256 digest and download disposition
          content:
            text/csv:
              schema: { type: string }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "503": { $ref: "#/components/responses/Unavailable" }
  /v1/admin/upload-quarantine/export:
    get:
      operationId: exportUploadQuarantineRegister
      tags: [Data operations]
      summary: Export complete filtered operational metadata as CSV or Excel
      description: |
        Uses the current authorized tenant list reader in one repeatable-read transaction.
        Starts at the first matching row and refuses cursor positions. Existing10,000-row
        and32MiB bounds apply; oversized exports fail without a partial artifact. The digest
        and row count are audited before bytes leave. CSV formulas are escaped; Excel cells
        are text. Excludes filenames, raw source rows, error/provider diagnostics, private
        resource/actor identities, rejected document bytes and source row attempts.
        Columns: id, kind, sha256, size_bytes, reason_code, status, created_at.
      x-permission: platform.jobs.manage
      parameters:
        - { name: format, in: query, required: true, schema: { type: string, enum: [csv, xlsx] } }
        - { name: kind, in: query, schema: { type: string, enum: [document, case_attachment, validation_evidence] } }
        - { name: status, in: query, schema: { type: string, enum: [pending, retry_requested, dismissed, recovered] } }
        - { name: sort, in: query, schema: { type: string, enum: [created_at_desc, created_at_asc], default: created_at_desc } }
      responses:
        "200":
          description: Complete filtered metadata with audited SHA-256 digest and download disposition
          content:
            text/csv:
              schema: { type: string }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "503": { $ref: "#/components/responses/Unavailable" }
  /v1/filing-obligations/export:
    get:
      operationId: exportFilingObligationsRegister
      tags: [Domain operations]
      summary: Export the complete filtered metadata register as CSV or Excel
      description: |
        Reuses the authorized tenant list reader in one repeatable-read transaction.
        Starts at the first matching row and refuses cursor input. Existing 10,000-row
        and 32 MiB bounds fail without a partial artifact. Digest and row count are audited;
        CSV formulas are escaped and Excel cells are text. Excludes private trigger
        references, customer/case/report links, actor identities, policy source URLs,
        calendars, checklists and document requirements. No workflow state is changed.
        Columns: id, policy_version_id, kind, event_type, due_at, status, recorded_at, met_at, met_late.
      x-permission: reporting.report.read
      parameters:
      - { name: format, in: query, required: true, schema: { type: string, enum: [csv, xlsx] } }
      - { name: status, in: query, schema: { type: string, enum: [pending, breached, met] } }
      - { name: kind, in: query, schema: { type: string, enum: [STR, CTR, SCUML, CBN_RETURN] } }
      - { name: sort, in: query, schema: { type: string, enum: [due_at_asc, due_at_desc], default: due_at_asc } }
      responses:
        '200':
          description: Complete matching metadata with audited SHA-256 digest and download disposition
          content:
            text/csv:
              schema: {type: string}
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: {type: string, format: binary}
        '400': {$ref: '#/components/responses/BadRequest'}
        '403': {$ref: '#/components/responses/Forbidden'}
        '503': {$ref: '#/components/responses/Unavailable'}
  /v1/filing-clocks/export:
    get:
      operationId: exportFilingClocksRegister
      tags: [Domain operations]
      summary: Export the complete filtered metadata register as CSV or Excel
      description: |
        Reuses the authorized tenant list reader in one repeatable-read transaction.
        Starts at the first matching row and refuses cursor input. Existing 10,000-row
        and 32 MiB bounds fail without a partial artifact. Digest and row count are audited;
        CSV formulas are escaped and Excel cells are text. Excludes private trigger
        references, customer/case/report links, actor identities, policy source URLs,
        calendars, checklists and document requirements. No workflow state is changed.
        Columns: id, key, version, kind, event_type, basis, status, effective_from, effective_to, payload_sha256, source_sha256, proposed_at.
      x-permission: reporting.report.read
      parameters:
      - { name: format, in: query, required: true, schema: { type: string, enum: [csv, xlsx] } }
      - { name: key, in: query, schema: { type: string, maxLength: 64 } }
      - { name: status, in: query, schema: { type: string, enum: [pending, approved, rejected] } }
      - { name: kind, in: query, schema: { type: string, enum: [STR, CTR, SCUML, CBN_RETURN] } }
      - { name: sort, in: query, schema: { type: string, enum: [proposed_at_desc, proposed_at_asc], default: proposed_at_desc } }
      responses:
        '200':
          description: Complete matching metadata with audited SHA-256 digest and download disposition
          content:
            text/csv:
              schema: {type: string}
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: {type: string, format: binary}
        '400': {$ref: '#/components/responses/BadRequest'}
        '403': {$ref: '#/components/responses/Forbidden'}
        '503': {$ref: '#/components/responses/Unavailable'}
  /v1/kyc-requirements/export:
    get:
      operationId: exportKYCRequirementsRegister
      tags: [Domain operations]
      summary: Export the complete filtered metadata register as CSV or Excel
      description: |
        Reuses the authorized tenant list reader in one repeatable-read transaction.
        Starts at the first matching row and refuses cursor input. Existing 10,000-row
        and 32 MiB bounds fail without a partial artifact. Digest and row count are audited;
        CSV formulas are escaped and Excel cells are text. Excludes private trigger
        references, customer/case/report links, actor identities, policy source URLs,
        calendars, checklists and document requirements. No workflow state is changed.
        Columns: id, key, version, reason, trust_kind, status, effective_from, effective_to, payload_sha256, proposed_at.
      x-permission: onboarding.customer.read
      parameters:
      - { name: format, in: query, required: true, schema: { type: string, enum: [csv, xlsx] } }
      - { name: key, in: query, schema: { type: string, maxLength: 64 } }
      - { name: status, in: query, schema: { type: string, enum: [pending, approved, rejected] } }
      - { name: reason, in: query, schema: { type: string, enum: [periodic, risk_change, pep_change, screening_hit, manual, edd] } }
      - { name: sort, in: query, schema: { type: string, enum: [proposed_at_desc, proposed_at_asc], default: proposed_at_desc } }
      responses:
        '200':
          description: Complete matching metadata with audited SHA-256 digest and download disposition
          content:
            text/csv:
              schema: {type: string}
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: {type: string, format: binary}
        '400': {$ref: '#/components/responses/BadRequest'}
        '403': {$ref: '#/components/responses/Forbidden'}
        '503': {$ref: '#/components/responses/Unavailable'}
  /v1/privacy/erasures/export:
    get:
      operationId: exportPrivacyErasureRegister
      tags: [Privacy]
      summary: Export the complete filtered privacy request metadata register
      description: |
        Reuses the existing privacy-authorized tenant list reader in one repeatable-read
        snapshot. Starts at the first matching row and refuses cursor input. Existing
        10,000-row/32 MiB limits fail without a partial artifact. Digest and count are audited;
        CSV formulas are escaped and Excel cells are text. Subject IDs, request references,
        reasons, authority names/references/legal basis, approvers and hold/source content
        are omitted before capture. No intake, restriction, approval or destruction changes.
        Columns: id, status, received_at, deadline_at, reviewed_at, executed_at, created_at, updated_at.
      x-permission: privacy.request.read
      parameters:
        - {name: format, in: query, required: true, schema: {type: string, enum: [csv, xlsx]}}
        - {name: status, in: query, schema: {type: string, enum: [pending_review, approved, refused, executed]}}
        - {name: sort, in: query, schema: {type: string, enum: [received_at_desc, received_at_asc], default: received_at_desc}}
      responses:
        '200':
          description: Complete matching metadata with audited digest and download disposition
          content:
            text/csv:
              schema: {type: string}
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: {type: string, format: binary}
        '400': {$ref: '#/components/responses/BadRequest'}
        '403': {$ref: '#/components/responses/Forbidden'}
        '503': {$ref: '#/components/responses/Unavailable'}
  /v1/privacy/authority-requests/export:
    get:
      operationId: exportPrivacyAuthorityRegister
      tags: [Privacy]
      summary: Export the complete filtered privacy request metadata register
      description: |
        Reuses the existing privacy-authorized tenant list reader in one repeatable-read
        snapshot. Starts at the first matching row and refuses cursor input. Existing
        10,000-row/32 MiB limits fail without a partial artifact. Digest and count are audited;
        CSV formulas are escaped and Excel cells are text. Subject IDs, request references,
        reasons, authority names/references/legal basis, approvers and hold/source content
        are omitted before capture. No intake, restriction, approval or destruction changes.
        Columns: id, status, received_at, deadline_at, reviewed_at, released_at, created_at, updated_at.
      x-permission: privacy.request.read
      parameters:
        - {name: format, in: query, required: true, schema: {type: string, enum: [csv, xlsx]}}
        - {name: status, in: query, schema: {type: string, enum: [pending_review, active, refused, release_pending, released]}}
        - {name: sort, in: query, schema: {type: string, enum: [received_at_desc, received_at_asc], default: received_at_desc}}
      responses:
        '200':
          description: Complete matching metadata with audited digest and download disposition
          content:
            text/csv:
              schema: {type: string}
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: {type: string, format: binary}
        '400': {$ref: '#/components/responses/BadRequest'}
        '403': {$ref: '#/components/responses/Forbidden'}
        '503': {$ref: '#/components/responses/Unavailable'}
  /v1/reference-datasets/export:
    get:
      operationId: exportReferenceDatasetsRegister
      tags: [Domain operations]
      summary: Export the complete filtered metadata queue as CSV or Excel
      description: |
        All filtered immutable reference versions; sources, rate/geography entries and actor identities excluded.
        Uses the authorized list reader in one repeatable-read transaction, starting at
        the first matching row. Cursor input is refused. Existing 10,000-row/32 MiB bounds
        fail without partial output. Digest and row count are audited; CSV formulas are
        escaped and Excel cells are text. No authority, release or review is conferred by export.
        Columns: id, kind, key, version, status, as_of, valid_until, source_sha256, payload_sha256, proposed_at.
      x-permission: rules.rule.read
      parameters:
      - {name: format, in: query, required: true, schema: {type: string, enum: [csv, xlsx]}}
      - {name: kind, in: query, schema: {type: string, enum: [geography, fx]}}
      - {name: key, in: query, schema: {type: string, maxLength: 64}}
      - {name: status, in: query, schema: {type: string, enum: [pending, approved, rejected]}}
      - {name: sort, in: query, schema: {type: string, enum: [proposed_at_desc, proposed_at_asc], default: proposed_at_desc}}
      responses:
        '200':
          description: Complete matching scoped metadata with audited digest and download disposition
          content:
            text/csv:
              schema: {type: string}
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: {type: string, format: binary}
        '400': {$ref: '#/components/responses/BadRequest'}
        '403': {$ref: '#/components/responses/Forbidden'}
        '409': {$ref: '#/components/responses/Conflict'}
        '503': {$ref: '#/components/responses/Unavailable'}
  /v1/decision-holds/export:
    get:
      operationId: exportActiveDecisionHoldsRegister
      tags: [Domain operations]
      summary: Export the complete filtered metadata queue as CSV or Excel
      description: |
        Active pending/release-proposed holds only; closed released/denied history is outside this queue. Private decision/account/source/rule/screening detail is excluded.
        Uses the authorized list reader in one repeatable-read transaction, starting at
        the first matching row. Cursor input is refused. Existing 10,000-row/32 MiB bounds
        fail without partial output. Digest and row count are audited; CSV formulas are
        escaped and Excel cells are text. No authority, release or review is conferred by export.
        Columns: id, state, product, degraded, created_at, expires_at, input_sha256, policy_sha256, rules_sha256, screening_sha256.
      x-permission: monitoring.alert.read
      parameters:
      - {name: format, in: query, required: true, schema: {type: string, enum: [csv, xlsx]}}
      - {name: state, in: query, schema: {type: string, enum: [pending, release_proposed]}}
      - {name: sort, in: query, schema: {type: string, enum: [created_at_desc, created_at_asc], default: created_at_desc}}
      responses:
        '200':
          description: Complete matching scoped metadata with audited digest and download disposition
          content:
            text/csv:
              schema: {type: string}
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: {type: string, format: binary}
        '400': {$ref: '#/components/responses/BadRequest'}
        '403': {$ref: '#/components/responses/Forbidden'}
        '409': {$ref: '#/components/responses/Conflict'}
        '503': {$ref: '#/components/responses/Unavailable'}
  /v1/rules/near-miss-samples/export:
    get:
      operationId: exportPendingNearMissSamplesRegister
      tags: [Domain operations]
      summary: Export the complete filtered metadata queue as CSV or Excel
      description: |
        Pending near-miss samples from labelled validation cohorts only; completed review history is outside this queue. These exploratory cohort results do not measure institution-wide missed activity. Current dataset privacy is rechecked for each request; labelled source IDs/digests remain, while sampled transaction/customer identities, booking data, segments, channels, raw labels and actors are excluded.
        Uses the authorized list reader in one repeatable-read transaction, starting at
        the first matching row. Cursor input is refused. Existing 10,000-row/32 MiB bounds
        fail without partial output. Digest and row count are audited; CSV formulas are
        escaped and Excel cells are text. No authority, release or review is conferred by export.
        Columns: id, sweep_id, state, created_at, source_kind, version_id, dataset_id, dataset_sha256, artifact_sha256, parameter_sha256.
      x-permission: rules.rule.simulate
      parameters:
      - {name: format, in: query, required: true, schema: {type: string, enum: [csv, xlsx]}}
      - {name: sweep_id, in: query, schema: {type: string, format: uuid}}
      - {name: sort, in: query, schema: {type: string, enum: [created_at_desc, created_at_asc], default: created_at_desc}}
      responses:
        '200':
          description: Complete matching scoped metadata with audited digest and download disposition
          content:
            text/csv:
              schema: {type: string}
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: {type: string, format: binary}
        '400': {$ref: '#/components/responses/BadRequest'}
        '403': {$ref: '#/components/responses/Forbidden'}
        '409': {$ref: '#/components/responses/Conflict'}
        '503': {$ref: '#/components/responses/Unavailable'}
  /v1/alerts/export:
    get:
      operationId: exportAlertsRegister
      tags: [Metrics]
      summary: Export the complete filtered register as CSV or Excel
      description: |
        Reuses the permission-filtered register in one repeatable-read transaction and walks
        every cursor. Up to 10,000 rows and 32 MiB are supported. Larger exports fail with no
        partial file; narrow the filters. The export digest and row count are audited before
        bytes leave the server. CSV formula prefixes are escaped and Excel cells are text.
        Starts from the first matching row; cursors are refused. Sensitive free-text fields
        are excluded unless already disclosed by the underlying customer register.
      x-permission: monitoring.alert.read
      parameters:
        - name: format
          in: query
          required: true
          schema: { type: string, enum: [csv, xlsx] }
        - name: status
          in: query
          schema:
            type: string
            enum:
            - open
            - assigned
            - in_review
            - escalated
            - closed_false_positive
            - closed_actioned
            - merged
        - name: priority
          in: query
          schema:
            type: string
            enum:
            - p1
            - p2
            - p3
            - p4
        - name: typology
          in: query
          schema:
            type: string
        - name: party_id
          in: query
          description: 'Narrows the queue to the alerts raised against one party, matched on the

            alert''s own subject rather than looked up per row. This is what a customer

            profile asks for; without it the only way to show one customer''s alert history

            is to read the whole triage queue and filter client-side, which silently goes

            wrong at the first page boundary. A value that is not a UUID is a 400, not an

            ignored filter.

            '
          schema:
            type: string
            format: uuid
        - {name: assignee, in: query, description: 'me or a tenant user UUID.', schema: {type: string}}
        - {name: rule_key, in: query, schema: {type: string}}
        - {name: severity, in: query, schema: {type: string, enum: [low, medium, high, critical]}}
        - {name: opened_after, in: query, description: Inclusive opening instant., schema: {type: string, format: date-time}}
        - {name: opened_before, in: query, description: Exclusive opening instant., schema: {type: string, format: date-time}}
        - {name: overdue, in: query, schema: {type: boolean}}
        - {name: ageing_bucket, in: query, schema: {type: string, enum: [0_7, 8_30, 31_90, 90_plus]}}
        - name: sort
          in: query
          description: Server ordering. Changing filters or sort starts a new cursor walk.
          schema:
            type: string
            enum:
            - priority
            - opened_at_desc
            - opened_at_asc
            default: priority
      responses:
        "200":
          description: Complete filtered register with Content-Disposition and SHA-256 digest
          content:
            text/csv:
              schema: { type: string }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/customers/export:
    get:
      operationId: exportCustomersRegister
      tags: [Metrics]
      summary: Export the complete filtered register as CSV or Excel
      description: |
        Reuses the permission-filtered register in one repeatable-read transaction and walks
        every cursor. Up to 10,000 rows and 32 MiB are supported. Larger exports fail with no
        partial file; narrow the filters. The export digest and row count are audited before
        bytes leave the server. CSV formula prefixes are escaped and Excel cells are text.
        Starts from the first matching row; cursors are refused. Sensitive free-text fields
        are excluded unless already disclosed by the underlying customer register.
      x-permission: onboarding.customer.read
      parameters:
        - name: format
          in: query
          required: true
          schema: { type: string, enum: [csv, xlsx] }
        - name: status
          in: query
          schema: { type: string, enum: [draft, pending_documents, pending_edd, pending_approval, active, rejected, exited] }
        - name: risk
          in: query
          schema: { type: string, enum: [low, medium, high, prohibited] }
        - name: q
          in: query
          schema: { type: string }
          description: |
            Matches the party's display name and the customer's own external_ref. Does not
            search BVN, NIN or any other encrypted identifier — see the operation description.
        - name: sort
          in: query
          schema: { type: string, enum: [id, risk_asc, risk_desc, next_review_asc, next_review_desc], default: id }
          description: Whole-book server order. Unknown risk and missing review dates remain last in both directions; UUID ascending breaks ties.
      responses:
        "200":
          description: Complete filtered register with Content-Disposition and SHA-256 digest
          content:
            text/csv:
              schema: { type: string }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/cases/export:
    get:
      operationId: exportCasesRegister
      tags: [Metrics]
      summary: Export the complete filtered register as CSV or Excel
      description: |
        Reuses the permission-filtered register in one repeatable-read transaction and walks
        every cursor. Up to 10,000 rows and 32 MiB are supported. Larger exports fail with no
        partial file; narrow the filters. The export digest and row count are audited before
        bytes leave the server. CSV formula prefixes are escaped and Excel cells are text.
        Starts from the first matching row; cursors are refused. Sensitive free-text fields
        are excluded unless already disclosed by the underlying customer register.
      x-permission: cases.case.read
      parameters:
        - name: format
          in: query
          required: true
          schema: { type: string, enum: [csv, xlsx] }
        - name: assignee
          in: query
          schema: { type: string }
          description: Current user (me) or a tenant user UUID.
        - name: overdue
          in: query
          schema: { type: boolean }
          description: Only active cases whose SLA has elapsed.
        - name: status
          in: query
          description: |
            An EXACT match on `case_record.status`, not a category. This list said
            `[open, in_progress, pending_approval, closed]` until a test walked the request
            bodies and query parameters as well as the schemas: `in_progress` and `closed` are
            not values the column has ever held, so a UI dropdown built from this contract had
            two options that returned an empty page forever and read as "no cases".
          schema:
            type: string
            enum: [open, investigating, pending_approval, closed_no_action, closed_reported, reopened]
        - name: party_id
          in: query
          description: |
            Narrows the case list to the cases raised against one party, matched on the
            case's own subject rather than looked up per row. This is what a customer
            profile asks for; without it the only way to show one customer's case history
            is to read the whole case list and filter client-side, which silently goes
            wrong at the first page boundary. A value that is not a UUID is a 400, not an
            ignored filter.
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Complete filtered register with Content-Disposition and SHA-256 digest
          content:
            text/csv:
              schema: { type: string }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/reports/export:
    get:
      operationId: exportReportsRegister
      tags: [Metrics]
      summary: Export the complete filtered register as CSV or Excel
      description: |
        Reuses the permission-filtered register in one repeatable-read transaction and walks
        every cursor. Up to 10,000 rows and 32 MiB are supported. Larger exports fail with no
        partial file; narrow the filters. The export digest and row count are audited before
        bytes leave the server. CSV formula prefixes are escaped and Excel cells are text.
        Starts from the first matching row; cursors are refused. Sensitive free-text fields
        are excluded unless already disclosed by the underlying customer register.
      x-permission: reporting.report.read
      parameters:
        - name: format
          in: query
          required: true
          schema: { type: string, enum: [csv, xlsx] }
        - name: kind
          in: query
          schema:
            type: string
            enum:
            - STR
            - CTR
            - SCUML
            - CBN_RETURN
            - BOARD
        - name: status
          in: query
          schema:
            type: string
            enum:
            - draft
            - validation_failed
            - in_review
            - approved
            - submitted
            - acknowledged
            - rejected
        - name: case_id
          in: query
          description: 'Return only reports linked to this case. The filter is applied before the

            `(generated_at,id)` keyset boundary, so the filtered register remains resumable.

            '
          schema:
            type: string
            format: uuid
        - name: sort
          in: query
          description: Server ordering. Changing filters or sort starts a new cursor walk.
          schema:
            type: string
            enum:
            - generated_at_desc
            - generated_at_asc
            default: generated_at_desc
      responses:
        "200":
          description: Complete filtered register with Content-Disposition and SHA-256 digest
          content:
            text/csv:
              schema: { type: string }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/screening/hits/export:
    get:
      operationId: exportScreeningHitsRegister
      tags: [Metrics]
      summary: Export the complete filtered register as CSV or Excel
      description: |
        Reuses the permission-filtered register in one repeatable-read transaction and walks
        every cursor. Up to 10,000 rows and 32 MiB are supported. Larger exports fail with no
        partial file; narrow the filters. The export digest and row count are audited before
        bytes leave the server. CSV formula prefixes are escaped and Excel cells are text.
        Starts from the first matching row; cursors are refused. Sensitive free-text fields
        are excluded unless already disclosed by the underlying customer register.
      x-permission: screening.hit.read
      parameters:
        - name: format
          in: query
          required: true
          schema: { type: string, enum: [csv, xlsx] }
        - name: assignee
          in: query
          description: Filter to the current user; accepts me or their own actor UUID
          schema: {type: string}
        - name: decision
          in: query
          schema: { type: string, enum: [pending, true_positive, false_positive, suppressed] }
        - name: party_id
          in: query
          description: |
            Narrows the queue to the hits raised against one party, matched on the party of the
            screening request rather than on the hit. This is what a customer screen asks for;
            without it the only way to show one customer's matches is to read the whole tenant's
            queue and filter client-side, which silently goes wrong at the first page boundary.
            A value that is not a UUID is a 400, not an ignored filter.
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Complete filtered register with Content-Disposition and SHA-256 digest
          content:
            text/csv:
              schema: { type: string }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/metrics/history/volume:
    get:
      operationId: getMetricHistoryVolume
      tags: [Metrics]
      summary: Observed volume with optional prior-period comparison
      description: |
        Uses immutable observations as of the requested end, never today's overwritten state.
        Periods before observation coverage are unavailable. Counts below five and complementary
        cells are withheld. Productivity exposes only pseudonymous staff references and requires
        its dedicated supervisor permission. Every successful read is audited.
      x-permission: analytics.metric.read
      parameters:
        - { $ref: "#/components/parameters/MetricFrom" }
        - { $ref: "#/components/parameters/MetricTo" }
        - name: compare
          in: query
          schema: { type: string, enum: [prior] }
        - name: stream
          in: query
          schema: { type: string, enum: [alert.outcome, case.lifecycle, filing.volume, screening.outcome], default: alert.outcome }
        - name: org_unit_id
          in: query
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Historical aggregate with explicit coverage and suppression
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MetricHistory" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/metrics/history/funnel:
    get:
      operationId: getMetricHistoryFunnel
      tags: [Metrics]
      summary: Observed funnel with optional prior-period comparison
      description: |
        Uses immutable observations as of the requested end, never today's overwritten state.
        Periods before observation coverage are unavailable. Counts below five and complementary
        cells are withheld. Productivity exposes only pseudonymous staff references and requires
        its dedicated supervisor permission. Every successful read is audited.
      x-permission: analytics.metric.read
      parameters:
        - { $ref: "#/components/parameters/MetricFrom" }
        - { $ref: "#/components/parameters/MetricTo" }
        - name: compare
          in: query
          schema: { type: string, enum: [prior] }
        - name: stream
          in: query
          schema: { type: string, enum: [alert.outcome, case.lifecycle, filing.volume, screening.outcome], default: alert.outcome }
        - name: org_unit_id
          in: query
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Historical aggregate with explicit coverage and suppression
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MetricHistory" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/metrics/history/productivity:
    get:
      operationId: getMetricHistoryProductivity
      tags: [Metrics]
      summary: Observed productivity with optional prior-period comparison
      description: |
        Uses immutable observations as of the requested end, never today's overwritten state.
        Periods before observation coverage are unavailable. Counts below five and complementary
        cells are withheld. Productivity exposes only pseudonymous staff references and requires
        its dedicated supervisor permission. Every successful read is audited.
      x-permission: analytics.productivity.read
      parameters:
        - { $ref: "#/components/parameters/MetricFrom" }
        - { $ref: "#/components/parameters/MetricTo" }
        - name: compare
          in: query
          schema: { type: string, enum: [prior] }
        - name: stream
          in: query
          schema: { type: string, enum: [alert.outcome, case.lifecycle, filing.volume, screening.outcome], default: alert.outcome }
        - name: org_unit_id
          in: query
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Historical aggregate with explicit coverage and suppression
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MetricHistory" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/alerts/{resourceID}/ai-explanation:
    post:
      operationId: explainAlertWithAI
      description: Requires monitoring.alert.read in addition to the declared cases.case.write permission. Generation persists a governed invocation; read-only reviewers can inspect retained provenance.
      summary: Generate an evidence-bound alert_explanation for human review
      tags: [Assistance]
      x-permission: cases.case.write
      parameters:
        - { name: resourceID, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                query: { type: string, minLength: 3, maxLength: 500 }
      responses:
        '201':
          description: Draft only; acceptance is a separate human action
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AIAssistance' }
        '409': { description: Assistance disabled or governance or evidence unavailable }
        '503': { description: Provider failed or output did not pass evidence validation }
  /v1/cases/{resourceID}/ai-provenance:
    get:
      operationId: listCaseAIAcceptanceProvenance
      summary: Read accepted AI evidence and model provenance, including while inference is disabled
      tags: [Assistance]
      x-permission: cases.case_content.read
      parameters:
        - { name: resourceID, in: path, required: true, schema: { type: string, format: uuid } }
        - { $ref: '#/components/parameters/Limit' }
        - { $ref: '#/components/parameters/Cursor' }
      responses:
        '200':
          description: Human acceptance and exact evidence/model references
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AIAcceptanceProvenancePage' }
  /v1/reports/{resourceID}/ai-provenance:
    get:
      operationId: listReportAIAcceptanceProvenance
      summary: Read accepted AI evidence and model provenance, including while inference is disabled
      tags: [Assistance]
      x-permission: reporting.report_content.read
      parameters:
        - { name: resourceID, in: path, required: true, schema: { type: string, format: uuid } }
        - { $ref: '#/components/parameters/Limit' }
        - { $ref: '#/components/parameters/Cursor' }
      responses:
        '200':
          description: Human acceptance and exact evidence/model references
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AIAcceptanceProvenancePage' }
  /v1/cases/{resourceID}/ai-handover:
    post:
      operationId: draftCaseHandoverWithAI
      description: Requires cases.case_content.read in addition to the declared cases.case.write permission. Generation persists a governed invocation; read-only reviewers can inspect retained provenance.
      summary: Generate an evidence-bound case_handover for human review
      tags: [Assistance]
      x-permission: cases.case.write
      parameters:
        - { name: resourceID, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                query: { type: string, minLength: 3, maxLength: 500 }
      responses:
        '201':
          description: Draft only; acceptance is a separate human action
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AIAssistance' }
        '409': { description: Assistance disabled or governance or evidence unavailable }
        '503': { description: Provider failed or output did not pass evidence validation }
  /v1/reports/{resourceID}/ai-narrative:
    post:
      operationId: draftReportNarrativeWithAI
      summary: Generate an evidence-bound str_narrative for human review
      tags: [Assistance]
      x-permission: reporting.report.generate
      parameters:
        - { name: resourceID, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                query: { type: string, minLength: 3, maxLength: 500 }
      responses:
        '201':
          description: Draft only; acceptance is a separate human action
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AIAssistance' }
        '409': { description: Assistance disabled or governance or evidence unavailable }
        '503': { description: Provider failed or output did not pass evidence validation }
  /v1/alerts/ai-filters:
    post:
      operationId: proposeAlertFiltersWithAI
      description: Requires cases.case.write in addition to monitoring.alert.read; prepares a governed model invocation without executing the proposed filters.
      summary: Generate an evidence-bound search_filters for human review
      tags: [Assistance]
      x-permission: cases.case.write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                query: { type: string, minLength: 3, maxLength: 500 }
      responses:
        '201':
          description: Draft only; acceptance is a separate human action
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AIAssistance' }
        '409': { description: Assistance disabled or governance or evidence unavailable }
        '503': { description: Provider failed or output did not pass evidence validation }
  /v1/cases/{resourceID}/ai-handover/{invocationID}/accept:
    post:
      operationId: acceptAICaseHandover
      summary: Accept the exact saved AI draft and record human authorship
      tags: [Assistance]
      x-permission: cases.case.write
      parameters:
        - { name: resourceID, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: invocationID, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                expected_revision: { type: integer, minimum: 0 }
      responses:
        '201':
          description: Saved note or immutable report successor, pending independent report approval
          content:
            application/json:
              schema:
                type: object
                required: [result_resource_id]
                properties:
                  result_resource_id: { type: string, format: uuid }
        '409': { description: Already accepted or evidence or approval changed }
  /v1/reports/{resourceID}/ai-narrative/{invocationID}/accept:
    post:
      operationId: acceptAIReportNarrative
      summary: Accept the exact saved AI draft and record human authorship
      tags: [Assistance]
      x-permission: reporting.report.generate
      parameters:
        - { name: resourceID, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: invocationID, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                expected_revision: { type: integer, minimum: 0 }
      responses:
        '201':
          description: Saved note or immutable report successor, pending independent report approval
          content:
            application/json:
              schema:
                type: object
                required: [result_resource_id]
                properties:
                  result_resource_id: { type: string, format: uuid }
        '409': { description: Already accepted or evidence or approval changed }
  /v1/reports/{reportID}/narrative:
    get:
      parameters:
      - name: reportID
        in: path
        required: true
        schema: {type: string, format: uuid}
      operationId: getReportNarrative
      summary: Read the current sectioned narrative and revision history identity
      tags: [Reporting]
      x-permission: reporting.report_content.read
      responses:
        '200':
          description: Narrative workspace
          content:
            application/json:
              schema: {$ref: '#/components/schemas/NarrativeWorkspace'}
        '403': {description: Report content permission required}
        '404': {description: Report not found}
    patch:
      parameters:
      - name: reportID
        in: path
        required: true
        schema: {type: string, format: uuid}
      operationId: updateReportNarrative
      summary: Create an immutable successor with revised narrative sections
      tags: [Reporting]
      x-permission: reporting.report.generate
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/NarrativeUpdateInput'}
      responses:
        '200':
          description: New report revision
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Report'}
        '400': {description: Invalid narrative sections or citations}
        '403': {description: Report generation permission required}
        '404': {description: Report not found}
        '409': {description: Report state or expected revision changed}
  /v1/reports/{reportID}/request-changes:
    post:
      operationId: requestReportChanges
      summary: Return a draft to its author with a recorded reason
      tags: [Reporting]
      x-permission: reporting.report.file
      parameters:
      - name: reportID
        in: path
        required: true
        schema: {type: string, format: uuid}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [reason]
              properties:
                reason: {type: string, minLength: 1, maxLength: 2000}
      responses:
        '200':
          description: Returned report
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Report'}
        '400': {description: A reason is required}
        '403': {description: Independent filing reviewer permission required}
        '404': {description: Report not found}
        '409': {description: Report cannot be returned in its current state}
  /v1/onboarding/applications:
    get:
      operationId: listOnboardingApplications
      summary: Review the permission-filtered onboarding queue
      tags: [Onboarding]
      x-permission: onboarding.application.review
      security:
      - bearerAuth: []
      parameters:
      - name: status
        in: query
        schema: {type: string, enum: [submitted, under_review, approved, rejected]}
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: Application summaries without submitted answers
          content:
            application/json:
              schema:
                type: object
                required: [items, has_more]
                properties:
                  items:
                    type: array
                    items: {$ref: '#/components/schemas/ApplicationSummary'}
                  has_more: {type: boolean}
                  next_cursor: {type: string}
        '400': {description: Invalid queue filter}
        '403': {description: Application review permission required}
  /v1/webhooks:
    get:
      operationId: listWebhooks
      summary: List signed domain-event subscriptions
      tags: [Integrations]
      x-permission: integrations.webhook.manage
      parameters:
        - { $ref: '#/components/parameters/Limit' }
        - { $ref: '#/components/parameters/Cursor' }
      responses:
        '200':
          description: A cursor-paged subscription register; signing secrets are never listed.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WebhookPage' }
    post:
      operationId: createWebhook
      summary: Register a public HTTPS event receiver
      description: The returned random signing secret is shown only once. Delivery authenticates timestamp plus body with HMAC-SHA256 and is at least once; deduplicate X-Baobyte-Event-ID. Redirects and private network addresses are refused. Subscription changes and replays are audited.
      tags: [Integrations]
      x-permission: integrations.webhook.manage
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [endpoint, event_types]
              properties:
                endpoint: { type: string, format: uri, maxLength: 2048 }
                delivery_format: { type: string, enum: [event, slack, teams], default: event }
                recipient_id: { type: string, format: uuid, description: Required for Slack or Teams deliveries. }
                approved_for_notifications: { type: boolean, default: false, description: Must be true for chat destinations. }
                event_types:
                  type: array
                  minItems: 1
                  maxItems: 13
                  items: { type: string }
      responses:
        '201':
          description: Subscription and one-time secret
          content:
            application/json:
              schema: { $ref: '#/components/schemas/RegisteredWebhook' }
        '400': { $ref: '#/components/responses/BadRequest' }
  /v1/webhooks/{subscriptionID}:
    patch:
      operationId: updateWebhook
      summary: Enable or disable a webhook subscription
      tags: [Integrations]
      x-permission: integrations.webhook.manage
      parameters:
        - { name: subscriptionID, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [enabled]
              properties:
                enabled: { type: boolean }
      responses:
        '204': { description: Subscription updated }
        '400': { $ref: '#/components/responses/BadRequest' }
        '404': { $ref: '#/components/responses/NotFound' }
  /v1/webhooks/{subscriptionID}/deliveries:
    get:
      operationId: listWebhookDeliveries
      summary: Inspect webhook attempts and dead letters
      tags: [Integrations]
      x-permission: integrations.webhook.manage
      parameters:
        - $ref: "#/components/parameters/Limit"
        - $ref: "#/components/parameters/Cursor"
        - { name: subscriptionID, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: Delivery register with explicit truncation when more than 200 items exist.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WebhookDeliveryPage' }
  /v1/webhook-deliveries/{deliveryID}/replay:
    post:
      operationId: replayWebhookDelivery
      summary: Retry a dead-letter webhook delivery
      tags: [Integrations]
      x-permission: integrations.webhook.manage
      parameters:
        - { name: deliveryID, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '204': { description: Replay queued with the original immutable event ID }
        '409': { description: Delivery is not a dead letter }
  /v1/accounts/batch:
    post:
      operationId: syncAccountBatch
      summary: Import or resume a bounded source chunk with per-row quarantine
      tags: [Domain operations]
      x-permission: monitoring.account.sync
      security:
      - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/SyncChunkInput' }
      responses:
        '200':
          description: Durable chunk outcomes and whole-batch reconciliation totals
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SyncBatch' }
        '400': { description: Invalid chunk metadata }
        '403': { description: Permission required }
        '409': { description: Source reference or numbered row conflicts with previous input }
        '503': { description: Sync capability unavailable }
  /v1/accounts/batches/{batchID}:
    get:
      operationId: getAccountSyncBatch
      summary: Inspect source sync progress and retained rejected rows
      tags: [Domain operations]
      x-permission: monitoring.account.sync
      security:
      - bearerAuth: []
      parameters:
      - name: batchID
        in: path
        required: true
        schema: {type: string, format: uuid}
      - name: offset
        in: query
        schema: {type: integer, format: int64, minimum: 0, default: 0}
      - name: limit
        in: query
        schema: {type: integer, minimum: 1, maximum: 100, default: 100}
      responses:
        '200':
          description: Batch totals and requested numbered row slice; increase offset to inspect subsequent rows
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SyncBatch' }
        '400': { description: Invalid row offset or limit }
        '403': { description: Permission required }
        '404': { description: Tenant-scoped batch not found }
  /v1/customers/batch:
    post:
      operationId: syncCustomerBatch
      summary: Import or resume a bounded source chunk with per-row quarantine
      tags: [Domain operations]
      x-permission: onboarding.customer.sync
      security:
      - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/SyncChunkInput' }
      responses:
        '200':
          description: Durable chunk outcomes and whole-batch reconciliation totals
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SyncBatch' }
        '400': { description: Invalid chunk metadata }
        '403': { description: Permission required }
        '409': { description: Source reference or numbered row conflicts with previous input }
        '503': { description: Sync capability unavailable }
  /v1/customers/batches/{batchID}:
    get:
      operationId: getCustomerSyncBatch
      summary: Inspect source sync progress and retained rejected rows
      tags: [Domain operations]
      x-permission: onboarding.customer.sync
      security:
      - bearerAuth: []
      parameters:
      - name: batchID
        in: path
        required: true
        schema: {type: string, format: uuid}
      - name: offset
        in: query
        schema: {type: integer, format: int64, minimum: 0, default: 0}
      - name: limit
        in: query
        schema: {type: integer, minimum: 1, maximum: 100, default: 100}
      responses:
        '200':
          description: Batch totals and requested numbered row slice; increase offset to inspect subsequent rows
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SyncBatch' }
        '400': { description: Invalid row offset or limit }
        '403': { description: Permission required }
        '404': { description: Tenant-scoped batch not found }
  /v1/customers/sync:
    post:
      operationId: syncCustomer
      summary: Register a source customer relationship without granting KYC approval
      tags: [Domain operations]
      x-permission: onboarding.customer.sync
      security:
      - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [external_ref, kind, display_name, kyc_tier, segment]
              properties:
                external_ref: {type: string, minLength: 1, maxLength: 200}
                kind: {type: string, enum: [natural, legal]}
                display_name: {type: string, minLength: 1, maxLength: 500}
                kyc_tier: {type: string, enum: [tier_1, tier_2, tier_3, corporate]}
                segment: {type: string, minLength: 1, maxLength: 64}
      responses:
        '200':
          description: Successful operation; a repeat source reference returns the existing record
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Customer'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '404':
          description: Tenant-scoped record not found
        '409':
          description: Source identity conflicts with an existing record
        '503':
          description: Capability unavailable
  /v1/accounts:
    post:
      operationId: upsertAccount
      summary: Register an account against a tenant customer with immutable owner and currency
      tags: [Domain operations]
      x-permission: monitoring.account.sync
      security:
      - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [customer_id, external_ref, currency]
              properties:
                customer_id: {type: string, format: uuid}
                external_ref: {type: string, minLength: 1, maxLength: 200}
                product_type: {type: string, maxLength: 64}
                currency: {type: string, pattern: '^[A-Z]{3}$'}
      responses:
        '200':
          description: Successful operation; a repeat source reference returns the existing record
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Account'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '404':
          description: Tenant-scoped record not found
        '409':
          description: Source identity conflicts with an existing record
        '503':
          description: Capability unavailable
  /v1/accounts/sync:
    post:
      operationId: syncAccount
      summary: Register an account against a tenant customer with immutable owner and currency
      tags: [Domain operations]
      x-permission: monitoring.account.sync
      security:
      - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [customer_id, external_ref, currency]
              properties:
                customer_id: {type: string, format: uuid}
                external_ref: {type: string, minLength: 1, maxLength: 200}
                product_type: {type: string, maxLength: 64}
                currency: {type: string, pattern: '^[A-Z]{3}$'}
      responses:
        '200':
          description: Successful operation; a repeat source reference returns the existing record
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Account'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '404':
          description: Tenant-scoped record not found
        '409':
          description: Source identity conflicts with an existing record
        '503':
          description: Capability unavailable
  /v1/case-tasks/{taskID}/assignment:
    post:
      operationId: assignCaseTask
      summary: Reassign a pending case task with a reason
      tags: [Domain operations]
      x-permission: cases.routing.manage
      security:
      - bearerAuth: []
      parameters:
      - name: taskID
        in: path
        required: true
        schema: {type: string, format: uuid}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [assignee_id, reason]
              properties:
                assignee_id: {type: string, format: uuid}
                reason: {type: string, minLength: 1, maxLength: 2000}
      responses:
        '200':
          description: Successful operation; a repeat source reference returns the existing record
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CaseTask'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '404':
          description: Tenant-scoped record not found
        '409':
          description: Source identity conflicts with an existing record
        '503':
          description: Capability unavailable
  /v1/case-tasks/{taskID}/cancellation:
    post:
      operationId: cancelCaseTask
      summary: Cancel a pending case task with a reason
      tags: [Domain operations]
      x-permission: cases.routing.manage
      security:
      - bearerAuth: []
      parameters:
      - name: taskID
        in: path
        required: true
        schema: {type: string, format: uuid}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [reason]
              properties:
                reason: {type: string, minLength: 1, maxLength: 2000}
      responses:
        '200':
          description: Successful operation; a repeat source reference returns the existing record
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CaseTask'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '404':
          description: Tenant-scoped record not found
        '409':
          description: Source identity conflicts with an existing record
        '503':
          description: Capability unavailable
  /healthz:
    get:
      operationId: getHealth
      tags: [Health]
      summary: Liveness probe
      security: []
      x-permission: public
      responses:
        "200":
          description: The process is running
          content:
            application/json:
              schema:
                type: object
                required: [status, version]
                properties:
                  status: { type: string, examples: [ok] }
                  version: { type: string }

  /readyz:
    get:
      operationId: getReady
      tags: [Health]
      summary: Readiness probe
      description: Reports ready only when Postgres is reachable, since nothing works without it.
      security: []
      x-permission: public
      responses:
        "200":
          description: Ready to serve traffic
          content:
            application/json:
              schema:
                type: object
                properties:
                  status: { type: string, examples: [ready] }
        "503": { $ref: "#/components/responses/Unavailable" }

  /v1/work-inbox:
    get:
      operationId: listWorkInbox
      tags:
      - Identity
      x-permission: authenticated
      description: Personal assignments and approval work. Data comes from current authorized
        module records, refreshed every 30 seconds; failures are reported rather than
        shown as empty work. Read markers are private to the current user.
      parameters:
      - name: kind
        in: query
        schema:
          type: string
          enum: [alert, case, kyc_review, approval, case_task, screening_hit, report, onboarding_application]
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: Current personal work
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WorkInboxPage'
  /v1/work-inbox/{kind}/{itemID}/read:
    post:
      operationId: markWorkInboxRead
      tags:
      - Identity
      x-permission: authenticated
      parameters:
      - name: kind
        in: path
        required: true
        schema:
          type: string
          enum:
          - alert
          - case
          - kyc_review
          - approval
          - case_task
          - screening_hit
          - report
          - onboarding_application
      - name: itemID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '204':
          description: Work item read marker updated
        '404':
          description: Work item unavailable to this user

  /v1/me/notifications:
    get:
      operationId: listNotifications
      tags: [Identity]
      x-permission: authenticated
      summary: List notifications visible to the current user
      description: |
        Filters run before the page limit. Cursors bind tenant, current recipient (for
        notifications), route, filters and global order. Old unbound cursors must restart.
      parameters:
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      - name: sort
        in: query
        schema: { type: string, enum: [created_at_desc, created_at_asc], default: created_at_desc }
      - name: read
        in: query
        schema: { type: string, enum: [read, unread] }
      - name: event_type
        in: query
        description: Exact retained event key without new normalization or length restriction. Empty selects all event types.
        schema: { type: string }
      responses:
        '200':
          description: Current recipient and permission-filtered notification page in selected global order
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/NotificationPage'
        '403': { $ref: '#/components/responses/Forbidden' }
  /v1/me/notifications/{notificationID}/read:
    post:
      operationId: markNotificationRead
      tags: [Identity]
      x-permission: authenticated
      summary: Mark the current user's notification read
      parameters:
      - name: notificationID
        in: path
        required: true
        schema: { type: string, format: uuid }
      responses:
        '200':
          description: Read state recorded
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [read]
                properties:
                  read: { type: boolean }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
  /v1/me/notification-preferences:
    get:
      operationId: getNotificationPreferences
      tags: [Identity]
      x-permission: authenticated
      summary: Read personal notification preferences
      responses:
        '200':
          description: Current preferences and email availability
          content:
            application/json:
              schema: { $ref: '#/components/schemas/NotificationPreferences' }
        '403': { $ref: '#/components/responses/Forbidden' }
    put:
      operationId: saveNotificationPreferences
      tags: [Identity]
      x-permission: authenticated
      summary: Update personal notification preferences
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/NotificationPreferenceInput' }
      responses:
        '200':
          description: Saved preferences and email availability
          content:
            application/json:
              schema: { $ref: '#/components/schemas/NotificationPreferences' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '422': { $ref: '#/components/responses/ValidationFailed' }

  /v1/me:
    get:
      operationId: getMe
      tags: [Identity]
      summary: The caller's identity, capabilities and tenant branding
      description: |
        The frontend renders its navigation from this rather than from a hardcoded role
        map, which is how an analyst and an executive see materially different
        applications from the same build (BRD §4.1). The permission list is advisory to
        the UI only: every request is still authorized server-side.
      x-permission: authenticated
      responses:
        "200":
          description: Caller context
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Me" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/search:
    get:
      operationId: searchRecords
      tags:
      - Identity
      x-permission: authenticated
      parameters:
      - name: kind
        in: query
        schema: { type: string, enum: [customer, account, hit, case, report, alert] }
        description: Narrow to an authorized record family.
      - name: report_status
        in: query
        schema: { type: string, enum: [approved] }
        description: Requires kind=report; narrows the picker to reviewed approved artifacts.
      - name: q
        in: query
        required: true
        schema:
          type: string
          minLength: 2
          maxLength: 120
      - name: limit
        in: query
        required: false
        schema:
          type: integer
          minimum: 1
          maximum: 40
          default: 20
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SearchResultPage'
        '403':
          $ref: '#/components/responses/Forbidden'
      description: Search customers, account references, screening hits, cases, reports and alert typologies. Exact BVN/NIN lookup uses tenant-keyed blind indexes; search audit retains only a keyed query digest.
        Each record kind is independently authorized. Restricted and erased subjects
        are excluded. Identifier values are never searched. Results report truncation
        when the limit is reached.
  /v1/workspace/{kind}:
    get:
      operationId: listWorkspaceDocuments
      tags:
      - Identity
      x-permission: authenticated
      parameters:
      - &id001
        name: kind
        in: path
        required: true
        schema:
          type: string
          enum:
          - onboarding
          - case_note
          - report_narrative
          - view
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WorkspaceDocumentPage'
        '403':
          $ref: '#/components/responses/Forbidden'
      description: Private to the current user and tenant; module capabilities are checked
        on every request. Responses are not cached.
  /v1/workspace/{kind}/{key}:
    get:
      operationId: getWorkspaceDocument
      tags:
      - Identity
      x-permission: authenticated
      parameters:
      - *id001
      - &id002
        name: key
        in: path
        required: true
        schema:
          type: string
          minLength: 1
          maxLength: 160
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WorkspaceDocument'
        '403':
          $ref: '#/components/responses/Forbidden'
      description: Private to the current user and tenant; module capabilities are checked
        on every request. Responses are not cached.
    put:
      operationId: saveWorkspaceDocument
      tags:
      - Identity
      x-permission: authenticated
      parameters:
      - *id001
      - *id002
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WorkspaceDocument'
        '403':
          $ref: '#/components/responses/Forbidden'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required:
              - expected_revision
              - payload
              properties:
                expected_revision:
                  type: integer
                  minimum: 0
                payload:
                  type: object
                  additionalProperties: true
      description: Private to the current user and tenant; module capabilities are checked
        on every request. Responses are not cached.
    delete:
      operationId: discardWorkspaceDocument
      tags:
      - Identity
      x-permission: authenticated
      parameters:
      - *id001
      - *id002
      - name: revision
        in: query
        required: true
        schema:
          type: integer
          minimum: 1
      responses:
        '204':
          description: Document discarded
        '409':
          description: Revision conflict
      description: Private to the current user and tenant; module capabilities are checked
        on every request. Responses are not cached.

  /v1/kyc-reviews:
    get:
      operationId: listKYCReviews
      summary: List k y c reviews
      tags:
      - Domain operations
      x-permission: onboarding.customer.read
      security:
      - bearerAuth: []
      parameters:
      - name: limit
        in: query
        schema:
          type: integer
          minimum: 1
          maximum: 200
          default: 50
      - name: cursor
        in: query
        schema:
          type: string
      - name: status
        in: query
        schema:
          type: string
      - name: customer_id
        in: query
        schema:
          type: string
          format: uuid
      - name: sort
        in: query
        description: Indexed tuple ordering; changing filters or order starts a new cursor walk.
        schema: { type: string, enum: [due_on_asc, due_on_desc], default: due_on_asc }
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/KYCReviewPage'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
  /v1/kyc-reviews/{reviewID}/claim:
    post:
      operationId: claimKYCReview
      summary: Claim k y c review
      tags:
      - Domain operations
      x-permission: onboarding.customer.write
      security:
      - bearerAuth: []
      parameters:
      - name: reviewID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/KYCReview'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
  /v1/kyc-reviews/{reviewID}/completions:
    get:
      operationId: listKYCCompletions
      summary: List k y c completions
      tags:
      - Domain operations
      x-permission: onboarding.customer.read
      security:
      - bearerAuth: []
      parameters:
      - name: reviewID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      - name: limit
        in: query
        schema:
          type: integer
          minimum: 1
          maximum: 200
          default: 50
      - name: cursor
        in: query
        schema:
          type: string
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/KYCCompletionPage'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
    post:
      operationId: prepareKYCCompletion
      summary: Prepare k y c completion
      tags:
      - Domain operations
      x-permission: onboarding.customer.write
      security:
      - bearerAuth: []
      parameters:
      - name: reviewID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/KYCCompletion'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/KYCCompletionInput'
  /v1/kyc-review-completions/{completionID}:
    get:
      operationId: previewKYCCompletion
      summary: Preview k y c completion
      tags:
      - Domain operations
      x-permission: onboarding.application.review
      security:
      - bearerAuth: []
      parameters:
      - name: completionID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/KYCCompletion'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
  /v1/kyc-review-completions/{completionID}/decision:
    post:
      operationId: decideKYCCompletion
      summary: Decide k y c completion
      tags:
      - Domain operations
      x-permission: onboarding.customer.edd
      security:
      - bearerAuth: []
      parameters:
      - name: completionID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/KYCCompletion'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/MaturityDecisionInput'
  /v1/transactions/batches/{batchID}/quarantine:
    get:
      operationId: listQuarantine
      summary: List quarantine
      tags:
      - Domain operations
      x-permission: monitoring.data_operations.read
      security:
      - bearerAuth: []
      parameters:
      - name: batchID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      - name: limit
        in: query
        schema:
          type: integer
          minimum: 1
          maximum: 200
          default: 50
      - name: cursor
        in: query
        schema:
          type: string
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/QuarantineRecordPage'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
  /v1/transactions/quarantine/{quarantineID}/resolution:
    post:
      operationId: resolveQuarantine
      summary: Resolve quarantine
      tags:
      - Domain operations
      x-permission: monitoring.data_operations.remediate
      security:
      - bearerAuth: []
      parameters:
      - name: quarantineID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/QuarantineResolution'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/QuarantineResolutionInput'
  /v1/transactions/source-manifests:
    get:
      operationId: listSourceManifests
      summary: List source manifests
      tags:
      - Domain operations
      description: |
        Filters apply before the bounded tuple page. Cursors bind tenant, scope and order.
        Old unbound cursors must restart. Every read rechecks current tenant permissions.
        batch_id filters the register and also prefills the operator create form.
      x-permission: monitoring.data_operations.read
      security:
      - bearerAuth: []
      parameters:
      - name: limit
        in: query
        schema:
          type: integer
          minimum: 1
          maximum: 200
          default: 50
      - name: cursor
        in: query
        schema:
          type: string
      - name: source
        in: query
        schema: { type: string, maxLength: 120 }
      - name: batch_id
        in: query
        schema: { type: string, format: uuid }
      - name: sort
        in: query
        description: Indexed tuple order; filter/order/tenant changes require a new cursor walk.
        schema: { type: string, enum: [recorded_at_desc, recorded_at_asc], default: recorded_at_desc }
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SourceManifestPage'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
    post:
      operationId: recordSourceManifest
      summary: Record source manifest
      tags:
      - Domain operations
      x-permission: monitoring.data_operations.remediate
      security:
      - bearerAuth: []
      parameters: []
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SourceManifest'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SourceManifestInput'
  /v1/transactions/source-manifests/{manifestID}/reconciliation:
    post:
      operationId: reconcileSourceManifest
      summary: Reconcile source manifest
      tags:
      - Domain operations
      x-permission: monitoring.data_operations.remediate
      security:
      - bearerAuth: []
      parameters:
      - name: manifestID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SourceReconciliation'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
  /v1/transactions/source-manifests/{manifestID}/reconciliations:
    get:
      operationId: listSourceReconciliations
      summary: List source reconciliations
      tags:
      - Domain operations
      x-permission: monitoring.data_operations.read
      security:
      - bearerAuth: []
      parameters:
      - name: manifestID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      - name: limit
        in: query
        schema:
          type: integer
          minimum: 1
          maximum: 200
          default: 50
      - name: cursor
        in: query
        schema:
          type: string
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SourceReconciliationPage'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
  /v1/cases/{caseID}/tasks:
    get:
      operationId: listCaseTasks
      summary: List case tasks
      tags:
      - Domain operations
      x-permission: cases.case_content.read
      security:
      - bearerAuth: []
      parameters:
      - name: caseID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      - name: limit
        in: query
        schema:
          type: integer
          minimum: 1
          maximum: 200
          default: 50
      - name: cursor
        in: query
        schema:
          type: string
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CaseTaskPage'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
    post:
      operationId: createCaseTask
      summary: Create case task
      tags:
      - Domain operations
      x-permission: cases.case.write
      security:
      - bearerAuth: []
      parameters:
      - name: caseID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CaseTask'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CaseTaskInput'
  /v1/case-tasks/{taskID}/completion:
    post:
      operationId: completeCaseTask
      summary: Complete case task
      tags:
      - Domain operations
      x-permission: cases.case.write
      security:
      - bearerAuth: []
      parameters:
      - name: taskID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CaseTask'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CaseTaskCompletionInput'
  /v1/cases/{caseID}/quality-reviews:
    get:
      operationId: listCaseQA
      summary: List case q a
      tags:
      - Domain operations
      x-permission: cases.case_content.read
      security:
      - bearerAuth: []
      parameters:
      - name: caseID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      - name: limit
        in: query
        schema:
          type: integer
          minimum: 1
          maximum: 200
          default: 50
      - name: cursor
        in: query
        schema:
          type: string
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CaseQualityReviewPage'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
    post:
      operationId: recordCaseQA
      summary: Record case q a
      tags:
      - Domain operations
      x-permission: cases.case.close
      security:
      - bearerAuth: []
      parameters:
      - name: caseID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CaseQualityReview'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CaseQualityReviewInput'
  /v1/case-playbooks:
    get:
      operationId: listCasePlaybooks
      summary: List case playbooks
      tags:
      - Domain operations
      x-permission: cases.case.read
      security:
      - bearerAuth: []
      parameters:
      - name: limit
        in: query
        schema:
          type: integer
          minimum: 1
          maximum: 200
          default: 50
      - name: cursor
        in: query
        schema:
          type: string
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CasePlaybookPage'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
    post:
      operationId: proposeCasePlaybook
      summary: Propose case playbook
      tags:
      - Domain operations
      x-permission: cases.routing.manage
      security:
      - bearerAuth: []
      parameters: []
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CasePlaybook'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CasePlaybookInput'
  /v1/case-playbooks/{playbookID}/decision:
    post:
      operationId: decideCasePlaybook
      summary: Decide case playbook
      tags:
      - Domain operations
      x-permission: cases.routing.manage
      security:
      - bearerAuth: []
      parameters:
      - name: playbookID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CasePlaybook'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/MaturityDecisionInput'
  /v1/cases/{caseID}/playbooks/{playbookID}/apply:
    post:
      operationId: applyCasePlaybook
      summary: Apply case playbook
      tags:
      - Domain operations
      x-permission: cases.case.write
      security:
      - bearerAuth: []
      parameters:
      - name: caseID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      - name: playbookID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CaseTaskPage'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
  /v1/iam/permissions:
    get:
      operationId: listPermissions
      tags: [IAM]
      summary: The global permission catalogue
      description: Delivered by content pack. A tenant composes roles from it but cannot invent a permission the code does not enforce.
      x-permission: iam.permission.read
      responses:
        "200":
          description: Permission catalogue
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PermissionPage" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/iam/roles:
    get:
      operationId: listRoles
      tags: [IAM]
      summary: Roles and their permission sets
      x-permission: iam.role.read
      responses:
        "200":
          description: Roles
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RolePage" }
        "403": { $ref: "#/components/responses/Forbidden" }
    post:
      operationId: createRole
      tags: [IAM]
      summary: Create a tenant role
      x-permission: iam.role.write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [key, name]
              properties:
                key: { type: string, pattern: "^[a-z][a-z0-9_]{1,63}$" }
                name: { type: string }
                description: { type: string }
                permissions:
                  type: array
                  items: { type: string }
      responses:
        "201":
          description: Role created
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Role" }
        "409": { $ref: "#/components/responses/Conflict" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/iam/roles/{roleID}:
    patch:
      operationId: updateRole
      tags: [IAM]
      summary: Update a tenant role
      description: |
        System roles delivered by a content pack are refused. A tenant needing a variant
        creates its own role, so a pack upgrade can correct a regulatory permission set
        without merging tenant edits into it (ADR-0006).
      x-permission: iam.role.write
      parameters: [{ $ref: "#/components/parameters/RoleID" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string }
                description: { type: string }
                permissions:
                  type: array
                  items: { type: string }
      responses:
        "200":
          description: Role updated
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Role" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: The role is delivered by a content pack and cannot be modified
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/iam/users/export:
    get:
      operationId: exportUsersRegister
      tags: [IAM]
      summary: Export the complete filtered user metadata register as CSV or Excel
      description: |
        Reuses current IAM authorization and filtered SQL in one repeatable-read transaction.
        Filters apply before LIMIT and preserve exact current role membership; the selected
        indexed ID direction applies across every page. Starts at the first matching row;
        cursor positions are refused. The existing10,000-row/32MiB bounds fail without a
        partial artifact. The digest and row count are audited before bytes leave.
        Only id, status, role_keys, org_unit_id, created_at and updated_at are captured.
        role_keys contains constrained current role keys, never arbitrary role display names.
        Excludes user names, emails, issuer/subject, MFA fields, login activity, tokens,
        credentials and provider diagnostics. CSV formulas are escaped; Excel cells are text.
      x-permission: iam.user.read
      parameters:
        - { name: format, in: query, required: true, schema: { type: string, enum: [csv, xlsx] } }
        - { name: role, in: query, schema: { type: string, pattern: "^[a-z][a-z0-9_]{1,63}$", maxLength: 64 } }
        - { name: status, in: query, schema: { type: string, enum: [active, suspended, deactivated] } }
        - { name: org_unit_id, in: query, schema: { type: string, format: uuid } }
        - { name: sort, in: query, schema: { type: string, enum: [id, id_asc, id_desc], default: id } }
      responses:
        "200":
          description: Complete matching metadata with audited SHA-256 digest and download disposition
          content:
            text/csv:
              schema: { type: string }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "503": { $ref: "#/components/responses/Unavailable" }
  /v1/iam/users:
    get:
      operationId: listUsers
      tags: [IAM]
      summary: List users
      description: |
        Filters apply before pagination and every page rechecks current role membership.
        Cursors bind the institution, role, status, organisational unit and ID direction. Start a new
        walk after changing these filters or direction; previously issued unbound cursors are refused.
        id is the retained alias of id_asc. The tenant/user primary key supports both orders.
      x-permission: iam.user.read
      parameters:
        - $ref: "#/components/parameters/Limit"
        - $ref: "#/components/parameters/Cursor"
        - name: status
          in: query
          schema: { type: string, enum: [active, suspended, deactivated] }
        - name: role
          in: query
          description: Exact current role key; an unknown valid key yields an empty matching page.
          schema: { type: string, pattern: "^[a-z][a-z0-9_]{1,63}$", maxLength: 64 }
        - name: org_unit_id
          in: query
          schema: { type: string, format: uuid }
        - name: sort
          in: query
          description: Global indexed user ID order; id retains the historical ascending order.
          schema: { type: string, enum: [id, id_asc, id_desc], default: id }
      responses:
        "200":
          description: A page of users
          content:
            application/json:
              schema: { $ref: "#/components/schemas/UserPage" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "503": { $ref: "#/components/responses/Unavailable" }
    post:
      operationId: createUser
      tags: [IAM]
      summary: Provision a user
      description: |
        Users are provisioned deliberately rather than created on first login. In an AML
        platform, who has access is a controlled decision, so a valid token for an
        unknown subject is refused rather than auto-enrolled.
      x-permission: iam.user.write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [subject, email, display_name]
              properties:
                subject: { type: string, description: The OIDC subject claim }
                email: { type: string, format: email }
                display_name: { type: string }
                org_unit_id:
                  type: string
                  format: uuid
                  description: |
                    Places the user in the organisational hierarchy at provisioning time.

                    This field was documented here and silently dropped by the handler: the
                    service input has carried it since Phase 1 and nothing populated it, so
                    `org_unit_id` could never be non-null on any real install while the schema
                    promised it. Create units with `POST /v1/iam/org-units` first.
                role_keys:
                  type: array
                  items: { type: string }
      responses:
        "201":
          description: User provisioned
          content:
            application/json:
              schema: { $ref: "#/components/schemas/User" }
        "409": { $ref: "#/components/responses/Conflict" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/iam/users/{userID}:
    patch:
      operationId: updateUser
      tags: [IAM]
      summary: Suspend, reactivate, deactivate or move a user
      description: |
        **The leaver path.** The authenticator refuses any principal whose user row is not
        `active`, so this is the only operation that can end somebody's access without deleting
        an audit actor — and until now it did not exist: user lifecycle over the API stopped at
        create, while `status` and its three states had been in the schema since Phase 1.

        A suspended or deactivated user's next request is refused with the same
        `not-provisioned` problem an unknown subject gets. That is deliberate: telling a rejected
        caller "that account is suspended" confirms the account exists.

        `org_unit_id` moves the user; `clear_org_unit: true` detaches them. Both are carried here
        rather than on a separate endpoint because "moved to Compliance" and "left the company"
        are changes to the same row and belong in the same audit event. An empty body is refused
        rather than recording an event that nothing changed.

        Deactivation emits `iam.user.deactivated`; anything else emits `iam.user.updated`, so an
        examiner filtering for "who lost access last quarter" is not reading display-name edits.
      x-permission: iam.user.write
      parameters: [{ $ref: "#/components/parameters/UserID" }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/UserUpdate" }
      responses:
        "200":
          description: The updated user
          content:
            application/json:
              schema: { $ref: "#/components/schemas/User" }
        "404": { $ref: "#/components/responses/NotFound" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/iam/users/{userID}/roles/{roleID}:
    post:
      operationId: assignUserRole
      tags: [IAM]
      summary: Grant a role to an existing user
      description: |
        Under `iam.user.write`, not `iam.role.write`. Composing what a role *means* and deciding
        *who holds one* are different duties: an administrator who may hand out roles should not
        thereby be able to redefine what those roles can do.

        Idempotent — granting a role the user already holds succeeds and changes nothing. The
        response is the whole user with the resulting role set, because what matters to a reviewer
        is what the person can do now, not which single grant moved.
      x-permission: iam.user.write
      parameters:
        - { $ref: "#/components/parameters/UserID" }
        - { $ref: "#/components/parameters/RoleID" }
      responses:
        "200":
          description: The user with the role granted
          content:
            application/json:
              schema: { $ref: "#/components/schemas/User" }
        "404": { $ref: "#/components/responses/NotFound" }

    delete:
      operationId: unassignUserRole
      tags: [IAM]
      summary: Revoke a role from a user
      description: |
        Emits `iam.role.unassigned`. Both that action and its counterpart have been in the audit
        vocabulary since Phase 1 and were emitted nowhere, because there was no route that could
        change a grant after the user existed.

        Revoking a role the user does not hold is a `404`, not a silent success: an administrator
        removing access needs to know whether the access was there.
      x-permission: iam.user.write
      parameters:
        - { $ref: "#/components/parameters/UserID" }
        - { $ref: "#/components/parameters/RoleID" }
      responses:
        "200":
          description: The user with the role revoked
          content:
            application/json:
              schema: { $ref: "#/components/schemas/User" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/iam/service-accounts:
    get:
      operationId: listServiceAccounts
      tags: [IAM]
      summary: List tenant machine identities
      description: |
        Returns safe metadata only. Credential digests and bearer secrets are never part of
        a read response. Results are tenant-scoped and resumable by ID.
        Status filters apply before the page limit. Cursors bind tenant, route, status
        and normalized ID order; old unbound cursors must restart.
      x-permission: iam.service_account.manage
      parameters:
        - $ref: "#/components/parameters/Limit"
        - $ref: "#/components/parameters/Cursor"
        - name: status
          in: query
          schema: { type: string, enum: [active, suspended, revoked] }
        - name: sort
          in: query
          schema: { type: string, enum: [id, id_asc, id_desc], default: id }
      responses:
        "200":
          description: A page of service accounts
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ServiceAccountPage" }
        "403": { $ref: "#/components/responses/Forbidden" }
    post:
      operationId: createServiceAccount
      tags: [IAM]
      summary: Create a service account and issue its first opaque credential
      description: |
        The `credential` is disclosed exactly once in this response and cannot be recovered.
        Store it in the calling system's secret manager before leaving this response. Veyndi
        stores only a SHA-256 digest of 32 uniformly random bytes.

        This is a Veyndi opaque API credential, not OAuth client_credentials and not an
        external authorization-server token. Assigned roles must contain only the closed
        machine-safe permission set: `monitoring.transaction.ingest`,
        `monitoring.batch.ingest`, `monitoring.account.sync`, `onboarding.customer.sync`,
        `screening.run` and `monitoring.alert.read`.
      x-permission: iam.service_account.manage
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ServiceAccountCreate" }
      responses:
        "201":
          description: Created; the bearer appears only in this response
          headers:
            Cache-Control:
              schema: { type: string, const: no-store }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/IssuedServiceAccount" }
        "409": { $ref: "#/components/responses/Conflict" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/iam/service-accounts/{serviceAccountID}:
    get:
      operationId: getServiceAccount
      tags: [IAM]
      summary: Read safe service-account and credential metadata
      x-permission: iam.service_account.manage
      parameters: [{ $ref: "#/components/parameters/ServiceAccountID" }]
      responses:
        "200":
          description: Service-account metadata; never a bearer or digest
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ServiceAccount" }
        "404": { $ref: "#/components/responses/NotFound" }
    patch:
      operationId: updateServiceAccount
      tags: [IAM]
      summary: Rename, suspend, reactivate or change expiry
      description: Revocation is terminal and uses the dedicated revoke operation.
      x-permission: iam.service_account.manage
      parameters: [{ $ref: "#/components/parameters/ServiceAccountID" }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ServiceAccountUpdate" }
      responses:
        "200":
          description: Updated metadata
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ServiceAccount" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409": { $ref: "#/components/responses/Conflict" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/iam/service-accounts/{serviceAccountID}/rotate:
    post:
      operationId: rotateServiceAccountCredential
      tags: [IAM]
      summary: Revoke the old credential and issue a new one
      description: |
        Rotation is atomic. The old credential is immediately revoked when the transaction
        commits, and the new bearer is disclosed exactly once in this non-cacheable response.
      x-permission: iam.service_account.manage
      parameters: [{ $ref: "#/components/parameters/ServiceAccountID" }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ServiceAccountCredentialRotate" }
      responses:
        "201":
          description: Rotated; the new bearer appears only in this response
          headers:
            Cache-Control:
              schema: { type: string, const: no-store }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/IssuedServiceAccount" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409": { $ref: "#/components/responses/Conflict" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/iam/service-accounts/{serviceAccountID}/revoke:
    post:
      operationId: revokeServiceAccount
      tags: [IAM]
      summary: Permanently revoke a service account and every current credential
      description: Idempotent. A revoked service account cannot be reactivated or rotated.
      x-permission: iam.service_account.manage
      parameters: [{ $ref: "#/components/parameters/ServiceAccountID" }]
      responses:
        "200":
          description: Revoked service account
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ServiceAccount" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/iam/service-accounts/{serviceAccountID}/roles/{roleID}:
    put:
      operationId: assignServiceAccountRole
      tags: [IAM]
      summary: Assign a machine-safe integration role to a service account
      description: |
        Refuses a role that is empty or grants any permission outside the two-key machine
        allowlist. Role permissions are checked again on every authentication, so later role
        widening fails closed.
      x-permission: iam.service_account.manage
      parameters:
        - { $ref: "#/components/parameters/ServiceAccountID" }
        - { $ref: "#/components/parameters/RoleID" }
      responses:
        "200":
          description: Service account with resulting roles
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ServiceAccount" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409": { $ref: "#/components/responses/Conflict" }
        "422": { $ref: "#/components/responses/ValidationFailed" }
    delete:
      operationId: unassignServiceAccountRole
      tags: [IAM]
      summary: Remove a role while retaining at least one machine-safe integration role
      x-permission: iam.service_account.manage
      parameters:
        - { $ref: "#/components/parameters/ServiceAccountID" }
        - { $ref: "#/components/parameters/RoleID" }
      responses:
        "200":
          description: Service account with resulting roles
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ServiceAccount" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409": { $ref: "#/components/responses/Conflict" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/iam/org-units:
    get:
      operationId: listOrgUnits
      tags: [IAM]
      summary: The organisational hierarchy
      description: |
        Ordered by code. The tree is bounded by the institution's own structure, so the page is
        complete rather than truncated.
      x-permission: iam.orgunit.read
      responses:
        "200":
          description: Org units
          content:
            application/json:
              schema: { $ref: "#/components/schemas/OrgUnitPage" }

    post:
      operationId: createOrgUnit
      tags: [IAM]
      summary: Create an organisational unit
      description: |
        BRD §7.2 names "user roles, permissions, and organizational hierarchy" together. The table
        has existed since migration 00003 with a self-referencing composite foreign key, RLS and
        two indexes, and was reachable from no route, no CLI and no screen.

        `code` is uppercase by constraint because a unit code is printed on reports and read aloud
        in meetings, and mixed case turns `HQ-Comp` and `HQ-COMP` into two units. `parent_id` must
        name a unit in the same tenant; the composite foreign key is what refuses anything else.

        The `org_units` tree in the `iam.access_policy` configuration document is **not**
        reconciled into these rows. Nothing materialises it, and a reconciler that deleted units
        a document no longer named would orphan every user assigned to them.
      x-permission: iam.orgunit.write
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/OrgUnitCreate" }
      responses:
        "201":
          description: The created unit
          content:
            application/json:
              schema: { $ref: "#/components/schemas/OrgUnit" }
        "409": { $ref: "#/components/responses/Conflict" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/iam/impersonation-grants:
    get:
      operationId: listImpersonationGrants
      tags: [IAM]
      summary: Veyndi support sessions opened into this tenant
      description: |
        Newest first, live and historic. Readable by the **tenant**, which is the half of Q16 that
        makes the other half checkable: "visible to the tenant" has to mean a screen the
        institution can open, not a report they can request from the vendor.

        A tenant-bound cursor traverses the selected grant-time order, including timestamp ties.
        Status and reason-code filters apply before LIMIT. Ordinary page requests re-evaluate
        current status; an export freezes one declared expiry cutoff across all pages.
      x-permission: iam.impersonation.read
      parameters:
        - { name: status, in: query, schema: { type: string, enum: [active, expired, revoked] } }
        - { name: reason_code, in: query, schema: { type: string, enum: [support_ticket, incident, migration, audit] } }
        - { name: sort, in: query, schema: { type: string, enum: [granted_at_desc, granted_at_asc], default: granted_at_desc } }
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: Support sessions
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ImpersonationGrantPage" }

    post:
      operationId: grantImpersonation
      tags: [IAM]
      summary: Open a support session
      description: |
        Time-boxed, reason-coded, and recorded in the hash chain on grant, on every use and on
        revoke (ADR-0003, Q12). Until now the grant and revoke paths were reachable only from
        inside a test, so Veyndi support could not actually open a session in production, and
        `iam.impersonation.granted` and `iam.impersonation.revoked` were emitted nowhere.

        The session **confers no permission the operator does not already hold**. It is a front
        door that is watched, not a back door: presenting the grant id in
        `X-Baobyte-Impersonation-Grant` marks the session and stamps every audit row it writes
        with the grant, and `GET /v1/me` reports `impersonating: true` with the grant id so the
        UI can tell the customer that support is in their data.

        `platform_actor` is the authenticated caller and is never taken from the body: the one
        field an examiner reads to find out *who* was in the data has to be unforgeable.

        **Honest limit.** A grant is scoped to the tenant the caller is authenticated in — the
        storage carries `tenant_id` and RLS — so there is no cross-tenant platform console. An
        operator can only open a session into a tenant they have been provisioned a user in. That
        floor is intentional: every session is preceded by the customer's own administrator
        creating the account, which is itself a consent record in the chain.
      x-permission: iam.impersonation.write
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ImpersonationGrantRequest" }
      responses:
        "201":
          description: The open session
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ImpersonationGrant" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/iam/impersonation-grants/{grantID}/revoke:
    post:
      operationId: revokeImpersonation
      tags: [IAM]
      summary: End a support session early
      description: |
        The next request presenting this grant is refused with `impersonation-not-live`, not
        silently downgraded to an ordinary session. Emits `iam.impersonation.revoked`.

        Revoking an already-expired grant succeeds: "who ended the support session, and when" is
        asked after the window has closed, not during it.
      x-permission: iam.impersonation.write
      parameters: [{ $ref: "#/components/parameters/GrantID" }]
      responses:
        "204": { description: Revoked }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/config/schemas:
    get:
      operationId: listConfigSchemas
      tags: [Configuration]
      summary: The configurable surface
      description: |
        Every key a compliance administrator may change, with its JSON Schema and whether
        it requires four-eyes. This endpoint is what makes BRD §7.2 auditable: what is
        configurable is data returned by the API, not a claim in a document.
      x-permission: config.document.read
      parameters:
        - name: category
          in: query
          schema:
            type: string
            enum: [risk, monitoring, screening, workflow, onboarding, reporting, iam, ui, platform, compliance]
      responses:
        "200":
          description: Registered configuration keys
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ConfigSchemaPage" }

  /v1/config/effective:
    get:
      operationId: getEffectiveConfig
      tags: [Configuration]
      summary: The whole effective configuration, with provenance
      x-permission: config.document.read
      responses:
        "200":
          description: Effective configuration keyed by configuration key
          content:
            application/json:
              schema:
                type: object
                additionalProperties: { $ref: "#/components/schemas/ResolvedConfig" }

  /v1/config/effective/{key}:
    get:
      operationId: getEffectiveConfigKey
      tags: [Configuration]
      summary: The effective value for one key
      description: |
        Returns the value and where it came from - the tenant's own override or the
        content-pack default. Provenance is not decoration: when an examiner asks why an
        alert fired at one threshold rather than another, the answer requires knowing
        which layer supplied the number and who approved it.
      x-permission: config.document.read
      parameters:
        - { $ref: "#/components/parameters/ConfigKey" }
        - name: as_of
          in: query
          description: Past or current RFC3339 instant. Uses retained override and pack-default intervals; refuses dates before historical pack coverage when no override was effective.
          schema: { type: string, format: date-time }
      responses:
        "200":
          description: Effective value
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ResolvedConfig" }
        "409": { description: Historical pack coverage unavailable; no current default substituted }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/config/documents/{key}/versions:
    get:
      operationId: listConfigVersions
      tags: [Configuration]
      summary: Version history for a configuration key
      description: |
        Documents are immutable, so this answers "what was the threshold on 12 March"
        directly rather than by reconstructing it from the audit trail.
      x-permission: config.document.read
      parameters:
        - { $ref: "#/components/parameters/ConfigKey" }
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: Versions, newest first
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ConfigDocumentPage" }

  /v1/config/documents/{key}:
    post:
      operationId: proposeConfigChange
      tags: [Configuration]
      summary: Propose a configuration change
      description: |
        Validates the payload against the key's registered JSON Schema before anything is
        written, then routes it through maker-checker if the schema requires approval.

        This is the Phase 0 proof that configuration-over-code and four-eyes hold
        together: a threshold change is data, it is validated, it needs a second pair of
        eyes, and both the proposal and the decision land in the audit chain.
      x-permission: config.document.propose
      parameters: [{ $ref: "#/components/parameters/ConfigKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [payload]
              properties:
                payload:
                  description: Must satisfy the JSON Schema registered for this key
                  type: object
                  additionalProperties: true
                note: { type: string }
                effective_from:
                  type: string
                  format: date-time
                  description: Optional future instant within one year. Scheduled changes always require an independent reviewer; approval queues application and applied_at stays absent until successful execution.
      responses:
        "201":
          description: |
            Proposal recorded. `approval` is present when the key requires four-eyes; when
            it does not, the document is already active.
          content:
            application/json:
              schema:
                type: object
                required: [document]
                properties:
                  document: { $ref: "#/components/schemas/ConfigDocument" }
                  approval: { $ref: "#/components/schemas/ApprovalRequest" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/approvals:
    get:
      operationId: listApprovals
      tags: [Approvals]
      summary: Approval requests
      description: |
        Queue metadata is available with `workflow.approval.read`. A
        `watchlists.entry.edit` request contains protected watchlist records; unless the
        caller also holds `watchlists.entry.read`, its payload and maker/checker rationales
        are replaced with the fixed restricted representation and
        `payload_restricted=true`; `subject_id` is the empty string because an entry-add
        subject embeds the protected external id. Action, subject type, digest, status,
        actors and timestamps remain visible so the queue can still route the request
        without disclosing its entry.
      x-permission: workflow.approval.read
      parameters:
        - name: status
          in: query
          schema: { type: string, enum: [pending, approved, rejected, withdrawn, expired] }
        - name: action
          in: query
          schema: { type: string }
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
        - name: sort
          in: query
          description: Indexed tuple ordering; changing filters or order starts a new cursor walk.
          schema: { type: string, enum: [proposed_at_desc, proposed_at_asc], default: proposed_at_desc }
      responses:
        "200":
          description: Approval requests, newest first
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApprovalRequestPage" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "503": { $ref: "#/components/responses/Unavailable" }

  /v1/approvals/{approvalID}:
    get:
      operationId: getApproval
      tags: [Approvals]
      summary: One approval request
      description: |
        For `watchlists.entry.edit`, the payload and free-text rationales are disclosed only
        when the caller also holds `watchlists.entry.read`. Otherwise the response blanks
        `subject_id`, preserves the non-identifying workflow metadata and sets
        `payload_restricted=true` with the fixed restricted payload marker.
      x-permission: workflow.approval.read
      parameters: [{ $ref: "#/components/parameters/ApprovalID" }]
      responses:
        "200":
          description: Approval request
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApprovalRequest" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/approvals/{approvalID}/customer-profile-preview:
    post:
      operationId: previewApprovalCustomerProfileChange
      tags: [Approvals]
      summary: Explicitly reveal an encrypted customer-profile proposal for checker review
      description: |
        A POST-only, on-demand disclosure for `onboarding.customer.field_change` requests that
        carry migration 00046's encrypted profile stage. The ordinary approval detail response
        and its server-rendered page continue to contain only the opaque stage id, ciphertext
        digest and changed-field names.

        The caller must hold `workflow.approval.decide`, satisfy the tenant's MFA policy for
        that permission, be different from the maker, and hold one of the checker roles currently
        configured for this exact action. The request must still be pending. Before decrypting,
        the service verifies the immutable workflow digest and the tenant-scoped stage's exact
        approval, customer, maker, ciphertext digest and changed-field linkage. Cross-tenant rows
        are indistinguishable from missing rows under RLS.

        A successful disclosure writes
        `workflow.approval.customer_profile_previewed` to the tamper-evident audit chain in the
        same transaction and is also classified as `data.accessed` approval-review content at the
        HTTP boundary. Audit state contains only identifiers, field names, the ciphertext digest
        and fixed access-classification metadata — never the proposed values. The response is
        `no-store`; values must not be copied into URLs, logs, workflow JSON or server-rendered
        HTML.
      x-permission: workflow.approval.decide
      parameters: [{ $ref: "#/components/parameters/ApprovalID" }]
      responses:
        "200":
          description: The exact staged profile values available to this checker for this review
          headers:
            Cache-Control:
              schema: { type: string, const: no-store }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CustomerProfileChangePreview" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409": { $ref: "#/components/responses/Conflict" }
        "410":
          description: The subject key was destroyed under an approved erasure request
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/approvals/{approvalID}/approve:
    post:
      operationId: approveRequest
      tags: [Approvals]
      summary: Approve a proposed change
      description: |
        Refused if the caller is the maker, and refused if the payload changed after it was
        proposed. The approval and the application of the change happen in one
        transaction, so an approval can never be recorded against a change that failed to
        apply (ADR-0008).

        Deciding a `watchlists.entry.edit` request additionally requires
        `watchlists.entry.read`, so a generic workflow checker cannot approve protected
        watchlist facts blind. Its immutable decision event contains only the safe approval
        envelope and payload digest, never the subject identifier, raw payload or free-text
        rationales.
      x-permission: workflow.approval.decide
      parameters: [{ $ref: "#/components/parameters/ApprovalID" }]
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                reason: { type: string }
      responses:
        "200":
          description: Approved and applied
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApprovalRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "409":
          description: |
            Four-eyes violation. `type` is `.../four-eyes-violation` when the caller is
            the maker or the payload digest no longer matches the proposal.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/approvals/{approvalID}/reject:
    post:
      operationId: rejectRequest
      tags: [Approvals]
      summary: Reject a proposed change
      description: |
        A reason is required, so an examiner can see why a control fired. Deciding a
        `watchlists.entry.edit` request additionally requires `watchlists.entry.read`, so a
        generic workflow checker cannot reject protected watchlist facts blind. The
        immutable decision event retains the safe approval envelope and digest, not the raw
        subject identifier, payload or free-text rationales.
      x-permission: workflow.approval.decide
      parameters: [{ $ref: "#/components/parameters/ApprovalID" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [reason]
              properties:
                reason: { type: string, minLength: 1 }
      responses:
        "200":
          description: Rejected
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApprovalRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "409": { $ref: "#/components/responses/Conflict" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/content-packs:
    get:
      operationId: listContentPacks
      tags: [Content packs]
      summary: Imported content packs
      x-permission: contentpack.pack.read
      responses:
        "200":
          description: Content packs
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ContentPackPage" }

  /v1/content-packs/installations:
    get:
      operationId: listPackInstallations
      tags: [Content packs]
      summary: This tenant's pack installation history
      x-permission: contentpack.pack.read
      responses:
        "200":
          description: Installations, newest first
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PackInstallationPage" }

  /v1/content-packs/{packID}/diff:
    get:
      operationId: diffContentPack
      tags: [Content packs]
      summary: Preview what applying a pack would change
      description: |
        Required by architectural mandate 5. `conflicts_with_overrides` counts the changes
        that need a human decision: a pack default moving underneath a customisation the
        tenant made deliberately. The override still wins, but the compliance officer needs
        to know the ground shifted beneath it.
      x-permission: contentpack.pack.read
      parameters: [{ $ref: "#/components/parameters/PackID" }]
      responses:
        "200":
          description: Upgrade diff
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PackDiff" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/content-packs/{packID}/install:
    post:
      operationId: installContentPack
      tags: [Content packs]
      summary: Propose applying a content pack
      description: |
        Applying regulatory content is a four-eyes action. The diff is what gets approved,
        and the approved diff is retained on the installation record so the decision is
        reconstructable.
      x-permission: contentpack.pack.install
      parameters: [{ $ref: "#/components/parameters/PackID" }]
      responses:
        "202":
          description: Installation proposed and awaiting approval
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApprovalRequest" }
        "400":
          description: The pack failed signature or digest verification
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/audit/events:
    get:
      operationId: listAuditEvents
      tags: [Audit]
      summary: The audit trail
      description: |
        Orders by immutable tenant sequence, newest first by default. Changing the sort,
        institution or filters requires a new cursor walk. Previously issued unbound cursors
        are refused; the explicit after_seq boundary remains supported in either direction.
      x-permission: audit.event.read
      parameters:
        - name: action
          in: query
          schema: { type: string }
        - name: resource_type
          in: query
          schema: { type: string }
        - name: resource_id
          in: query
          schema: { type: string }
        - name: sort
          in: query
          schema: { type: string, enum: [seq_desc, seq_asc, seq], default: seq_desc }
          description: seq is a retained alias for descending sequence order.
        - name: after_seq
          in: query
          description: |
            Keyset position on the per-tenant sequence, in the clear. Predates `cursor` and
            still works; `cursor` wins if both are sent.
          schema: { type: integer, format: int64, minimum: 0 }
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: A page of audit events in the selected immutable sequence order
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AuditPage" }

        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/audit/events/export:
    get:
      operationId: exportAuditRegister
      tags: [Audit]
      summary: Export the complete filtered audit metadata index as CSV or Excel
      description: |
        Walks the authorized audit register in one repeatable-read transaction. Excludes
        actor labels, actor identifiers, resource identifiers, IPs, request identifiers,
        before/after state and metadata. Retains event identity, immutable sequence,
        disposition and chain digests. This metadata index cannot recompute full event
        digests without the omitted content; use the independent chain-verification tools.
        Up to 10,000 rows and 32 MiB are supported. Larger exports fail without a partial
        artifact. The artifact digest and row count are audited before bytes are returned.
        Cursor and after_seq positions are refused: exports start at the first matching row.
      x-permission: audit.event.read
      parameters:
        - { name: format, in: query, required: true, schema: { type: string, enum: [csv, xlsx] } }
        - { name: action, in: query, schema: { type: string } }
        - { name: resource_type, in: query, schema: { type: string } }
        - { name: resource_id, in: query, schema: { type: string } }
        - { name: sort, in: query, schema: { type: string, enum: [seq_desc, seq_asc, seq], default: seq_desc } }
      responses:
        "200":
          description: Complete filtered metadata index with an audited digest
          content:
            text/csv:
              schema: { type: string, format: binary }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/Forbidden" }
        default: { $ref: "#/components/responses/ProblemResponse" }

  /v1/audit/chain-integrity:
    get:
      operationId: verifyAuditChain
      tags: [Audit]
      summary: Verify this tenant's audit chain
      description: |
        Recomputes the chain from genesis and checks every anchor, on demand. It does not
        read a stored verdict: a cached "valid" flag is precisely what an attacker would
        set. `broken_at_seq` locates the first divergence so an investigator has somewhere
        to start.
      x-permission: audit.chain.verify
      responses:
        "200":
          description: Chain status
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ChainStatus" }

  /v1/audit/retention-policies:
    get:
      operationId: listRetentionPolicies
      tags: [Audit]
      summary: List retention coverage and effective hold state
      description: |
        Returns every member of the closed evidence-family vocabulary, including families for
        which this tenant has no configured policy. Missing coverage is explicit and is never
        treated as an implicit five-year policy.

        A hold is a conservative tenant-wide summary for subject-scoped evidence. An active or
        release-pending hold blocks reductions but permits increases; it does not claim every row
        belongs to the held subject. NEEDS-COMPLIANCE-VALIDATION (Q5). This surface does not purge
        data, choose an erasure boundary, or override a legal hold.
      x-permission: audit.retention.read
      responses:
        "200":
          description: Complete retention-policy coverage
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RetentionPolicyPage" }

  /v1/audit/retention-policies/{resourceType}/history:
    get:
      operationId: listRetentionPolicyHistory
      tags: [Audit]
      summary: List immutable applied versions for an evidence family
      x-permission: audit.retention.read
      parameters:
        - name: resourceType
          in: path
          required: true
          schema:
            type: string
            enum:
              - alert_records
              - audit_events
              - case_records
              - configuration_history
              - customer_records
              - onboarding_evidence
              - privacy_records
              - regulatory_reports
              - screening_records
              - transaction_records
      responses:
        "200":
          description: Applied policy versions, newest first
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RetentionHistoryPage" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/audit/retention-policies/{resourceType}/proposals:
    post:
      operationId: proposeRetentionPolicy
      tags: [Audit]
      summary: Propose a retention-period change for independent approval
      description: |
        Creates a digest-bound approval request; it does not change the effective policy. The
        maker cannot approve their own request. The five-year floor is validated before storage
        and enforced again by the database. An active hold refuses a reduction both here and when
        the checker later applies it, closing the approval-delay race. No deletion is performed.
      x-permission: audit.retention.propose
      parameters:
        - name: resourceType
          in: path
          required: true
          schema:
            type: string
            enum:
              - alert_records
              - audit_events
              - case_records
              - configuration_history
              - customer_records
              - onboarding_evidence
              - privacy_records
              - regulatory_reports
              - screening_records
              - transaction_records
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [retain_years, reason]
              properties:
                retain_years:
                  type: integer
                  format: int32
                  minimum: 5
                reason:
                  type: string
                  minLength: 1
                  maxLength: 2000
                  description: Non-whitespace explanation presented to the independent checker.
      responses:
        "202":
          description: Proposal recorded; policy unchanged pending a different checker
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RetentionProposal" }
        "409":
          description: An active or release-pending hold blocks this reduction
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/tenants/export:
    get:
      operationId: exportTenantRegistry
      tags: [Platform]
      summary: Export the complete authorized metadata register as CSV or Excel
      description: |
        A single platform repeatable-read snapshot of authorized registry metadata. Callers without tenancy.tenant.write receive only their own institution. No identity-provider, provisioning, quota or invitation configuration is captured.
        All pages use the same read connection. After the read snapshot commits, a separate
        caller-tenant transaction rechecks current active identity, original permission ceiling
        and any existing grant binding without consuming another support use, then commits
        the digest/row-count audit receipt. Bytes are withheld on either phase failure.
        There is no cross-pool atomicity claim. No added platform app-table privileges.
        Maximum 10,000 rows/32 MiB; no partial artifact; cursor input is refused. CSV formulas
        are escaped and Excel cells are text. Metadata columns: id, slug, display_name, status, deployment_mode, isolation_strategy, data_residency, segment, created_at, updated_at.
      x-permission: tenancy.tenant.read
      parameters:
        - { name: format, in: query, required: true, schema: { type: string, enum: [csv, xlsx] } }
        - { name: sort, in: query, schema: { type: string, enum: [created_at_desc, created_at_asc], default: created_at_desc } }
        - { name: status, in: query, schema: { type: string, enum: [provisioning, active, suspended, closed] } }
      responses:
        "200":
          description: Complete authorized metadata with audited artifact digest
          content:
            text/csv:
              schema: { type: string, format: binary }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "503": { $ref: "#/components/responses/Unavailable" }
  /v1/iam/impersonation-grants/export:
    get:
      operationId: exportSupportAccessRegister
      tags: [Platform]
      summary: Export the complete authorized metadata register as CSV or Excel
      description: |
        A single tenant repeatable-read snapshot with tenant RLS and one declared status cutoff. Excludes platform_actor, free reason and reference before JSON capture. This is not an estate-wide support reader.
        All pages use the same read connection. After the read snapshot commits, a separate
        caller-tenant transaction rechecks current active identity, original permission ceiling
        and any existing grant binding without consuming another support use, then commits
        the digest/row-count audit receipt. Bytes are withheld on either phase failure.
        There is no cross-pool atomicity claim. No added platform app-table privileges.
        Maximum 10,000 rows/32 MiB; no partial artifact; cursor input is refused. CSV formulas
        are escaped and Excel cells are text. Metadata columns: id, reason_code, status, granted_at, expires_at, revoked_at, first_used_at, last_used_at, use_count.
      x-permission: iam.impersonation.read
      parameters:
        - { name: format, in: query, required: true, schema: { type: string, enum: [csv, xlsx] } }
        - { name: status, in: query, schema: { type: string, enum: [active, expired, revoked] } }
        - { name: reason_code, in: query, schema: { type: string, enum: [support_ticket, incident, migration, audit] } }
        - { name: sort, in: query, schema: { type: string, enum: [granted_at_desc, granted_at_asc], default: granted_at_desc } }
      responses:
        "200":
          description: Complete authorized metadata with audited artifact digest
          content:
            text/csv:
              schema: { type: string, format: binary }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "503": { $ref: "#/components/responses/Unavailable" }
  /v1/tenants:
    get:
      operationId: listTenants
      tags: [Platform]
      summary: Tenants visible to the caller
      description: |
        **Your own tenant, unless you are a platform operator.** `tenancy.tenant.read` is a read
        of your own institution's record and returns exactly one row. Seeing the estate requires
        `tenancy.tenant.write`.

        That distinction is a fix, not a nicety. This operation previously ran an unfiltered list
        inside a platform transaction and returned it to anybody holding `tenancy.tenant.read` —
        which the ng-core pack grants to `system_admin`, `executive` and `auditor`. Three of the
        seven BRD §4.1 personas could enumerate every other institution on the installation:
        slug, legal name, segment, data residency and status.

        The estate view is resumable with a caller/authority/status/order-bound `cursor`, keyed on
        (`created_at`, `id`) in either selected direction. Changed authority requires a new walk. The
        single-tenant view returns at most its own matching row and carries no cursor, because a cursor on
        your own record would claim there is more of it.
      x-permission: tenancy.tenant.read
      parameters:
        - { name: sort, in: query, schema: { type: string, enum: [created_at_desc, created_at_asc], default: created_at_desc } }
        - name: status
          in: query
          schema: { type: string, enum: [provisioning, active, suspended, closed] }
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: Tenants
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TenantPage" }

    post:
      operationId: createTenant
      tags: [Platform]
      summary: Provision an institution
      description: |
        The platform control plane. Creates the tenant in **`provisioning`**, never `active`: the
        authenticator refuses every request from a tenant that is not active, so a tenant left
        provisioning cannot serve traffic until a content pack has been installed and an
        administrator provisioned. Creating it active would open a door into an installation with
        no roles in it (Q11).

        `slug` is the subdomain and cannot be changed afterwards — every IdP redirect URI and
        webhook callback binds to it, so renaming is a migration with a cutover rather than an
        edit.
      x-permission: tenancy.tenant.write
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TenantCreate" }
      responses:
        "201":
          description: Provisioned, awaiting activation
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Tenant" }
        "400":
          description: The slug is malformed or reserved
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "409":
          description: That slug is already in use
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/tenants/{tenantID}:
    get:
      operationId: getTenant
      tags: [Platform]
      summary: One tenant
      description: |
        Without `tenancy.tenant.write` a caller may read only their own tenant, and asking for
        another id returns the same `404` a non-existent id returns. A `403` would confirm the
        tenant exists, which is the fact being withheld.
      x-permission: tenancy.tenant.read
      parameters: [{ $ref: "#/components/parameters/TenantID" }]
      responses:
        "200":
          description: The tenant
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Tenant" }
        "404": { $ref: "#/components/responses/NotFound" }

    patch:
      operationId: updateTenant
      tags: [Platform]
      summary: Correct a tenant's metadata
      description: |
        Replaces display name, segment and residency together rather than patching single fields.
        A partial update over three columns needs three "was this key present" checks and the one
        that gets forgotten silently blanks a column — `data_residency` defaulting itself back to
        empty would put a tenant outside the BRD §9 residency check while looking like a rename.

        Status is **not** settable here. See `POST /v1/tenants/{tenantID}/status`.
      x-permission: tenancy.tenant.write
      parameters: [{ $ref: "#/components/parameters/TenantID" }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TenantUpdate" }
      responses:
        "200":
          description: The updated tenant
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Tenant" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/tenants/{tenantID}/status:
    post:
      operationId: setTenantStatus
      tags: [Platform]
      summary: Suspend, resume or close a tenant
      description: |
        Its own operation rather than a field on the PATCH, because the blast radius is different
        in kind: a suspended tenant has **every** request refused by the authenticator with
        `tenant-inactive` from the moment this returns. An act with that reach should not be
        reachable by a form that also fixes a typo in the display name.

        A `reason` is required for anything but a resume. The audit row is the only place the
        "why" survives, and "who suspended this bank, and why" is asked after the fact.
      x-permission: tenancy.tenant.write
      parameters: [{ $ref: "#/components/parameters/TenantID" }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/TenantStatusChange" }
      responses:
        "200":
          description: The tenant in its new state
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Tenant" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  # ----------------------------------------------------------- Commercial terms

  /v1/commercial/summary:
    get:
      operationId: getCommercialSummary
      tags: [Platform]
      summary: This tenant's commercial summary
      description: |
        Own-tenant, read-only view of the recorded agreement, immutable offer version,
        entitlement-only components, commercial status and usage evidence. Missing agreement or
        measurement is labelled unavailable rather than rendered as zero. A sanctions or
        adverse-media add-on is never proof that a provider feed is licensed or connected.

        This is not an invoice or payment statement, and a past-due/disputed status does not
        suspend AML, screening or ingestion. Suspension remains the separate explicit tenant
        lifecycle operation.
      x-permission: tenancy.commercial.read
      responses:
        "200":
          description: Recorded commercial terms and coverage
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CommercialSummary" }

  /v1/commercial/agreements/{agreementID}/history:
    get:
      operationId: listCommercialAgreementHistory
      tags: [Platform]
      summary: Immutable history for this tenant's agreement
      description: Filters apply before LIMIT. Cursors bind caller institution, selected tenant, agreement, read authority mode, filters and the actual stored revision direction.
      x-permission: tenancy.commercial.read
      parameters:
        - { name: sort, in: query, schema: { type: string, enum: [revision_desc, revision_asc], default: revision_desc } }
        - { name: status, in: query, schema: { type: string, enum: [provisioning, current, renewal_due, grace, past_due, disputed, ended, not_applicable] } }
        - { name: event_type, in: query, schema: { type: string, enum: [created, status_changed] } }
        - name: agreementID
          in: path
          required: true
          schema: { type: string, format: uuid }
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: Typed selected-agreement revisions in the requested stored revision order
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CommercialHistoryPage" }

  /v1/admin/commercial/offers/export:
    get:
      operationId: exportCommercialOfferRegister
      tags: [Platform]
      summary: Export the complete authorized commercial metadata register as CSV or Excel
      description: |
        One authenticated platform-pool repeatable-read snapshot, using the same supplied read connection on all pages.
        After that snapshot commits, a separate caller-tenant transaction non-consumingly
        rechecks the active original caller identity, original/current required permission
        intersection and any existing support-grant binding and current expiry/revocation,
        then commits the exact artifact digest, row count, selected scope and ordering receipt.
        Bytes are withheld on either phase failure. No cross-pool atomicity claim or platform
        app-table grants. Own-history remains own tenant; management remains explicit platform authority.
        Free notes/source, operator identity/labels, free revision reason and component private
        descriptions are excluded before JSON capture. Monetary terms and revision metadata
        use exact decimal strings; missing supplied money remains absent, never zero.
        No charges, invoices, licence assertions or commercial write transitions are added.
        Maximum 10,000 rows and 32 MiB; no partial artifact; cursor input is refused.
        Columns: id, offer_key, version, display_name, deployment_mode, base_term_type, billing_cadence, allowance_interval, transaction_allowance, user_allowance, currency, base_amount_minor, transaction_overage_minor, user_overage_minor, available_from, available_until, created_at.
      x-permission: platform.commercial.manage
      parameters:
        - { name: format, in: query, required: true, schema: { type: string, enum: [csv, xlsx] } }
        - { name: sort, in: query, schema: { type: string, enum: [created_at_desc, created_at_asc], default: created_at_desc } }
        - { name: deployment_mode, in: query, schema: { type: string, enum: [saas, onprem] } }
        - { name: base_term_type, in: query, schema: { type: string, enum: [saas_subscription, onprem_licence] } }
        - { name: offer_key, in: query, schema: { type: string, maxLength: 64 } }
      responses:
        "200":
          description: Complete metadata with retained caller audit receipt
          content:
            text/csv:
              schema: { type: string, format: binary }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "503": { $ref: "#/components/responses/Unavailable" }

  /v1/commercial/agreements/{agreementID}/history/export:
    get:
      operationId: exportOwnCommercialAgreementHistory
      tags: [Platform]
      summary: Export the complete authorized commercial metadata register as CSV or Excel
      description: |
        One tenant RLS repeatable-read snapshot, using the same supplied read connection on all pages.
        After that snapshot commits, a separate caller-tenant transaction non-consumingly
        rechecks the active original caller identity, original/current required permission
        intersection and any existing support-grant binding and current expiry/revocation,
        then commits the exact artifact digest, row count, selected scope and ordering receipt.
        Bytes are withheld on either phase failure. No cross-pool atomicity claim or platform
        app-table grants. Own-history remains own tenant; management remains explicit platform authority.
        Free notes/source, operator identity/labels, free revision reason and component private
        descriptions are excluded before JSON capture. Monetary terms and revision metadata
        use exact decimal strings; missing supplied money remains absent, never zero.
        No charges, invoices, licence assertions or commercial write transitions are added.
        Maximum 10,000 rows and 32 MiB; no partial artifact; cursor input is refused.
        Columns: id (agreement/revision identity), agreement_id, revision, event_type, offer_version_id, status, renewal_mode, term_start, term_end, grace_until, billing_timezone, occurred_at.
      x-permission: tenancy.commercial.read
      parameters:
        - { name: agreementID, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: format, in: query, required: true, schema: { type: string, enum: [csv, xlsx] } }
        - { name: sort, in: query, schema: { type: string, enum: [revision_desc, revision_asc], default: revision_desc } }
        - { name: status, in: query, schema: { type: string, enum: [provisioning, current, renewal_due, grace, past_due, disputed, ended, not_applicable] } }
        - { name: event_type, in: query, schema: { type: string, enum: [created, status_changed] } }
      responses:
        "200":
          description: Complete metadata with retained caller audit receipt
          content:
            text/csv:
              schema: { type: string, format: binary }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "503": { $ref: "#/components/responses/Unavailable" }

  /v1/admin/tenants/{tenantID}/commercial/agreements/{agreementID}/history/export:
    get:
      operationId: exportAdminCommercialAgreementHistory
      tags: [Platform]
      summary: Export the complete authorized commercial metadata register as CSV or Excel
      description: |
        One authenticated platform-pool repeatable-read snapshot, using the same supplied read connection on all pages.
        After that snapshot commits, a separate caller-tenant transaction non-consumingly
        rechecks the active original caller identity, original/current required permission
        intersection and any existing support-grant binding and current expiry/revocation,
        then commits the exact artifact digest, row count, selected scope and ordering receipt.
        Bytes are withheld on either phase failure. No cross-pool atomicity claim or platform
        app-table grants. Own-history remains own tenant; management remains explicit platform authority.
        Free notes/source, operator identity/labels, free revision reason and component private
        descriptions are excluded before JSON capture. Monetary terms and revision metadata
        use exact decimal strings; missing supplied money remains absent, never zero.
        No charges, invoices, licence assertions or commercial write transitions are added.
        Maximum 10,000 rows and 32 MiB; no partial artifact; cursor input is refused.
        Columns: id (agreement/revision identity), agreement_id, revision, event_type, offer_version_id, status, renewal_mode, term_start, term_end, grace_until, billing_timezone, occurred_at.
      x-permission: platform.commercial.manage
      parameters:
        - { $ref: "#/components/parameters/TenantID" }
        - { name: agreementID, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: format, in: query, required: true, schema: { type: string, enum: [csv, xlsx] } }
        - { name: sort, in: query, schema: { type: string, enum: [revision_desc, revision_asc], default: revision_desc } }
        - { name: status, in: query, schema: { type: string, enum: [provisioning, current, renewal_due, grace, past_due, disputed, ended, not_applicable] } }
        - { name: event_type, in: query, schema: { type: string, enum: [created, status_changed] } }
      responses:
        "200":
          description: Complete metadata with retained caller audit receipt
          content:
            text/csv:
              schema: { type: string, format: binary }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "503": { $ref: "#/components/responses/Unavailable" }

  /v1/admin/commercial/offers:
    get:
      operationId: listCommercialOffers
      tags: [Platform]
      summary: List immutable commercial offer versions
      description: Platform catalogue with exact deployment, base-term and offer-key predicates before LIMIT and genuine created_at/id order in either direction. Cursors bind caller institution, all filters and order. Normal supplied terms and components remain unchanged; this is not an invoice.
      x-permission: platform.commercial.manage
      parameters:
        - { name: sort, in: query, schema: { type: string, enum: [created_at_desc, created_at_asc], default: created_at_desc } }
        - { name: deployment_mode, in: query, schema: { type: string, enum: [saas, onprem] } }
        - { name: base_term_type, in: query, schema: { type: string, enum: [saas_subscription, onprem_licence] } }
        - { name: offer_key, in: query, schema: { type: string, maxLength: 64 } }
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: Offer versions
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CommercialOfferPage" }
    post:
      operationId: createCommercialOffer
      tags: [Platform]
      summary: Create an immutable offer version
      description: |
        Records supplied terms without inventing a price. Money is optional integer minor units
        plus a supported ISO currency. SaaS supports monthly/annual subscriptions and optional
        allowances/rates. On-prem supports one-time/annual licence terms and cannot commit
        without a separately typed annual support/maintenance component. Add-ons and
        professional services remain separate components.
      x-permission: platform.commercial.manage
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CommercialOfferCreate" }
      responses:
        "201":
          description: Immutable offer version
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CommercialOffer" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "409":
          description: The offer key/version already exists
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/admin/tenants/{tenantID}/commercial:
    get:
      operationId: getAdminCommercialSummary
      tags: [Platform]
      summary: One tenant's commercial summary
      description: Vendor control-plane read. It does not grant access to customer/AML records.
      x-permission: platform.commercial.manage
      parameters: [{ $ref: "#/components/parameters/TenantID" }]
      responses:
        "200":
          description: Recorded terms and usage coverage
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CommercialSummary" }

  /v1/admin/tenants/{tenantID}/commercial/agreements:
    post:
      operationId: createCommercialAgreement
      tags: [Platform]
      summary: Record a tenant commercial agreement
      description: |
        Links an immutable offer version to a tenant, with an explicit half-open term and IANA
        billing timezone. Selected components must belong to that exact offer; on-prem terms
        require selected annual support. This operation records commercial state only—it does
        not take payment, issue an invoice, enable a vendor feed or change tenant lifecycle.
      x-permission: platform.commercial.manage
      parameters: [{ $ref: "#/components/parameters/TenantID" }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CommercialAgreementCreate" }
      responses:
        "201":
          description: Agreement and first immutable history revision
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CommercialAgreement" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: A live agreement or agreement reference already exists
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/admin/tenants/{tenantID}/commercial/agreements/{agreementID}/status:
    post:
      operationId: updateCommercialAgreementStatus
      tags: [Platform]
      summary: Transition commercial agreement status
      description: |
        Follows the closed lifecycle graph and appends an immutable revision. Past due and
        disputed are visible commercial states, never automatic AML suspension or quota gates.
      x-permission: platform.commercial.manage
      parameters:
        - { $ref: "#/components/parameters/TenantID" }
        - name: agreementID
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CommercialAgreementStatusChange" }
      responses:
        "200":
          description: Agreement in its new commercial state
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CommercialAgreement" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: Concurrent revision conflict
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/admin/tenants/{tenantID}/commercial/agreements/{agreementID}/history:
    get:
      operationId: listAdminCommercialAgreementHistory
      tags: [Platform]
      summary: Immutable history for a managed tenant agreement
      description: Filters apply before LIMIT. Cursors bind caller institution, selected tenant, agreement, read authority mode, filters and the actual stored revision direction.
      x-permission: platform.commercial.manage
      parameters:
        - { name: sort, in: query, schema: { type: string, enum: [revision_desc, revision_asc], default: revision_desc } }
        - { name: status, in: query, schema: { type: string, enum: [provisioning, current, renewal_due, grace, past_due, disputed, ended, not_applicable] } }
        - { name: event_type, in: query, schema: { type: string, enum: [created, status_changed] } }
        - { $ref: "#/components/parameters/TenantID" }
        - name: agreementID
          in: path
          required: true
          schema: { type: string, format: uuid }
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: Typed selected-agreement revisions in the requested stored revision order
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CommercialHistoryPage" }

  /v1/admin/key-rotations:
    post:
      operationId: proposeSubjectDEKRotation
      tags: [Platform]
      summary: Propose a tenant subject-DEK root-key rewrap ceremony
      description: |
        The source must be the active configured root and the target must already be configured
        but inactive. A distinct system administrator approves the resulting maker-checker
        request. Approval installs an irreversible write barrier for the source while it is
        still active; it does not switch keys or rewrap data. New subject and audit-anchor
        writes may therefore refuse during the deliberately short operator cutover. There is
        no cancel/unblock operation and this endpoint never authorizes physical root removal.
      x-permission: platform.key_rotation.manage
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [source_key_id, target_key_id, reason]
              properties:
                source_key_id: { type: string, pattern: "^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$" }
                target_key_id: { type: string, pattern: "^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$" }
                reason: { type: string, minLength: 1, maxLength: 2000 }
      responses:
        "201":
          description: Pending four-eyes approval; no barrier or wrapper has changed yet
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApprovalRequest" }
        "409":
          description: A proposal is already pending or the source/target state is not valid
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "503":
          description: The provider cannot enumerate every configured root, so rotation refuses fail closed
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/admin/key-rotations/{rotationID}:
    get:
      operationId: getSubjectDEKRotation
      tags: [Platform]
      summary: Read rotation progress, readiness and retirement dependencies
      description: |
        Distinguishes the expected approved-awaiting-key-switch phase from a runnable or
        blocked configuration. Dependency counts are tenant-scoped. Immutable historical
        identifier blind indexes and audit anchors normally keep `tenant_dependencies_clear`
        false, and every tenant would have to be assessed before a process-wide software root
        could even be considered for a separate retirement ceremony. This API always reports
        `physical_retirement_supported: false`.
      x-permission: platform.key_rotation.manage
      parameters:
        - name: rotationID
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Durable rotation cursor and fail-closed readiness
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SubjectDEKRotationReadiness" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/admin/key-rotations/{rotationID}/run:
    post:
      operationId: runSubjectDEKRotation
      tags: [Platform]
      summary: Start or resume bounded subject-DEK wrapper batches
      description: |
        Refuses until the approved target is active, the source remains configured, provider
        enumeration is complete and both key fingerprints still match approval. The worker
        authenticates and rewraps at most 100 subject-DEK envelopes per transaction, records
        immutable per-subject evidence, and transactionally enqueues the next page. It never
        decrypts or rewrites subject fields. Repeating this call while work is active is
        idempotent. It does not remove the source root.
      x-permission: platform.key_rotation.manage
      parameters:
        - name: rotationID
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "202":
          description: Bounded resumable work accepted
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SubjectDEKRotationReadiness" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: Awaiting target activation, blocked, or already complete
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  # ----------------------------------------------------------- Usage measurement

  /v1/usage:
    get:
      operationId: listUsage
      tags: [Platform]
      summary: Recorded usage for this tenant
      description: |
        Returns measurements that have already been **recorded**, in the requested global period/ID order. A period
        nobody measured comes back absent, not zero: those are different facts, and conflating
        them reports a quiet month for a tenant whose measurement simply never ran.

        These rows are usage evidence, not invoices or payments. Open rows may be corrected;
        closed rows name the IANA billing timezone and cannot be changed.
      x-permission: platform.usage.read
      parameters:
        - { $ref: "#/components/parameters/PeriodStart" }
        - { $ref: "#/components/parameters/PeriodEnd" }
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
        - { name: metric, in: query, schema: { type: string, enum: [transaction.count, user.active] } }
        - { name: state, in: query, schema: { type: string, enum: [open, closed] } }
        - { name: sort, in: query, schema: { type: string, enum: [period_start_desc, period_start_asc], default: period_start_desc } }
      responses:
        "200":
          description: Recorded measurements
          content:
            application/json:
              schema: { $ref: "#/components/schemas/UsagePage" }

  /v1/usage/export:
    get:
      operationId: exportUsageRegister
      tags: [Platform]
      summary: Export recorded usage measurements as CSV or Excel
      description: |
        Uses the same authorized filtered measurement reader in one repeatable-read tenant
        snapshot. Starts at the first matching row; cursor input is refused. Up to 10,000
        rows/32 MiB, with no partial artifact. Audits SHA-256 and row count before returning
        bytes. CSV formulas are escaped and Excel cells are text. Recorded metric values,
        half-open periods, method, measurement state, billing timezone and closure time
        are included. Missing measurements remain absent. No invoices or charges are calculated.
      x-permission: platform.usage.read
      parameters:
        - { name: format, in: query, required: true, schema: { type: string, enum: [csv, xlsx] } }
        - { $ref: "#/components/parameters/PeriodStart" }
        - { $ref: "#/components/parameters/PeriodEnd" }

        - { name: metric, in: query, schema: { type: string, enum: [transaction.count, user.active] } }
        - { name: state, in: query, schema: { type: string, enum: [open, closed] } }
        - { name: sort, in: query, schema: { type: string, enum: [period_start_desc, period_start_asc], default: period_start_desc } }
      responses:
        "200":
          description: Complete recorded measurements and audited digest
          content:
            text/csv:
              schema: { type: string }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "503": { $ref: "#/components/responses/Unavailable" }

  /v1/usage/measurements:
    post:
      operationId: measureUsage
      tags: [Platform]
      summary: Measure and record a period
      description: |
        `POST`, not `GET`, because it **writes**. The snapshot is the fact; the query that
        produced it is not repeatable once retention has purged the source rows, so a live count
        would let a closed period's usage change retroactively or vanish.

        The window is **half-open**: `[period_start, period_end)`. A closed range double-counts a
        transaction booked exactly at a boundary midnight into two months. Timestamps rather than
        dates, because `2026-08-01` is two different instants in Lagos and in UTC — an hour of a
        bank's transactions either side of an invoice line.

        Re-measuring an open period corrects the recorded row in place rather than appending a
        second one and is refused after closure. Maximum window: one year. A daily run-on-start
        worker closes the previous local calendar month from the agreement's explicit IANA
        timezone; its half-open period key makes retries idempotent.
      x-permission: platform.usage.read
      parameters:
        - { $ref: "#/components/parameters/PeriodStartRequired" }
        - { $ref: "#/components/parameters/PeriodEndRequired" }
      responses:
        "201":
          description: The measurements recorded for the period
          content:
            application/json:
              schema: { $ref: "#/components/schemas/UsagePage" }
        "400":
          description: The window is empty, inverted or longer than a year
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  # ---------------------------------------------------------------- AML domain

  /v1/customers:
    get:
      operationId: listCustomers
      tags: [Customers]
      summary: The customer book
      description: |
        Filters by status, risk and a filter-bound cursor; orders the whole matching book by UUID, risk or review deadline, and free-text searches by `q` against the party's
        `display_name` and the customer's own `external_ref`, both by case-insensitive
        substring match against the trigram indexes migration 00022 added.

        **`q` does not reach BVN or NIN.** Both are encrypted under the subject's own key with
        an HMAC blind index beside the ciphertext (ADR-0019), and the blind index is an
        exact-match structure — it answers "does this value equal this identifier", never
        "does this identifier contain this substring". `FindPartyByIdentifier` is the only
        lawful way to look one up, and it takes the whole value. Indexing plaintext
        identifiers to make substring search possible would put them back outside the
        encryption boundary this platform exists to keep them inside, so this endpoint does
        not do it. A front-office user searching by a partial BVN gets no matches on that
        term, not a slower or approximate one.
      x-permission: onboarding.customer.read
      parameters:
        - name: status
          in: query
          schema: { type: string, enum: [draft, pending_documents, pending_edd, pending_approval, active, rejected, exited] }
        - name: risk
          in: query
          schema: { type: string, enum: [low, medium, high, prohibited] }
        - name: q
          in: query
          schema: { type: string }
          description: |
            Matches the party's display name and the customer's own external_ref. Does not
            search BVN, NIN or any other encrypted identifier — see the operation description.
        - name: sort
          in: query
          schema: { type: string, enum: [id, risk_asc, risk_desc, next_review_asc, next_review_desc], default: id }
          description: Whole-book server order. Unknown risk and missing review dates remain last in both directions; UUID ascending breaks ties.
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: Customers
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CustomerPage" }

    post:
      operationId: onboardCustomer
      tags: [Customers]
      summary: Onboard a customer from a submitted CDD form
      description: |
        The write path BRD §4.1-03 gives the relationship/front-office persona, whose entire
        job description is "onboarding, CDD capture". Until this operation existed the role
        held `onboarding.customer.read` and nothing else, so the only job the BRD gives that
        persona could not be performed by anybody through this API at all.

        One call, one transaction: the party with its names, identifiers and attributes; the
        customer relationship and its tier; and the submitted answers stored verbatim against
        the form version in force. Splitting it would permit a party with no customer — invisible
        to every list the front office has — or a customer whose CDD answers were never recorded.

        **`answers` is keyed by the form's own field keys.** Call `GET /v1/cdd-forms` for the
        questions in force; a key that is not on the form, a required question left unanswered,
        or an answer to a question the form's `show_if` predicate did not ask, are all refused
        together as a `422` listing every problem at once. A front-office user correcting a form
        one field per round trip is how a five-minute account opening becomes a twenty-minute one.

        **Numbers are decoded with `UseNumber` and are never rounded.** A number answered on the
        form is compared against the field's declared type as an integer, not as a float.

        **No identifier is recorded as verified.** `verified_by_source` is unreachable from this
        path: identifiers are captured, encrypted and blind-indexed as UNVERIFIED, because there
        is no NIBSS or NIMC adapter and the previous behaviour took the caller's word for it
        (Q26).

        Identifier requirement sets are enforced with the rest of the form. The official CBN
        baseline is Tier 1 individuals: BVN or NIN; Tiers 2/3: BVN and NIN. Submission proves
        presence only. Relationship approval separately requires authoritative electronic
        verification and refuses a mock or unverified value.

        The form's document requirements are snapshotted onto the application. A relationship
        starts in `pending_documents` when that snapshot has requirements and advances to
        `pending_approval` as evidence is collected; a form with no required evidence starts
        directly in `pending_approval`. Approval still requires independent verification of
        every required, unexpired object (Q32 owns whether the configured list is correct).
      x-permission: onboarding.customer.write
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [customer_type, tier, answers]
              properties:
                customer_type:
                  type: string
                  description: |
                    Selects the form. The shipped document defines `individual` and `corporate`;
                    `app.party.kind` is a two-value CHECK, so a third customer type is a schema
                    decision rather than a configuration one (Q27).
                tier:
                  type: string
                  enum: [tier_1, tier_2, tier_3, corporate]
                  description: |
                    Selects the questions and the required documents, and is recorded on the
                    customer as its KYC tier — so it cannot be inferred from the answers.
                answers:
                  type: object
                  additionalProperties: true
                  description: The submitted answer set, keyed by the form's own field keys.
                external_ref:
                  type: string
                  description: |
                    The institution's own customer number, independent of the request's
                    `Idempotency-Key`. When this field is omitted, the header supplies the
                    customer number for compatibility. Retrying the same request key requires
                    identical request bytes; corrected submissions use a new key.
                segment:
                  type: string
                  description: |
                    Feeds the monitoring thresholds. Derived from `customer_type` when omitted —
                    never defaulted to `individual`, because a corporate account evaluated against
                    individual thresholds is a monitoring failure that looks like a working system.
                additional_names:
                  type: array
                  description: |
                    Aliases and transliterations captured beside the primary name. Not a question
                    on the form: they are what the counter noticed, and they are what makes
                    screening work on a customer known by two spellings (ADR-0015).
                  items:
                    type: object
                    required: [full_name]
                    properties:
                      type: { type: string, enum: [primary, alias, former, transliteration, trading], default: alias }
                      full_name: { type: string, minLength: 1 }
      responses:
        "201":
          description: The customer, the party behind it, the stored application and the form it answered
          content:
            application/json:
              schema: { $ref: "#/components/schemas/OnboardResult" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "409":
          description: |
            An identifier given already belongs to a party this platform holds. Refused rather
            than attached: deciding two records are the same person is a merge, and a merge
            performed implicitly by an account-opening screen is how two customers become one.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "422": { $ref: "#/components/responses/ValidationFailed" }
        "503":
          description: |
            No CDD form definitions can be resolved on this installation, so no customer can be
            onboarded. A deployment fault rather than a problem with the request.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/customers/{customerID}:
    get:
      operationId: getCustomer
      tags: [Customers]
      summary: A customer profile with its risk decomposition
      description: |
        Returns the profile, the party behind it, its accounts, the latest risk assessment
        with per-factor contributions, and any resolved beneficial owners — in one response.

        Identifiers are returned masked. Decrypting them is a separate, audited action
        (ADR-0019), because reading a customer's BVN is an event a supervisor is entitled
        to see a record of.

        `assigned_org_unit` is present when the relationship has been routed to a branch or
        team (`POST /v1/customers/{customerID}/assign`), naming the unit's id and current
        name rather than only its id — the name is looked up at read time, not denormalised,
        so a renamed unit does not require rewriting every customer pointed at it.

        `pending_application_id` names the customer's onboarding application still awaiting a
        decision, so the customer workspace and the application-review screen
        (`GET /v1/onboarding/applications/{applicationID}`) can be linked directly. Absent
        once the application has been decided, or if the customer has none outstanding.

        `screening_hits` carries the party's sanctions and PEP matches, under a SECOND
        permission on top of the one that opens this route: a caller holding
        `onboarding.customer.read` but not `screening.hit.read` gets the profile with the key
        absent rather than empty, so reading the customer book cannot be used to acquire a
        screening surface the role was never granted.

        `corporate_profile` is present when the party is a legal entity, and carries whether
        its beneficial-ownership register has been VERIFIED and not merely declared — see
        `GET /v1/customers/{customerID}/risk-assessments` for the sibling endpoint this
        response does NOT try to be: `risk_assessment` above is only the latest rating, and
        the full history lives there rather than growing this response without bound.
      x-permission: onboarding.customer.read
      parameters:
        - { $ref: "#/components/parameters/CustomerID" }
      responses:
        "200":
          description: The customer workspace
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CustomerDetail" }
        "404": { $ref: "#/components/responses/NotFound" }

    patch:
      operationId: updateCustomer
      tags: [Customers]
      summary: Correct external_ref, or propose a governed customer-profile change
      description: |
        Until this operation existed there was no way to correct a customer once onboarded:
        `external_ref`, `segment`, `kyc_tier` and structured CDD facts could all be typed wrong
        at the counter and never fixed.

        The two classes of field in this request are handled differently, deliberately.

        **`external_ref` is applied directly**, in the same transaction, and the response is
        a plain `200` with the corrected customer. It is the institution's own customer
        number and feeds nothing else this platform reasons over — no rule, no threshold, no
        form resolution reads it — so a typo fixed here cannot silently move what the
        customer is measured against.

        **`segment`, `kyc_tier` and `profile` are NOT applied directly, however this request arrives.**
        `segment` selects the monitoring thresholds every transaction on this customer's
        accounts is compared against; `kyc_tier` selects the CDD form and the documents
        BRD §8.1 requires for the relationship. Both are exactly the class of change this
        codebase already requires a second reviewer on elsewhere — a configuration threshold,
        a monitoring rule, the risk model that assigns tiers in the first place, a case's
        outcome. Address geography, occupation/industry, nationality/country, source of funds,
        cash intensity and beneficial ownership are themselves screening corroboration, risk
        inputs or CDD evidence. A manual correction to any of them raises a maker-checker proposal
        (`workflow.ActionCustomerFieldChange`) instead of changing anything. `reason` is
        required whenever any governed field is sent: it is what the checker reads before deciding
        and is retained in workflow and audit metadata. Because it is readable free text, it must
        not contain names, addresses, identifiers, source-of-funds details or any other profile/PII
        value.

        The staged profile fields themselves never enter the workflow request's readable JSONB or
        the append-only audit metadata. They are canonicalised (including NBS state/LGA codes for
        Nigerian addresses), encrypted under the party's subject DEK in immutable staging, and
        represented to workflow only by an opaque id, a digest of unpredictable ciphertext, and
        sorted field names. The separately supplied non-sensitive `reason` remains readable and
        auditable. On approval the same transaction applies the values, retains superseded
        ownership edges, invalidates any attestation over a replaced register, runs ongoing
        screening for the party and replacement owners, writes a `profile_update` risk assessment
        and opens/reconciles a `risk_change` KYC review. Any failed control rolls the whole approval
        back.

        Identifiers and documents are deliberately not accepted. Identifier verification has its
        own authority-backed lifecycle; evidence documents are immutable.

        Sending `external_ref` together with `segment` or `kyc_tier` in one request applies
        the first immediately and raises the proposal for the second in the same
        transaction; the response is a `202` naming the pending approval, and `customer` in
        that body already reflects the applied `external_ref`.
      x-permission: onboarding.customer.write
      parameters:
        - { $ref: "#/components/parameters/CustomerID" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              oneOf:
                - title: Direct external-reference correction
                  type: object
                  additionalProperties: false
                  required: [external_ref]
                  properties:
                    external_ref:
                      type: string
                      minLength: 1
                      description: Corrected directly. Cannot be corrected to blank.
                    reason:
                      type: string
                      minLength: 1
                      maxLength: 1000
                      description: Accepted but ignored for a direct external-reference correction.
                - title: Governed profile or classification correction
                  anyOf:
                    - title: Segment correction
                      type: object
                      additionalProperties: false
                      required: [segment, reason]
                      properties:
                        external_ref:
                          type: string
                          minLength: 1
                          description: Corrected directly in the same transaction, when supplied.
                        segment:
                          type: string
                          minLength: 1
                          description: Proposed via four-eyes.
                        kyc_tier:
                          type: string
                          enum: [tier_1, tier_2, tier_3, corporate]
                          description: Proposed via four-eyes.
                        profile:
                          $ref: "#/components/schemas/CustomerProfileChange"
                        reason:
                          type: string
                          minLength: 1
                          maxLength: 1000
                          description: |
                            The bounded rationale the checker reads before deciding and that workflow
                            and audit metadata retain. Do not include names, addresses, identifiers,
                            source-of-funds details or any other profile/PII value.
                    - title: KYC-tier correction
                      type: object
                      additionalProperties: false
                      required: [kyc_tier, reason]
                      properties:
                        external_ref:
                          type: string
                          minLength: 1
                          description: Corrected directly in the same transaction, when supplied.
                        segment:
                          type: string
                          minLength: 1
                          description: Proposed via four-eyes.
                        kyc_tier:
                          type: string
                          enum: [tier_1, tier_2, tier_3, corporate]
                          description: Proposed via four-eyes.
                        profile:
                          $ref: "#/components/schemas/CustomerProfileChange"
                        reason:
                          type: string
                          minLength: 1
                          maxLength: 1000
                          description: |
                            The bounded rationale the checker reads before deciding and that workflow
                            and audit metadata retain. Do not include names, addresses, identifiers,
                            source-of-funds details or any other profile/PII value.
                    - title: Structured-profile correction
                      type: object
                      additionalProperties: false
                      required: [profile, reason]
                      properties:
                        external_ref:
                          type: string
                          minLength: 1
                          description: Corrected directly in the same transaction, when supplied.
                        segment:
                          type: string
                          minLength: 1
                          description: Proposed via four-eyes.
                        kyc_tier:
                          type: string
                          enum: [tier_1, tier_2, tier_3, corporate]
                          description: Proposed via four-eyes.
                        profile:
                          $ref: "#/components/schemas/CustomerProfileChange"
                        reason:
                          type: string
                          minLength: 1
                          maxLength: 1000
                          description: |
                            The bounded rationale the checker reads before deciding and that workflow
                            and audit metadata retain. Do not include names, addresses, identifiers,
                            source-of-funds details or any other profile/PII value.
      responses:
        "200":
          description: external_ref was corrected, and nothing else was requested
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Customer" }
        "202":
          description: A segment, KYC-tier or structured profile change is pending a second pair of eyes
          content:
            application/json:
              schema:
                type: object
                required: [customer, approval]
                properties:
                  customer: { $ref: "#/components/schemas/Customer" }
                  approval: { $ref: "#/components/schemas/ApprovalRequest" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: |
            Another external_ref is already in use, or a governed customer-profile proposal is
            already pending for this customer.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/customers/{customerID}/profile:
    get:
      operationId: revealCustomerProfile
      tags: [Customers]
      summary: Reveal the mutable structured customer profile for correction
      description: |
        Returns only the structured facts supported by the governed maintenance workflow.
        Address is decrypted under the party's subject key, so this is separate from the
        ordinary customer workspace: opening the editor is an explicit sensitive read recorded
        both in the central access catalogue and as a field-specific `pii.read` event.

        `legacy_address`, when present, is an older free-text value retained for readability. A
        correction must submit a structured `address`; Nigerian addresses are resolved to the
        embedded NBS state/LGA catalogue and stored as canonical codes.

        Identifiers and document content are absent by design and cannot be changed here.
      x-permission: onboarding.customer.write
      parameters:
        - { $ref: "#/components/parameters/CustomerID" }
      responses:
        "200":
          description: The audited mutable-profile reveal
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CustomerProfile" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/customers/{customerID}/risk-assessments:
    get:
      operationId: listCustomerRiskAssessments
      tags: [Customers]
      summary: A customer's full rating history
      description: |
        `GET /v1/customers/{customerID}` returns only the LATEST risk assessment, because
        "why is this customer rated low today" is the question a customer profile answers
        first and making an analyst fetch a whole history for it would be wrong the other
        way. This is the history behind that one number.

        `app.risk_assessment` is append-only by design (BRD §8.2): a re-score writes a new
        row rather than overwriting the old one, so a rating from eighteen months ago, and
        the model version it was pinned to, is still readable exactly as it stood. Until this
        operation existed nothing on the API surface could reach any assessment but the
        latest — the history was always in the database and had no door.

        Each entry carries its own per-factor decomposition, the same shape the latest
        assessment on the customer response does, newest first.
      x-permission: onboarding.customer.read
      parameters:
        - { $ref: "#/components/parameters/CustomerID" }
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: The rating history, newest first
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RiskAssessmentPage" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/customers/{customerID}/exit:
    post:
      operationId: exitCustomer
      tags: [Customers]
      summary: Formally offboard an active customer relationship
      description: |
        Moves `onboarding_status` to `exited` — a value the CHECK constraint on
        `app.customer` has accepted since this platform's first onboarding migration, and
        that nothing, before this operation, could ever write.

        Only reachable from `active`. A relationship that never reached `active` is declined
        or rejected through the existing EDD and application-review paths, not exited: those
        are the record of a relationship that did not start, and this is the record of one
        that formally ended.

        `reason` is required. It is not routed through four-eyes the way a segment or
        KYC-tier change is (`PATCH /v1/customers/{customerID}`): exiting does not change what
        the platform measures the customer against, it stops measuring the customer at all,
        and the record of why is the required reason and the audit event this writes, the
        same shape `completeCustomerEDD`'s findings requirement already establishes for a
        judgement of this kind.
      x-permission: onboarding.customer.exit
      parameters:
        - { $ref: "#/components/parameters/CustomerID" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [reason]
              properties:
                reason: { type: string, minLength: 1 }
      responses:
        "200":
          description: The customer, now exited
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Customer" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: The customer is not active, so there is no relationship to exit.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/customers/{customerID}/assign:
    post:
      operationId: assignCustomerOrgUnit
      tags: [Customers]
      summary: Route a customer relationship to an owning branch or team
      description: |
        Sets or clears `assigned_org_unit_id`, the same organisational hierarchy
        `POST /v1/iam/org-units` builds and `PATCH /v1/iam/users/{userID}` already routes
        staff into — applied here to the customer relationship rather than to a member of
        staff.

        Send `org_unit_id` to assign, or `clear_org_unit` to unroute. The unit is validated
        by the composite tenant-carrying foreign key rather than by a lookup: a unit id from
        another tenant is refused the same way an unknown one is.

        Its own permission, separate from `onboarding.customer.write`: which desk owns a
        relationship is an operational routing decision, not a correction to the
        relationship's own data, and a tenant may reasonably grant one right without the
        other.
      x-permission: onboarding.customer.assign
      parameters:
        - { $ref: "#/components/parameters/CustomerID" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                org_unit_id: { type: string, format: uuid }
                clear_org_unit:
                  type: boolean
                  description: Detach the customer from any assigned org unit.
      responses:
        "200":
          description: The customer, with its assignment changed
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Customer" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "404":
          description: The customer does not exist, or org_unit_id names no unit in this tenant.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/cdd-forms:
    get:
      operationId: getCDDForm
      tags: [Customers]
      summary: The CDD questions in force for a customer type and tier
      description: |
        BRD §7.2-05 requires the CDD/EDD fields and required documents per customer type to be
        configurable without a deploy, so the form is a read rather than a static asset.

        The response carries the configuration provenance — `source` is `pack_default` or
        `tenant_override`, and `version` is the document version — so a submitted application
        records which form it was answering. Re-rendering a two-year-old application against
        today's definition would show a different set of questions than the customer actually
        saw.

        The active document is re-validated against the storage vocabulary on the way out. A
        form containing a field the platform cannot store is refused HERE rather than at submit
        time with a customer at the counter (ADR-0024).
      x-permission: onboarding.customer.read
      parameters:
        - name: customer_type
          in: query
          required: true
          schema: { type: string }
          description: "`individual` or `corporate` in the shipped document (Q27)."
        - name: tier
          in: query
          required: true
          schema: { type: string, enum: [tier_1, tier_2, tier_3, corporate] }
      responses:
        "200":
          description: The resolved form
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CDDForm" }
        "404":
          description: The document defines no such customer type or tier. The message names what it does define.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/reference-data/nigeria-locations:
    get:
      operationId: getNigeriaLocations
      tags: [Customers]
      summary: Read the Nigerian state, LGA and FCT area-council catalogue
      description: |
        Returns the one immutable NBS-coded catalogue used by onboarding validation. Source
        labels are preserved verbatim; explicitly recorded constitutional aliases are metadata,
        not a claim that Veyndi has corrected the source. The response distinguishes the six
        FCT area councils from state LGAs and carries source URLs plus the exact embedded-dataset
        digest so an application can prove which vocabulary it displayed.
      x-permission: onboarding.customer.read
      responses:
        "200":
          description: Nigerian location reference data and provenance
          content:
            application/json:
              schema: { $ref: "#/components/schemas/NigeriaLocationCatalog" }

  /v1/customers/{customerID}/edd:
    post:
      operationId: completeCustomerEDD
      tags: [Customers]
      summary: Complete an enhanced due diligence review
      description: |
        `app.customer.edd_completed_at` had no writer at all, in any deployment, by any route —
        so a customer whom risk scoring moved into `pending_edd` could never leave that state,
        and "EDD is triggered automatically for high-risk customers" was true and useless.

        The resulting onboarding status is derived from `outcome` server-side and is not a field
        on this request: letting a caller name the resulting state is how a declined EDD becomes
        an active account. `cleared` activates the customer; `declined` rejects them.

        Findings are required. An enhanced due diligence review that concluded nothing in writing
        did not happen, and this text is what an examiner reads when asking why a high-risk
        customer was accepted. A database CHECK pairs the completion timestamp with the actor, so
        a background job cannot sign one off — enhanced due diligence is a judgement.
      x-permission: onboarding.customer.edd
      parameters:
        - { $ref: "#/components/parameters/CustomerID" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [outcome, findings]
              properties:
                outcome: { type: string, enum: [cleared, declined] }
                findings: { type: string, minLength: 1 }
      responses:
        "200":
          description: The customer in its new state
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Customer" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: |
            The customer is not in a state this completes from — not flagged for EDD, or already
            completed. The message says which, because "not found" would send a compliance officer
            looking for a customer who is right there.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/customers/{customerID}/beneficial-owners:
    post:
      operationId: declareBeneficialOwners
      tags: [Customers]
      summary: Declare a corporate customer's beneficial owners
      description: |
        Direct capture is an onboarding-only writer, available while the customer is `draft` or
        `pending_documents`. Once review can have begun, a beneficial-owner mutation must use
        the encrypted customer-profile change and maker-checker approval workflow; this endpoint
        refuses rather than bypassing that control.

        A declaration, not a verification: it records what the customer told the institution.
        `owns_party_id` is how a chain is expressed — omit it and the owner holds a stake in the
        customer itself, set it and the owner holds a stake in another party already in the
        chain, which is what makes the resolver return more than a flat list.

        Direct stakes are summed across declarations and refused past 100%. Every mutation
        invalidates the prior register attestation and active-edge verification before writing,
        because a checker did not examine the changed ownership graph.
      x-permission: onboarding.ownership.write
      parameters:
        - { $ref: "#/components/parameters/CustomerID" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [owners]
              properties:
                owners:
                  type: array
                  minItems: 1
                  maxItems: 100
                  items:
                    type: object
                    properties:
                      existing_party_id:
                        type: string
                        format: uuid
                        description: |
                          Attaches an owner the platform already holds, which is how a screened
                          counterparty becomes a recorded owner without being duplicated.
                      kind: { type: string, enum: [natural, legal] }
                      display_name: { type: string }
                      owns_party_id:
                        type: string
                        format: uuid
                        description: Which party in the chain this owner owns. Absent means the customer itself.
                      ownership_pct:
                        type: number
                        description: |
                          The direct stake, 0 exclusive to 100. Omitted rather than zero for a
                          controlling director with no shareholding: that is a real case and it is
                          not a 0% owner.
                      control_type: { type: string }
                      identifiers:
                        type: array
                        items:
                          type: object
                          required: [scheme, value]
                          properties:
                            scheme: { type: string, enum: [BVN, NIN, CAC, TIN, PASSPORT, SCUML, DRIVERS_LICENCE, VOTERS_CARD, OTHER] }
                            value: { type: string }
                      attributes:
                        type: object
                        additionalProperties: { type: string }
      responses:
        "201":
          description: The resolved ownership chain, which may be longer than what was declared
          content:
            application/json:
              schema:
                type: object
                required: [beneficial_owners]
                properties:
                  beneficial_owners:
                    type: array
                    items: { $ref: "#/components/schemas/BeneficialOwner" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: |
            That party is already a declared direct owner, or onboarding has progressed beyond
            direct capture and the governed customer-profile change workflow is required.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/customers/{customerID}/beneficial-owners/verification:
    post:
      operationId: verifyBeneficialOwners
      tags: [Customers]
      summary: Record that a declared ownership register was checked against evidence
      description: |
        A separate right from declaring the register, deliberately: the declaration is what the
        customer said and the verification is what the institution confirmed, and one person
        holding both makes the second a formality.

        BRD §8.1 requires beneficial ownership "capture and verification" and does not say what
        verification is. Each value of `method` is a human attesting they compared the declared
        register against a document they held; none is a direct registry query, because the
        integrations adapter that would make one does not exist. Whether CBN requires a direct
        CAC check is a legal interpretation rather than a default this API gets to write (Q28).

        `reference` is required: a verification with no evidence reference is a boolean somebody
        set.
      x-permission: onboarding.ownership.verify
      parameters:
        - { $ref: "#/components/parameters/CustomerID" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [method, reference]
              properties:
                method:
                  type: string
                  enum: [board_resolution_and_id, cac_status_report, certified_ubo_register]
                reference: { type: string, minLength: 1 }
      responses:
        "200":
          description: The corporate profile with its verification provenance
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CorporateProfile" }
        "404": { $ref: "#/components/responses/NotFound" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/customers/{customerID}/identifiers/reveal:
    post:
      operationId: revealCustomerIdentifiers
      tags: [Customers]
      summary: Decrypt an active customer's identifiers
      description: |
        `GET /v1/onboarding/applications/{applicationID}` reveals an applicant's identifiers
        exactly once, at review. Nothing gave that same audited reveal to an MLRO investigating
        a case, or answering a supervisory or regulatory request, against a customer who has
        been active for two years — the front office's one look at the counter was the only
        reveal this platform could ever produce for a relationship's whole lifetime.

        `RevealIdentifiers` (the same method the application review calls) already writes its
        own `pii.read` audit event on every call, unconditionally — this endpoint adds no
        further permission check inside the transaction beyond the one this operation declares,
        because the decryption and its log entry are one atomic act, not two.

        A crypto-shredded subject's identifiers come back as an empty list rather than a 404
        or an error: the customer relationship and its audit history survive an NDPA erasure,
        the identity fields behind it do not (Q5). No amount of holding this permission
        resurrects a destroyed key.
      x-permission: onboarding.identifiers.reveal
      parameters:
        - { $ref: "#/components/parameters/CustomerID" }
      responses:
        "200":
          description: The customer's identifiers, with `value` populated
          content:
            application/json:
              schema:
                type: object
                required: [identifiers]
                properties:
                  identifiers:
                    type: array
                    items: { $ref: "#/components/schemas/PartyIdentifier" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/onboarding/applications/{applicationID}:
    get:
      operationId: reviewOnboardingApplication
      tags: [Customers]
      summary: A submitted CDD application, with the applicant's identifiers revealed
      description: |
        The second pair of eyes on an application. Loading one DECRYPTS the applicant's
        identifiers and therefore writes a `pii.read` event into the hash chain (ADR-0019), which
        is why it carries its own permission rather than riding on the customer read: approving an
        application whose BVN nobody could read is the same defect as approving a form whose
        answers cannot be stored — a control exercised on something nobody examined.

        `submitted_data` is the answer set exactly as it arrived, against the form version named
        on the record, so the application can be re-rendered as the customer saw it.

        A crypto-shredded subject comes back with no identifiers rather than an error: the
        application and the relationship survive an NDPA erasure; the identity behind them does
        not (Q5).

        **Opening an application under review SCREENS its subject** (`mode: onboarding`), and the
        result comes back on `screening`. That is where BRD §8.4's screening-at-onboarding
        happens: the review is the moment the control is exercised, so the hits arrive in the same
        payload as the decrypted identifiers and a checker reads the name, the BVN and what the
        lists say in one pass. A decided application is not re-screened — reading a historical
        record is not a control — and a screening failure does not block the review; it comes back
        as `screening_unavailable` with the reason, so "not screened" can never read as "clear".

        The first successful onboarding run is pinned to the application. Reopening the review
        does not manufacture duplicate runs or hits; analysts decide the pinned run's hits in the
        screening queue and approval remains blocked until none are unresolved.
      x-permission: onboarding.application.review
      parameters:
        - { $ref: "#/components/parameters/ApplicationID" }
      responses:
        "200":
          description: The application, its subject and the identity data a checker needs
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApplicationReview" }
        "404": { $ref: "#/components/responses/NotFound" }
        "410":
          description: The subject's key was destroyed under a data-subject erasure request.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/onboarding/applications/{applicationID}/documents:
    post:
      operationId: uploadOnboardingDocument
      tags: [Customers]
      summary: Upload immutable CDD evidence
      description: |
        Stores an encrypted PDF or image against the document requirements snapshotted when the
        application was submitted. The object store receives ciphertext under an opaque,
        server-generated key; the database records a plaintext SHA-256 digest and encrypted
        storage reference. Reusing the same UUID `Idempotency-Key` with the same bytes returns the
        same record, while reusing it for different evidence is refused.
      x-permission: onboarding.customer.write
      parameters:
        - { $ref: "#/components/parameters/ApplicationID" }
        - name: Idempotency-Key
          in: header
          required: true
          schema: { type: string, format: uuid }
        - name: doc_type
          in: query
          required: true
          schema: { type: string }
        - name: filename
          in: query
          required: true
          schema: { type: string, maxLength: 255 }
        - name: expires_on
          in: query
          schema: { type: string, format: date }
      requestBody:
        required: true
        content:
          application/pdf:
            schema: { type: string, format: binary, maxLength: 20971520 }
          image/jpeg:
            schema: { type: string, format: binary, maxLength: 20971520 }
          image/png:
            schema: { type: string, format: binary, maxLength: 20971520 }
      responses:
        "201":
          description: Evidence stored, encrypted and linked to the application
          content:
            application/json:
              schema: { $ref: "#/components/schemas/OnboardingDocument" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409": { $ref: "#/components/responses/Conflict" }
        "413":
          description: Document exceeds the 20 MiB evidence limit
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "415":
          description: Only PDF, JPEG and PNG evidence is accepted
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/onboarding/documents/{documentID}/content:
    get:
      operationId: downloadOnboardingDocument
      tags: [Customers]
      summary: Download and audit access to CDD evidence
      description: |
        Decrypts the immutable object, verifies its SHA-256 digest and writes a `pii.read` event
        in the same transaction. The response media type is the one recorded at upload.
      x-permission: onboarding.application.review
      parameters:
        - name: documentID
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Original evidence bytes
          headers:
            Digest:
              description: RFC Digest header containing the verified SHA-256 bytes in base64.
              schema: { type: string, example: "sha-256=47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=" }
          content:
            application/pdf: { schema: { type: string, format: binary } }
            image/jpeg: { schema: { type: string, format: binary } }
            image/png: { schema: { type: string, format: binary } }
        "404": { $ref: "#/components/responses/NotFound" }
        "410":
          description: The subject's key was destroyed under an erasure request
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/onboarding/documents/{documentID}/decision:
    post:
      operationId: decideOnboardingDocument
      tags: [Customers]
      summary: Verify or reject one evidence object
      description: |
        A maker-checker decision: the uploader cannot verify or reject their own object. Evidence
        is immutable; a rejected object remains in history and the front office uploads a new one.
      x-permission: onboarding.application.decide
      parameters:
        - name: documentID
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [decision]
              properties:
                decision: { type: string, enum: [verified, rejected] }
                reason: { type: string, description: Required when rejected. }
      responses:
        "200":
          description: Evidence decision recorded
          content:
            application/json:
              schema: { $ref: "#/components/schemas/OnboardingDocument" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409": { $ref: "#/components/responses/Conflict" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/onboarding/applications/{applicationID}/decision:
    post:
      operationId: decideOnboardingApplication
      tags: [Customers]
      summary: Approve or reject a customer application
      description: |
        Enforces maker-checker. Approval is fail-closed and atomic: every required document must
        be verified and unexpired, the pinned onboarding screening run must have no unresolved
        hit, a fresh explainable risk assessment is written and applied, then the relationship
        moves to `active` or `pending_edd`. Rejection requires a written reason and moves the
        relationship to `rejected`.
      x-permission: onboarding.application.decide
      parameters:
        - { $ref: "#/components/parameters/ApplicationID" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [decision]
              properties:
                decision: { type: string, enum: [approve, reject] }
                reason: { type: string, description: Required when rejected; optional approval note. }
      responses:
        "200":
          description: Application and customer state after the decision
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApplicationDecision" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: Maker-checker violation, missing evidence, unresolved screening hits or stale state
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/privacy/erasures:
    get:
      operationId: listErasureRequests
      tags: [Privacy]
      summary: List data-subject erasure requests
      x-permission: privacy.request.read
      parameters:
        - name: status
          in: query
          schema: { type: string, enum: [pending_review, approved, refused, executed] }
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
        - {name: sort, in: query, schema: {type: string, enum: [received_at_desc, received_at_asc], default: received_at_desc}}
      description: Global received_at and ID tuple order, newest by default. Cursors bind institution, request kind, current status filter and selected order; old cursor walks must restart.
      responses:
        "200":
          description: Erasure request queue
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErasureRequestPage" }
    post:
      operationId: createErasureRequest
      tags: [Privacy]
      summary: Record an erasure request and restrict the subject pending review
      description: |
        Creates a maker-checker proposal. Recording the request does not decide Q5 and does not
        destroy data. The linked party becomes `restricted` until a second authorised actor
        approves or refuses it.
      x-permission: privacy.erasure.create
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ErasureRequestCreate" }
      responses:
        "202":
          description: Recorded and awaiting a different reviewer's decision
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErasureRequest" }
        "409": { $ref: "#/components/responses/Conflict" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/privacy/erasures/{erasureID}:
    get:
      operationId: getErasureRequest
      tags: [Privacy]
      summary: Read an erasure request and immutable history
      x-permission: privacy.request.read
      parameters:
        - name: erasureID
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Erasure request
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErasureRequest" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/privacy/erasures/{erasureID}/execute:
    post:
      operationId: executeErasureRequest
      tags: [Privacy]
      summary: Execute an approved erasure if no hold blocks it
      description: |
        Fails closed while any hold is active or release-pending. Otherwise destroys the wrapped
        subject DEK and redacts mutable plaintext onboarding PII. AML transaction, screening,
        risk, alert, case, report and audit skeletons remain; the audit hash chain is never
        rewritten. Repeating a completed execution is idempotent.
      x-permission: privacy.erasure.execute
      parameters:
        - name: erasureID
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Executed request, or the already-executed request on a retry
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErasureRequest" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: Not approved, or blocked by an active/release-pending legal hold
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/privacy/authority-requests:
    get:
      operationId: listAuthorityRequests
      tags: [Privacy]
      summary: List authority requests and legal-hold state
      x-permission: privacy.request.read
      parameters:
        - name: status
          in: query
          schema: { type: string, enum: [pending_review, active, refused, release_pending, released] }
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
        - {name: sort, in: query, schema: {type: string, enum: [received_at_desc, received_at_asc], default: received_at_desc}}
      description: Global received_at and ID tuple order, newest by default. Cursors bind institution, request kind, current status filter and selected order; old cursor walks must restart.
      responses:
        "200":
          description: Authority request queue
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AuthorityRequestPage" }
    post:
      operationId: createAuthorityRequest
      tags: [Privacy]
      summary: Record an authority request and propose subject holds
      description: |
        Creates pending hold rows and a maker-checker proposal. Holds become active only after a
        different authorised reviewer approves. This is neutral intake, not an EFCC schema,
        authenticity attestation, or direct submission mechanism (Q34).
      x-permission: privacy.authority.create
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/AuthorityRequestCreate" }
      responses:
        "202":
          description: Recorded and awaiting activation review
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AuthorityRequest" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/privacy/authority-requests/{authorityRequestID}:
    get:
      operationId: getAuthorityRequest
      tags: [Privacy]
      summary: Read an authority request, holds and immutable history
      x-permission: privacy.request.read
      parameters:
        - name: authorityRequestID
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Authority request
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AuthorityRequest" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/privacy/authority-requests/{authorityRequestID}/release:
    post:
      operationId: proposeAuthorityRelease
      tags: [Privacy]
      summary: Propose release of every hold on an authority request
      description: |
        Release is itself maker-checker governed. Until a different authorised actor approves,
        every linked hold remains blocking; a refused release restores `active`.
      x-permission: privacy.legal_hold.release
      parameters:
        - name: authorityRequestID
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [reason]
              properties:
                reason: { type: string, minLength: 1 }
      responses:
        "202":
          description: Release proposed and holds still blocking
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AuthorityRequest" }
        "409": { $ref: "#/components/responses/Conflict" }

  /v1/privacy/authority-requests/{authorityRequestID}/response-exports:
    post:
      operationId: exportAuthorityResponse
      tags: [Privacy]
      summary: Generate and retain a hashed evidence manifest
      description: |
        Returns a neutral inventory with per-domain record counts, SHA-256 digests, scope and
        provenance. It is auditable and reproducible, but intentionally is not an invented EFCC
        payload and performs no external submission.
      x-permission: privacy.authority.response_export
      parameters:
        - name: authorityRequestID
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "201":
          description: Recorded response-package manifest
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AuthorityResponsePackage" }
        "409": { $ref: "#/components/responses/Conflict" }

  /v1/privacy/authority-requests/{authorityRequestID}/response-exports/{exportID}:
    get:
      operationId: getAuthorityResponseExport
      tags: [Privacy]
      summary: Read an exact previously generated evidence manifest
      description: The stored JSON is the same manifest whose SHA-256 was recorded and audited at generation.
      x-permission: privacy.authority.response_export
      parameters:
        - name: authorityRequestID
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: exportID
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Stored response-package manifest
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AuthorityResponsePackage" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/privacy/subjects/{partyID}/status:
    get:
      operationId: getPrivacySubjectStatus
      tags: [Privacy]
      summary: Read a subject's restricted/erased state and hold count
      description: |
        This endpoint is intentionally protected by `privacy.request.read`, not customer read.
        Front-office roles cannot infer that an authority has placed a customer on hold (Q34).
      x-permission: privacy.request.read
      parameters:
        - name: partyID
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Privacy and hold status
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PrivacySubjectStatus" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/identifiers/verify:
    post:
      operationId: verifyIdentifier
      tags: [Customers]
      summary: Verify a captured identifier against its authoritative source
      description: |
        **This operation answers `503` unless an identity provider is configured. No
        production NIBSS/NIMC provider ships with this build, and that refusal is the honest
        state rather than a bug.**

        BRD §8.1 requires "BVN/NIN verification integration". The provider registry and bounded
        adapter seam exist, but there is no production NIBSS adapter, NIMC adapter, credentials
        or commercial agreement. No authority is invented here. A deterministic mock may be
        enabled only outside production; its result is stored with `verification_assurance=mock`
        and cannot satisfy the CBN approval gate.

        It is documented and routed rather than omitted for two reasons. The refusal becomes a
        machine-readable state of the product instead of a `404` that reads as "we forgot"; and
        the generated client carries the shape a real answer will have, so integrating a provider
        is a server change rather than a contract change.

        What this replaces was worse than absent. `verified_by_source` used to be filled from a
        string the CALLER supplied, so a front-office user could type "NIBSS" beside a number
        nobody had checked and every screen and every examiner afterwards read a verified
        identifier. That field is now unreachable from the write path. The service refuses BEFORE
        decrypting anything, so no PII access is logged for a call that could never succeed.

        See open question Q26 for the remaining provider procurement, credential, retry and
        operational-ownership decisions. An outage may leave capture pending, but it cannot be
        presented as an authoritative verification or activate the relationship.
      x-permission: onboarding.customer.write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [party_id, scheme]
              properties:
                party_id: { type: string, format: uuid }
                scheme:
                  type: string
                  enum: [BVN, NIN, CAC]
                  description: BVN against NIBSS, NIN against NIMC, CAC against the Corporate Affairs Commission.
      responses:
        "200":
          description: The identifier, now carrying the authority that verified it
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PartyIdentifier" }
        "404": { $ref: "#/components/responses/NotFound" }
        "422": { $ref: "#/components/responses/ValidationFailed" }
        "503":
          description: |
            No verification provider is configured. The identifier stays captured and UNVERIFIED,
            which is the true state (Q26).
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/screening/runs:
    post:
      operationId: runScreening
      tags: [Screening]
      summary: Screen a name against the published watchlist index
      description: |
        **The only way to screen a name in this product.**

        Everything downstream of a screening hit shipped before this endpoint did. The
        IDF-weighted matcher, the corroboration adjustment, the per-tenant policy resolution,
        the watchlist version pinning, the four-eyes suppression and the audit chaining are all
        built and tested — and `Screening.Screen` had exactly one non-test caller in the
        repository, the demo seeder. Every screening hit that existed in this product had been
        manufactured by a fixture, and a compliance officer handed a name by a correspondent
        bank had no answer from it. BRD §8.4 requires the capability; nothing could invoke it.

        It works today against the institution's own internal lists, which need no licence, and
        it works unchanged the day a licensed sanctions feed is registered (Q6).

        ### There is no allow/deny field, deliberately

        Q7 — "is real-time screening blocking a payment authorization?" — is still open. Its
        implemented default is a synchronous endpoint with a per-tenant timeout **and** an
        explicit per-tenant fail-open/fail-closed policy that "must be the client's documented,
        signed choice, surfaced in the admin console rather than buried in a config file". The
        timeout half is built; the policy half is not. An endpoint answering `decision: allow`
        would imply a posture nobody has agreed to, and would make the *absence of a hit* look
        like a positive clearance. `POST /v1/transactions` withholds a decision for the same
        reason and in the same words.

        So this returns what it knows: which entries matched, how strongly, on which pinned
        list version, and what corroborated or contradicted each one. Whether a payment stops
        is the caller's policy decision, with somewhere left for Q7's answer to land.

        ### The deadline

        Bounded by `screening.match.timeout_ms`, the per-tenant budget (default 2000 ms, BRD
        §9's sub-two-second figure). It is applied as a context deadline covering the whole
        request, so exceeding it cancels the database work and releases the pool connection
        instead of leaving a query running behind a caller who has given up. Nothing is
        committed when it fires — a request row without its hits would read as a run that found
        nothing — so a `503` here is never evidence that a name is clear, and retrying is safe.

        ### Not idempotent, and deliberately not

        A run is a stored resource with its own id, its snapshotted policy and its latency, and
        it is the row a filing cites two years later. The same name screened twice against a
        list that changed in between is two compliance events and both must exist, so this
        endpoint takes no `Idempotency-Key` and collapses nothing.

        `identifiers` is not accepted. `ScreenInput` carries no identifier field and the
        corroboration code never assigns an identifier result, so the field would be inert —
        and an inert field advertising a check nobody performs is worse than an absent one.
      x-permission: screening.run.create
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name, mode]
              properties:
                party_id:
                  type: string
                  format: uuid
                  description: |
                    Optional: the subject of a run is often not a customer. When present it is
                    load-bearing — an approved match suppression applies per party, so it is
                    what stops an analyst clearing the same false hit every morning.
                name:
                  type: string
                  description: |
                    The subject name. The only thing matched on: the index is names and
                    aliases, and every other field here corroborates or contradicts a name that
                    already matched.
                date_of_birth:
                  type: string
                  format: date
                  description: |
                    ISO-8601 calendar date, `YYYY-MM-DD`. Refused in any other notation rather
                    than ignored, because it is compared as a string and an unreadable date
                    scores as a MISMATCH — taking the full penalty off the score and suppressing
                    the very hit it was sent to strengthen. Entries carrying only a year are
                    handled: the comparison falls back to the year, from this same value.
                nationality:
                  type: string
                  description: |
                    Corroboration only, compared case-insensitively against the list entry's own
                    value. It can only add a bonus on a match, never subtract, which is why it
                    is not format-checked the way `date_of_birth` is.
                mode:
                  type: string
                  enum: [onboarding, ongoing, realtime, batch, adhoc]
                  description: |
                    Why this name is being screened. Required rather than defaulted: it is
                    stored on the run and is the difference between evidence that a customer was
                    screened at onboarding and a note that somebody looked a name up.
      responses:
        "201":
          description: |
            The run, its hits, and what the engine actually did. `201` because a run is a stored
            resource, not a repeatable read.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ScreeningResult" }
        "409":
          description: |
            No watchlist has been published, so there was nothing to screen against. An error
            rather than an empty result: reporting "no hits" when no list exists is a silent
            compliance failure.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "422": { $ref: "#/components/responses/ValidationFailed" }
        "503":
          description: |
            The run exceeded this tenant's `screening.match.timeout_ms` budget and was rolled
            back. Nothing was recorded, so this is not evidence that the name is clear. Retrying
            is safe.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/screening/hits:
    get:
      operationId: listScreeningHits
      tags: [Screening]
      summary: Sanctions and PEP screening hits
      x-permission: screening.hit.read
      parameters:
        - name: sort
          in: query
          description: Server ordering applied before pagination; changing it starts a new cursor walk.
          schema: { type: string, enum: [created_at_desc, created_at_asc, score_desc] }
        - name: assignee
          in: query
          description: Filter to the current user; accepts me or their own actor UUID
          schema: {type: string}
        - name: decision
          in: query
          schema: { type: string, enum: [pending, true_positive, false_positive, suppressed] }
        - name: party_id
          in: query
          description: |
            Narrows the queue to the hits raised against one party, matched on the party of the
            screening request rather than on the hit. This is what a customer screen asks for;
            without it the only way to show one customer's matches is to read the whole tenant's
            queue and filter client-side, which silently goes wrong at the first page boundary.
            A value that is not a UUID is a 400, not an ignored filter.
          schema: { type: string, format: uuid }
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: Hits in the requested server order, newest first by default
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ScreeningHitPage" }

  /v1/screening/hits/{hitID}/occurrences:
    get:
      operationId: listScreeningHitOccurrences
      tags: [Screening]
      x-permission: screening.hit.read
      summary: List the requests sharing an unresolved counterparty hit
      description: Each occurrence preserves its request and match evidence. Adjudicated hits are never reused for a different name-only request.
      parameters:
      - name: hitID
        in: path
        required: true
        schema: { type: string, format: uuid }
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: Occurrences ordered newest first
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ScreeningHitOccurrencePage' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }

  /v1/screening/hits/{hitID}:
    get:
      operationId: getScreeningHit
      tags: [Screening]
      summary: One screening hit, with the evidence behind it
      description: |
        The hit workspace. The queue row carries two names, a score and three corroboration
        pills, which is enough to sort work and not enough to decide any of it — declaring a
        customer a sanctions match commits the institution to freezing assets and to filing.

        Five things come back together, because a decision assembled from five screens is a
        decision most analysts take from the first one:

          `hit`      the match, including the identity of the listed party SNAPSHOTTED at
                     match time. Those fields are absent on a hit raised before the snapshot
                     existed, which is a real state and not a null to paper over.
          `entry`    the watchlist entry as the list holds it TODAY, with every recorded
                     spelling and the corroboration attributes the score was computed from.
                     Where this disagrees with the snapshot on `hit`, the difference is
                     itself evidence — a delisting, or a corrected programme — and a screen
                     must label which of the two it is showing.
          `version`  the published list version the hit is pinned to. This is what makes
                     "which list, as it stood when" answerable about a filing years later.
          `request`  the run: its mode, its latency, and the POLICY DOCUMENT snapshotted when
                     it ran. That last one is what answers "what threshold was in force when
                     this ran" — the configuration may have been retuned since, and reading
                     it live would answer a different question.
          `party`    the subject's own profile. ABSENT, not null, when the run screened a
                     free-text counterparty with no party row — a name off a payment message
                     is the common case — and also when the party cannot be read.
      x-permission: screening.hit.read
      parameters:
        - { $ref: "#/components/parameters/HitID" }
      responses:
        "200":
          description: The hit, the listed party, the version pin and the run
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ScreeningHitDetail" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/screening/hits/{hitID}/decision:
    post:
      operationId: decideScreeningHit
      tags: [Screening]
      summary: Clear or confirm a screening hit
      description: |
        Confirming a match escalates it, in the transaction that records the decision: a KYC
        review is raised against the customer with reason `screening_hit` (BRD §8.1, §8.4) and
        the subject is re-scored with trigger `screening_hit` and the hit id as the trigger
        reference (BRD §8.2). Clearing a hit does neither — the analyst has just said this is
        not the listed person.

        Nothing in that escalation can fail the decision. The states that would stop it — no
        party behind the hit, no customer behind the party, a review already outstanding, no
        active risk model — are ordinary, are detected before anything is written, and are
        reported in `escalation_skipped` rather than raised. What remains is the database
        failing, and that fails the request, leaves the hit `pending` and is safe to retry.
      x-permission: screening.hit.decide
      parameters:
        - { $ref: "#/components/parameters/HitID" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [decision]
              properties:
                decision: { type: string, enum: [true_positive, false_positive] }
                note:
                  type: string
                  description: Why. A cleared hit with no rationale is not a decision, it is a dismissal.
      responses:
        "200":
          description: |
            The decision and what it obliged. Previously a 204, which made the escalation
            invisible to the analyst who caused it.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ScreeningDecision" }
        "202":
          description: |
            The clearance was sent for approval and has NOT been applied. The hit is still
            pending and nothing was escalated. Track `request_id` through `/v1/approvals`.
          content:
            application/json:
              schema:
                type: object
                required: [request_id, action_key, hit_id, decision, reason]
                properties:
                  request_id: { type: string, format: uuid }
                  action_key: { type: string, enum: [screening.hit.decide] }
                  hit_id: { type: string, format: uuid }
                  decision: { type: string, enum: [false_positive] }
                  reason:
                    type: string
                    description: |
                      Why this clearance was held, in the words to show the analyst — which list
                      kind or which band did it. A four-eyes refusal that says only "approval
                      required" is one analysts learn to route around.
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: |
            The hit has already been decided. Reopen it to decide it again — this used to be a
            `404`, which told an analyst that a match they were looking at did not exist.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/screening/hits/{hitID}/reopen:
    post:
      operationId: reopenScreeningHit
      tags: [Screening]
      summary: Return a decided screening hit to the review queue
      description: |
        Undoes a determination. The hit returns to `pending`, and its decision, author,
        timestamp and rationale are cleared from the row — the audit chain
        (`screening.hit.reopened`) becomes the only record of what was decided, which is why the
        reason is mandatory.

        It exists because a determination used to be final: the decision UPDATE is guarded by
        `AND decision = 'pending'`, so a `true_positive` recorded by a mis-click could not be
        undone through any surface of this product, and every attempt answered "not found".

        Reopening DECIDES nothing. The hit returns to the state in which the four-eyes gate on
        clearances applies again in full, so it cannot be used to walk a clearance past a
        checker. It carries its own permission, granted more narrowly than
        `screening.hit.decide`, because erasing a determination is a larger capability than
        making one.

        The review deadline is deliberately NOT reset: a hit raised on Monday and reopened on
        Friday is immediately in breach, which is the truth. Restarting the clock would make
        decide-then-reopen a way to clear an SLA breach without reviewing anything.

        Refused with `409` on a hit that is already pending, and on a `suppressed` one: a
        suppression is a standing approved decision, and the way to undo it is to revoke the
        suppression rather than to reopen the hit it silenced.
      x-permission: screening.hit.reopen
      parameters:
        - { $ref: "#/components/parameters/HitID" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [reason]
              properties:
                reason:
                  type: string
                  description: |
                    Why the determination is being undone. Written to the audit chain beside the
                    decision it displaced.
      responses:
        "204":
          description: |
            The hit is back in the queue. No body: nothing was decided, and a hit built from
            this UPDATE could not carry `party_id` or `mode` — read it from the queue instead.
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: The hit is pending, or is suppressed rather than decided.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/screening/hits/{hitID}/suppress:
    post:
      operationId: proposeMatchSuppression
      tags: [Screening]
      summary: Propose that a cleared match stops being raised
      description: |
        This does not suppress anything. It records a maker-checker proposal; a different,
        role-authorised user approves it through `/v1/approvals/{approvalID}/approve`, and the
        suppression is written inside that approval's transaction.

        Deciding a hit answers "is this customer that listed person, today". A suppression
        answers it for every screening run until it expires, which is why it is a two-step
        control rather than a second button beside the decision. `app.match_suppression`
        requires two distinct people in a CHECK constraint, and both ids are taken from the
        approval record: the maker from the request, the checker from its decision. Neither
        can be named in a request body, which is the defect migration 00013 closed on case
        closure and migration 00016 recorded as still open here.

        **Nothing identifying is read from the body.** The party, the watchlist and the
        matched entry's external id are resolved server-side from the hit itself. A caller
        able to name the party could stop the institution screening a customer of their
        choosing, and the evidence of that would be an absence of hits nobody is looking for.

        The hit must already be decided `false_positive` by a named user: a suppression makes
        a REVIEWED determination durable, and one raised on a pending hit would silence a
        match before anybody examined it. It also needs a customer — a hit from an ad-hoc name
        screening has no party, and a suppression keyed to a name alone would silence the
        match for everyone who shares it.
      x-permission: screening.match.suppress
      parameters:
        - { $ref: "#/components/parameters/HitID" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [reason]
              properties:
                reason:
                  type: string
                  minLength: 1
                  description: |
                    Why this match is not this customer. It is what the approver reads before
                    deciding, and it is what an examiner asks about when they find a sanctions
                    match that stopped being raised.
                expires_in_days:
                  type: integer
                  minimum: 1
                  maximum: 730
                  description: |
                    How long the match stays silenced. Omit it for 365 days. There is no
                    permanent option: the underlying list entry changes beneath a suppression
                    and nothing puts it back on a queue, so one nobody revisits is a control
                    nobody operates (ADR-0015).
      responses:
        "202":
          description: The approval request awaiting a second pair of eyes
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApprovalRequest" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: |
            The hit is not a cleared false positive, it has no customer behind it, or a
            suppression proposal is already pending on it.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "422": { $ref: "#/components/responses/ValidationFailed" }
  /v1/screening/hits/{hitID}/assign:
    post:
      operationId: assignScreeningHit
      tags: [Screening]
      summary: Take a screening hit
      description: |
        Assigns the hit to the calling user. Self-assignment only, which is what a triage
        queue needs: an endpoint accepting an assignee would let one analyst push a sanctions
        review into another's queue with nothing having authorised it.

        Gated on screening.hit.decide rather than a separate key, mirroring
        monitoring.alert.triage, which covers both assign and close. Taking a match is the
        first act of reviewing it, and a role able to claim ownership of a sanctions review it
        cannot then complete is a worse arrangement than one permission for both.

        404 when the hit does not exist in this tenant OR has already been decided: a finished
        review is not assignable, and the caller must not be told an assignment happened that
        did not.
      x-permission: screening.hit.decide
      parameters:
        - { $ref: "#/components/parameters/HitID" }
      responses:
        "204": { description: Assigned }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/rules:
    get:
      operationId: listRules
      tags: [Monitoring]
      summary: The monitoring rule library and its active versions
      x-permission: rules.rule.read
      responses:
        "200":
          description: Rules with the version currently in force for each
          content:
            application/json:
              schema:
                type: object
                required: [rules, active_versions]
                properties:
                  rules: { $ref: "#/components/schemas/RulePage" }
                  active_versions: { $ref: "#/components/schemas/RuleVersionPage" }
    post:
      operationId: createRule
      tags: [Monitoring]
      summary: Create a monitoring rule and its first draft version
      description: |
        One request, because a rule with no version is not a rule: it is a name in a table the
        engine will never load, listed in the library, apparently installed and doing nothing.

        The version created is a DRAFT. Simulate it before proposing it for activation.
      x-permission: rules.rule.write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              allOf:
                - type: object
                  required: [key, name]
                  properties:
                    key:
                      type: string
                      minLength: 1
                      description: |
                        Stable, and what the threshold document names to configure this rule per
                        customer segment. Renaming it orphans its thresholds.
                    name: { type: string, minLength: 1 }
                    description: { type: string }
                - $ref: "#/components/schemas/RuleVersionDraft"
      responses:
        "201":
          description: The rule and its first draft version
          content:
            application/json:
              schema:
                type: object
                required: [rule, version]
                properties:
                  rule: { $ref: "#/components/schemas/Rule" }
                  version: { $ref: "#/components/schemas/RuleVersion" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/rules/vocabulary:
    get:
      operationId: getRuleVocabulary
      tags: [Monitoring]
      summary: The typed field vocabulary a rule may reference
      description: |
        What the rule builder's field picker is drawn from (ADR-0028).

        Served from the same table the expression validator refuses against and the evaluator
        binds at run time, so a field the form offers is necessarily a field a rule may name.
        Two hand-kept lists — one for the picker, one for the check — is how a builder comes to
        offer a field that fails on save.

        Thresholds are NOT in this catalogue. They are referenced as `params.<name>`, resolved
        per customer segment from the rule's configuration document, and are deliberately never
        literals in the expression (ADR-0016). Every statically named parameter and its CEL type
        are checked against the effective threshold document before proposal and activation; see
        the `note` in the response.
      x-permission: rules.rule.read
      responses:
        "200":
          description: The vocabulary, grouped by namespace
          content:
            application/json:
              schema:
                type: object
                required: [activation_version, namespaces, params_namespace, note]
                properties:
                  activation_version:
                    type: integer
                    description: |
                      The CEL variable set this build compiles rules against. A stored version
                      authored against a different one cannot be opened in the builder or
                      activated, and this is how a client explains why.
                  namespaces:
                    type: array
                    items: { $ref: "#/components/schemas/RuleVocabularyGroup" }
                  params_namespace: { type: string }
                  note: { type: string }

  /v1/rules/{ruleKey}/versions:
    get:
      operationId: listRuleVersions
      tags: [Monitoring]
      summary: A rule's version history
      description: |
        What is live, what was retired, and what somebody drafted and never activated — each
        with its condition tree, so the builder can open any of them.
      x-permission: rules.rule.read
      parameters:
        - name: ruleKey
          in: path
          required: true
          schema: { type: string }
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: The versions, newest first
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RuleVersionPage" }
    post:
      operationId: createRuleVersion
      tags: [Monitoring]
      summary: Draft a new version of a rule
      description: |
        Always a DRAFT. Nothing on this path can put a rule live: activation supersedes the
        version an institution's alerts already reference and is a four-eyes change (ADR-0008).

        Supply either a `condition_tree`, which is what the builder posts, or an `expression`,
        which is what an expert posts. Supplying both is allowed and checked — the tree is
        recompiled and a pair that disagree is refused, because a stored rule that shows one
        thing and runs another is worse than either alone.
      x-permission: rules.rule.write
      parameters:
        - name: ruleKey
          in: path
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/RuleVersionDraft" }
      responses:
        "201":
          description: The stored draft
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RuleVersion" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/rule-versions/{versionID}:
    get:
      operationId: getRuleVersion
      tags: [Monitoring]
      summary: One rule version, and whether the builder can render it
      description: |
        `editable` is ADR-0028's refusal made visible. An expression using a construct the
        condition tree cannot hold — a macro, a function call, arithmetic nested more than one
        level — comes back with `editable: false` and a reason, and the builder shows the
        expression read-only rather than rendering an approximation it would then save back
        over the author's rule.
      x-permission: rules.rule.read
      parameters:
        - name: versionID
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: The version, with its tree when one can be shown
          content:
            application/json:
              schema:
                type: object
                required: [version, editable, reason]
                properties:
                  version: { $ref: "#/components/schemas/RuleVersion" }
                  editable: { type: boolean }
                  reason:
                    type: string
                    description: Why the builder declines to render it, empty when it does not.
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/rule-versions/{versionID}/simulations:
    post:
      operationId: simulateRuleVersion
      tags: [Monitoring]
      summary: Replay a candidate rule over history without raising alerts
      description: |
        The endpoint the rule builder is built around (ADR-0016).

        A builder without a simulator lets an administrator activate a rule across a live book
        with no idea whether it will fire on nothing or on everything. Both are catastrophic and
        only one is visible: a rule that fires on nothing looks exactly like a clean book.

        It is the SAME EVALUATOR the ingest path runs, with window aggregates from the same
        query — ADR-0016 requires that, because an approximate simulator tells a compliance
        officer a comfortable lie about the alert volume they are about to create.

        It writes NO ALERTS. The only row it creates is the record of the question having been
        asked, which is what an examiner is looking for when they ask whether a rule was tested
        before it went live.

        POST rather than GET because it scans the ledger, writes that record, and moves a draft
        to `simulated`. It is not a safe, repeatable read.

        What it does not reproduce, stated because a silent difference is the failure mode:
        correlation and de-duplication (so `alerts_would_raise` counts firings and the number of
        triage-queue rows is lower — `distinct_subjects` is the honest lower bound), alert
        scoring and priority, and the per-segment enable switch.
      x-permission: rules.rule.simulate
      parameters:
        - name: versionID
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                from:
                  type: string
                  format: date-time
                  description: Defaults to 30 days before `to`.
                to:
                  type: string
                  format: date-time
                  description: Defaults to now.
                max_transactions:
                  type: integer
                  description: |
                    Bounds the scan. A simulation is a synchronous request on a latency budget,
                    and a rule proposed against five years of a retail bank's ledger would hold
                    a connection until it timed out with nothing to show. Truncation is reported
                    rather than hidden, because "12 alerts" from a truncated scan means nothing
                    and reads like a small number.
                sample_size:
                  type: integer
                  description: How many worked examples to return. The count says how many; the sample says on what.
      responses:
        "201":
          description: What the candidate would have done
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RuleSimulation" }
        "404": { $ref: "#/components/responses/NotFound" }
        "422": { $ref: "#/components/responses/ValidationFailed" }
    get:
      operationId: listRuleSimulations
      tags: [Monitoring]
      summary: Previous simulations of a candidate
      x-permission: rules.rule.simulate
      parameters:
        - name: versionID
          in: path
          required: true
          schema: { type: string, format: uuid }
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: The runs, newest first
          content:
            application/json:
              schema:
                type: object
                required: [items]
                properties:
                  items:
                    type: array
                    items: { $ref: "#/components/schemas/RuleSimulation" }
                  next_cursor: { $ref: "#/components/schemas/NextCursor" }
                  truncated: { $ref: "#/components/schemas/Truncated" }
                  truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
                  total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

  /v1/rule-versions/{versionID}/activation:
    post:
      operationId: proposeRuleActivation
      tags: [Monitoring]
      summary: Propose that a rule version go live
      description: |
        Proposes. It does not activate.

        Architectural mandate 8 requires four-eyes on rule changes, and the activation happens
        inside the APPROVING transaction (ADR-0008) — so approving and applying either both
        happen or neither does. An approval recorded against a change that failed to apply
        would be a lie in the audit trail.

        The rationale is required. A checker approving "activate rule version 7" with nothing
        else in front of them is a rubber stamp with an audit trail.
      x-permission: rules.rule.write
      parameters:
        - name: versionID
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [rationale]
              properties:
                rationale: { type: string, minLength: 1 }
      responses:
        "202":
          description: The approval request awaiting a second pair of eyes
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApprovalRequest" }
        "409": { $ref: "#/components/responses/Conflict" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/risk-models/active:
    get:
      operationId: getActiveRiskModel
      tags: [Monitoring]
      summary: The live customer risk-scoring model
      description: |
        As it was snapshotted at activation, not as configuration reads today. An assessment
        pins the model version it was scored under, so serving today's configuration here would
        misdescribe every rating computed before the last change.
      x-permission: rules.rule.read
      responses:
        "200":
          description: The active model version
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RiskModel" }
        "404":
          description: |
            No model has been activated. Fresh bootstrap intentionally reaches this state:
            signed but unvalidated pack metadata is projected as a blocked candidate, and a
            live model appears only after artifact-backed inventory and maker-checker approval.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/risk-models/activation:
    post:
      operationId: proposeRiskModelActivation
      tags: [Monitoring]
      summary: Propose a change to the customer risk-scoring model
      description: |
        Four-eyes, like a rule change and for a sharper reason: an assessment pins the model
        version it was scored under, so activating a model has no effect on past ratings and
        total effect on every future one.

        Input is an approved `inventory_version_id`. Its immutable candidate definition is
        loaded server-side and copied into the digest-bound approval payload, so an operator
        never pastes governed JSON a second time and an intervening inventory cannot be selected.
      x-permission: rules.risk_model.write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [inventory_version_id, rationale]
              additionalProperties: false
              properties:
                inventory_version_id:
                  type: string
                  format: uuid
                  description: Approved immutable risk-model inventory candidate to activate.
                rationale: { type: string, minLength: 1 }
      responses:
        "202":
          description: The approval request awaiting a second pair of eyes
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApprovalRequest" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/model-inventory:
    get:
      operationId: listModelInventory
      tags: [Monitoring]
      summary: Scenario and model inventory with active-asset coverage
      description: |
        Returns immutable approved inventory history and one coverage row for every active
        monitoring rule and risk model. A legacy active artifact without a pin is returned as
        `missing`; it is never omitted or described as clean. `evidence_integrity_verified` is
        derived from exact same-tenant finalized encrypted artifacts, never from caller metadata.
        It proves artifact integrity and authenticity, not the substantive independence or
        quality of the institution's validation assertion.
      x-permission: rules.inventory.read
      responses:
        "200":
          description: Inventory history, deployment coverage and explicit activation policy
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ModelInventoryResponse" }

  /v1/model-inventory/history:
    get:
      operationId: listModelInventoryHistory
      tags: [Monitoring]
      summary: Page immutable scenario and model inventory versions
      description: Newest-first keyset history ordered by `(created_at,id)`.
      x-permission: rules.inventory.read
      parameters:
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: Resumable immutable inventory history
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ModelInventoryVersionPage" }
        "400": { $ref: "#/components/responses/BadRequest" }

  /v1/model-inventory/deployments:
    get:
      operationId: listModelInventoryDeployments
      tags: [Monitoring]
      summary: Page immutable inventory deployment lifecycle events
      description: Newest-first keyset history ordered by `(deployed_at,id)`.
      x-permission: rules.inventory.read
      parameters:
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: Resumable activated and deactivated deployment events
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ModelInventoryDeploymentPage" }
        "400": { $ref: "#/components/responses/BadRequest" }

  /v1/model-inventory/coverage:
    get:
      operationId: listModelInventoryCoverage
      tags: [Monitoring]
      summary: Page fail-visible active scenario and model coverage
      description: |
        Stable `(asset_type,asset_key)` keyset coverage. Missing, stale, drifted and
        unverified active assets are returned explicitly rather than omitted.
      x-permission: rules.inventory.read
      parameters:
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: Resumable active-asset coverage
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ModelInventoryCoveragePage" }
        "400": { $ref: "#/components/responses/BadRequest" }

  /v1/model-inventory/rule-candidates:
    get:
      operationId: listRuleInventoryCandidates
      tags: [Monitoring]
      summary: Page exact monitoring-rule candidates for inventory proposals
      description: |
        Returns bounded selector metadata only; the proposal service reloads and digests the
        exact immutable rule version in its tenant transaction. In addition to the declared
        inventory-write permission, callers must hold `rules.inventory.read` and
        `rules.rule.read`; lacking either is refused before any database read.
      x-permission: rules.inventory.write
      parameters:
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: Newest-first keyset page of inventory-eligible rule-version addresses
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RuleInventoryCandidatePage" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/model-inventory/risk-model-candidates:
    get:
      operationId: listRiskModelActivationCandidates
      tags: [Monitoring]
      summary: Page governed risk-model candidates eligible for activation
      description: |
        Returns current, production-policy inventory candidates backed by finalized encrypted
        evidence artifacts. In addition to the declared risk-model-write permission, callers
        must hold `rules.inventory.read` and `rules.rule.read`; lacking either is refused before
        any database read. Activation reloads the exact definition server-side by inventory id.
      x-permission: rules.risk_model.write
      parameters:
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: Newest-first keyset page of governed activation candidates
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ModelInventoryVersionPage" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/model-inventory/proposals:
    post:
      operationId: proposeModelInventory
      tags: [Monitoring]
      summary: Propose an exact artifact-bound inventory version
      description: |
        Creates a maker-checker request; it does not create or attach an inventory row. The
        approved payload is bound to an exact rule-version digest or canonical risk-model
        definition. Activation remains a separate governed decision and fails closed until a
        current approved inventory version permits it. The declared inventory-write permission
        is necessary but not sufficient: monitoring-rule proposals also require
        `rules.rule.read`, while risk-model proposals also require `rules.risk_model.write`
        because their payload contains an executable model definition.
      x-permission: rules.inventory.write
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ModelInventoryProposal" }
      responses:
        "202":
          description: Inventory proposal awaiting a separate configured checker
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApprovalRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "409": { $ref: "#/components/responses/Conflict" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/model-validation-evidence:
    post:
      operationId: uploadModelValidationEvidence
      tags: [Monitoring]
      summary: Upload one encrypted immutable validation artifact
      description: |
        Streams a raw body of at most 10 MiB. `Idempotency-Key` is a caller-owned UUIDv7;
        exact retries verify filename, MIME type, plaintext digest and the write-once object.
        Filenames are accepted only in `X-Filename`, never in a URL. JSON and text are
        structurally validated; PDF fails closed unless a real malware scanner is configured.
      x-permission: rules.validation_evidence.upload
      parameters:
        - name: Idempotency-Key
          in: header
          required: true
          schema: { type: string, format: uuid }
        - name: X-Filename
          in: header
          required: true
          schema: { type: string, minLength: 1, maxLength: 255 }
      requestBody:
        required: true
        content:
          application/json: { schema: { type: string, format: binary } }
          text/plain: { schema: { type: string, format: binary } }
          application/pdf: { schema: { type: string, format: binary } }
      responses:
        "201":
          description: Finalized encrypted artifact metadata
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ValidationEvidenceArtifact" }
        "409": { $ref: "#/components/responses/Conflict" }
        "413": { description: Artifact exceeds 10 MiB }
        "422": { $ref: "#/components/responses/ValidationFailed" }
        "503": { $ref: "#/components/responses/Unavailable" }
    get:
      operationId: listModelValidationEvidence
      tags: [Monitoring]
      summary: Page finalized model-validation artifacts
      x-permission: rules.validation_evidence.read
      parameters:
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: Newest-first keyset page; never includes pending intents
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ValidationEvidenceArtifactPage" }
        "400": { $ref: "#/components/responses/BadRequest" }

  /v1/model-validation-evidence/pending:
    get:
      operationId: listPendingModelValidationEvidence
      tags: [Monitoring]
      summary: Page retryable upload intents not yet inventory-eligible
      description: |
        Makes object-store/process and finalization/audit crash windows operationally visible.
        Rows remain ineligible until exact bytes are finalized and a durable audit receipt exists.
      x-permission: rules.validation_evidence.read
      parameters:
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: Newest-first pending/stalled intents
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PendingValidationEvidencePage" }
        "400": { $ref: "#/components/responses/BadRequest" }

  /v1/model-validation-evidence/{artifactID}:
    get:
      operationId: getModelValidationEvidence
      tags: [Monitoring]
      summary: Read one finalized validation artifact's metadata
      x-permission: rules.validation_evidence.read
      parameters:
        - name: artifactID
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Authenticated metadata including the decrypted display filename
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ValidationEvidenceArtifact" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/model-validation-evidence/{artifactID}/content:
    get:
      operationId: downloadModelValidationEvidence
      tags: [Monitoring]
      summary: Download authenticated validation evidence bytes
      description: |
        Rechecks ciphertext digest/size, artifact-bound AEAD, plaintext digest and size before
        appending access evidence. Audit failure withholds the response. Returned as an
        attachment with no-store and nosniff headers.
      x-permission: rules.validation_evidence.download
      parameters:
        - name: artifactID
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Exact immutable artifact bytes
          headers:
            Content-Disposition: { schema: { type: string } }
            Digest: { schema: { type: string } }
            Cache-Control: { schema: { type: string } }
            X-Content-Type-Options: { schema: { type: string } }
          content:
            application/json: { schema: { type: string, format: binary } }
            text/plain: { schema: { type: string, format: binary } }
            application/pdf: { schema: { type: string, format: binary } }
        "404": { $ref: "#/components/responses/NotFound" }
        "503": { $ref: "#/components/responses/Unavailable" }

  /v1/model-validation-evidence/{artifactID}/recover:
    post:
      operationId: recoverModelValidationEvidence
      tags: [Monitoring]
      summary: Recover a finalized artifact whose upload audit did not commit
      description: |
        Separately permissioned two-phase operational recovery. It first re-authenticates the
        stored object (ciphertext size/digest, artifact-bound AEAD, plaintext size/digest) and
        commits the recovery audit event. A writer-only second transaction then finalizes the
        immutable eligibility receipt. If that writer transaction is unavailable, the intent
        remains fail-visible and retryable rather than being reported as finalized. Recovery
        retains the immutable original uploader and metadata; it cannot create or replace bytes
        or repair a failed integrity check.
      x-permission: rules.validation_evidence.recover
      parameters:
        - name: artifactID
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ValidationEvidenceRecoveryRequest" }
      responses:
        "200":
          description: Exact artifact metadata after durable recovery audit/receipt
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ValidationEvidenceArtifact" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "404": { $ref: "#/components/responses/NotFound" }
        "422": { $ref: "#/components/responses/ValidationFailed" }
        "503": { $ref: "#/components/responses/Unavailable" }

  /v1/transactions:
    post:
      operationId: ingestTransaction
      tags: [Monitoring]
      summary: Ingest one transaction for real-time monitoring
      description: |
        The API-based real-time monitoring path of BRD §8.3, for PSPs and payment rails. The
        transaction is stored and the active monitoring rules are evaluated against it before
        this call returns; any alerts raised are in the response.

        **This is not a payment authorization endpoint.** It returns what happened — stored or
        already stored, evaluated or not, which alerts fired — and no `decision` field. Open
        question Q7 defaults to a synchronous decision endpoint with a per-tenant timeout and
        an explicit per-tenant fail-open / fail-closed policy that "must be the client's
        documented, signed choice, surfaced in the admin console rather than buried in a
        config file". None of that exists yet, so this endpoint does not imply it. A caller
        that blocks its payment rail on this response is making a decision this platform has
        not agreed to and cannot honour an SLA for.

        **Idempotency.** `Idempotency-Key` and `external_ref` are one identity, not two: send
        either, or both with the same value. Idempotency is enforced by a unique database
        constraint on (tenant, source, external_ref, booking_ts), not by an application check
        — checking for existence before inserting is a race, and at payment-rail volumes it is
        a race that gets lost (ADR-0014). A replay is a `200` with `duplicate: true`, no
        re-evaluation and no second alert.

        **Financial-event lifecycle.** An ordinary transaction defaults to `event_type:
        posted`. A reversal, correction, cancellation or chargeback is another immutable
        monitored transaction which names the exact prior `(original_source,
        original_external_ref, original_booking_ts)` identity and supplies a reason. The
        original is never updated. Corrections may form a linear chain; terminal events may
        not be superseded, concurrent branches are refused, and every successor must have a
        strictly later booking timestamp. Monitoring aggregates expose the effective state
        without erasing raw-event provenance. A correction is re-evaluated for automatic CTR
        using its corrected amount; terminal events retain/link any prior automatic CTR in an
        explicit amendment, withdrawal or cancellation-review disposition. Those dispositions
        are workflow evidence, not claims that a regulator received an amendment.

        **Latency.** The handler carries a fixed 2s budget (BRD §9). A request that exceeds it
        is rolled back and answered `503`; retrying is safe and is what the idempotency
        identity is for. The budget is not per-tenant configurable — that is the Q7 work.
      x-permission: monitoring.transaction.ingest
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [account_ref, booking_ts, direction, amount_minor, currency]
              properties:
                source:
                  type: string
                  pattern: "^[a-z][a-z0-9_.-]{0,31}$"
                  default: api
                  description: |
                    A short stable label for the integration sending this — `nibss`,
                    `core_banking`. It is part of the idempotency identity, so it must not
                    vary between a request and its retry, and two rails sharing a label also
                    share a reference namespace.
                external_ref:
                  type: string
                  maxLength: 128
                  description: The sender's own reference for this transaction. Required unless sent as Idempotency-Key.
                account_ref:
                  type: string
                  description: The account's reference in the sending system. The account must already exist.
                booking_ts:
                  type: string
                  format: date-time
                  description: |
                    Required, never defaulted. It is part of the idempotency identity and it
                    selects the monthly partition, so a defaulted value would give a retry a
                    different identity and store the payment twice.
                value_date: { type: string, format: date }
                direction: { type: string, enum: [credit, debit] }
                amount_minor:
                  type: integer
                  format: int64
                  minimum: 0
                  description: |
                    Minor units, never a decimal or a float: ₦4,400,000.00 is 440000000. A
                    debit is expressed by `direction`, not by a negative amount.
                currency:
                  type: string
                  minLength: 3
                  maxLength: 3
                  description: |
                    ISO 4217. Refused if this platform does not know the currency's minor-unit
                    exponent, because an amount whose scale is unknown can neither be compared
                    to a threshold nor stated in a filing.
                channel: { type: string }
                counterparty_name: { type: string }
                counterparty_account: { type: string }
                counterparty_bank: { type: string }
                corridor_country: { type: string, minLength: 2, maxLength: 2 }
                narrative: { type: string }
                business_evidence: { $ref: "#/components/schemas/TransactionBusinessEvidence" }
                event_type:
                  type: string
                  enum: [posted, reversal, correction, cancellation, chargeback]
                  default: posted
                  description: |
                    `posted` is an ordinary transaction. Every other value appends an
                    immutable lifecycle event and requires all original_* fields plus
                    lifecycle_reason.
                original_source:
                  type: string
                  pattern: "^[a-z][a-z0-9_.-]{0,31}$"
                  description: Stable source label of the exact transaction being superseded.
                original_external_ref:
                  type: string
                  maxLength: 128
                  description: Sender reference of the exact transaction being superseded.
                original_booking_ts:
                  type: string
                  format: date-time
                  description: Partition/idempotency timestamp of the exact transaction being superseded; it must be strictly earlier than booking_ts.
                lifecycle_reason:
                  type: string
                  minLength: 1
                  maxLength: 500
                  description: Required operational reason retained with the immutable event link.
      responses:
        "201":
          description: Stored and evaluated
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TransactionIngestResult" }
        "200":
          description: |
            Already stored. An idempotent replay: nothing was written, no rules were re-run,
            and the alerts raised the first time are not repeated.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TransactionIngestResult" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "422": { $ref: "#/components/responses/ValidationFailed" }
        "409":
          description: The idempotency identity was reused with different content, or the original already has a lifecycle successor.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "503":
          description: |
            Evaluation exceeded the real-time budget or exact business-evidence numeric
            capacity, or a lifecycle event's automatic CTR impact could not be recorded.
            The whole transaction was rolled back. Retain the same external_ref for a
            retry; a capacity error requires source allocation review or an approved
            suitable rule window before retrying.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/transactions/batch:
    post:
      operationId: ingestTransactionBatch
      tags: [Monitoring]
      summary: Ingest an end-of-day core-banking export
      description: |
        The file/batch ingestion path of BRD §8.3. The body is the CSV export itself
        (`curl --data-binary @export.csv`), not a multipart form: the caller is a scheduled
        job, not a browser.

        Malformed rows are quarantined with their line number and parse error rather than
        dropped or made fatal, and the response is the per-file reconciliation record an
        operations team needs to prove an export was consumed exactly once (ADR-0014).

        Lifecycle-capable exports may add `event_type`, `original_source`,
        `original_external_ref`, `original_booking_ts` and `lifecycle_reason` columns. Missing
        `event_type` remains compatible and means `posted`; every non-posted row requires the
        other four columns and a strictly later booking timestamp.

        The reconciliation row commits before parsing. Parsed failures and canonically ordered
        transaction rows then commit in bounded chunks, with the counters updated in the same
        transaction as each chunk. A failure therefore leaves both the successfully processed
        prefix and a durable failed reconciliation record. Re-sending the same bytes with the
        same `source` is safe: committed rows conflict on their idempotency identity and are
        counted as duplicates before processing continues into the uncommitted suffix.

        `resumable: true` describes replay-based recovery; it does not claim the HTTP upload
        itself can restart at an arbitrary byte offset. `X-Baobyte-Batch-ID` is returned on
        both success and post-creation errors so an operator can reconcile the durable attempt.

        **This operation takes no `Idempotency-Key` header.** It declared one until stream B4
        removed it, and `ingestBatch` has never read it: the documented parameter had no
        effect, which is worse than no parameter at all — a caller could set it, believe the
        file was protected against a double send, and be relying on nothing. Per-FILE replay
        protection would mean recording the key on `app.ingest_batch` and returning the
        original `batch_id` on a re-send; that is not built. What IS built is per-ROW
        idempotency, which makes a duplicate send harmless in the way that matters: re-posting
        the same export inserts nothing and counts every row as a duplicate. It produces a
        second `ingest_batch` row, so the reconciliation trail shows two attempts — which is
        the truth about what happened.
      x-permission: monitoring.batch.ingest
      parameters:
        - name: source
          in: query
          description: |
            The integration label recorded on every row of this file, and part of each row's
            idempotency identity. A re-sent export must carry the same one.
          schema: { type: string, pattern: "^[a-z][a-z0-9_.-]{0,31}$", default: core_banking }
        - name: filename
          in: query
          description: The export's file name, retained on the reconciliation record.
          schema: { type: string, maxLength: 255 }
      requestBody:
        required: true
        content:
          text/csv:
            schema: { type: string }
      responses:
        "200":
          description: The reconciliation record for this file
          headers:
            X-Baobyte-Batch-ID:
              description: Durable reconciliation identity for this ingest attempt.
              schema: { type: string, format: uuid }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/IngestBatchResult" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "413":
          description: The export exceeds the endpoint's size limit. Split it; the parts are individually idempotent.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "415":
          description: The body was not a CSV export. To ingest a single transaction as JSON, POST /v1/transactions.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "422":
          description: |
            The file's header could not be read, so the whole export is unusable. Nothing was
            ingested — and because the batch is one transaction, the reconciliation row for
            the attempt was rolled back with it.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/alerts/bulk-disposition:
    post:
      operationId: bulkAlertDisposition
      tags: [Work]
      x-permission: monitoring.alert.triage
      summary: Queue per-record audited alert decisions
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/BulkInput'}
      responses:
        '202':
          description: Durable background operation; each record retains its own outcome.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/BulkOperation'}
        '400': {$ref: '#/components/responses/BadRequest'}
  /v1/screening/hits/bulk-decision:
    post:
      operationId: bulkScreeningDecision
      tags: [Work]
      x-permission: screening.hit.decide
      summary: Queue per-record audited screening_hit decisions
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/BulkInput'}
      responses:
        '202':
          description: Durable background operation; each record retains its own outcome.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/BulkOperation'}
        '400': {$ref: '#/components/responses/BadRequest'}
  /v1/me/bulk-operations/{operationID}:
    get:
      operationId: getBulkOperation
      tags: [Work]
      x-permission: authenticated
      parameters:
        - {name: operationID, in: path, required: true, schema: {type: string, format: uuid}}
      responses:
        '200':
          description: Current result of this user's operation, including independently held approvals.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/BulkOperation'}
        '404': {$ref: '#/components/responses/NotFound'}
  /v1/alerts:
    get:
      operationId: listAlerts
      tags:
      - Alerts
      summary: The triage queue
      x-permission: monitoring.alert.read
      parameters:
      - name: status
        in: query
        schema:
          type: string
          enum:
          - open
          - assigned
          - in_review
          - escalated
          - closed
          - closed_false_positive
          - closed_actioned
          - merged
      - name: priority
        in: query
        schema:
          type: string
          enum:
          - p1
          - p2
          - p3
          - p4
      - name: typology
        in: query
        schema:
          type: string
      - name: party_id
        in: query
        description: 'Narrows the queue to the alerts raised against one party, matched on the

          alert''s own subject rather than looked up per row. This is what a customer

          profile asks for; without it the only way to show one customer''s alert history

          is to read the whole triage queue and filter client-side, which silently goes

          wrong at the first page boundary. A value that is not a UUID is a 400, not an

          ignored filter.

          '
        schema:
          type: string
          format: uuid
      - {name: assignee, in: query, description: 'me or a tenant user UUID.', schema: {type: string}}
      - {name: rule_key, in: query, schema: {type: string}}
      - {name: severity, in: query, schema: {type: string, enum: [low, medium, high, critical]}}
      - {name: opened_after, in: query, description: Inclusive opening instant., schema: {type: string, format: date-time}}
      - {name: opened_before, in: query, description: Exclusive opening instant., schema: {type: string, format: date-time}}
      - {name: overdue, in: query, schema: {type: boolean}}
      - {name: ageing_bucket, in: query, schema: {type: string, enum: [0_7, 8_30, 31_90, 90_plus]}}
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      - name: sort
        in: query
        description: Server ordering. Changing filters or sort starts a new cursor walk.
        schema:
          type: string
          enum:
          - priority
          - opened_at_desc
          - opened_at_asc
          default: priority
      responses:
        '200':
          description: Alerts, highest priority first
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AlertPage'
  /v1/alerts/{alertID}:
    get:
      operationId: getAlert
      tags: [Alerts]
      summary: One alert
      x-permission: monitoring.alert.read
      parameters:
        - { $ref: "#/components/parameters/AlertID" }
      responses:
        "200":
          description: The alert
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Alert" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/alerts/{alertID}/trace:
    get:
      operationId: getAlertTrace
      tags: [Alerts]
      summary: Why this alert fired
      description: |
        The arithmetic, not the outcome: the rule version and its expression, the parameter
        values that were in force at evaluation time, the window, the computed aggregates,
        and the transactions the rule was looking at.

        This is what makes an alert defensible two years later, when the thresholds have
        been retuned three times and nobody remembers what they were in August (mandate 7).
      x-permission: monitoring.alert.read
      parameters:
        - { $ref: "#/components/parameters/AlertID" }
      responses:
        "200":
          description: The evaluation trace and its evidence
          content:
            application/json:
              schema:
                type: object
                required: [trace, transactions]
                properties:
                  trace: { $ref: "#/components/schemas/EvaluationTrace" }
                  transactions:
                    type: array
                    items: { $ref: "#/components/schemas/Transaction" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/alerts/{alertID}/assign:
    post:
      operationId: assignAlert
      tags: [Alerts]
      summary: Take an alert
      description: Assigns the alert to the calling user. Self-assignment only, which is what a triage queue needs.
      x-permission: monitoring.alert.triage
      parameters:
        - { $ref: "#/components/parameters/AlertID" }
      responses:
        "204": { description: Assigned }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/alerts/{alertID}/close:
    post:
      operationId: closeAlert
      tags: [Alerts]
      summary: Close an alert without escalating
      x-permission: monitoring.alert.triage
      parameters:
        - { $ref: "#/components/parameters/AlertID" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [status, reason]
              properties:
                status:
                  type: string
                  # Read from what alert.status allows and what the service accepts, not from
                  # memory of them. This said `closed`, which the service refuses outright —
                  # so the published contract offered a value that produced a 500. The enum
                  # parity test cannot see a request-body enum, which is how it survived.
                  enum: [closed_false_positive, closed_actioned]
                  description: |
                    Which kind of closure this was. A dismissal and an actioned close are
                    different facts about the same alert, and the false-positive rate in
                    BRD §13 is computed from the difference.
                reason:
                  type: string
                  description: |
                    Required. The false-positive rate in BRD §13 is only measurable if
                    every dismissal says why it was a dismissal.
      responses:
        "200":
          description: The closed alert
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Alert" }
        "404": { $ref: "#/components/responses/NotFound" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/cases:
    get:
      operationId: listCases
      tags: [Cases]
      summary: Investigation cases
      description: |
        A metadata-safe caseload register. Each row contains only its opaque id, reference,
        lifecycle state, priority and opened/SLA/closed times. It never returns the title,
        narrative summary, subject/customer identity, names, outcome, assignee or actor ids.
        Those investigation details require `cases.case_content.read` on the case workspace.
      x-permission: cases.case.read
      parameters:
        - name: sort
          in: query
          description: Server ordering applied before pagination; changing it starts a new cursor walk.
          schema: { type: string, enum: [priority, opened_at_desc, opened_at_asc] }
        - name: assignee
          in: query
          schema: { type: string }
          description: Current user (me) or a tenant user UUID.
        - name: overdue
          in: query
          schema: { type: boolean }
          description: Only active cases whose SLA has elapsed.
        - name: status
          in: query
          description: |
            An EXACT match on `case_record.status`, not a category. This list said
            `[open, in_progress, pending_approval, closed]` until a test walked the request
            bodies and query parameters as well as the schemas: `in_progress` and `closed` are
            not values the column has ever held, so a UI dropdown built from this contract had
            two options that returned an empty page forever and read as "no cases".
          schema:
            type: string
            enum: [open, investigating, pending_approval, closed_no_action, closed_reported, reopened]
        - name: party_id
          in: query
          description: |
            Narrows the case list to the cases raised against one party, matched on the
            case's own subject rather than looked up per row. This is what a customer
            profile asks for; without it the only way to show one customer's case history
            is to read the whole case list and filter client-side, which silently goes
            wrong at the first page boundary. A value that is not a UUID is a 400, not an
            ignored filter.
          schema: { type: string, format: uuid }
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: Cases
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CasePage" }
    post:
      operationId: openCase
      tags: [Cases]
      summary: Escalate alerts or screening hits into a case
      description: |
        The case subject is taken from the evidence rather than from the request body, so an
        analyst cannot open a case against the wrong customer by mistyping. Alerts lead when
        both kinds are present — an alert names an account and a transaction as well as a party
        — and a screening hit supplies the subject when there is no alert to take it from.

        `alert_ids` and `screening_hit_ids` may name at most 200 records in total. Correlation
        groups are expanded before any write and the expanded combined set must remain within
        that boundary; overflow is a 422 and no case is created.
      x-permission: cases.case.write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [title]
              properties:
                title: { type: string, minLength: 1 }
                summary: { type: string }
                priority: { type: string, enum: [p1, p2, p3, p4] }
                alert_ids:
                  type: array
                  maxItems: 200
                  uniqueItems: true
                  items: { type: string, format: uuid }
                screening_hit_ids:
                  type: array
                  maxItems: 200
                  uniqueItems: true
                  items: { type: string, format: uuid }
                  description: |
                    Confirmed sanctions, PEP or internal-list matches this case is being opened
                    over. They are LINKED to the case, so a filing drawn from it traces back to
                    the pinned watchlist version the match was made against instead of to a
                    paragraph somebody retyped. An id naming no hit in this tenant is refused
                    with a 422 rather than dropped.
      responses:
        "201":
          description: The case
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Case" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/cases/{caseID}:
    get:
      operationId: getCase
      tags: [Cases]
      summary: The case workspace
      description: |
        One response distinguishes the immutable evidence linked to this case from the wider
        history of the same subject. `alerts`, `screening_hits`, `attachments` and
        `transactions` remain linked filing provenance. Each linked collection is bounded at
        200 with an explicit `truncated: true`/`service_cannot_resume` marker; it is never a
        silent partial array. The four broader subject collections (alerts, transactions,
        screening runs and screening hits) are independently keyset-resumable investigation
        context with independent read permissions and explicit coverage. Paging one collection
        never moves any other collection, and transaction cursors are valid only with the exact
        half-open window echoed by the response.

        Linked `transactions` deliberately remains a bounded, explicitly truncated filing-
        provenance view. `subject_transaction_history` is the resumable traversal path for the
        subject's activity inside the selected window. Its database work is a bounded k-way
        account merge; customers with more than 200 accounts get
        `unavailable_account_limit` and no misleading partial activity.

        A broader-history key is ABSENT when its permission is absent. When permission is
        present but the case has no usable subject/customer/account, the key is present with an
        `unavailable_*` or `available_no_accounts` coverage value. An empty `available` list
        therefore means the query really ran and found no rows; it never means "not allowed".
      x-permission: cases.case_content.read
      parameters:
        - { $ref: "#/components/parameters/CaseID" }
        - { $ref: "#/components/parameters/NotesLimit" }
        - { $ref: "#/components/parameters/NotesCursor" }
        - { $ref: "#/components/parameters/EventsLimit" }
        - { $ref: "#/components/parameters/EventsCursor" }
        - { $ref: "#/components/parameters/SubjectAlertsLimit" }
        - { $ref: "#/components/parameters/SubjectAlertsCursor" }
        - { $ref: "#/components/parameters/SubjectTransactionsLimit" }
        - { $ref: "#/components/parameters/SubjectTransactionsCursor" }
        - { $ref: "#/components/parameters/SubjectTransactionsFrom" }
        - { $ref: "#/components/parameters/SubjectTransactionsTo" }
        - { $ref: "#/components/parameters/SubjectScreeningRunsLimit" }
        - { $ref: "#/components/parameters/SubjectScreeningRunsCursor" }
        - { $ref: "#/components/parameters/SubjectScreeningHitsLimit" }
        - { $ref: "#/components/parameters/SubjectScreeningHitsCursor" }
      responses:
        "200":
          description: The workspace
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CaseDetail" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/cases/{caseID}/summary:
    get:
      operationId: getCaseSummary
      tags: [Cases]
      summary: Read the case header and assignment without loading investigation collections
      description: |
        Independent workspace read using the same tenant, case-content and subject-privacy
        checks as the compound case response. Notes retain their sensitive-read audit.
        Linked evidence keeps its explicit hard caps and subject histories their independent
        permissions and cursors. Absent evidence fields indicate missing permission.
        Summary echoes the transaction window so separately streamed sections preserve it.
      x-permission: cases.case_content.read
      parameters:
        - { $ref: "#/components/parameters/CaseID" }
        - { $ref: "#/components/parameters/SubjectTransactionsFrom" }
        - { $ref: "#/components/parameters/SubjectTransactionsTo" }
      responses:
        "200":
          description: Requested workspace section
          content:
            application/json:
              schema:
                type: object
                required: [case, assignment, subject_transaction_window]
                properties:
                  case: { $ref: "#/components/schemas/Case" }
                  assignment: { $ref: "#/components/schemas/CaseAssignment" }
                  subject_transaction_window:
                    type: object
                    required: [from, to]
                    properties:
                      from: { type: string, format: date-time }
                      to: { type: string, format: date-time }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/cases/{caseID}/events:
    get:
      operationId: getCaseEvents
      tags: [Cases]
      summary: Read the case timeline independently with cursor paging
      description: |
        Independent workspace read using the same tenant, case-content and subject-privacy
        checks as the compound case response. Notes retain their sensitive-read audit.
        Linked evidence keeps its explicit hard caps and subject histories their independent
        permissions and cursors. Absent evidence fields indicate missing permission.
        Summary echoes the transaction window so separately streamed sections preserve it.
      x-permission: cases.case_content.read
      parameters:
        - { $ref: "#/components/parameters/CaseID" }
        - { $ref: "#/components/parameters/EventsLimit" }
        - { $ref: "#/components/parameters/EventsCursor" }
      responses:
        "200":
          description: Requested workspace section
          content:
            application/json:
              schema:
                type: object
                required: [events]
                properties:
                  events: { $ref: "#/components/schemas/CaseEventPage" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/cases/{caseID}/evidence:
    get:
      operationId: getCaseEvidence
      tags: [Cases]
      summary: Read case-linked evidence and permission-filtered subject histories
      description: |
        Independent workspace read using the same tenant, case-content and subject-privacy
        checks as the compound case response. Notes retain their sensitive-read audit.
        Linked evidence keeps its explicit hard caps and subject histories their independent
        permissions and cursors. Absent evidence fields indicate missing permission.
        Summary echoes the transaction window so separately streamed sections preserve it.
      x-permission: cases.case_content.read
      parameters:
        - { $ref: "#/components/parameters/CaseID" }
        - { $ref: "#/components/parameters/SubjectAlertsLimit" }
        - { $ref: "#/components/parameters/SubjectAlertsCursor" }
        - { $ref: "#/components/parameters/SubjectTransactionsLimit" }
        - { $ref: "#/components/parameters/SubjectTransactionsCursor" }
        - { $ref: "#/components/parameters/SubjectTransactionsFrom" }
        - { $ref: "#/components/parameters/SubjectTransactionsTo" }
        - { $ref: "#/components/parameters/SubjectScreeningRunsLimit" }
        - { $ref: "#/components/parameters/SubjectScreeningRunsCursor" }
        - { $ref: "#/components/parameters/SubjectScreeningHitsLimit" }
        - { $ref: "#/components/parameters/SubjectScreeningHitsCursor" }
      responses:
        "200":
          description: Requested workspace section
          content:
            application/json:
              schema:
                type: object
                required: [alerts, screening_hits]
                properties:
                  alerts: { $ref: "#/components/schemas/CaseLinkedAlertPage" }
                  screening_hits: { $ref: "#/components/schemas/CaseLinkedScreeningHitPage" }
                  attachments: { $ref: "#/components/schemas/CaseAttachmentPage" }
                  transactions: { $ref: "#/components/schemas/CaseTransactionHistory" }
                  subject_alert_history: { $ref: "#/components/schemas/SubjectAlertHistory" }
                  subject_transaction_history: { $ref: "#/components/schemas/SubjectTransactionHistory" }
                  subject_screening_history: { $ref: "#/components/schemas/SubjectScreeningHistory" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/cases/{caseID}/notes:
    get:
      operationId: getCaseNotes
      tags: [Cases]
      summary: Read case notes independently with cursor paging
      description: |
        Independent workspace read using the same tenant, case-content and subject-privacy
        checks as the compound case response. Notes retain their sensitive-read audit.
        Linked evidence keeps its explicit hard caps and subject histories their independent
        permissions and cursors. Absent evidence fields indicate missing permission.
        Summary echoes the transaction window so separately streamed sections preserve it.
      x-permission: cases.case_content.read
      parameters:
        - { $ref: "#/components/parameters/CaseID" }
        - { $ref: "#/components/parameters/NotesLimit" }
        - { $ref: "#/components/parameters/NotesCursor" }
      responses:
        "200":
          description: Requested workspace section
          content:
            application/json:
              schema:
                type: object
                required: [notes]
                properties:
                  notes: { $ref: "#/components/schemas/CaseNotePage" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
    post:
      operationId: addCaseNote
      tags: [Cases]
      summary: Record an investigation note
      description: |
        Notes are encrypted at rest under the subject's key and are append-only. An
        investigation record that can be edited afterwards is not evidence of anything.
      x-permission: cases.case.write
      parameters:
        - { $ref: "#/components/parameters/CaseID" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [body]
              properties:
                body: { type: string, minLength: 1 }
                draft_revision:
                  type: integer
                  minimum: 0
                  description: Consume this private case-note draft revision atomically with the note. Stale or already consumed revisions return 409.
      responses:
        "201":
          description: The note
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CaseNote" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "409": { description: Draft revision changed or was already consumed. No note was created. }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/cases/{caseID}/attachments:
    post:
      operationId: uploadCaseAttachment
      tags: [Cases]
      summary: Attach immutable investigation evidence
      description: |
        Encrypts the bytes and original filename under the case subject's DEK before writing
        to the configured write-once object store. The object key contains no case, person,
        filename or user data. Reusing the UUID `Idempotency-Key` for the same attachment is
        safe; reusing it for different bytes or metadata is refused.

        Legacy `?filename=` query metadata is refused even when `X-Filename` is also present,
        because silently ignoring it would leave the sensitive value in upstream access logs.
      x-permission: cases.evidence.write
      parameters:
        - { $ref: "#/components/parameters/CaseID" }
        - name: Idempotency-Key
          in: header
          required: true
          schema: { type: string, format: uuid }
        - name: X-Filename
          in: header
          required: true
          description: |
            Sensitive display metadata encrypted before storage and never used as an object
            path. It MUST be redacted from gateway/application logs and MUST NOT be copied into
            a URL or query string, which access infrastructure commonly records before the
            handler can redact it. The value must be valid UTF-8, at most 255 bytes, and contain
            no control character or `/` or `\` path separator.
          schema: { type: string, minLength: 1, maxLength: 255 }
      requestBody:
        required: true
        content:
          application/pdf: { schema: { type: string, format: binary, maxLength: 20971520 } }
          image/jpeg: { schema: { type: string, format: binary, maxLength: 20971520 } }
          image/png: { schema: { type: string, format: binary, maxLength: 20971520 } }
          text/plain: { schema: { type: string, format: binary, maxLength: 20971520 } }
      responses:
        "201":
          description: Immutable encrypted evidence metadata
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CaseAttachment" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409": { $ref: "#/components/responses/Conflict" }
        "413":
          description: Attachment exceeds the 20 MiB evidence limit.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "415":
          description: The declared type is unsupported or does not match the bytes.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/cases/{caseID}/attachments/{attachmentID}/content:
    get:
      operationId: downloadCaseAttachment
      tags: [Cases]
      summary: Download and audit immutable case evidence
      description: |
        Loads the tenant-scoped metadata first, decrypts the opaque object reference and bytes,
        verifies the stored plaintext SHA-256, and records both PII access and download audit
        events. The response is always an attachment with `no-store` and `nosniff` headers.
      x-permission: cases.evidence.read
      parameters:
        - { $ref: "#/components/parameters/CaseID" }
        - name: attachmentID
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Original verified evidence bytes
          headers:
            Digest:
              schema: { type: string }
              description: Verified plaintext SHA-256 in RFC Digest form.
          content:
            application/pdf: { schema: { type: string, format: binary } }
            image/jpeg: { schema: { type: string, format: binary } }
            image/png: { schema: { type: string, format: binary } }
            text/plain: { schema: { type: string, format: binary } }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/cases/{caseID}/assignment:
    post:
      operationId: assignCase
      tags: [Cases]
      summary: Route a case to a queue or eligible investigator
      description: |
        The queue snapshots its owning organisational unit onto the case. If an assignee is
        supplied they must currently be active, belong to that exact unit and hold at least one
        eligible role configured on the queue. Omitting the assignee leaves work owned by the
        queue without inventing an individual owner.
      x-permission: cases.assignment.write
      parameters:
        - { $ref: "#/components/parameters/CaseID" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [queue_id]
              properties:
                queue_id: { type: string, format: uuid }
                assignee_id: { type: string, format: uuid }
      responses:
        "200":
          description: Current assignment snapshot
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CaseAssignment" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409": { $ref: "#/components/responses/Conflict" }

  /v1/case-queues:
    get:
      operationId: listCaseQueues
      tags: [Cases]
      summary: Configured case-routing queues
      x-permission: cases.assignment.write
      parameters:
        - name: include_retired
          in: query
          schema: { type: boolean, default: false }
      responses:
        "200":
          description: Tenant case queues
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/CaseQueue" }
    post:
      operationId: createCaseQueue
      tags: [Cases]
      summary: Configure an organisational case queue
      x-permission: cases.routing.manage
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CaseQueueInput" }
      responses:
        "201":
          description: Queue created
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CaseQueue" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "409": { $ref: "#/components/responses/Conflict" }

  /v1/case-queues/{queueID}:
    patch:
      operationId: updateCaseQueue
      tags: [Cases]
      summary: Update a live case queue and its priority routes
      x-permission: cases.routing.manage
      parameters:
        - { $ref: "#/components/parameters/QueueID" }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CaseQueueInput" }
      responses:
        "200":
          description: Queue updated
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CaseQueue" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409": { $ref: "#/components/responses/Conflict" }

  /v1/case-queues/{queueID}/automation:
    get:
      operationId: getQueueAutomation
      parameters:
        - {$ref: "#/components/parameters/QueueID"}
      tags: [Cases]
      x-permission: cases.routing.manage
      responses:
        '200':
          description: Assignment and SLA escalation policy for this queue.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/QueueAutomation'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
    put:
      operationId: setQueueAutomation
      parameters:
        - {$ref: "#/components/parameters/QueueID"}
      tags: [Cases]
      x-permission: cases.routing.manage
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/QueueAutomationInput'}
      responses:
        '200':
          description: Saved assignment and SLA escalation policy.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/QueueAutomation'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
  /v1/case-queues/{queueID}/retire:
    post:
      operationId: retireCaseQueue
      tags: [Cases]
      summary: Retire a case queue without deleting assignment history
      x-permission: cases.routing.manage
      parameters:
        - { $ref: "#/components/parameters/QueueID" }
      responses:
        "200":
          description: Retired queue
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CaseQueue" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/case-queues/{queueID}/eligible-assignees:
    get:
      operationId: listEligibleCaseAssignees
      tags: [Cases]
      summary: Active tenant users eligible for a queue
      x-permission: cases.assignment.write
      parameters:
        - { $ref: "#/components/parameters/QueueID" }
      responses:
        "200":
          description: Current eligible users; email addresses are not returned.
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/EligibleCaseAssignee" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/cases/{caseID}/close:
    post:
      operationId: proposeCaseClosure
      tags: [Cases]
      summary: Propose closing a case
      description: |
        This does not close the case. It records a maker-checker proposal and moves the case
        to `pending_approval`; a different, role-authorised user approves it through
        `/v1/approvals/{approvalID}/approve`, and the closure is applied inside that
        approval's transaction.

        The two-step flow is the control. Until Phase 2 the closer named their own approver
        in this request body, with no foreign key and no check that the named person had
        agreed to anything — the four-eyes rule was self-attested. The proposal payload is
        digest-bound, so editing the outcome after review invalidates the approval rather
        than riding on it.

        Which roles may approve a case closure is `workflow.approvals` configuration, not
        code (BRD §7.2).
      x-permission: cases.case.close
      parameters:
        - { $ref: "#/components/parameters/CaseID" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [outcome, rationale]
              properties:
                outcome:
                  type: string
                  enum: [false_positive, no_suspicion, str_filed, ctr_filed, escalated_externally, customer_exited]
                  description: |
                    The closed *status* is derived from this server-side, so a case can never
                    be marked closed-no-action while its outcome says a report was filed.
                rationale:
                  type: string
                  minLength: 1
                  description: |
                    Required. It is what the checker reads before deciding, and it becomes the
                    case's closing note — a closure proposed with no stated reasoning is one
                    nobody can defend two years later.
      responses:
        "202":
          description: The approval request awaiting a second pair of eyes
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApprovalRequest" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "422": { $ref: "#/components/responses/ValidationFailed" }
        "409":
          description: The case is already closed, or a closure proposal is already pending on it.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/cases/{caseID}/reports:
    post:
      operationId: generateCaseReport
      tags: [Reporting]
      summary: Draft a regulatory filing from a case
      description: |
        The figures are assembled from the evidence already linked to the case, not from
        the request body. A filing whose amounts were retyped into a form is a filing whose
        amounts cannot be reconciled against the transactions they came from.

        The draft is validated on generation and every field records the expression that
        produced it. A document that fails validation is stored as `validation_failed`
        rather than discarded, so the failure is inspectable.

        Synchronous generation is fail-closed at 200 linked alerts and 200 distinct linked
        transactions. Overflow returns 409 before rendering or persistence. This installation
        has no complete filing path for an older case above that boundary; a partial regulatory
        report is never generated.
      x-permission: reporting.report.generate
      parameters:
        - { $ref: "#/components/parameters/CaseID" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                kind: { type: string, enum: [STR, CTR, SCUML, CBN_RETURN, BOARD], default: STR }
                draft_revision:
                  type: integer
                  format: int64
                  minimum: 1
                  description: Consume this exact saved report narrative revision atomically with successful report generation.
                narrative:
                  type: string
                  description: The analyst's narrative. Defaults to the case summary if omitted.
      responses:
        "201":
          description: The generated draft
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Report" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409":
          description: Linked alert or transaction evidence exceeds the synchronous complete-evidence boundary; no partial report was generated.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/reports:
    get:
      operationId: listReports
      tags:
      - Reporting
      summary: Regulatory reports
      description: 'A bounded, keyset-resumable filing register. Every item is a `ReportSummary` limited

        to reference, type, lifecycle/validation state, validator identity and generation

        time. It never returns case or party identifiers, validation error text, actor ids,

        external acknowledgements, source-event keys, free-text status reasons, document or

        schema digests, field traces, or rendered content. Those richer fields require

        `reporting.report_content.read` through the report-detail endpoint.

        '
      x-permission: reporting.report.read
      parameters:
      - name: kind
        in: query
        schema:
          type: string
          enum:
          - STR
          - CTR
          - SCUML
          - CBN_RETURN
          - BOARD
      - name: status
        in: query
        schema:
          type: string
          enum:
          - draft
          - validation_failed
          - in_review
          - approved
          - submitted
          - acknowledged
          - rejected
      - name: case_id
        in: query
        description: 'Return only reports linked to this case. The filter is applied before the

          `(generated_at,id)` keyset boundary, so the filtered register remains resumable.

          '
        schema:
          type: string
          format: uuid
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      - name: sort
        in: query
        description: Server ordering. Changing filters or sort starts a new cursor walk.
        schema:
          type: string
          enum:
          - generated_at_desc
          - generated_at_asc
          default: generated_at_desc
      responses:
        '200':
          description: Reports
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReportPage'
        '400':
          $ref: '#/components/responses/BadRequest'
  /v1/report-schemas:
    get:
      operationId: listReportSchemas
      tags: [Reporting]
      summary: Installed report-schema validation provenance
      description: |
        Lists bounded metadata and the SHA-256 digest of each immutable schema version; it
        never returns the XSD body. Authoritative schemas can be activated only from a signed
        content pack after maker-checker approval, and only when the exact self-contained XSD
        compiles under the recorded validator. This release supports XSD 1.0 and deliberately
        refuses XSD 1.1 and `xs:include`/`xs:import`; it never resolves network or host files.
      x-permission: reporting.report.read
      responses:
        "200":
          description: Complete installed schema catalogue
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReportSchemaPage" }

  /v1/reports/lifecycle-effects:
    get:
      operationId: listCTRLifecycleEffects
      tags: [Reporting]
      summary: List immutable automatic-CTR lifecycle review records
      description: |
        A tenant-scoped, keyset-resumable operational queue for corrections, reversals,
        cancellations and chargebacks that affected automatic CTR reporting. Each row links
        the exact financial-event predecessor and the current statuses of any prior/resulting
        CTRs. `action_required` means an operator must follow the linked report or external
        amendment/withdrawal procedure; it does not claim assignment, resolution or regulator
        delivery. Batch-ingested and synchronous lifecycle events use the same ledger.
      x-permission: reporting.report_content.read
      parameters:
        - name: event_type
          in: query
          schema: { type: string, enum: [reversal, correction, cancellation, chargeback] }
        - name: disposition
          in: query
          schema:
            type: string
            enum: [no_report_impact, new_report_required, amendment_required,
                   withdrawal_review_required, cancellation_review_required]
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: Newest lifecycle review records first
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CTRLifecycleReviewPage" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/reports/lifecycle-effects/{transactionID}:
    get:
      operationId: getCTRLifecycleEffect
      tags: [Reporting]
      summary: Read one immutable automatic-CTR lifecycle review record
      description: |
        Reads the record by its exact partitioned financial-event identity. This is evidence
        of the reporting effect, not evidence that an external amendment or withdrawal was
        delivered.
      x-permission: reporting.report_content.read
      parameters:
        - name: transactionID
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: booking_ts
          in: query
          required: true
          description: Exact booking timestamp of the lifecycle transaction, including timezone.
          schema: { type: string, format: date-time }
      responses:
        "200":
          description: The immutable lifecycle review record
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CTRLifecycleReviewRecord" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/reports/{reportID}:
    get:
      operationId: getReport
      tags: [Reporting]
      summary: A report, its rendered document and its field provenance
      description: |
        Returns customer-level filing content, content-derived validation detail and field
        provenance. Filing-register permission alone is insufficient.
      x-permission: reporting.report_content.read
      parameters:
        - { $ref: "#/components/parameters/ReportID" }
      responses:
        "200":
          description: The report with its document and traces
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReportDetail" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/reports/{reportID}/export:
    get:
      operationId: exportReport
      tags: [Reporting]
      summary: Download the immutable rendered report payload
      description: |
        Returns the bytes stored at generation time, not a document rebuilt from the current
        active template. `X-Content-SHA256` is the lowercase SHA-256 digest of the response.
        The payload contains customer-level filing content and requires the dedicated content
        permission; filing-register permission alone is insufficient.
      x-permission: reporting.report_content.read
      parameters:
        - { $ref: "#/components/parameters/ReportID" }
      responses:
        "200":
          description: Persisted filing payload
          headers:
            X-Content-SHA256:
              schema: { type: string, pattern: "^[a-f0-9]{64}$" }
          content:
            application/xml: { schema: { type: string } }
            text/csv: { schema: { type: string } }
            application/json: { schema: { type: object } }
            application/pdf: { schema: { type: string, format: binary } }
            application/octet-stream: { schema: { type: string, format: binary } }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/reports/{reportID}/{action}:
    post:
      operationId: decideReport
      tags: [Reporting]
      summary: Review, approve, record external filing evidence or record a regulator receipt
      description: |
        This installation has no built-in NFIU/goAML transport endpoint or credentials.
        Local validation and approval never claim delivery. `record-submission` is the
        explicit manual boundary: after an authorised user exports and files the exact
        bytes through the authorised external channel, they record the externally obtained
        reference and actual filing time. The server binds that evidence to the authenticated
        actor and the immutable payload/schema digests. The database refuses `submitted`,
        `acknowledged` and `rejected` states without matching evidence.

        The legacy `submit` action is intentionally absent from the supported enum and fails
        closed if an older client calls it. Placeholder schemas and stale XSD proof remain
        independently non-fileable (Q1).
      x-permission: reporting.report.file
      parameters:
        - { $ref: "#/components/parameters/ReportID" }
        - name: action
          in: path
          required: true
          schema: { type: string, enum: [review, approve, record-submission, acknowledge, reject] }
      requestBody:
        description: |
          Required for `record-submission`, `acknowledge` and `reject`; omitted for `review` and
          `approve`. OpenAPI cannot condition `requestBody.required` on the `action` path
          parameter, so the operation remains optional while each accepted body shape is closed
          and requires its own evidence fields.
        required: false
        content:
          application/json:
            schema:
              oneOf:
                - $ref: "#/components/schemas/ExternalSubmissionInput"
                - type: object
                  additionalProperties: false
                  required: [external_reference]
                  properties:
                    external_reference:
                      type: string
                      minLength: 1
                      description: Required for acknowledge and reject; the regulator's later receipt reference.
                    reason:
                      type: string
                      minLength: 1
                      maxLength: 2000
                      description: Required for reject; the bounded rejection reason returned by the regulator.
      responses:
        "200":
          description: The report in its new state
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Report" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "422":
          description: External filing evidence is missing, malformed or inconsistent with approval time.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "409":
          description: |
            The transition is not allowed from the report's current state, or the report
            was generated against a non-authoritative schema, has stale validation proof,
            lacks immutable external filing evidence, or direct transport is unavailable.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  # --------------------------------------------------- Aggregate report distribution
  # This surface is intentionally separate from /v1/reports. It cannot create or submit a
  # regulatory filing. Every artifact is built from disclosure-controlled aggregate metrics.

  /v1/report-board-layouts:
    get:
      operationId: listReportBoardLayouts
      tags: [Report distribution]
      summary: List validated internal-board layouts
      description: |
        Returns the fully resolved, closed-vocabulary layouts available to this tenant. A
        schedule selects one key; the complete canonical layout and its provenance are then
        snapshotted into each immutable occurrence, so later configuration changes cannot
        rewrite an already-created board pack.
      x-permission: distribution.schedule.read
      responses:
        "200":
          description: Validated board layouts
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReportBoardLayoutPage" }

  /v1/report-schedules:
    get:
      operationId: listReportSchedules
      tags: [Report distribution]
      summary: List aggregate report schedules
      description: |
        Returns tenant-owned schedules. Retired schedules are hidden by default but their
        immutable run history is retained. Recipient addresses are never stored on schedules;
        only tenant user identifiers are returned. Results are ordered by creation time,
        newest first by default. Cursors bind the institution, include_retired filter and selected order.
      x-permission: distribution.schedule.read
      parameters:
        - $ref: "#/components/parameters/Limit"
        - $ref: "#/components/parameters/Cursor"
        - name: include_retired
          in: query
          description: Include soft-retired schedules without deleting their history.
          schema: { type: boolean, default: false }
        - name: sort
          in: query
          description: Indexed tuple ordering; changing filters or order starts a new cursor walk.
          schema: { type: string, enum: [created_at_desc, created_at_asc], default: created_at_desc }
      responses:
        "200":
          description: Aggregate report schedules
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReportSchedulePage" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "503": { $ref: "#/components/responses/Unavailable" }

    post:
      operationId: createReportSchedule
      tags: [Report distribution]
      summary: Create an aggregate report schedule
      description: |
        Stores tenant user identifiers, not email addresses. Current tenant email addresses
        are resolved immediately before delivery so an address correction does not leave a
        second plaintext copy in scheduling history.
      x-permission: distribution.schedule.manage
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ReportScheduleInput" }
      responses:
        "201":
          description: The active schedule and its first occurrence
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReportSchedule" }
        "400": { $ref: "#/components/responses/BadRequest" }

  /v1/report-schedules/preview:
    post:
      operationId: previewScheduledReport
      tags: [Report distribution]
      summary: Preview an aggregate board artifact
      description: |
        Builds a disclosure-controlled artifact for an explicit half-open window without
        creating a schedule or claiming email delivery. Missing metric streams remain marked
        unavailable; suppressed cells remain suppressed rather than becoming zero. This is a
        generation operation and appends an audit event, so read-only artifact-download access
        is insufficient.
      x-permission: distribution.schedule.manage
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ReportPreviewInput" }
      responses:
        "200":
          description: Generated preview bytes
          headers:
            Digest:
              description: RFC 3230 SHA-256 digest of the returned bytes.
              schema: { type: string }
            X-Content-SHA256:
              schema: { type: string, pattern: "^[a-f0-9]{64}$" }
          content:
            application/json: { schema: { type: string, format: binary } }
            text/csv: { schema: { type: string, format: binary } }
        "400": { $ref: "#/components/responses/BadRequest" }

  /v1/report-schedules/{scheduleID}:
    get:
      operationId: getReportSchedule
      tags: [Report distribution]
      summary: Get an aggregate report schedule
      x-permission: distribution.schedule.read
      parameters:
        - { $ref: "#/components/parameters/ReportScheduleID" }
      responses:
        "200":
          description: The schedule
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReportSchedule" }
        "404": { $ref: "#/components/responses/NotFound" }
    patch:
      operationId: updateReportSchedule
      tags: [Report distribution]
      summary: Replace an aggregate report schedule's editable configuration
      description: Existing run occurrences and their recipient user snapshots are unchanged.
      x-permission: distribution.schedule.manage
      parameters:
        - { $ref: "#/components/parameters/ReportScheduleID" }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ReportScheduleInput" }
      responses:
        "200":
          description: The updated schedule
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReportSchedule" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/report-schedules/{scheduleID}/state/{action}:
    post:
      operationId: changeReportScheduleState
      tags: [Report distribution]
      summary: Pause, resume or retire an aggregate report schedule
      description: Pausing or retiring is soft; immutable run and delivery history is retained.
      x-permission: distribution.schedule.manage
      parameters:
        - { $ref: "#/components/parameters/ReportScheduleID" }
        - name: action
          in: path
          required: true
          schema: { type: string, enum: [pause, resume, retire] }
      responses:
        "200":
          description: The schedule in its new state
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReportSchedule" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/report-schedules/{scheduleID}/run:
    post:
      operationId: runReportSchedule
      tags: [Report distribution]
      summary: Queue the schedule's latest completed reporting window
      description: |
        The occurrence key is the schedule and scheduled-for instant. Repeating this request
        for the same occurrence returns the existing run and cannot enqueue a second delivery.
      x-permission: distribution.schedule.manage
      parameters:
        - { $ref: "#/components/parameters/ReportScheduleID" }
      responses:
        "200":
          description: The occurrence already existed
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReportRunRequestResult" }
        "201":
          description: A new occurrence was durably queued
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReportRunRequestResult" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409": { $ref: "#/components/responses/Conflict" }

  /v1/report-schedules/{scheduleID}/runs:
    get:
      operationId: listScheduledReportRuns
      tags: [Report distribution]
      summary: List a schedule's immutable run ledger
      x-permission: distribution.schedule.read
      parameters:
        - { $ref: "#/components/parameters/ReportScheduleID" }
        - { $ref: "#/components/parameters/Limit" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: Newest report occurrences first
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReportRunPage" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/report-runs/{runID}:
    get:
      operationId: getScheduledReportRun
      tags: [Report distribution]
      summary: Get an immutable aggregate report run
      x-permission: distribution.schedule.read
      parameters:
        - { $ref: "#/components/parameters/ReportRunID" }
      responses:
        "200":
          description: The run and its current delivery state
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReportRun" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/report-runs/{runID}/events:
    get:
      operationId: listScheduledReportRunEvents
      tags: [Report distribution]
      summary: List append-only generation and delivery transitions
      x-permission: distribution.schedule.read
      parameters:
        - { $ref: "#/components/parameters/ReportRunID" }
      responses:
        "200":
          description: The immutable transition ledger
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReportRunEventPage" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/report-runs/{runID}/artifact:
    get:
      operationId: downloadScheduledReportArtifact
      tags: [Report distribution]
      summary: Download the stored aggregate artifact bytes
      description: |
        Returns the write-once bytes generated for this occurrence, not a reconstruction from
        live data. The digest identifies those exact bytes. This artifact is not a regulatory
        filing or proof of any external submission.
      x-permission: distribution.artifact.download
      parameters:
        - { $ref: "#/components/parameters/ReportRunID" }
      responses:
        "200":
          description: Immutable artifact bytes
          headers:
            Digest:
              description: RFC 3230 SHA-256 digest of the returned bytes.
              schema: { type: string }
            X-Content-SHA256:
              schema: { type: string, pattern: "^[a-f0-9]{64}$" }
          content:
            application/json: { schema: { type: string, format: binary } }
            text/csv: { schema: { type: string, format: binary } }
        "404": { $ref: "#/components/responses/NotFound" }
        "409": { $ref: "#/components/responses/Conflict" }

  # ------------------------------------------------------------- Metrics
  #
  # Every operation below returns counts and nothing else. Small-cell suppression happens
  # INSIDE the SQL, so a filtered count of 1..4 never leaves the database, and there is
  # deliberately no parameter anywhere on this surface that relaxes it (ADR-0027, Q29).

  /v1/metrics/executive:
    get:
      operationId: getExecutiveAnalytics
      tags: [Metrics]
      summary: Current active-book risk exposure plus filing trend and deadline status
      description: |
        BRD §8.8-05..10's aggregate executive surface. Risk is the complete CURRENT active
        customer book at `risk_as_of`; the filing window does not filter customers by their
        relationship start and is not presented as historical risk. `historical_risk_available`
        remains false until an append-only/SCD risk source exists.

        Sector is derived from the legal party's shipped industry vocabulary or the natural
        party's bounded occupation risk codes. Unknown/free-text values collapse to `other`, and
        geography admits only a two-letter code or `UNKNOWN`, so a suppressed cell label cannot
        itself contain a customer's name. Counts below five are replaced by null inside SQL and
        complementary cells are withheld in the service. Projection coverage compares analytics'
        active rows with onboarding's authoritative active-customer control total; matrices are
        withheld when those differ. Every successful read is appended to the tenant audit chain.
      x-permission: analytics.metric.read
      parameters:
        - { $ref: "#/components/parameters/MetricFrom" }
        - { $ref: "#/components/parameters/MetricTo" }
        - name: grain
          in: query
          schema: { type: string, enum: [day, week, month, quarter, year], default: month }
        - name: dimensions
          in: query
          style: form
          explode: false
          description: One to three unique current-risk dimensions. Defaults to all three.
          schema:
            type: array
            minItems: 1
            maxItems: 3
            uniqueItems: true
            items: { type: string, enum: [sector, geography, kyc_tier] }
      responses:
        "200":
          description: Disclosure-controlled executive aggregate; no customer records or identifiers.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ExecutiveAnalytics" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/metrics/executive/export:
    get:
      operationId: exportExecutiveAnalytics
      tags: [Metrics]
      summary: Export the exact executive aggregate as JSON or CSV
      description: |
        Computes one ExecutiveAnalytics object and serialises that same object once; the CSV
        path does not issue a second query. Content-Disposition names the artifact, Digest and
        X-Content-SHA256 identify its exact bytes, and the query plus digest are appended to the
        tenant's audit chain before any bytes leave the process.
      x-permission: analytics.executive.export
      parameters:
        - { $ref: "#/components/parameters/MetricFrom" }
        - { $ref: "#/components/parameters/MetricTo" }
        - name: grain
          in: query
          schema: { type: string, enum: [day, week, month, quarter, year], default: month }
        - name: dimensions
          in: query
          style: form
          explode: false
          schema:
            type: array
            minItems: 1
            maxItems: 3
            uniqueItems: true
            items: { type: string, enum: [sector, geography, kyc_tier] }
        - name: format
          in: query
          required: true
          schema: { type: string, enum: [json, csv, pdf, xlsx] }
      responses:
        "200":
          description: The exact aggregate artifact bytes.
          headers:
            Content-Disposition:
              schema: { type: string }
            Digest:
              schema: { type: string }
            X-Content-SHA256:
              schema: { type: string, pattern: "^[a-f0-9]{64}$" }
          content:
            application/json: { schema: { type: string, format: binary } }
            text/csv: { schema: { type: string, format: binary } }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/metrics/alerts/false-positive-rate:
    get:
      operationId: getFalsePositiveRate
      tags: [Metrics]
      summary: The alert false-positive rate over a window
      description: |
        BRD §13's headline alert KPI, and the number ADR-0017 says an MLRO manages by.

        `rate` is null whenever either component was suppressed, or when nothing closed in the
        window. Publishing "3%" against a visible denominator of 100 republishes the numerator
        that was suppressed for a reason, and one division is not a defence. "0% false positives"
        and "nothing was closed" are opposite reports of the same fact, so the second is an absent
        rate rather than a zero.

        `breakdown` carries every closing disposition rather than only the numerator: an MLRO
        managing false positives needs to see what the other closures were.
      x-permission: analytics.metric.read
      parameters:
        - { $ref: "#/components/parameters/MetricFrom" }
        - { $ref: "#/components/parameters/MetricTo" }
        - name: rule_key
          in: query
          description: |
            Narrows to one rule. This is the parameter that makes suppression necessary rather
            than tidy: it is the knob that narrows a population until a count names somebody.
          schema: { type: string }
      responses:
        "200":
          description: The rate, its components and the coverage of the stream behind it
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MetricRate" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/metrics/cases/ageing:
    get:
      operationId: getCaseAgeing
      tags: [Metrics]
      summary: Ageing bands for cases still open
      description: |
        BRD §8.8's ageing tile, computed in the database over every open case rather than in the
        browser over a bounded page of them. The dashboard previously derived this from
        `?limit=100`: at a microfinance bank that is wasteful, at a tier-1 bank the tile describes
        the first hundred rows and looks exactly as confident as a correct one.
      x-permission: analytics.metric.read
      parameters:
        - { $ref: "#/components/parameters/MetricAsOf" }
        - name: priority
          in: query
          schema: { type: string, enum: [p1, p2, p3, p4] }
      responses:
        "200":
          description: One cell per ageing band
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MetricDistribution" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/metrics/screening/false-positive-rate:
    get:
      operationId: getScreeningFalsePositiveRate
      tags: [Metrics]
      summary: The screening false-positive rate over a window
      description: |
        BRD §8.4-08 asks for configurable match sensitivity balancing false positives against
        risk. This is the half of that sentence the product could not previously show.

        Screening is the highest-volume false-positive generator in the platform — one common
        surname against a consolidated sanctions list produces hits by the thousand — and until
        the `screening.outcome` stream existed the only number held about it was a live count of
        the pending queue. Nothing said how many decided hits were wrong, so a tenant moving
        `screening.match.threshold` was turning a dial with no gauge attached.

        Identical semantics to the alert rate, deliberately: `rate` is null whenever either
        component was suppressed or nothing was decided in the window, and `breakdown` carries
        every disposition — `true_positive`, `false_positive` and `suppressed` — because the
        other decisions are what make the rate interpretable. A hit cleared by a standing
        suppression is counted as decided at the instant it was raised, since the human decision
        it rests on was made before the hit existed.
      x-permission: analytics.metric.read
      parameters:
        - { $ref: "#/components/parameters/MetricFrom" }
        - { $ref: "#/components/parameters/MetricTo" }
        - name: watchlist_key
          in: query
          description: |
            Narrows to one list. The dimension that makes the number actionable: a rate
            concentrated in one list is a list problem, the same rate spread evenly is a
            threshold problem. It is also a filter that narrows a population until a count could
            name somebody, which is why suppression is inside the query.
          schema: { type: string }
      responses:
        "200":
          description: The rate, its components and the coverage of the stream behind it
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MetricRate" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/metrics/screening/ageing:
    get:
      operationId: getScreeningHitAgeing
      tags: [Metrics]
      summary: Ageing bands for screening hits still awaiting a decision
      description: |
        How long hits have been waiting, which the pending count on the dashboard has never
        been able to say. Forty hits raised this morning and forty raised five weeks ago are the
        same tile and are not the same institution, and the second one is what an examiner opens
        with.

        Counts only hits that are still pending. A decided hit has an age, but "how long did we
        take" and "how long has this been sitting" are different questions, and conflating them
        is how an ageing chart improves by deciding nothing. The bands are the same ones the case
        ageing panel uses, so the two can be read side by side without rescaling.
      x-permission: analytics.metric.read
      parameters:
        - { $ref: "#/components/parameters/MetricAsOf" }
        - name: watchlist_key
          in: query
          description: Narrows to one list.
          schema: { type: string }
      responses:
        "200":
          description: One cell per ageing band
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MetricDistribution" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/metrics/sla/breaches:
    get:
      operationId: getSLABreaches
      tags: [Metrics]
      summary: SLA breach counts, split by whether the work is late now or was delivered late
      x-permission: analytics.metric.read
      parameters:
        - { $ref: "#/components/parameters/MetricAsOf" }
        - name: stream
          in: query
          description: Omit for every stream that carries a deadline.
          schema:
            type: string
            enum: [alert.outcome, case.lifecycle, filing.volume, filing.deadline, screening.outcome]
      responses:
        "200":
          description: One cell per stream and breach kind
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MetricDistribution" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/metrics/filings/volumes:
    get:
      operationId: getFilingVolumes
      tags: [Metrics]
      summary: Filing volumes and trend, bucketed by period
      x-permission: analytics.metric.read
      parameters:
        - { $ref: "#/components/parameters/MetricFrom" }
        - { $ref: "#/components/parameters/MetricTo" }
        - name: grain
          in: query
          description: |
            The period bucket. A closed set because it is bound into `date_trunc`: a value
            outside it would arrive at the caller as a Postgres error through a dashboard.
          schema: { type: string, enum: [day, week, month, quarter, year], default: month }
        - name: kind
          in: query
          description: Narrows to one report kind.
          schema: { type: string, enum: [STR, CTR, SCUML, CBN_RETURN, BOARD] }
      responses:
        "200":
          description: One point per period, kind and status
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MetricSeries" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/metrics/filings/deadlines:
    get:
      operationId: getFilingDeadlines
      tags: [Metrics]
      summary: Regulatory deadline tracking
      description: |
        Reporting creates deadlines from governed reporting.deadlines configuration, publishes
        each current state, sweeps breached items and marks submitted filings met. A tenant for
        which the stream has never been published still returns UNAVAILABLE, never a confident
        zero; `coverage.reason` names reporting and freshness remains visible.

        Configured intervals retain their compliance-validation provenance rather than being
        presented here as hard-coded statutory claims.
      x-permission: analytics.metric.read
      parameters:
        - { $ref: "#/components/parameters/MetricAsOf" }
        - name: kind
          in: query
          schema: { type: string, enum: [STR, CTR, SCUML, CBN_RETURN, BOARD] }
      responses:
        "200":
          description: One cell per deadline status and horizon
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MetricDistribution" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /v1/metrics/coverage:
    get:
      operationId: getMetricCoverage
      tags: [Metrics]
      summary: Which metric streams are being published, and the live review-queue count
      description: |
        What a dashboard should render before it renders a single tile: per stream, whether
        anybody publishes it and when they last did. A stream that stopped being published a
        fortnight ago must not read as a quiet fortnight, and a stream nobody has ever published
        must name the module that owes it.

        `review_queue.pending_screening_hits` is the one live count on this surface and is
        deliberately NOT an analytics metric. It is a count of work in progress rather than a KPI
        over a period, screening already owns it, and routing it through a published fact would
        add publication lag to a number whose entire value is being current (ADR-0027).
      x-permission: analytics.metric.read
      responses:
        "200":
          description: Coverage per stream, plus the review-queue badge
          content:
            application/json:
              schema:
                type: object
                required: [coverage, review_queue]
                properties:
                  coverage: { $ref: "#/components/schemas/MetricCoveragePage" }
                  review_queue:
                    type: object
                    required: [pending_screening_hits]
                    properties:
                      pending_screening_hits: { type: integer, format: int64 }
        "403": { $ref: "#/components/responses/Forbidden" }

  # ------------------------------------------------------------- Watchlists

  /v1/watchlists/lists:
    get:
      operationId: listWatchlists
      tags: [Watchlists]
      summary: The internal lists this institution maintains
      x-permission: watchlists.list.read
      responses:
        "200":
          description: Internal lists, complete
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WatchlistPage" }
        "403": { $ref: "#/components/responses/Forbidden" }
    post:
      operationId: createWatchlist
      tags: [Watchlists]
      summary: Register an internal blacklist or greylist
      description: |
        A blacklist and a greylist are different decisions rather than two severities of one: a
        blacklist entry says "do not do business with this party", a greylist entry says "do
        business and watch it". Both surface as screening hits and the analyst has to be able to
        tell them apart, so the distinction is a column rather than a convention.

        A duplicate key is refused rather than silently updated: two teams maintaining a list
        under the same key is how an institution ends up with a third copy nobody is sure is
        authoritative.
      x-permission: watchlists.list.write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [key, kind]
              properties:
                key: { type: string, minLength: 1 }
                name: { type: string }
                kind: { type: string, enum: [internal_black, internal_grey] }
                description: { type: string }
      responses:
        "201":
          description: The list
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Watchlist" }
        "409": { $ref: "#/components/responses/Conflict" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/watchlists/lists/{listKey}/entries:
    get:
      operationId: listWatchlistEntries
      tags: [Watchlists]
      summary: A list's entries
      description: |
        Removal is a soft delete, so `include_removed=true` is how an examiner asking who was on
        the blacklist in March gets an answer. The maintenance screen does not want them, which
        is why it is opt-in.

        Results use an immutable descending UUIDv7 keyset. `next_cursor` resumes after the last
        entry on this bounded page, so every matching row remains reachable without OFFSET scans
        and edits to a name or rationale cannot move a row across a page boundary. Counts derived
        from `items` are page-scoped, never totals for the master list.
      x-permission: watchlists.entry.read
      parameters:
        - { $ref: "#/components/parameters/ListKey" }
        - name: include_removed
          in: query
          schema: { type: boolean, default: false }
        - name: party_id
          in: query
          description: Narrows to the entries about one party this platform holds.
          schema: { type: string, format: uuid }
        - { $ref: "#/components/parameters/Cursor" }
        - { $ref: "#/components/parameters/Limit" }
      responses:
        "200":
          description: A bounded, resumable page of entries in immutable descending UUIDv7 order
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WatchlistEntryPage" }
        "404": { $ref: "#/components/responses/NotFound" }
    post:
      operationId: addWatchlistEntry
      tags: [Watchlists]
      summary: Add or update one entry
      description: |
        Re-adding an existing `external_id` UPDATES the entry rather than failing, because the
        alternative is a maintenance screen that can only ever append. The unique index covers
        live rows only, so a customer exited in 2024 and re-onboarded and re-exited in 2026 gets
        a second entry while the first stays as the record of the first exit.

        `reason` is required and enforced non-empty by the database: an entry nobody can justify
        is one nobody will ever dare remove. `party_id` is what lets screening tell a self-match
        from a real one.

        Adding to a blacklist is a mandatory maker-checker change. In that case this operation
        records the exact digest-bound proposal, applies no entry, and returns `202` with the
        approval identity. Adding to a greylist increases scrutiny and remains an immediate
        `201` operation.
      x-permission: watchlists.list.write
      parameters:
        - { $ref: "#/components/parameters/ListKey" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [external_id, primary_name, reason]
              properties:
                external_id: { type: string, minLength: 1 }
                entity_kind: { type: string, enum: [natural, legal, vessel, aircraft, unknown], default: natural }
                primary_name: { type: string, minLength: 1 }
                aliases:
                  type: array
                  items: { type: string }
                party_id: { type: string, format: uuid }
                reason_code:
                  type: string
                  description: |
                    Deliberately not a database CHECK. BRD §7.2 makes vocabularies like this
                    tenant-configurable, and an institution needing "correspondent de-risked"
                    should not need a migration to record it. `exited_customer`,
                    `internal_flag`, `fraud`, `regulatory_request` and `other` are the defaults a
                    UI offers, not a closed set.
                reason: { type: string, minLength: 1 }
                date_of_birth: { type: string }
                nationality: { type: string }
                identifier: { type: string }
                expires_at:
                  type: string
                  format: date-time
                  description: |
                    An internal list that only grows becomes a list nobody trusts — the same
                    argument ADR-0015 makes for expiring match suppressions.
      responses:
        "201":
          description: The entry
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WatchlistEntry" }
        "202":
          description: A blacklist addition was recorded for independent approval and was not applied.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WatchlistChangeApproval" }
        "404": { $ref: "#/components/responses/NotFound" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/watchlists/entries/{entryID}/removal:
    post:
      operationId: removeWatchlistEntry
      tags: [Watchlists]
      summary: Remove an entry, with a reason
      description: |
        A soft delete. The row survives, because an audit entry pointing at a row that no longer
        exists is only half a record, and "who was on the blacklist in March, and why" needs the
        row.

        The required compliance rationale travels only in a closed JSON body. It must never be a
        query parameter: URLs are retained by access logs, browser history, referrers and support
        screenshots. Taking a name OFF a blacklist is the change an examiner is most likely to
        ask about, so a missing, blank or over-long body refuses the operation. The existing
        `watchlists.list.write` permission and its configured MFA policy still govern this action.
        The rationale remains on the protected soft-deleted entry; the generic immutable audit
        event records only opaque entry/list ids, the reason code and that a removal rationale was
        recorded, so `audit.event.read` does not bypass `watchlists.entry.read`.

        Removal from either blacklist or greylist is mandatory maker-checker. A valid request
        therefore records the exact digest-bound proposal and returns `202`; the entry remains
        live until a different authorised user approves it. `200` is retained for installations
        deliberately constructed without the optional workflow dependency, whose audit record
        explicitly states that four-eyes was not enforced.
      x-permission: watchlists.list.write
      parameters:
        - { $ref: "#/components/parameters/EntryID" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [reason]
              properties:
                reason:
                  type: string
                  minLength: 1
                  maxLength: 2000
      responses:
        "200":
          description: The removed entry, still readable
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WatchlistEntry" }
        "202":
          description: The removal was recorded for independent approval and was not applied.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WatchlistChangeApproval" }
        "404":
          description: No such entry, or it was already removed — a second removal must not write a second audit event.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/watchlists/lists/{listKey}/import:
    post:
      operationId: importWatchlist
      tags: [Watchlists]
      summary: Bulk import entries from a CSV
      description: |
        The body is the CSV itself (`curl --data-binary @list.csv`), not a multipart form: the
        caller is an operations script or a compliance officer, not a browser.

        **Malformed rows are quarantined, not fatal, and the run finishes `partial`.** ADR-0014
        made this argument for transaction ingest and it is stronger here: an upload that aborts
        on row 9 leaves the institution screening against the list as it stood before the upload
        while the screen says the upload failed — a state that reads as a fixable inconvenience
        and is actually a compliance gap, because the names in rows 10 through 40,000 are not
        being screened for and nobody has been told which ones. The rejected rows are kept
        verbatim with their line numbers and are readable at `/imports/{importID}/quarantine`.

        A missing required HEADER column is treated differently and fails the whole file, because
        every row would quarantine for the same reason and forty thousand identical quarantine
        lines hide the one fact that matters.

        The format is exactly what `/export` produces. The two round-trip, and a test asserts it.
        An optional bare filename travels in the bounded `X-Filename` header, never a query
        parameter: request URLs are routinely retained in access logs, browser history and
        support traces. It is retained on the protected reconciliation row and is not copied to
        the generic audit event.

        A blacklist import is mandatory maker-checker, including a one-row file so bulk import
        cannot bypass the single-entry gate. The parsed valid records and quarantined failures
        are bound into the approval payload; no list entry or reconciliation row is written
        before approval. Greylist import increases scrutiny and remains an immediate `200`.
      x-permission: watchlists.list.import
      parameters:
        - { $ref: "#/components/parameters/ListKey" }
        - $ref: "#/components/parameters/IdempotencyKey"
        - name: X-Filename
          in: header
          description: Optional bare filename retained on the reconciliation record; path separators are refused.
          schema: { type: string, maxLength: 255 }
      requestBody:
        required: true
        content:
          text/csv:
            schema: { type: string }
      responses:
        "200":
          description: The reconciliation record for this file
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WatchlistImportResult" }
        "202":
          description: A blacklist import was parsed and recorded for independent approval, but no entries were applied.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WatchlistChangeApproval" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "404": { $ref: "#/components/responses/NotFound" }
        "413":
          description: The file exceeds the endpoint's limit. Split it; import matches on external_id, so an overlap is an update.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }
        "415":
          description: The body was not a CSV.
          content:
            application/problem+json:
              schema: { $ref: "#/components/schemas/Problem" }

  /v1/watchlists/lists/{listKey}/export:
    get:
      operationId: exportWatchlist
      tags: [Watchlists]
      summary: Export a list in the format import accepts
      description: |
        Round-tripping is a requirement rather than a nicety: an export a compliance team cannot
        feed back in is a dead end, and the usual way it becomes one is a field that survives the
        database and not the file.

        Only live entries are exported — not removed, not expired. `X-Watchlist-Entry-Count`
        carries the row count so a script can reconcile what it received without parsing the file
        it just downloaded.

        Deliberately unaudited: an export reads, and it changes no list.
      x-permission: watchlists.list.import
      parameters:
        - { $ref: "#/components/parameters/ListKey" }
      responses:
        "200":
          description: The list as CSV
          headers:
            X-Watchlist-Entry-Count:
              description: How many live entries were written.
              schema: { type: integer }
            Content-Disposition:
              schema: { type: string }
          content:
            text/csv:
              schema: { type: string }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/watchlists/imports/{importID}/quarantine:
    get:
      operationId: getWatchlistQuarantine
      tags: [Watchlists]
      summary: The rows one import rejected
      description: |
        This is what makes quarantining better than failing rather than merely different. Rows
        held in a table that nothing can read are rows that were dropped with extra steps.
      x-permission: watchlists.list.import
      parameters:
        - { $ref: "#/components/parameters/ImportID" }
      responses:
        "200":
          description: Quarantined rows, with their line numbers and reasons
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WatchlistRowErrorPage" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/watchlists/lists/{listKey}/publish:
    post:
      operationId: publishWatchlist
      tags: [Watchlists]
      summary: Publish a list into the screening index
      description: |
        Its own permission because it is its own decision: editing an entry changes a list,
        publishing changes who the institution screens against from that moment on. Every
        screening hit pins the version it matched, which is what makes "which list, as it stood
        when, produced this hit" answerable about a filing made two years ago (ADR-0015).

        Idempotent on CONTENT rather than on time. The version string is a timestamp plus a
        digest over the entry set, so republishing an unchanged list writes nothing and comes
        back with `published: false`. A version per save would turn the version history into a
        log of who pressed the button, and every hit pins a version precisely so that history
        means something.
      x-permission: watchlists.list.publish
      parameters:
        - { $ref: "#/components/parameters/ListKey" }
      responses:
        "200":
          description: What was published, or that nothing needed to be
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WatchlistPublishResult" }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/watchlists/sources:
    get:
      operationId: listWatchlistSources
      tags: [Watchlists]
      summary: Configured provider feeds and their refresh state
      description: |
        Expect this to be empty, and expect any row in it to be failing. No provider adapter
        ships (Q6), so a configured source records `ErrNoProvider` against itself on every run —
        which is the honest state of an installation with no licensed feed, and far better than a
        placeholder that makes screening look like it is happening.
      x-permission: watchlists.source.read
      responses:
        "200":
          description: Sources, complete
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WatchlistSourcePage" }

  /v1/watchlists/sources/{listKey}:
    put:
      operationId: configureWatchlistSource
      tags: [Watchlists]
      summary: Bind a list to a provider feed
      description: |
        PUT rather than POST because there is at most one source per list key and the underlying
        write is an upsert: sending the same body twice must leave the same single binding.

        `enabled` defaults to false and should stay there until somebody licenses a feed. Q6 has
        not established whether a commercial list may be redistributed to an on-premise client's
        data centre at all, and a source that defaulted to enabled would answer that question by
        accident on first install.

        `list_kind` and `list_source` restate CHECK constraints that also live on `app.watchlist`.
        The duplication is accepted deliberately: this module cannot read that table, and
        discovering after a fetch and a parse that "PEP" is not a valid kind turns a configuration
        mistake into a failed job. Failing at configuration time is the cheaper place to be wrong.
      x-permission: watchlists.source.configure
      parameters:
        - { $ref: "#/components/parameters/ListKey" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [provider]
              properties:
                provider:
                  type: string
                  description: |
                    The adapter id. No adapter ships, so any value here refers to nothing until
                    somebody licenses a feed and registers an implementation (Q6).
                list_name: { type: string }
                list_kind: { type: string, enum: [sanctions, pep, adverse_media], default: sanctions }
                list_source: { type: string, enum: [UN, OFAC, EU, UK_HMT, NFIU, CBN, NIGSAC, COMMERCIAL], default: COMMERCIAL }
                enabled: { type: boolean, default: false }
                settings:
                  type: object
                  additionalProperties: true
                  description: The adapter's own configuration — endpoint, credentials reference, list selection. Opaque here on purpose.
                interval_hours:
                  type: integer
                  minimum: 1
                  default: 24
                  description: |
                    Hours rather than a cron expression: the free consolidated lists publish daily
                    at best, and a cron field invites a schedule nobody can reason about from a
                    screen.
      responses:
        "200":
          description: The source binding
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WatchlistSource" }
        "422": { $ref: "#/components/responses/ValidationFailed" }

  /v1/watchlists/sources/{listKey}/refresh:
    post:
      operationId: refreshWatchlistSource
      tags: [Watchlists]
      summary: Refresh one source now
      description: |
        Runs the source whether or not it is due, synchronously, so the operator sees the answer
        rather than being told a job was queued. The scheduled equivalent is the six-hourly
        `refresh_watchlists` job, which runs every source that has fallen due.

        A refresh that cannot run comes back `200` with `status: "failed"` and the reason, not as
        an error. The refusal is a FACT about that feed which has just been recorded against the
        source, and a 5xx would roll back the record of why it failed — the one thing an operator
        needs. In every installation today the reason is that no provider adapter is registered.
      x-permission: watchlists.source.configure
      parameters:
        - { $ref: "#/components/parameters/ListKey" }
      responses:
        "200":
          description: The outcome, including a recorded failure
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WatchlistRefreshResult" }
        "404": { $ref: "#/components/responses/NotFound" }


  /v1/kyc-reviews/{reviewID}:
    get:
      operationId: getKYCReview
      summary: Get k y c review
      tags:
      - Domain operations
      x-permission: onboarding.customer.read
      security:
      - bearerAuth: []
      parameters:
      - name: reviewID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/KYCReview'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
  /v1/kyc-reviews/{reviewID}/evidence:
    get:
      operationId: listReviewDocuments
      summary: List review documents
      description: Requires customer read and either customer write for the assigned review investigator or application review for a checker.
      x-additional-permissions-any-of:
      - onboarding.customer.write
      - onboarding.application.review
      tags:
      - Domain operations
      x-permission: onboarding.customer.read
      security:
      - bearerAuth: []
      parameters:
      - name: reviewID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      - name: limit
        in: query
        schema:
          type: integer
          minimum: 1
          maximum: 200
          default: 50
      - name: cursor
        in: query
        schema:
          type: string
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OnboardingDocumentPage'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
    post:
      operationId: uploadReviewDocument
      summary: Upload review document
      tags:
      - Domain operations
      x-permission: onboarding.customer.write
      security:
      - bearerAuth: []
      parameters:
      - name: reviewID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      - name: Idempotency-Key
        in: header
        required: true
        schema:
          type: string
          format: uuid
      - name: Content-Disposition
        in: header
        required: true
        schema:
          type: string
      - name: doc_type
        in: query
        required: true
        schema:
          type: string
      - name: expires_on
        in: query
        schema:
          type: string
          format: date
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OnboardingDocument'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/pdf:
            schema:
              type: string
              format: binary
          image/jpeg:
            schema:
              type: string
              format: binary
          image/png:
            schema:
              type: string
              format: binary
  /v1/customers/{customerID}/expected-activity:
    get:
      operationId: getExpectedActivity
      summary: Get expected activity
      tags:
      - Domain operations
      x-permission: onboarding.application.review
      security:
      - bearerAuth: []
      parameters:
      - name: customerID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ExpectedActivityBaseline'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
  /v1/customers/{customerID}/ownership-graph:
    get:
      operationId: getOwnershipGraph
      summary: Get ownership graph
      tags:
      - Domain operations
      x-permission: onboarding.customer.read
      security:
      - bearerAuth: []
      parameters:
      - name: customerID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      - name: as_of
        in: query
        schema:
          type: string
          format: date-time
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OwnershipGraph'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
  /v1/transactions/batches:
    get:
      operationId: listBatchRegister
      summary: List batch register
      tags:
      - Domain operations
      description: |
        Filters apply before the bounded tuple page. Cursors bind tenant, scope and order.
        Old unbound cursors must restart. Every read rechecks current tenant permissions.
      x-permission: monitoring.data_operations.read
      security:
      - bearerAuth: []
      parameters:
      - name: limit
        in: query
        schema:
          type: integer
          minimum: 1
          maximum: 200
          default: 50
      - name: cursor
        in: query
        schema:
          type: string
      - name: source
        in: query
        schema: { type: string, maxLength: 120 }
      - name: status
        in: query
        schema: { type: string, enum: [running, completed, failed, partial] }
      - name: sort
        in: query
        description: Indexed tuple order; filter/order/tenant changes require a new cursor walk.
        schema: { type: string, enum: [started_at_desc, started_at_asc], default: started_at_desc }
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/IngestBatchSummaryPage'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
  /v1/transactions/source-manifests/{manifestID}:
    get:
      operationId: getSourceManifest
      summary: Get source manifest
      tags:
      - Domain operations
      x-permission: monitoring.data_operations.read
      security:
      - bearerAuth: []
      parameters:
      - name: manifestID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SourceManifest'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
  /v1/reference-datasets:
    get:
      operationId: listReferenceDatasets
      summary: List reference datasets
      tags:
      - Domain operations
      x-permission: rules.rule.read
      security:
      - bearerAuth: []
      parameters:
      - name: limit
        in: query
        schema:
          type: integer
          minimum: 1
          maximum: 200
          default: 50
      - name: cursor
        in: query
        schema:
          type: string
      - {name: kind, in: query, schema: {type: string, enum: [geography, fx]}}
      - {name: key, in: query, schema: {type: string, maxLength: 64}}
      - {name: status, in: query, schema: {type: string, enum: [pending, approved, rejected]}}
      - {name: sort, in: query, schema: {type: string, enum: [proposed_at_desc, proposed_at_asc], default: proposed_at_desc}}
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReferenceVersionPage'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
    post:
      operationId: proposeReferenceDataset
      summary: Propose reference dataset
      tags:
      - Domain operations
      x-permission: rules.rule.write
      security:
      - bearerAuth: []
      parameters: []
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReferenceVersion'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ReferenceInput'
  /v1/reference-datasets/{referenceID}/decision:
    post:
      operationId: decideReferenceDataset
      summary: Decide reference dataset
      tags:
      - Domain operations
      x-permission: rules.rule.write
      security:
      - bearerAuth: []
      parameters:
      - name: referenceID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReferenceVersion'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/MaturityDecisionInput'
  /v1/reference-datasets/fx-conversion:
    post:
      operationId: convertFX
      summary: Convert f x
      tags:
      - Domain operations
      x-permission: rules.rule.read
      security:
      - bearerAuth: []
      parameters: []
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FXConversion'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/FXConversionInput'
  /v1/filing-clocks:
    get:
      operationId: listFilingClocks
      summary: List filing clocks
      tags:
      - Domain operations
      x-permission: reporting.report.read
      security:
      - bearerAuth: []
      parameters:
      - name: limit
        in: query
        schema:
          type: integer
          minimum: 1
          maximum: 200
          default: 50
      - name: cursor
        in: query
        schema:
          type: string
      - { name: key, in: query, schema: { type: string, maxLength: 64 } }
      - { name: status, in: query, schema: { type: string, enum: [pending, approved, rejected] } }
      - { name: kind, in: query, schema: { type: string, enum: [STR, CTR, SCUML, CBN_RETURN] } }
      - { name: sort, in: query, schema: { type: string, enum: [proposed_at_desc, proposed_at_asc], default: proposed_at_desc } }
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FilingClockPage'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
    post:
      operationId: proposeFilingClock
      summary: Propose filing clock
      tags:
      - Domain operations
      x-permission: reporting.report.file
      security:
      - bearerAuth: []
      parameters: []
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FilingClock'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/FilingClockInput'
  /v1/filing-clocks/{clockID}/decision:
    post:
      operationId: decideFilingClock
      summary: Decide filing clock
      tags:
      - Domain operations
      x-permission: reporting.report.file
      security:
      - bearerAuth: []
      parameters:
      - name: clockID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FilingClock'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/MaturityDecisionInput'
  /v1/filing-obligations:
    get:
      operationId: listFilingObligations
      summary: List filing obligations
      tags:
      - Domain operations
      x-permission: reporting.report.read
      security:
      - bearerAuth: []
      parameters:
      - name: limit
        in: query
        schema:
          type: integer
          minimum: 1
          maximum: 200
          default: 50
      - name: cursor
        in: query
        schema:
          type: string
      - { name: status, in: query, schema: { type: string, enum: [pending, breached, met] } }
      - { name: kind, in: query, schema: { type: string, enum: [STR, CTR, SCUML, CBN_RETURN] } }
      - { name: sort, in: query, schema: { type: string, enum: [due_at_asc, due_at_desc], default: due_at_asc } }
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FilingObligationPage'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
    post:
      operationId: recordFilingObligation
      summary: Record filing obligation
      tags:
      - Domain operations
      x-permission: reporting.report.generate
      security:
      - bearerAuth: []
      parameters: []
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FilingObligation'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ObligationInput'
  /v1/filing-obligations/{obligationID}/report:
    post:
      operationId: linkFilingObligation
      summary: Link filing obligation
      tags:
      - Domain operations
      x-permission: reporting.report.generate
      security:
      - bearerAuth: []
      parameters:
      - name: obligationID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FilingObligation'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ObligationReportInput'
  /v1/reports/{reportID}/deliver:
    post:
      operationId: deliverReport
      summary: deliverReport
      tags:
      - Reporting
      security:
      - bearerAuth: []
      x-permission: reporting.report.file
      parameters:
      - name: reportID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Bound artifact delivery record; fixture receipts never advance report submission.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReportDeliveryAttempt'
        '403':
          description: Permission required
        '409':
          description: Unapproved or conflicting artifact
        '503':
          description: Channel unavailable
  /v1/reports/{reportID}/delivery-attempts:
    get:
      operationId: listReportDeliveryAttempts
      summary: listReportDeliveryAttempts
      tags:
      - Reporting
      security:
      - bearerAuth: []
      x-permission: reporting.report_content.read
      parameters:
      - name: reportID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      - name: limit
        in: query
        schema:
          type: integer
          minimum: 1
          maximum: 200
          default: 50
      - name: cursor
        in: query
        schema:
          type: string
      responses:
        '200':
          description: Bound artifact delivery record; fixture receipts never advance report submission.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReportDeliveryAttemptPage'
        '403':
          description: Permission required
        '409':
          description: Unapproved or conflicting artifact
        '503':
          description: Channel unavailable
  /v1/report-delivery-attempts/{attemptID}/reconcile:
    post:
      operationId: reconcileReportDelivery
      summary: reconcileReportDelivery
      tags:
      - Reporting
      security:
      - bearerAuth: []
      x-permission: reporting.report.file
      parameters:
      - name: attemptID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Bound artifact delivery record; fixture receipts never advance report submission.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReportDeliveryAttempt'
        '403':
          description: Permission required
        '409':
          description: Unapproved or conflicting artifact
        '503':
          description: Channel unavailable
  /v1/privacy/erasures/{erasureID}/disposition-plans:
    post:
      operationId: createRetentionDispositionPlan
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RetentionDispositionInput'
        required: true
      responses:
        '201':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RetentionDispositionPlan'
          description: Retention disposition result
        '409':
          $ref: '#/components/responses/Conflict'
        '503':
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
          description: Retention policy or inventory archive unavailable
      tags:
      - Privacy
      x-permission: privacy.erasure.create
      parameters:
      - in: path
        name: erasureID
        required: true
        schema:
          format: uuid
          type: string
  /v1/privacy/erasures/{erasureID}/disposition-plans/{planID}:
    get:
      operationId: getRetentionDispositionPlan
      responses:
        '200':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RetentionDispositionPlan'
          description: Retention disposition result
        '409':
          $ref: '#/components/responses/Conflict'
        '503':
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
          description: Retention policy or inventory archive unavailable
      tags:
      - Privacy
      x-permission: privacy.request.read
      parameters:
      - in: path
        name: erasureID
        required: true
        schema:
          format: uuid
          type: string
      - in: path
        name: planID
        required: true
        schema:
          format: uuid
          type: string
  /v1/privacy/erasures/{erasureID}/disposition-plans/{planID}/decision:
    post:
      operationId: decideRetentionDispositionPlan
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RetentionDispositionDecisionInput'
        required: true
      responses:
        '200':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RetentionDispositionPlan'
          description: Retention disposition result
        '409':
          $ref: '#/components/responses/Conflict'
        '503':
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
          description: Retention policy or inventory archive unavailable
      tags:
      - Privacy
      x-permission: privacy.erasure.execute
      parameters:
      - in: path
        name: erasureID
        required: true
        schema:
          format: uuid
          type: string
      - in: path
        name: planID
        required: true
        schema:
          format: uuid
          type: string
  /v1/privacy/erasures/{erasureID}/disposition-preview:
    post:
      operationId: previewRetentionDisposition
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RetentionDispositionInput'
        required: true
      responses:
        '200':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RetentionDispositionPreview'
          description: Retention disposition result
        '409':
          $ref: '#/components/responses/Conflict'
        '503':
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
          description: Retention policy or inventory archive unavailable
      tags:
      - Privacy
      x-permission: privacy.request.read
      parameters:
      - in: path
        name: erasureID
        required: true
        schema:
          format: uuid
          type: string
  /v1/report-delivery-attempts/{attemptID}/replacement:
    post:
      operationId: recordDeliveryRecovery
      summary: Link an independently approved corrected artifact to a rejected receipt
      x-permission: reporting.report.file
      security:
      - bearerAuth: []
      parameters:
      - name: attemptID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DeliveryRecoveryInput'
      responses:
        '200':
          description: Immutable rejection recovery link
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DeliveryRecovery'
        '409':
          description: Artifact is not an approved correction in the original context
  /v1/cases/{caseID}/suspicion:
    post:
      operationId: recognizeSuspicion
      summary: Recognize suspicion
      tags:
      - Domain operations
      x-permission: cases.case.write
      security:
      - bearerAuth: []
      parameters:
      - name: caseID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SuspicionRecognition'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SuspicionInput'
  /v1/rules/outcome-reviews:
    get:
      operationId: listOutcomeReviews
      summary: List outcome reviews
      tags:
      - Domain operations
      x-permission: rules.rule.read
      security:
      - bearerAuth: []
      parameters:
      - name: limit
        in: query
        schema:
          type: integer
          minimum: 1
          maximum: 200
          default: 50
      - name: cursor
        in: query
        schema:
          type: string
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OutcomeReviewPage'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
    post:
      operationId: createOutcomeReview
      summary: Create outcome review
      tags:
      - Domain operations
      x-permission: rules.rule.write
      security:
      - bearerAuth: []
      parameters: []
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OutcomeReview'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/OutcomeReviewInput'

  /v1/typology-templates:
    get:
      operationId: getTypologyTemplates
      summary: Get typology templates
      tags:
      - Domain operations
      x-permission: rules.rule.read
      security:
      - bearerAuth: []
      parameters: []
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TypologyCatalogue'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable

  /v1/typology-templates/{templateKey}/drafts:
    post:
      operationId: createTypologyDraft
      summary: Create typology draft
      tags:
      - Domain operations
      x-permission: rules.rule.write
      security:
      - bearerAuth: []
      parameters:
      - name: templateKey
        in: path
        required: true
        schema:
          type: string
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TypologyDraft'
        '400':
          description: Invalid input
        '403':
          description: Permission required
        '409':
          description: Conflicting workflow state
        '503':
          description: Capability unavailable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TypologyDraftInput'
  /v1/transactions/expected-feeds:
    get:
      operationId: listExpectedFeeds
      tags:
      - Monitoring
      x-permission: monitoring.data_operations.read
      responses:
        '200':
          description: Current feed control
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ExpectedFeedPage'
      parameters:
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
    post:
      operationId: proposeExpectedFeed
      tags:
      - Monitoring
      x-permission: monitoring.data_operations.remediate
      responses:
        '200':
          description: Current feed control
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ExpectedFeed'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ExpectedFeedInput'
  /v1/transactions/expected-feeds/{feedID}/decision:
    post:
      operationId: decideExpectedFeed
      tags:
      - Monitoring
      x-permission: monitoring.data_operations.remediate
      responses:
        '200':
          description: Current feed control
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ExpectedFeed'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
              - decision
              properties:
                decision:
                  type: string
                  enum:
                  - approved
                  - rejected
                  - disabled
      parameters:
      - name: feedID
        in: path
        required: true
        schema:
          type: string
          format: uuid
  /v1/transactions/expected-feed-windows:
    get:
      operationId: listExpectedFeedWindows
      tags:
      - Monitoring
      x-permission: monitoring.data_operations.read
      responses:
        '200':
          description: Current feed control
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ExpectedFeedWindowPage'
      parameters:
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      - name: status
        in: query
        schema:
          type: string
          enum:
          - pending
          - matched
          - missing_feed
          - variance
  /v1/transactions/expected-feeds/sweep:
    post:
      operationId: sweepExpectedFeeds
      tags:
      - Monitoring
      x-permission: monitoring.data_operations.remediate
      responses:
        '200':
          description: Current feed control
          content:
            application/json:
              schema:
                type: object
                required:
                - generated_windows
                - batch_limit
                properties:
                  generated_windows:
                    type: integer
                    format: int64
                    minimum: 0
                  batch_limit:
                    type: integer
                    format: int64
                    minimum: 0

  /v1/transactions/expected-feed-owners:
    get:
      operationId: listExpectedFeedOwners
      tags:
      - Reporting
      x-permission: monitoring.data_operations.remediate
      responses:
        '200':
          description: Current scoped workflow
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ExpectedFeedOwnerPage'
      parameters:
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
  /v1/filing-event-coverage:
    get:
      operationId: listFilingEventCoverage
      tags:
      - Reporting
      x-permission: reporting.report.read
      responses:
        '200':
          description: Current scoped workflow
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FilingEventCoveragePage'
      parameters:
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
  /v1/filing-event-coverage/catchup:
    post:
      operationId: backfillFilingEventCoverage
      tags:
      - Reporting
      x-permission: reporting.report.file
      responses:
        '200':
          description: Current scoped workflow
          content:
            application/json:
              schema:
                type: object
                required:
                - covered_events
                - batch_limit
                properties:
                  covered_events:
                    type: integer
                    format: int64
                    minimum: 0
                  batch_limit:
                    type: integer
                    format: int64
                    minimum: 0
  /v1/report-delivery-attempts/{attemptID}/supplements:
    post:
      operationId: proposeDeliverySupplement
      tags:
      - Reporting
      x-permission: reporting.report.file
      responses:
        '200':
          description: Current scoped workflow
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DeliverySupplement'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DeliverySupplementInput'
      parameters:
      - name: attemptID
        in: path
        required: true
        schema:
          type: string
          format: uuid
  /v1/report-delivery-supplements/{supplementID}/decision:
    post:
      operationId: decideDeliverySupplement
      tags:
      - Reporting
      x-permission: reporting.report.file
      responses:
        '200':
          description: Current scoped workflow
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DeliverySupplement'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
              - approve
              properties:
                approve:
                  type: boolean
      parameters:
      - name: supplementID
        in: path
        required: true
        schema:
          type: string
          format: uuid
  /v1/reports/{reportID}/supplements:
    get:
      operationId: listDeliverySupplements
      tags:
      - Reporting
      x-permission: reporting.report_content.read
      responses:
        '200':
          description: Current scoped workflow
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DeliverySupplementPage'
      parameters:
      - name: reportID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'

  /v1/kyc-requirements:
    get:
      operationId: listReviewRequirements
      summary: List review requirements
      tags:
      - Maturity
      x-permission: onboarding.customer.read
      parameters:
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      - { name: key, in: query, schema: { type: string, maxLength: 64 } }
      - { name: status, in: query, schema: { type: string, enum: [pending, approved, rejected] } }
      - { name: reason, in: query, schema: { type: string, enum: [periodic, risk_change, pep_change, screening_hit, manual, edd] } }
      - { name: sort, in: query, schema: { type: string, enum: [proposed_at_desc, proposed_at_asc], default: proposed_at_desc } }
      responses:
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReviewRequirementVersionPage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '409':
          $ref: '#/components/responses/Conflict'
    post:
      operationId: proposeReviewRequirement
      summary: Propose review requirement
      tags:
      - Maturity
      x-permission: onboarding.customer.write
      parameters: []
      responses:
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReviewRequirementVersion'
        '409':
          $ref: '#/components/responses/Conflict'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ReviewRequirementInput'
  /v1/kyc-requirements/{requirementID}/decision:
    post:
      operationId: decideReviewRequirement
      summary: Decide review requirement
      tags:
      - Maturity
      x-permission: onboarding.application.decide
      parameters:
      - name: requirementID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReviewRequirementVersion'
        '409':
          $ref: '#/components/responses/Conflict'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/MaturityDecisionInput'
  /v1/kyc-review-assignees:
    get:
      operationId: listReviewAssignees
      summary: List review assignees
      tags:
      - Maturity
      x-permission: onboarding.customer.edd
      parameters:
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReviewAssigneePage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '409':
          $ref: '#/components/responses/Conflict'
  /v1/kyc-reviews/{reviewID}/requirements:
    get:
      operationId: getReviewRequirements
      summary: Get review requirements
      tags:
      - Maturity
      x-permission: onboarding.customer.read
      parameters:
      - name: reviewID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReviewRequirements'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '409':
          $ref: '#/components/responses/Conflict'
  /v1/kyc-reviews/{reviewID}/assignment:
    post:
      operationId: assignReview
      summary: Assign review
      tags:
      - Maturity
      x-permission: onboarding.customer.edd
      parameters:
      - name: reviewID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/KYCReview'
        '409':
          $ref: '#/components/responses/Conflict'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ReviewAssignmentInput'
  /v1/kyc-reviews/{reviewID}/evidence-requests:
    get:
      operationId: listEvidenceRequests
      summary: List evidence requests
      tags:
      - Maturity
      x-permission: onboarding.customer.read
      parameters:
      - name: reviewID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReviewEvidenceRequestPage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '409':
          $ref: '#/components/responses/Conflict'
    post:
      operationId: createEvidenceRequest
      summary: Create evidence request
      tags:
      - Maturity
      x-permission: onboarding.customer.write
      parameters:
      - name: reviewID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReviewEvidenceRequest'
        '409':
          $ref: '#/components/responses/Conflict'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ReviewEvidenceRequestInput'
  /v1/kyc-evidence-requests/{requestID}/fulfillment:
    post:
      operationId: fulfillEvidenceRequest
      summary: Fulfill evidence request
      tags:
      - Maturity
      x-permission: onboarding.customer.write
      parameters:
      - name: requestID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReviewEvidenceRequest'
        '409':
          $ref: '#/components/responses/Conflict'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DocumentReferenceInput'
  /v1/case-qa-sampling-plans:
    get:
      operationId: listSamplingPlans
      summary: List sampling plans
      tags:
      - Maturity
      x-permission: cases.case.close
      parameters:
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SamplingPlanPage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '409':
          $ref: '#/components/responses/Conflict'
    post:
      operationId: proposeSamplingPlan
      summary: Propose sampling plan
      tags:
      - Maturity
      x-permission: cases.routing.manage
      parameters: []
      responses:
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SamplingPlan'
        '409':
          $ref: '#/components/responses/Conflict'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SamplingPlanInput'
  /v1/case-qa-sampling-plans/{planID}/decision:
    post:
      operationId: decideSamplingPlan
      summary: Decide sampling plan
      tags:
      - Maturity
      x-permission: cases.routing.manage
      parameters:
      - name: planID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SamplingPlan'
        '409':
          $ref: '#/components/responses/Conflict'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/MaturityDecisionInput'
  /v1/case-qa-sampling-runs:
    get:
      operationId: listSamplingRuns
      summary: List sampling runs
      tags:
      - Maturity
      x-permission: cases.case.close
      parameters:
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SamplingRunPage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '409':
          $ref: '#/components/responses/Conflict'
    post:
      operationId: createSamplingRun
      summary: Create sampling run
      tags:
      - Maturity
      x-permission: cases.case.close
      parameters: []
      responses:
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SamplingRun'
        '409':
          $ref: '#/components/responses/Conflict'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SamplingRunInput'
  /v1/case-qa-samples:
    get:
      operationId: listSupervisorSamples
      summary: List supervisor samples
      tags:
      - Maturity
      x-permission: cases.case_content.read
      parameters:
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      - name: status
        in: query
        schema:
          type: string
          enum:
          - pending
          - overdue
          - reviewed
      responses:
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SupervisorSamplePage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '409':
          $ref: '#/components/responses/Conflict'
  /v1/case-qa-samples/{sampleID}/claim:
    post:
      operationId: claimSupervisorSample
      summary: Claim supervisor sample
      tags:
      - Maturity
      x-permission: cases.case.close
      parameters:
      - name: sampleID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SupervisorSample'
        '409':
          $ref: '#/components/responses/Conflict'
  /v1/case-qa-remediation-assignees:
    get:
      operationId: listRemediationAssignees
      summary: List remediation assignees
      tags:
      - Maturity
      x-permission: cases.case.close
      parameters:
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RemediationAssigneePage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '409':
          $ref: '#/components/responses/Conflict'
  /v1/case-tasks/{taskID}/acceptance:
    post:
      operationId: acceptRemediation
      summary: Accept remediation
      tags:
      - Maturity
      x-permission: cases.case.close
      parameters:
      - name: taskID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RemediationAcceptance'
        '409':
          $ref: '#/components/responses/Conflict'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RemediationAcceptanceInput'
  /v1/ownership-edges/{edgeID}/history:
    get:
      operationId: listOwnershipHistory
      summary: List ownership history
      tags:
      - Maturity
      x-permission: onboarding.customer.write
      parameters:
      - name: edgeID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OwnershipSnapshotPage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '409':
          $ref: '#/components/responses/Conflict'
  /v1/ownership-edges/{edgeID}/evidence:
    post:
      operationId: recordRelationshipEvidence
      summary: Record relationship evidence
      tags:
      - Maturity
      x-permission: onboarding.ownership.verify
      parameters:
      - name: edgeID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RelationshipEvidence'
        '409':
          $ref: '#/components/responses/Conflict'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DocumentReferenceInput'
  /v1/ownership-edges/{edgeID}/documents:
    get:
      operationId: listRelationshipDocuments
      summary: List relationship documents
      tags:
      - Maturity
      x-permission: onboarding.ownership.verify
      parameters:
      - name: edgeID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OnboardingDocumentPage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '409':
          $ref: '#/components/responses/Conflict'
  /v1/customers/{customerID}/ownership-accounts:
    get:
      operationId: listOwnershipAccounts
      summary: List ownership accounts
      tags:
      - Maturity
      x-permission: cases.evidence.read
      parameters:
      - name: customerID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      - name: as_of
        in: query
        required: true
        schema:
          type: string
          format: date-time
        description: Fixed historical knowledge and effective ownership instant, also
          bound to the cursor.
      responses:
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/LinkedOwnershipAccountPage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '409':
          $ref: '#/components/responses/Conflict'
  /v1/customers/{customerID}/ownership-activity:
    get:
      operationId: listOwnershipActivity
      summary: List ownership activity
      tags:
      - Maturity
      x-permission: cases.evidence.read
      parameters:
      - name: customerID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      - name: as_of
        in: query
        required: true
        schema:
          type: string
          format: date-time
        description: Fixed historical knowledge and effective ownership instant, also
          bound to the cursor.
      responses:
        '200':
          description: Scoped result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/LinkedOwnershipActivityPage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          description: Required approved governance definition or service unavailable
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '409':
          $ref: '#/components/responses/Conflict'

  /v1/privacy/erasures/{erasureID}/receipt:
    post:
      operationId: retainErasureReceipt
      x-permission: privacy.erasure.execute
      security:
      - bearerAuth: []
      tags:
      - Privacy
      summary: Retain a committed destruction decision independently of PostgreSQL
      description: Requires privacy.erasure.execute and step-up. Idempotently writes
        and authenticates the neutral signed decision in write-once storage after execution
        committed. Storage failure remains retryable; an erased subject stays erased.
        Independent offsite/WORM custody and latest-watermark recovery remain estate
        obligations.
      parameters:
      - name: erasureID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Independently stored signed neutral destruction receipt
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RetainedDestructionReceipt'
        '503':
          description: Independent receipt storage unavailable; retry retention after committed erasure.
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'

  /v1/rule-validation-datasets:
    get:
      operationId: listValidationDatasets
      summary: List validation datasets
      tags:
      - Maturity
      x-permission: rules.rule.read
      parameters:
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: Bounded scoped result; approval preserves immutable evidence.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ValidationDatasetSummaryPage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
    post:
      operationId: proposeValidationDataset
      summary: Propose validation dataset
      tags:
      - Maturity
      x-permission: rules.rule.simulate
      parameters: []
      responses:
        '200':
          description: Bounded scoped result; approval preserves immutable evidence.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ValidationDataset'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ValidationDatasetInput'

  /v1/rule-validation-datasets/{assuranceID}:
    get:
      operationId: getValidationDataset
      summary: Get validation dataset
      tags:
      - Maturity
      x-permission: rules.rule.read
      parameters:
      - name: assuranceID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Bounded scoped result; approval preserves immutable evidence.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ValidationDataset'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'

  /v1/rule-validation-datasets/{assuranceID}/decision:
    post:
      operationId: decideValidationDataset
      summary: Decide validation dataset
      tags:
      - Maturity
      x-permission: rules.rule.write
      parameters:
      - name: assuranceID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Bounded scoped result; approval preserves immutable evidence.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ValidationDataset'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/MaturityDecisionInput'

  /v1/rule-scenario-suites:
    get:
      operationId: listScenarioSuites
      summary: List scenario suites
      tags:
      - Maturity
      x-permission: rules.rule.read
      parameters:
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: Bounded scoped result; approval preserves immutable evidence.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ScenarioSuiteSummaryPage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
    post:
      operationId: proposeScenarioSuite
      summary: Propose scenario suite
      tags:
      - Maturity
      x-permission: rules.rule.simulate
      parameters: []
      responses:
        '200':
          description: Bounded scoped result; approval preserves immutable evidence.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ScenarioSuite'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ScenarioSuiteInput'

  /v1/rule-scenario-suites/{assuranceID}:
    get:
      operationId: getScenarioSuite
      summary: Get scenario suite
      tags:
      - Maturity
      x-permission: rules.rule.read
      parameters:
      - name: assuranceID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Bounded scoped result; approval preserves immutable evidence.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ScenarioSuite'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'

  /v1/rule-scenario-suites/{assuranceID}/decision:
    post:
      operationId: decideScenarioSuite
      summary: Decide scenario suite
      tags:
      - Maturity
      x-permission: rules.rule.write
      parameters:
      - name: assuranceID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Bounded scoped result; approval preserves immutable evidence.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ScenarioSuite'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/MaturityDecisionInput'

  /v1/rule-comparisons:
    get:
      operationId: listRuleComparisons
      summary: List rule comparisons
      tags:
      - Maturity
      x-permission: rules.rule.read
      parameters:
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: Bounded scoped result; approval preserves immutable evidence.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RuleComparisonSummaryPage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
    post:
      operationId: proposeRuleComparison
      summary: Propose rule comparison
      tags:
      - Maturity
      x-permission: rules.rule.simulate
      parameters: []
      responses:
        '200':
          description: Bounded scoped result; approval preserves immutable evidence.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RuleComparison'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RuleComparisonInput'

  /v1/rule-comparisons/{assuranceID}:
    get:
      operationId: getRuleComparison
      summary: Get rule comparison
      tags:
      - Maturity
      x-permission: rules.rule.read
      parameters:
      - name: assuranceID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Bounded scoped result; approval preserves immutable evidence.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RuleComparison'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'

  /v1/rule-comparisons/{assuranceID}/decision:
    post:
      operationId: decideRuleComparison
      summary: Decide rule comparison
      tags:
      - Maturity
      x-permission: rules.rule.write
      parameters:
      - name: assuranceID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Bounded scoped result; approval preserves immutable evidence.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RuleComparison'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/MaturityDecisionInput'

  /v1/rule-validation-sources:
    get:
      operationId: listValidationSources
      summary: List validation sources
      tags:
      - Maturity
      x-permission: rules.rule.simulate
      parameters:
      - name: from
        in: query
        required: true
        schema:
          type: string
          format: date-time
      - name: to
        in: query
        required: true
        schema:
          type: string
          format: date-time
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: Bounded scoped result; approval preserves immutable evidence.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ValidationSubjectReferencePage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'

  /v1/rule-versions/{versionID}/assurance:
    get:
      operationId: getRuleAssurance
      summary: Get rule assurance
      tags:
      - Maturity
      x-permission: rules.rule.read
      parameters:
      - name: versionID
        in: path
        required: true
        schema:
          type: string
          format: uuid
      responses:
        '200':
          description: Bounded scoped result; approval preserves immutable evidence.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RuleAssurance'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'

  /v1/reference-datasets/fx-decisions:
    get:
      operationId: listFXDecisions
      summary: List f x decisions
      tags:
      - Maturity
      x-permission: rules.rule.read
      parameters:
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: Bounded scoped result; approval preserves immutable evidence.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FXDecisionPage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
    post:
      operationId: recordFXDecision
      summary: Record f x decision
      tags:
      - Maturity
      x-permission: rules.rule.write
      parameters: []
      responses:
        '200':
          description: Bounded scoped result; approval preserves immutable evidence.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FXDecision'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/FXDecisionInput'

  /v1/admin/feature-flags:
    get:
      operationId: listTenantFeatureFlags
      tags: [Platform]
      summary: Read effective tenant feature switches
      description: Uses the tenant database and works offline. Only declared product capabilities are accepted; switches cannot bypass authorization or compliance controls.
      x-permission: platform.feature_flags.manage
      responses:
        '200':
          description: Effective switch values and optimistic revisions
          content:
            application/json:
              schema:
                type: object
                required: [items]
                properties:
                  items:
                    type: array
                    items:
                      type: object
                      required: [key, enabled, revision, updated_at]
                      properties:
                        key: { type: string, enum: [operations.job_console, ai.assistance] }
                        enabled: { type: boolean }
                        revision: { type: integer, minimum: 0 }
                        updated_at: { type: [string, 'null'], format: date-time }
  /v1/admin/feature-flags/{flagKey}:
    put:
      operationId: setTenantFeatureFlag
      tags: [Platform]
      summary: Audit a tenant feature switch change
      x-permission: platform.feature_flags.manage
      parameters:
        - { name: flagKey, in: path, required: true, schema: { type: string, enum: [operations.job_console, ai.assistance] } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [enabled, expected_revision, reason]
              properties:
                enabled: { type: boolean }
                expected_revision: { type: integer, minimum: 0 }
                reason: { type: string, minLength: 8, maxLength: 500 }
      responses:
        '200':
          description: Committed audited change
          content:
            application/json:
              schema:
                type: object
                required: [key, enabled, revision]
                properties:
                  key: { type: string }
                  enabled: { type: boolean }
                  revision: { type: integer, minimum: 1 }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Conflict' }

  /v1/me/session/revoke:
    post:
      operationId: revokeInteractiveSession
      tags: [Identity]
      summary: Revoke the current interactive authentication session
      description: Audits and revokes the current verified issuer/subject/authentication-time binding across API replicas. Token refresh from the same authentication event cannot revive it. Machine credentials are refused.
      x-permission: authenticated
      responses:
        '204': { description: Session revoked }
        '401': { description: Session already expired or revoked }
        '403': { description: An interactive session is required }

  /v1/admin/upload-quarantine:
    get:
      operationId: listUploadQuarantine
      tags: [Platform]
      summary: Rejected-upload metadata and verified reupload status
      description: |
        Filters apply before the bounded tuple page. Cursors bind tenant, scope and order.
        Old unbound cursors must restart. Every read rechecks current tenant permissions.
      x-permission: platform.jobs.manage
      parameters:
        - $ref: '#/components/parameters/Limit'
        - $ref: '#/components/parameters/Cursor'
        - name: kind
          in: query
          schema: { type: string, enum: [document, case_attachment, validation_evidence] }
        - name: status
          in: query
          schema: { type: string, enum: [pending, retry_requested, dismissed, recovered] }
        - name: sort
          in: query
          description: Indexed tuple order; filter/order/tenant changes require a new cursor walk.
          schema: { type: string, enum: [created_at_desc, created_at_asc], default: created_at_desc }
      responses:
        '200':
          description: Quarantine metadata; no file bytes, filenames or subject references
          content:
            application/json:
              schema: { $ref: '#/components/schemas/UploadQuarantinePage' }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "503": { $ref: "#/components/responses/Unavailable" }

  /v1/admin/upload-quarantine/{quarantineID}/disposition:
    post:
      operationId: dispositionUploadQuarantine
      tags: [Platform]
      summary: Request a fresh scan or dismiss a rejected upload
      x-permission: platform.jobs.manage
      parameters:
        - name: quarantineID
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/UploadQuarantineDisposition' }
      responses:
        '200':
          description: Audited disposition recorded; rejected bytes can never be released
          content:
            application/json:
              schema: { $ref: '#/components/schemas/UploadQuarantineDisposition' }
        '409': { $ref: '#/components/responses/Conflict' }
  /v1/admin/jobs:
    get:
      operationId: listAdminJobs
      tags: [Platform]
      summary: List retained background jobs for the authenticated tenant
      description: |
        Operational metadata only: arguments, errors, metadata targets and global sweep jobs
        are excluded before JSON leaves the tenant reader. Exact state/kind/queue filters
        run before LIMIT. Numeric bigint ID ordering supports id_desc and id_asc without
        JavaScript number conversion. Canonical cursors bind tenant, all filters and order.
        The legacy unfiltered id_desc before/next_before walk remains supported; before
        cannot be combined with a canonical cursor, a filter or ascending order.
      x-permission: platform.jobs.manage
      parameters:
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 50 } }
        - { name: before, in: query, deprecated: true, schema: { type: string, pattern: '^[1-9][0-9]{0,18}$' } }
        - { $ref: '#/components/parameters/Cursor' }
        - { name: sort, in: query, schema: { type: string, enum: [id_desc, id_asc], default: id_desc } }
        - { name: state, in: query, schema: { type: string, enum: [available, cancelled, completed, discarded, pending, retryable, running, scheduled] } }
        - { name: kind, in: query, schema: { type: string, maxLength: 127 } }
        - { name: queue, in: query, schema: { type: string, maxLength: 127 } }
      responses:
        '200':
          description: Retained tenant jobs
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AdminJobPage' }
        '400': { $ref: '#/components/responses/BadRequest' }

  /v1/admin/jobs/export:
    get:
      operationId: exportAdminJobRegister
      tags: [Platform]
      summary: Export all matching retained tenant job metadata as CSV or Excel
      description: |
        Uses one tenant repeatable-read snapshot and the same tenant-owned filtered reader
        on every page. Only id, kind, queue, state, attempt, max_attempts, created_at,
        scheduled_at and finalized_at enter the capture. Job args, errors, metadata targets,
        other tenants and global sweep work never enter the artifact. The job-console feature
        switch and current platform.jobs.manage permission remain required. Audit digest and
        complete row count commit in the same snapshot transaction before bytes are delivered.
        Up to 10,000 rows and 32 MiB; no partial artifact. Each reader page remains bounded to 100 rows.
        Cursor and legacy before input are refused. Retry/discard/cancellation semantics are unchanged.
      x-permission: platform.jobs.manage
      parameters:
        - { name: format, in: query, required: true, schema: { type: string, enum: [csv, xlsx] } }
        - { name: sort, in: query, schema: { type: string, enum: [id_desc, id_asc], default: id_desc } }
        - { name: state, in: query, schema: { type: string, enum: [available, cancelled, completed, discarded, pending, retryable, running, scheduled] } }
        - { name: kind, in: query, schema: { type: string, maxLength: 127 } }
        - { name: queue, in: query, schema: { type: string, maxLength: 127 } }
      responses:
        '200':
          description: Complete tenant metadata with committed digest receipt
          content:
            text/csv:
              schema: { type: string, format: binary }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        '400': { $ref: '#/components/responses/BadRequest' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '503': { $ref: '#/components/responses/Unavailable' }

  /v1/admin/jobs/{jobID}/retry:
    post:
      operationId: retryAdminJob
      tags: [Platform]
      summary: Audit and retry a failed or cancelled tenant job
      description: Atomically records the operator reason and makes a retryable, discarded or cancelled job available. Running and completed jobs are refused.
      x-permission: platform.jobs.manage
      parameters:
        - { name: jobID, in: path, required: true, schema: { type: string, pattern: '^[1-9][0-9]{0,18}$' } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/AdminJobControlInput' }
      responses:
        '200':
          description: Audited state transition
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AdminJobTransition' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Conflict' }

  /v1/admin/jobs/{jobID}/discard:
    post:
      operationId: discardAdminJob
      tags: [Platform]
      summary: Audit and discard a queued tenant job
      description: Atomically records the reason and discards available, retryable, scheduled or pending work. Running or finalized work is refused.
      x-permission: platform.jobs.manage
      parameters:
        - { name: jobID, in: path, required: true, schema: { type: string, pattern: '^[1-9][0-9]{0,18}$' } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/AdminJobControlInput' }
      responses:
        '200':
          description: Audited state transition
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AdminJobTransition' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Conflict' }

  /auth/tenant-oidc/{slug}:
    get:
      operationId: getTenantLoginSettings
      summary: Resolve public tenant OAuth metadata; no secret is returned
      tags:
      - Tenancy
      security: []
      x-permission: public
      parameters:
      - name: slug
        in: path
        required: true
        schema:
          type: string
          minLength: 2
          maxLength: 63
      responses:
        '200':
          description: Operation result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TenantLoginSettings'
  /v1/admin/tenant-provisioning:
    post:
      operationId: provisionInstitution
      summary: Resume exact tenant, signed pack and first administrator provisioning
      tags:
      - Tenancy
      x-permission: tenancy.tenant.write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TenantProvisionInput'
      responses:
        '201':
          description: Operation result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TenantProvisionResult'
  /v1/admin/tenants/{tenantID}/administrator-invitation:
    get:
      operationId: getAdministratorInvitationStatus
      summary: Read first-administrator invitation relay status without recipient or identity claims
      tags: [Tenancy]
      x-permission: tenancy.tenant.write
      parameters:
      - $ref: '#/components/parameters/TenantID'
      responses:
        '200':
          description: Retained invitation delivery status; sent means relay acceptance only
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AdministratorInvitation'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '503':
          $ref: '#/components/responses/Unavailable'
  /v1/admin/tenants/{tenantID}/administrator-invitation/retry:
    post:
      operationId: retryAdministratorInvitation
      summary: Retry the exact original administrator invitation without changing its identity binding
      tags: [Tenancy]
      x-permission: tenancy.tenant.write
      parameters:
      - $ref: '#/components/parameters/TenantID'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AdministratorInvitationRetry'
      responses:
        '202':
          description: Delivery retry queued or already accepted by the mail relay
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AdministratorInvitation'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
  /v1/admin/tenants/{tenantID}/identity-provider:
    get:
      operationId: getTenantIdentityProvider
      summary: Read platform tenant identity-provider
      tags:
      - Tenancy
      x-permission: tenancy.tenant.write
      responses:
        '200':
          description: Operation result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TenantControlRecord'
      parameters:
      - $ref: '#/components/parameters/TenantID'
    put:
      operationId: updateTenantIdentityProvider
      summary: Revise tenant identity-provider with durable actor/reason history
      tags:
      - Tenancy
      x-permission: tenancy.tenant.write
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TenantControlUpdate'
      responses:
        '200':
          description: Operation result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TenantControlRecord'
      parameters:
      - $ref: '#/components/parameters/TenantID'
  /v1/admin/tenants/{tenantID}/resource-quotas:
    get:
      operationId: getTenantResourceQuota
      summary: Read platform tenant resource-quotas
      tags:
      - Tenancy
      x-permission: platform.commercial.manage
      responses:
        '200':
          description: Operation result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TenantControlRecord'
      parameters:
      - $ref: '#/components/parameters/TenantID'
    put:
      operationId: updateTenantResourceQuota
      summary: Revise tenant resource-quotas with durable actor/reason history
      tags:
      - Tenancy
      x-permission: platform.commercial.manage
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TenantControlUpdate'
      responses:
        '200':
          description: Operation result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TenantControlRecord'
      parameters:
      - $ref: '#/components/parameters/TenantID'
  /v1/admin/tenants/{tenantID}/provisioning:
    get:
      operationId: getTenantProvisioning
      summary: Read platform tenant provisioning
      tags:
      - Tenancy
      x-permission: tenancy.tenant.write
      responses:
        '200':
          description: Operation result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TenantControlRecord'
      parameters:
      - $ref: '#/components/parameters/TenantID'
  /v1/usage/resources:
    get:
      operationId: getResourceUsage
      summary: Read own tenant metered calls and reserved ciphertext storage
      tags:
      - Tenancy
      x-permission: platform.usage.read
      responses:
        '200':
          description: Operation result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ResourceUsageSummary'

  /v1/board-commentaries:
    get:
      operationId: listBoardCommentaries
      tags: [Analytics]
      x-permission: analytics.metric.read
      summary: listBoardCommentaries
      parameters:
        - $ref: '#/components/parameters/Limit'
        - $ref: '#/components/parameters/Cursor'
      responses:
        "200":
          description: Exact evidence-bound board commentary. Approval requires an independent current MLRO.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BoardCommentaryList" }
        default: { $ref: "#/components/responses/ProblemResponse" }
    post:
      operationId: proposeBoardCommentary
      tags: [Analytics]
      x-permission: distribution.schedule.manage
      summary: proposeBoardCommentary
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/BoardCommentaryInput" }
      responses:
        "200":
          description: Exact evidence-bound board commentary. Approval requires an independent current MLRO.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BoardCommentary" }
        default: { $ref: "#/components/responses/ProblemResponse" }
  /v1/board-commentaries/{commentaryID}:
    get:
      operationId: getBoardCommentary
      tags: [Analytics]
      x-permission: analytics.metric.read
      summary: getBoardCommentary
      parameters:
        - name: commentaryID
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Exact evidence-bound board commentary. Approval requires an independent current MLRO.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BoardCommentary" }
        default: { $ref: "#/components/responses/ProblemResponse" }
  /v1/board-commentaries/{commentaryID}/decision:
    post:
      operationId: decideBoardCommentary
      tags: [Analytics]
      x-permission: reporting.report.file
      summary: decideBoardCommentary
      parameters:
        - name: commentaryID
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/BoardCommentaryDecision" }
      responses:
        "200":
          description: Exact evidence-bound board commentary. Approval requires an independent current MLRO.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BoardCommentary" }
        default: { $ref: "#/components/responses/ProblemResponse" }
  /v1/board-commentaries/{commentaryID}/artifact:
    get:
      operationId: exportBoardCommentary
      tags: [Analytics]
      x-permission: distribution.artifact.download
      summary: exportBoardCommentary
      parameters:
        - name: commentaryID
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: format
          in: query
          schema: { type: string, enum: [json, csv, pdf, xlsx], default: pdf }
      responses:
        "200":
          description: Exact evidence-bound board commentary. Approval requires an independent current MLRO.
          content:
            application/json:
              schema: { type: string, format: binary }
            text/csv:
              schema: { type: string, format: binary }
            application/pdf:
              schema: { type: string, format: binary }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        default: { $ref: "#/components/responses/ProblemResponse" }

  /v1/rules/parameter-sweeps:
    post:
      operationId: createParameterSweep
      summary: createParameterSweep
      tags:
      - Maturity
      x-permission: rules.rule.simulate
      responses:
        '200':
          description: Immutable tuning evidence or review result.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ParameterSweep'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ParameterSweepInput'
  /v1/rules/parameter-sweeps/{sweepID}:
    get:
      operationId: getParameterSweep
      summary: getParameterSweep
      tags:
      - Maturity
      x-permission: rules.rule.simulate
      responses:
        '200':
          description: Immutable tuning evidence or review result.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ParameterSweep'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
      parameters:
      - in: path
        name: sweepID
        required: true
        schema: &tuningpath001
          type: string
          format: uuid
  /v1/rules/near-miss-samples:
    get:
      operationId: listNearMissSamples
      summary: listNearMissSamples
      tags:
      - Maturity
      x-permission: rules.rule.simulate
      responses:
        '200':
          description: Immutable tuning evidence or review result.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/NearMissReviewPage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
      parameters:
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      - {name: sweep_id, in: query, schema: {type: string, format: uuid}}
      - {name: sort, in: query, schema: {type: string, enum: [created_at_desc, created_at_asc], default: created_at_desc}}

  /v1/rules/near-miss-samples/{sampleID}/review:
    post:
      operationId: reviewNearMiss
      summary: reviewNearMiss
      tags:
      - Maturity
      x-permission: rules.rule.simulate
      responses:
        '200':
          description: Immutable tuning evidence or review result.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/NearMissReview'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
      parameters:
      - in: path
        name: sampleID
        required: true
        schema: *tuningpath001
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/NearMissReviewInput'

  /v1/parties/{partyID}/network:
    get:
      operationId: getPartyNetwork
      tags: [Customers]
      summary: Inspect recorded shared-attribute links and bounded cycles
      x-permission: onboarding.customer.read
      parameters:
        - {name: partyID, in: path, required: true, schema: {type: string, format: uuid}}
        - {name: as_of, in: query, schema: {type: string, format: date-time}}
      responses:
        '200':
          description: Permission and privacy checked network; shared attributes are unverified signals
          content:
            application/json:
              schema: {$ref: '#/components/schemas/PartyNetwork'}
        default: {$ref: '#/components/responses/ProblemResponse'}
  /v1/parties/{partyID}/network-observations:
    post:
      operationId: observeEntity
      tags: [Customers]
      summary: Record a source-attributed unverified network signal
      x-permission: monitoring.data_operations.remediate
      parameters:
        - {name: partyID, in: path, required: true, schema: {type: string, format: uuid}}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/NetworkObservationInput'}
      responses:
        '200':
          description: Immutable observation without raw signal value
          content:
            application/json:
              schema: {$ref: '#/components/schemas/NetworkObservation'}
        default: {$ref: '#/components/responses/ProblemResponse'}
  /v1/network-observations/{observationID}/withdrawal:
    post:
      operationId: withdrawEntityObservation
      tags: [Customers]
      summary: Withdraw an incorrect signal while preserving its history
      x-permission: monitoring.data_operations.remediate
      parameters:
        - {name: observationID, in: path, required: true, schema: {type: string, format: uuid}}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [reason]
              properties:
                reason: {type: string, minLength: 1, maxLength: 2000}
      responses:
        '200':
          description: Signal withdrawn from current graphs
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [withdrawn]
                properties:
                  withdrawn: {type: boolean}
        default: {$ref: '#/components/responses/ProblemResponse'}

  /v1/decisions:
    post:
      operationId: decideTransaction
      summary: decideTransaction
      tags:
      - Maturity
      x-permission: monitoring.transaction.ingest
      responses:
        '200':
          description: Immutable decision or independent release state. No transaction is booked.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TransactionDecision'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TransactionDecisionInput'
  /v1/decisions/{decisionID}:
    get:
      operationId: getTransactionDecision
      summary: getTransactionDecision
      tags:
      - Maturity
      x-permission: monitoring.transaction.ingest
      responses:
        '200':
          description: Immutable decision or independent release state. No transaction is booked.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TransactionDecision'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
      parameters:
      - in: path
        name: decisionID
        required: true
        schema:
          type: string
          format: uuid
  /v1/decision-holds:
    get:
      operationId: listDecisionHolds
      summary: listDecisionHolds
      tags:
      - Maturity
      x-permission: monitoring.alert.read
      responses:
        '200':
          description: Immutable decision or independent release state. No transaction is booked.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DecisionHoldPage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
      parameters:
      - $ref: '#/components/parameters/Limit'
      - $ref: '#/components/parameters/Cursor'
      - {name: state, in: query, schema: {type: string, enum: [pending, release_proposed]}}
      - {name: sort, in: query, schema: {type: string, enum: [created_at_desc, created_at_asc], default: created_at_desc}}

  /v1/decision-holds/{decisionID}/release:
    post:
      operationId: proposeDecisionRelease
      summary: proposeDecisionRelease
      tags:
      - Maturity
      x-permission: monitoring.alert.triage
      responses:
        '200':
          description: Immutable decision or independent release state. No transaction is booked.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DecisionHold'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
      parameters:
      - in: path
        name: decisionID
        required: true
        schema:
          type: string
          format: uuid
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/HoldReleaseInput'
  /v1/decision-holds/{decisionID}/decision:
    post:
      operationId: reviewDecisionRelease
      summary: reviewDecisionRelease
      tags:
      - Maturity
      x-permission: workflow.approval.decide
      responses:
        '200':
          description: Immutable decision or independent release state. No transaction is booked.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DecisionHold'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/ValidationFailed'
        '503':
          $ref: '#/components/responses/Unavailable'
      parameters:
      - in: path
        name: decisionID
        required: true
        schema:
          type: string
          format: uuid
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                decision:
                  type: string
                  enum:
                  - approve
                  - reject
                reason:
                  type: string
              required:
              - decision

  /v1/rules/outcome-rollups:
    post:
      operationId: createRuleOutcomeRollup
      summary: Immutable per-rule outcomes with all historical versions and deduplicated
        case conversion.
      tags:
      - Maturity
      x-permission: rules.rule.write
      responses:
        '200':
          description: Recorded rule outcomes.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RuleOutcomeRollup'
        default:
          $ref: '#/components/responses/ProblemResponse'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RuleOutcomeInput'
  /v1/rules/outcome-rollups/{rollupID}:
    get:
      operationId: getRuleOutcomeRollup
      summary: Immutable per-rule outcomes with all historical versions and deduplicated
        case conversion.
      tags:
      - Maturity
      x-permission: rules.rule.read
      responses:
        '200':
          description: Recorded rule outcomes.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RuleOutcomeRollup'
        default:
          $ref: '#/components/responses/ProblemResponse'
      parameters:
      - in: path
        name: rollupID
        required: true
        schema:
          type: string
          format: uuid

  /v1/me/notifications/export:
    get:
      operationId: exportPersonalNotificationMetadata
      tags: [Identity]
      summary: Export complete filtered metadata as CSV or Excel
      x-permission: authenticated
      description: |
        The same authorized list reader walks one tenant repeatable-read snapshot.
        Personal notifications remain recipient-specific and respect permission/preference
        filters. Starts at the first row and refuses cursor input. Existing 10,000-row and
        32 MiB limits apply; capacity errors return no partial file. The artifact digest
        and row count are audited before bytes leave. CSV formulas are escaped and Excel
        cells are text. Private notification titles/resource identities/links and service
        account descriptions, display names and all credential metadata are excluded
        before JSON capture. This is operational metadata, not a credential recovery path.
        Columns: id, event_type, resource_type, created_at, read_at.
      parameters:
        - { name: format, in: query, required: true, schema: { type: string, enum: [csv, xlsx] } }
        - { name: read, in: query, schema: { type: string, enum: [read, unread] } }
        - { name: event_type, in: query, description: Exact retained event key without normalization, schema: { type: string } }
        - { name: sort, in: query, schema: { type: string, enum: [created_at_desc, created_at_asc], default: created_at_desc } }
      responses:
        '200':
          description: Complete filtered metadata with audited SHA-256 and download disposition
          content:
            text/csv:
              schema: { type: string }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        '400': { $ref: '#/components/responses/BadRequest' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '503': { $ref: '#/components/responses/Unavailable' }
  /v1/iam/service-accounts/export:
    get:
      operationId: exportServiceAccountRegister
      tags: [Identity]
      summary: Export complete filtered metadata as CSV or Excel
      x-permission: iam.service_account.manage
      description: |
        The same authorized list reader walks one tenant repeatable-read snapshot.
        Personal notifications remain recipient-specific and respect permission/preference
        filters. Starts at the first row and refuses cursor input. Existing 10,000-row and
        32 MiB limits apply; capacity errors return no partial file. The artifact digest
        and row count are audited before bytes leave. CSV formulas are escaped and Excel
        cells are text. Private notification titles/resource identities/links and service
        account descriptions, display names and all credential metadata are excluded
        before JSON capture. This is operational metadata, not a credential recovery path.
        Columns: id, key, status, role_keys, expires_at, revoked_at, last_used_at, created_at, updated_at.
      parameters:
        - { name: format, in: query, required: true, schema: { type: string, enum: [csv, xlsx] } }
        - { name: status, in: query, schema: { type: string, enum: [active, suspended, revoked] } }
        - { name: sort, in: query, schema: { type: string, enum: [id, id_asc, id_desc], default: id } }
      responses:
        '200':
          description: Complete filtered metadata with audited SHA-256 and download disposition
          content:
            text/csv:
              schema: { type: string }
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema: { type: string, format: binary }
        '400': { $ref: '#/components/responses/BadRequest' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '503': { $ref: '#/components/responses/Unavailable' }
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT or bby_sa_v1 opaque credential
      description: |
        Human requests use an OIDC token from the configured issuer. The identity provider
        says who the caller is; this platform decides what they may do (ADR-0003).

        Ingest integrations may instead use a Veyndi opaque credential in the form
        `bby_sa_v1.<tenant-uuid>.<credential-uuid>.<random-secret>`. This is intentionally
        not an OAuth client_credentials flow: Veyndi is not an external authorization
        server. The routing UUIDs are non-secret; the 256-bit random suffix is the secret.
        Any bearer with this prefix is handled only as a machine credential and never falls
        through to OIDC when malformed or invalid.

  parameters:
    Limit:
      name: limit
      in: query
      description: Page size, capped at 200.
      schema: { type: integer, minimum: 1, maximum: 200, default: 50 }
    Cursor:
      name: cursor
      in: query
      description: |
        Opaque keyset cursor from a previous response. Offset pagination is deliberately
        not offered: `OFFSET 500000` is a table scan, and if it were offered it would be
        used (ADR-0012).

        Only the collections that document this parameter can be resumed. The rest report
        `truncated: true` and refuse a cursor rather than silently returning the first page
        again — see the `truncated` field on the page schemas.
      schema: { type: string }
    NotesLimit:
      name: notes_limit
      in: query
      description: Page size for the `notes` sub-collection of the case workspace, capped at 200.
      schema: { type: integer, minimum: 1, maximum: 200, default: 50 }

    NotesCursor:
      name: notes_cursor
      in: query
      description: |
        Opaque keyset cursor for the `notes` sub-collection, taken from `notes.next_cursor`
        on a previous response.

        Prefixed rather than reusing `cursor` because this response pages TWO children
        independently. One shared `cursor` would apply a position taken from the timeline to
        the notes, and the notes would come back from the wrong place under the right key —
        wrong data presented as right, which is worse than an error.

        Following it re-reads the case header and the linked alerts as well. That is the
        stated cost of paging a workspace through its own route instead of adding a second
        door onto encrypted case notes, whose decryption is a logged PII access.
      schema: { type: string }

    EventsLimit:
      name: events_limit
      in: query
      description: Page size for the `events` sub-collection of the case workspace, capped at 200.
      schema: { type: integer, minimum: 1, maximum: 200, default: 50 }

    EventsCursor:
      name: events_cursor
      in: query
      description: |
        Opaque keyset cursor for the `events` (timeline) sub-collection, taken from
        `events.next_cursor` on a previous response.
      schema: { type: string }

    SubjectAlertsLimit:
      name: subject_alerts_limit
      in: query
      description: Page size for broader subject alerts, capped at 200.
      schema: { type: integer, minimum: 1, maximum: 200, default: 50 }

    SubjectAlertsCursor:
      name: subject_alerts_cursor
      in: query
      description: |
        Opaque `(opened_at,id)` keyset cursor from `subject_alert_history.next_cursor`.
        It moves only the alert history; every other case-workspace cursor is independent.
      schema: { type: string }

    SubjectTransactionsLimit:
      name: subject_transactions_limit
      in: query
      description: Page size for broader subject transactions, capped at 200.
      schema: { type: integer, minimum: 1, maximum: 200, default: 50 }

    SubjectTransactionsCursor:
      name: subject_transactions_cursor
      in: query
      description: |
        Opaque `(booking_ts,id)` keyset cursor from
        `subject_transaction_history.next_cursor`. Resubmit the exact echoed
        `subject_transactions_from` and `subject_transactions_to` values with it.
      schema: { type: string }

    SubjectTransactionsFrom:
      name: subject_transactions_from
      in: query
      description: |
        Inclusive RFC3339 start of the broader subject transaction window. Defaults to one
        calendar year before `subject_transactions_to`; the window may not exceed 366 days.
      schema: { type: string, format: date-time }

    SubjectTransactionsTo:
      name: subject_transactions_to
      in: query
      description: |
        Exclusive RFC3339 end of the broader subject transaction window. Defaults to request
        time. The response echoes both exact instants so the bounded coverage is reproducible.
      schema: { type: string, format: date-time }

    SubjectScreeningRunsLimit:
      name: subject_screening_runs_limit
      in: query
      description: Page size for broader subject screening runs, capped at 200.
      schema: { type: integer, minimum: 1, maximum: 200, default: 50 }

    SubjectScreeningRunsCursor:
      name: subject_screening_runs_cursor
      in: query
      description: |
        Opaque `(requested_at,id)` keyset cursor from
        `subject_screening_history.runs.next_cursor`.
      schema: { type: string }

    SubjectScreeningHitsLimit:
      name: subject_screening_hits_limit
      in: query
      description: Page size for broader subject screening hits, capped at 200.
      schema: { type: integer, minimum: 1, maximum: 200, default: 50 }

    SubjectScreeningHitsCursor:
      name: subject_screening_hits_cursor
      in: query
      description: |
        Opaque `(created_at,id)` keyset cursor from
        `subject_screening_history.hits.next_cursor`.
      schema: { type: string }

    IdempotencyKey:
      name: Idempotency-Key
      in: header
      description: |
        The caller's own reference for this operation. ADR-0012 requires it on mutating
        endpoints because payment-adjacent callers retry and a duplicate filing is a
        regulatory incident.

        On the ingest endpoints it is not a separate identity: it supplies `external_ref`
        when the body omits it, and the uniqueness of (tenant, source, external_ref,
        booking_ts) in the database is what makes the retry harmless (ADR-0014). Sending
        both with different values is refused rather than resolved.
      schema: { type: string, maxLength: 128 }
    TenantID:
      name: tenantID
      in: path
      required: true
      schema: { type: string, format: uuid }

    UserID:
      name: userID
      in: path
      required: true
      schema: { type: string, format: uuid }

    ServiceAccountID:
      name: serviceAccountID
      in: path
      required: true
      schema: { type: string, format: uuid }

    GrantID:
      name: grantID
      in: path
      required: true
      schema: { type: string, format: uuid }

    PeriodStart:
      name: period_start
      in: query
      description: |
        Inclusive lower bound, RFC 3339. A timestamp rather than a date, because `2026-08-01`
        means two different instants in Lagos and in UTC.
      schema: { type: string, format: date-time }

    PeriodEnd:
      name: period_end
      in: query
      description: Exclusive upper bound, RFC 3339. The window is half-open.
      schema: { type: string, format: date-time }

    PeriodStartRequired:
      name: period_start
      in: query
      required: true
      description: Inclusive lower bound, RFC 3339.
      schema: { type: string, format: date-time }

    PeriodEndRequired:
      name: period_end
      in: query
      required: true
      description: Exclusive upper bound, RFC 3339. A transaction booked exactly here belongs to the next period.
      schema: { type: string, format: date-time }

    RoleID:
      name: roleID
      in: path
      required: true
      schema: { type: string, format: uuid }
    ApprovalID:
      name: approvalID
      in: path
      required: true
      schema: { type: string, format: uuid }
    PackID:
      name: packID
      in: path
      required: true
      schema: { type: string, format: uuid }
    ConfigKey:
      name: key
      in: path
      required: true
      description: A configuration key such as `monitoring.thresholds`.
      schema: { type: string, pattern: "^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)+$" }
    CustomerID:
      name: customerID
      in: path
      required: true
      schema: { type: string, format: uuid }
    HitID:
      name: hitID
      in: path
      required: true
      schema: { type: string, format: uuid }
    AlertID:
      name: alertID
      in: path
      required: true
      schema: { type: string, format: uuid }
    CaseID:
      name: caseID
      in: path
      required: true
      schema: { type: string, format: uuid }
    QueueID:
      name: queueID
      in: path
      required: true
      schema: { type: string, format: uuid }
    ReportID:
      name: reportID
      in: path
      required: true
      schema: { type: string, format: uuid }
    ReportScheduleID:
      name: scheduleID
      in: path
      required: true
      description: Tenant-scoped aggregate report schedule identifier.
      schema: { type: string, format: uuid }
    ReportRunID:
      name: runID
      in: path
      required: true
      description: Tenant-scoped immutable aggregate report occurrence identifier.
      schema: { type: string, format: uuid }
    ApplicationID:
      name: applicationID
      in: path
      required: true
      schema: { type: string, format: uuid }
    ListKey:
      name: listKey
      in: path
      required: true
      description: |
        An internal list's stable key. Text rather than a uuid because it is also the contract
        between this module and the screening index, which may not be referenced by a foreign key
        across the module boundary (ADR-0001).
      schema: { type: string }
    EntryID:
      name: entryID
      in: path
      required: true
      schema: { type: string, format: uuid }
    ImportID:
      name: importID
      in: path
      required: true
      schema: { type: string, format: uuid }
    MetricFrom:
      name: from
      in: query
      required: true
      description: |
        Start of the half-open window, inclusive. Required and never defaulted: a metric whose
        period was chosen by the server is a number nobody can reproduce, and two identical
        requests a minute apart would return different figures with no visible reason.
      schema: { type: string, format: date-time }
    MetricTo:
      name: to
      in: query
      required: true
      description: |
        End of the window, EXCLUSIVE. Half-open because a closed interval double-counts the
        boundary instant whenever two periods are compared — which is what a trend chart does by
        design. Must be after `from`.
      schema: { type: string, format: date-time }
    MetricAsOf:
      name: as_of
      in: query
      description: |
        The instant the question is asked about. Defaults to now. Supplying it is how a board
        pack reproduces last month's figure rather than recomputing a different one.
      schema: { type: string, format: date-time }

  responses:
    ProblemResponse:
      description: The operation could not be completed.
      content:
        application/problem+json:
          schema: { $ref: "#/components/schemas/Problem" }
    BadRequest:
      description: The request could not be understood
      content:
        application/problem+json:
          schema: { $ref: "#/components/schemas/Problem" }
    Unauthorized:
      description: Authentication required
      content:
        application/problem+json:
          schema: { $ref: "#/components/schemas/Problem" }
    Forbidden:
      description: The caller lacks the required permission
      content:
        application/problem+json:
          schema: { $ref: "#/components/schemas/Problem" }
    NotFound:
      description: |
        Not found. Under row-level security this is also the response when a resource
        belongs to another tenant: the two are indistinguishable by design, so a probing
        caller cannot learn that another tenant's record exists.
      content:
        application/problem+json:
          schema: { $ref: "#/components/schemas/Problem" }
    Conflict:
      description: The request conflicts with the current state
      content:
        application/problem+json:
          schema: { $ref: "#/components/schemas/Problem" }
    ValidationFailed:
      description: One or more fields are invalid
      content:
        application/problem+json:
          schema: { $ref: "#/components/schemas/Problem" }
    Unavailable:
      description: A required dependency is unreachable
      content:
        application/problem+json:
          schema: { $ref: "#/components/schemas/Problem" }

  schemas:
    SkippedRule:
      type: object
      additionalProperties: false
      required: [rule_key, reason, records]
      properties:
        rule_key: {type: string}
        reason: {type: string}
        records: {type: integer, format: int64}
    BacklogTotals:
      type: object
      additionalProperties: false
      required: [total, overdue, unassigned, escalated]
      properties:
        total: {type: integer, format: int64}
        overdue: {type: integer, format: int64}
        unassigned: {type: integer, format: int64}
        escalated: {type: integer, format: int64}
    TransactionDecisionInput:
      type: object
      additionalProperties: false
      properties:
        source:
          type: string
        transaction:
          $ref: '#/components/schemas/CorrectedTransactionInput'
      required:
      - source
      - transaction
    DecisionRuleEvidence:
      type: object
      additionalProperties: false
      properties:
        version_id:
          type: string
          format: uuid
        rule_key:
          type: string
        expression:
          type: string
        aggregates:
          type: object
          additionalProperties: true
        parameters:
          type: object
          additionalProperties: true
        window_from:
          type: string
          format: date-time
        window_to:
          type: string
          format: date-time
      required:
      - version_id
      - rule_key
      - expression
      - aggregates
      - parameters
      - window_from
      - window_to
    DecisionScreeningEvidence:
      type: object
      additionalProperties: false
      properties:
        entry_id:
          type: string
          format: uuid
        version_id:
          type: string
          format: uuid
        list_key:
          type: string
        score:
          type: number
      required:
      - entry_id
      - version_id
      - list_key
      - score
    TransactionDecision:
      type: object
      additionalProperties: false
      properties:
        id:
          type: string
          format: uuid
        account_id:
          type: string
          format: uuid
        product:
          type: string
        outcome:
          type: string
          enum:
          - allow
          - review
          - hold
          - deny
        degraded:
          type: boolean
        reason:
          type: string
        input_sha256:
          type: string
        policy_sha256:
          type: string
        rules_sha256:
          type: string
        screening_sha256:
          type: string
        rules:
          type: array
          items:
            $ref: '#/components/schemas/DecisionRuleEvidence'
        screening:
          type: array
          items:
            $ref: '#/components/schemas/DecisionScreeningEvidence'
        skipped:
          type: array
          items:
            $ref: '#/components/schemas/SkippedRule'
        latency_ms:
          type: integer
          format: int64
        created_at:
          type: string
          format: date-time
        expires_at:
          type: string
          format: date-time
      required:
      - id
      - account_id
      - product
      - outcome
      - degraded
      - reason
      - input_sha256
      - policy_sha256
      - rules_sha256
      - screening_sha256
      - rules
      - screening
      - skipped
      - latency_ms
      - created_at
      - expires_at
    DecisionHold:
      type: object
      additionalProperties: false
      properties:
        decision:
          $ref: '#/components/schemas/TransactionDecision'
        state:
          type: string
        proposed_outcome:
          type: string
        reason_code:
          type: string
        proposed_by:
          type: string
          format: uuid
        reviewed_by:
          type: string
          format: uuid
        reviewed_at:
          type: string
          format: date-time
      required:
      - decision
      - state
    HoldReleaseInput:
      type: object
      additionalProperties: false
      properties:
        outcome:
          type: string
          enum:
          - allow
          - deny
        reason_code:
          type: string
          enum:
          - review_complete
          - upstream_cancelled
          - confirmed_risk
      required:
      - outcome
      - reason_code
    DecisionHoldPage:
      type: object
      additionalProperties: false
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/DecisionHold'
        next_cursor:
          type: string
        total_count:
          type: integer
          format: int64
        backlog:
          $ref: '#/components/schemas/BacklogTotals'
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64
      required:
      - items
    ParameterSweepInput:
      type: object
      additionalProperties: false
      properties:
        version_id: &tuningschema001
          type: string
          format: uuid
        dataset_id: *tuningschema001
        parameter: &tuningschema002
          type: string
        values: &tuningschema003
          type: array
          items:
            type: integer
            format: int64
        sample_per_stratum: &tuningschema004
          type: integer
      required:
      - version_id
      - dataset_id
      - parameter
      - values
      - sample_per_stratum
    SweepPoint:
      type: object
      additionalProperties: false
      properties:
        value:
          type: integer
          format: int64
        quality:
          $ref: '#/components/schemas/QualityMetrics'
        newly_hit:
          type: array
          items: *tuningschema001
        dropped:
          type: array
          items: *tuningschema001
      required:
      - value
      - quality
      - newly_hit
      - dropped
    SweepCandidate:
      type: object
      additionalProperties: false
      properties:
        transaction_id: *tuningschema001
        booking_ts: &tuningschema005
          type: string
          format: date-time
        segment: &tuningschema006
          type: string
        channel: &tuningschema007
          type: string
      required:
      - transaction_id
      - booking_ts
      - segment
      - channel
    ParameterSweep:
      type: object
      additionalProperties: false
      properties:
        version_id: *tuningschema001
        dataset_id: *tuningschema001
        parameter: *tuningschema002
        values: *tuningschema003
        sample_per_stratum: *tuningschema004
        id: *tuningschema001
        artifact_sha256:
          type: string
        parameter_sha256:
          type: string
        dataset_sha256:
          type: string
        baseline:
          $ref: '#/components/schemas/QualityMetrics'
        points:
          type: array
          items:
            $ref: '#/components/schemas/SweepPoint'
        near_misses:
          type: array
          items:
            $ref: '#/components/schemas/SweepCandidate'
        created_by: *tuningschema001
        created_at: *tuningschema005
      required:
      - version_id
      - dataset_id
      - parameter
      - values
      - sample_per_stratum
      - id
      - artifact_sha256
      - parameter_sha256
      - dataset_sha256
      - baseline
      - points
      - near_misses
      - created_by
      - created_at
    NearMissProvenance:
      type: object
      additionalProperties: false
      description: Immutable labelled validation cohort lineage authorized afresh on each list request; not an institution-wide effectiveness claim.
      required: [source_kind, version_id, dataset_id, dataset_sha256, artifact_sha256, parameter_sha256]
      properties:
        source_kind: {type: string, description: Always labelled_validation_dataset for these exploratory samples.}
        version_id: {type: string, format: uuid}
        dataset_id: {type: string, format: uuid}
        dataset_sha256: {type: string}
        artifact_sha256: {type: string}
        parameter_sha256: {type: string}
    NearMissReview:
      type: object
      additionalProperties: false
      properties:
        provenance:
          $ref: '#/components/schemas/NearMissProvenance'
        can_review:
          type: boolean
          description: Current human is independent of the sweep maker; server review authorization is rechecked on submission.
        id: *tuningschema001
        sweep_id: *tuningschema001
        transaction_id: *tuningschema001
        booking_ts: *tuningschema005
        segment: *tuningschema006
        channel: *tuningschema007
        state:
          type: string
        outcome:
          type: string
        reviewed_by: *tuningschema001
        reviewed_at: *tuningschema005
        created_at: *tuningschema005
      required:
      - id
      - sweep_id
      - transaction_id
      - booking_ts
      - segment
      - channel
      - state
      - created_at
    NearMissReviewInput:
      type: object
      additionalProperties: false
      properties:
        outcome:
          type: string
          enum:
          - potential_false_negative
          - legitimate
          - insufficient_evidence
      required:
      - outcome
    NearMissReviewPage:
      type: object
      additionalProperties: false
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/NearMissReview'
        next_cursor:
          type: string
        total_count:
          type: integer
          format: int64
        backlog:
          $ref: '#/components/schemas/BacklogTotals'
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64
      required:
      - items

    SourceMappingDefinition:
      type: object
      additionalProperties: false
      required: [system, format, version, columns]
      properties:
        record_kind: { type: string, enum: [customer, account, transaction] }
        system: { type: string, minLength: 1 }
        format: { type: string, minLength: 1 }
        version: { type: string, minLength: 1, maxLength: 128 }
        delimiter: { type: string, maxLength: 1 }
        columns:
          type: object
          minProperties: 1
          maxProperties: 32
          additionalProperties: { $ref: '#/components/schemas/SourceMappingField' }
    SourceMappingField:
      type: object
      additionalProperties: false
      description: Exactly one source is required by the server (from, const or direction_from_sign_of). Transformations run without floating-point conversion.
      properties:
        from: { type: string, maxLength: 128 }
        const: { type: string, maxLength: 2048 }
        time_layout: { type: string }
        amount_scale: { type: integer, minimum: 0, maximum: 9 }
        absolute: { type: boolean }
        direction_from_sign_of: { type: string }
        values: { type: object, maxProperties: 256, additionalProperties: { type: string } }
        upper: { type: boolean }
    BoardCommentaryInput:
      type: object
      required: [window, layout_key, text, evidence_sections]
      properties:
        window: { $ref: "#/components/schemas/ReportWindow" }
        layout_key: { type: string }
        text: { type: string, minLength: 1, maxLength: 12000 }
        evidence_sections: { type: array, minItems: 1, items: { type: string } }
        prior_id: { type: string, format: uuid }
    BoardCommentaryDecision:
      type: object
      required: [decision, review_sha256, reason]
      properties:
        decision: { type: string, enum: [approved, rejected] }
        review_sha256: { type: string }
        reason: { type: string, minLength: 1, maxLength: 4000 }
    BoardCommentarySummary:
      type: object
      required: [id, window, layout_key, snapshot_sha256, review_sha256, evidence_sections, status, author_id, created_at]
      properties:
        id: { type: string, format: uuid }
        window: { $ref: "#/components/schemas/ReportWindow" }
        layout_key: { type: string }
        snapshot_sha256: { type: string }
        review_sha256: { type: string }
        evidence_sections: { type: array, items: { type: string } }
        status: { type: string, enum: [pending, approved, rejected] }
        author_id: { type: string, format: uuid }
        created_at: { type: string, format: date-time }
        prior_id: { type: string, format: uuid }
        decided_by: { type: string, format: uuid }
        decided_at: { type: string, format: date-time }
    BoardCommentary:
      type: object
      required: [id, window, layout_key, snapshot_sha256, review_sha256, evidence_sections, status, author_id, created_at, text, snapshot]
      properties:
        id: { type: string, format: uuid }
        window: { $ref: "#/components/schemas/ReportWindow" }
        layout_key: { type: string }
        snapshot_sha256: { type: string }
        review_sha256: { type: string }
        evidence_sections: { type: array, items: { type: string } }
        status: { type: string, enum: [pending, approved, rejected] }
        author_id: { type: string, format: uuid }
        created_at: { type: string, format: date-time }
        prior_id: { type: string, format: uuid }
        decided_by: { type: string, format: uuid }
        decided_at: { type: string, format: date-time }
        text: { type: string }
        snapshot: { type: object, additionalProperties: true }
        decision_reason: { type: string }
    BoardCommentaryList:
      type: object
      required: [items]
      properties:
        items: { type: array, items: { $ref: "#/components/schemas/BoardCommentarySummary" } }
        next_cursor: { type: string }
    WatchlistVersionDelta:
      type: object
      additionalProperties: false
      required: [version_id, list_key, added, changed, removed]
      properties:
        version_id: { type: string, format: uuid }
        previous_version_id: { type: string, format: uuid }
        list_key: { type: string }
        added: { type: integer, minimum: 0 }
        changed: { type: integer, minimum: 0 }
        removed: { type: integer, minimum: 0 }
    TenantIdentityProvider:
      type: object
      additionalProperties: false
      required:
      - issuer
      - audience
      - access_token_types
      - authorized_client_ids
      - required_scopes
      - required_roles
      - trusted_mfa_acr_values
      - web_client_id
      - web_secret_name
      - web_scopes
      - public_origin
      properties:
        issuer:
          type: string
        audience:
          type: string
        access_token_types:
          type: array
          items:
            type: string
        authorized_client_ids:
          type: array
          items:
            type: string
        required_scopes:
          type: array
          items:
            type: string
        required_roles:
          type: array
          items:
            type: string
        trusted_mfa_acr_values:
          type: array
          items:
            type: string
        web_client_id:
          type: string
        web_secret_name:
          type: string
        web_scopes:
          type: string
        web_step_up_acr_values:
          type: array
          items:
            type: string
        public_origin:
          type: string
    TenantControlRecord:
      type: object
      additionalProperties: false
      required:
      - tenant_id
      - kind
      - revision
      - payload
      - reason
      - updated_at
      properties:
        tenant_id:
          type: string
          format: uuid
        kind:
          type: string
        revision:
          type: integer
          format: int64
        payload:
          type: object
          additionalProperties: true
        reason:
          type: string
        updated_at:
          type: string
          format: date-time
    TenantControlUpdate:
      type: object
      additionalProperties: false
      required:
      - expected_revision
      - payload
      - reason
      properties:
        expected_revision:
          type: integer
          format: int64
        payload:
          type: object
          additionalProperties: true
        reason:
          type: string
          minLength: 8
          maxLength: 500
    TenantProvisionInput:
      type: object
      additionalProperties: false
      required:
      - slug
      - display_name
      - segment
      - admin_email
      - admin_name
      - admin_subject
      - identity_provider
      - reason
      properties:
        slug:
          type: string
        display_name:
          type: string
        segment:
          type: string
        admin_email:
          type: string
        admin_name:
          type: string
        admin_subject:
          type: string
        identity_provider:
          $ref: '#/components/schemas/TenantIdentityProvider'
        reason:
          type: string
    AdministratorInvitation:
      type: object
      additionalProperties: false
      required: [id, status, attempts]
      properties:
        id:
          type: string
          format: uuid
        status:
          type: string
          description: pending, sent (accepted by configured relay), or blocked; never proof of recipient delivery
        reason:
          type: string
          description: Closed safe delivery reason; contains no recipient or provider diagnostics
        attempts:
          type: integer
          format: int64
          minimum: 0
        last_attempt_at:
          type: string
          format: date-time
        sent_at:
          type: string
          format: date-time
    AdministratorInvitationRetry:
      type: object
      additionalProperties: false
      required: [reason]
      properties:
        reason:
          type: string
          minLength: 8
          maxLength: 500
    TenantProvisionResult:
      type: object
      additionalProperties: false
      required:
      - tenant
      - administrator_id
      - status
      - invitation_url
      - monitoring_activated
      properties:
        tenant:
          $ref: '#/components/schemas/Tenant'
        administrator_id:
          type: string
          format: uuid
        status:
          type: string
        invitation_url:
          type: string
        invitation:
          $ref: '#/components/schemas/AdministratorInvitation'
        monitoring_activated:
          type: boolean
    TenantLoginSettings:
      type: object
      additionalProperties: false
      required:
      - issuer
      - client_id
      - secret_name
      - scopes
      - public_origin
      - revision
      properties:
        issuer:
          type: string
        client_id:
          type: string
        secret_name:
          type: string
        scopes:
          type: string
        step_up_acr_values:
          type: array
          items:
            type: string
        public_origin:
          type: string
        revision:
          type: integer
          format: int64
    ResourceUsage:
      type: object
      additionalProperties: false
      required:
      - metric
      - used
      - limit
      - period_start
      - measured_since
      properties:
        metric:
          type: string
        used:
          type: integer
          format: int64
        limit:
          type: integer
          nullable: true
          format: int64
        period_start:
          type: string
          format: date-time
        measured_since:
          type: string
          nullable: true
          format: date-time
    ResourceUsageSummary:
      type: object
      additionalProperties: false
      required:
      - items
      - storage_coverage
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/ResourceUsage'
        storage_coverage:
          type: string
        storage_inventory:
          $ref: '#/components/schemas/StorageInventoryReceipt'
    StorageInventoryReceipt:
      type: object
      additionalProperties: false
      description: Latest completed current-object scan receipt. Observed counts and bytes describe this scan only. Union bytes retain the greatest size for each key across all completed scans and upload reservations, including uncertain writes and previously observed objects that later disappeared. Reconciled usage also preserves the prior conservative usage floor. This is not a historical point-in-time snapshot or proof of deletion.
      required: [tenant_id, run_id, observed_objects, observed_bytes, union_bytes, previous_usage, reconciled_usage, scan_digest, completed_at]
      properties:
        tenant_id: {type: string, format: uuid}
        run_id: {type: string, format: uuid}
        observed_objects: {type: integer, format: int64, minimum: 0, description: Distinct keys observed in this completed scan.}
        observed_bytes: {type: integer, format: int64, minimum: 0, description: Sum of per-key maximum ciphertext sizes observed in this scan.}
        union_bytes: {type: integer, format: int64, minimum: 0, description: Cumulative per-key maximum bytes across all completed observations and reservations.}
        previous_usage: {type: integer, format: int64, minimum: 0}
        reconciled_usage: {type: integer, format: int64, minimum: 0}
        scan_digest: {type: string, pattern: '^[a-f0-9]{64}$', description: Digest of the ordered observation stream including repeats; not a canonical checksum reconstructible from deduplicated retained rows.}
        completed_at: {type: string, format: date-time}
    GenAIModelDefinition:
      type: object
      additionalProperties: false
      required: [provider, model, model_version, prompt_version, allowed_uses]
      properties:
        provider: { type: string, enum: [local, claude] }
        model: { type: string, minLength: 1, maxLength: 200 }
        model_version: { type: string, minLength: 1, maxLength: 200 }
        prompt_version: { type: string, enum: [evidence-assistant-v2] }
        allowed_uses:
          type: array
          minItems: 1
          maxItems: 4
          uniqueItems: true
          items: { type: string, enum: [alert_explanation, case_handover, str_narrative, search_filters] }
    AIAcceptanceProvenance:
      type: object
      required: [invocation_id, result_resource_id, inventory_version_id, accepted_by, accepted_at, model, model_version, prompt_hash, response_hash, evidence_hashes]
      properties:
        invocation_id: { type: string, format: uuid }
        result_resource_id: { type: string, format: uuid }
        inventory_version_id: { type: string, format: uuid }
        accepted_by: { type: string, format: uuid }
        accepted_at: { type: string, format: date-time }
        model: { type: string }
        model_version: { type: string }
        prompt_hash: { type: string }
        response_hash: { type: string }
        evidence_hashes: { type: object, additionalProperties: { type: string } }
    UploadQuarantine:
      type: object
      additionalProperties: false
      required: [id, kind, sha256, size_bytes, reason_code, status, created_at]
      properties:
        id: { type: string, format: uuid }
        kind: { type: string, enum: [document, case_attachment, validation_evidence] }
        sha256: { type: string, pattern: '^[a-f0-9]{64}$' }
        size_bytes: { type: integer, format: int64 }
        reason_code: { type: string, enum: [malware_detected, scanner_unavailable, unsafe_content] }
        status: { type: string, enum: [pending, retry_requested, dismissed, recovered] }
        created_at: { type: string, format: date-time }
    UploadQuarantinePage:
      type: object
      required: [items]
      properties:
        items: { type: array, items: { $ref: '#/components/schemas/UploadQuarantine' } }
        next_cursor: { type: string }
        total_count: { type: integer, format: int64 }
        backlog: { $ref: '#/components/schemas/BacklogTotals' }
        truncated: { type: boolean }
        truncation_reason: { type: string }
        total_estimate: { type: integer, format: int64 }
    UploadQuarantineDisposition:
      type: object
      additionalProperties: false
      required: [status]
      properties:
        status: { type: string, enum: [retry_requested, dismissed] }
    AIAcceptanceProvenancePage:
      type: object
      required: [items]
      properties:
        items: { type: array, items: { $ref: '#/components/schemas/AIAcceptanceProvenance' } }
        next_cursor: { type: string }
        total_count: { type: integer, format: int64 }
        total_estimate: { type: integer, format: int64 }
        backlog: { $ref: '#/components/schemas/BacklogTotals' }
        truncated: { type: boolean }
        truncation_reason: { type: string }
    AIAssistance:
      type: object
      required: [id, use_case, model, model_version, inventory_version_id, output]
      properties:
        id: { type: string, format: uuid }
        use_case: { type: string, enum: [alert_explanation, case_handover, str_narrative, search_filters] }
        model: { type: string }
        model_version: { type: string }
        inventory_version_id: { type: string, format: uuid }
        output: { $ref: '#/components/schemas/AIOutput' }
    AIOutput:
      type: object
      required: [statements, filters]
      properties:
        statements:
          type: array
          items: { $ref: '#/components/schemas/AIStatement' }
        filters:
          type: object
          additionalProperties: { type: string }
    AIStatement:
      type: object
      required: [section, text, evidence_ids]
      properties:
        section: { type: string, enum: [summary, who, what, when, where, why, how] }
        text: { type: string, maxLength: 2000 }
        evidence_ids:
          type: array
          items: { type: string }
    ActivityBaseline:
      type: object
      additionalProperties: false
      required: [id, as_of, window_from, mean_minor, stddev_minor, p95_minor, current_minor, deviation_defined, zscore_bps]
      properties:
        id: {type: string, format: uuid}
        as_of: {type: string, format: date-time}
        window_from: {type: string, format: date-time}
        mean_minor: {type: string, description: Exact decimal daily mean of the metric named by its enclosing field (turnover, credit or debit)}
        stddev_minor: {type: string, description: Exact decimal population standard deviation}
        p95_minor: {type: integer, format: int64}
        current_minor: {type: integer, format: int64}
        customer_count: {type: integer, format: int64}
        deviation_defined: {type: boolean}
        zscore_bps: {type: integer, format: int64, description: Standard deviations multiplied by 10000; meaningful only when deviation_defined}
    NarrativeSections:
      type: object
      additionalProperties: false
      description: Six narrative sections with at most 32000 characters in total; evidence citation tokens are validated against the case.
      required: [who, what, when, where, why, how]
      properties:
        who: {type: string, maxLength: 32000}
        what: {type: string, maxLength: 32000}
        when: {type: string, maxLength: 32000}
        where: {type: string, maxLength: 32000}
        why: {type: string, maxLength: 32000}
        how: {type: string, maxLength: 32000}
    NarrativeUpdateInput:
      type: object
      additionalProperties: false
      required: [expected_revision, sections]
      properties:
        expected_revision: {type: integer, format: int64, minimum: 0}
        sections: {$ref: '#/components/schemas/NarrativeSections'}
    NarrativeWorkspace:
      type: object
      additionalProperties: false
      required: [report_id, root_report_id, latest_report_id, revision, sections, missing_sections]
      properties:
        report_id: {type: string, format: uuid}
        root_report_id: {type: string, format: uuid}
        latest_report_id: {type: string, format: uuid}
        revision: {type: integer, format: int64, minimum: 0}
        sections: {$ref: '#/components/schemas/NarrativeSections'}
        missing_sections:
          type: array
          items: {type: string, enum: [who, what, when, where, why, how]}
        return_reason: {type: string}
        returned_at: {type: string, format: date-time}
    AdminJob:
      type: object
      additionalProperties: false
      required: [id, kind, queue, state, attempt, max_attempts, created_at, scheduled_at, finalized_at]
      properties:
        id: { type: string, pattern: '^[1-9][0-9]{0,18}$', description: Decimal River identifier serialized as a string to preserve 64-bit precision. }
        kind: { type: string }
        queue: { type: string }
        state: { type: string, enum: [available, cancelled, completed, discarded, pending, retryable, running, scheduled] }
        attempt: { type: integer, minimum: 0 }
        max_attempts: { type: integer, minimum: 1 }
        created_at: { type: string, format: date-time }
        scheduled_at: { type: string, format: date-time }
        finalized_at: { type: [string, 'null'], format: date-time }
    AdminJobPage:
      type: object
      additionalProperties: false
      required: [items, next_before]
      properties:
        items: { type: array, items: { $ref: '#/components/schemas/AdminJob' } }
        next_before: { type: [string, 'null'], description: Legacy unfiltered newest-first continuation; otherwise null. }
        next_cursor: { type: string, description: Tenant/filter/order-bound canonical decimal bigint position. }
    AdminJobControlInput:
      type: object
      additionalProperties: false
      required: [reason]
      properties:
        reason: { type: string, minLength: 8, maxLength: 500 }
    AdminJobTransition:
      type: object
      additionalProperties: false
      required: [id, previous_state, state]
      properties:
        id: { type: string }
        previous_state: { type: string }
        state: { type: string, enum: [available, discarded] }
    ApplicationSummary:
      type: object
      additionalProperties: false
      required: [id, customer_id, status, submitted_at]
      properties:
        id: {type: string, format: uuid}
        customer_id: {type: string, format: uuid}
        status: {type: string, enum: [submitted, under_review, approved, rejected]}
        submitted_at: {type: string, format: date-time}
        submitted_by: {type: string, format: uuid}
        review_started_by: {type: string, format: uuid}
    Webhook:
      type: object
      required: [id, endpoint, event_types, enabled, created_at]
      properties:
        delivery_format: { type: string, enum: [event, slack, teams], default: event }
        recipient_id: { type: string, format: uuid, description: Required for Slack or Teams deliveries. }
        approved_for_notifications: { type: boolean, default: false, description: Must be true for Slack or Teams destinations. }
        id: { type: string, format: uuid }
        endpoint: { type: string, format: uri }
        event_types: { type: array, items: { type: string } }
        enabled: { type: boolean }
        created_at: { type: string, format: date-time }
    RegisteredWebhook:
      type: object
      required: [id, endpoint, event_types, enabled, created_at, secret]
      properties:
        delivery_format: { type: string, enum: [event, slack, teams], default: event }
        recipient_id: { type: string, format: uuid, description: Required for Slack or Teams deliveries. }
        approved_for_notifications: { type: boolean, default: false, description: Must be true for Slack or Teams destinations. }
        secret: { type: string }
        id: { type: string, format: uuid }
        endpoint: { type: string, format: uri }
        event_types: { type: array, items: { type: string } }
        enabled: { type: boolean }
        created_at: { type: string, format: date-time }
    WebhookPage:
      type: object
      required: [items]
      properties:
        items: { type: array, items: { $ref: '#/components/schemas/Webhook' } }
        next_cursor: { type: string }
    BulkInput:
      type: object
      additionalProperties: false
      required: [ids, action, reason]
      properties:
        ids: {type: array, minItems: 1, maxItems: 1000, items: {type: string, format: uuid}}
        action: {type: string, enum: [assign_to_me, closed_false_positive, closed_actioned, true_positive, false_positive]}
        reason: {type: string, maxLength: 4000}
    BulkItem:
      type: object
      required: [id, status]
      properties:
        id: {type: string, format: uuid}
        status: {type: string, enum: [pending, succeeded, failed, awaiting_approval]}
        error: {type: string}
        approval_id: {type: string, format: uuid}
    BulkOperation:
      type: object
      required: [id, kind, action, status, created_at, items]
      properties:
        id: {type: string, format: uuid}
        kind: {type: string, enum: [alert, screening_hit]}
        action: {type: string}
        status: {type: string, enum: [pending, completed]}
        created_at: {type: string, format: date-time}
        items: {type: array, items: {$ref: '#/components/schemas/BulkItem'}}
    QueueAutomationInput:
      type: object
      additionalProperties: false
      required: [assignment_mode, route_alerts]
      properties:
        assignment_mode: {type: string, enum: [manual, round_robin, least_loaded]}
        route_alerts: {type: boolean}
        escalation_role_key: {type: string, maxLength: 64}
    QueueAutomation:
      type: object
      required: [queue_id, assignment_mode, route_alerts]
      properties:
        queue_id: {type: string, format: uuid}
        assignment_mode: {type: string, enum: [manual, round_robin, least_loaded]}
        route_alerts: {type: boolean}
        escalation_role_key: {type: string, maxLength: 64}
    WebhookDelivery:
      type: object
      required: [id, subscription_id, event_id, status, attempts, next_attempt_at]
      properties:
        created_at: {type: string, format: date-time}
        id: { type: string, format: uuid }
        subscription_id: { type: string, format: uuid }
        event_id: { type: string, format: uuid }
        status: { type: string }
        attempts: { type: integer }
        next_attempt_at: { type: string, format: date-time }
        last_status: { type: integer }
        last_error: { type: string }
    WebhookDeliveryPage:
      type: object
      required: [items]
      properties:
        items: { type: array, items: { $ref: '#/components/schemas/WebhookDelivery' } }
        next_cursor: { type: string }
    SyncChunkInput:
      type: object
      additionalProperties: false
      required: [source, external_reference, offset, total_rows, rows]
      properties:
        source: {type: string, pattern: '^[a-z][a-z0-9_.-]{0,31}$'}
        external_reference: {type: string, minLength: 1, maxLength: 200}
        offset: {type: integer, format: int64, minimum: 0}
        total_rows: {type: integer, format: int64, minimum: 1, maximum: 1000000}
        retry_quarantined: {type: boolean, default: false}
        mapping:
          description: Optional source layout, pinned to the batch and required unchanged on every resumed chunk. Mapping failures are quarantined with the original source object.
          $ref: '#/components/schemas/SourceMappingDefinition'
        rows:
          type: array
          minItems: 1
          maxItems: 100
          description: Canonical customer or account sync objects, as accepted by the corresponding single-record sync route. Invalid individual records are retained in quarantine. Corrections must preserve external_ref when present.
          items: {}
    SyncRow:
      type: object
      additionalProperties: false
      required: [index, status, original, current, attempts]
      properties:
        index: {type: integer, format: int64, minimum: 0}
        status: {type: string, enum: [imported, quarantined]}
        resource_id: {type: string, format: uuid}
        error_code: {type: string}
        original: {}
        current: {}
        attempts: {type: integer, format: int64, minimum: 1}
    SyncBatch:
      type: object
      additionalProperties: false
      required: [id, kind, source, external_reference, expected_rows, received, imported, quarantined, status, created_at]
      properties:
        id: {type: string, format: uuid}
        kind: {type: string, enum: [account, customer]}
        mapping: { $ref: '#/components/schemas/SourceMappingDefinition' }
        source: {type: string}
        external_reference: {type: string}
        expected_rows: {type: integer, format: int64}
        received: {type: integer, format: int64}
        imported: {type: integer, format: int64}
        quarantined: {type: integer, format: int64}
        status: {type: string, enum: [receiving, completed, needs_attention]}
        created_at: {type: string, format: date-time}
        rows:
          type: array
          items: {$ref: '#/components/schemas/SyncRow'}
    CasePlaybook:
      additionalProperties: false
      properties:
        approved_by:
          format: uuid
          type: string
        decided_at:
          format: date-time
          type: string
        id:
          format: uuid
          type: string
        key:
          type: string
        proposed_at:
          format: date-time
          type: string
        proposed_by:
          format: uuid
          type: string
        status:
          type: string
        tasks:
          items:
            $ref: '#/components/schemas/CaseTaskDefinition'
          type: array
        version:
          format: int64
          type: integer
      required:
      - id
      - key
      - version
      - tasks
      - status
      - proposed_by
      - proposed_at
      type: object
    CasePlaybookInput:
      additionalProperties: false
      properties:
        key:
          type: string
        tasks:
          items:
            $ref: '#/components/schemas/CaseTaskDefinition'
          type: array
      required:
      - key
      - tasks
      type: object
    CaseTaskDefinition:
      additionalProperties: false
      properties:
        depends_on:
          items:
            type: string
          type: array
        due_hours:
          format: int64
          type: integer
        evidence_required:
          type: boolean
        key:
          type: string
        kind:
          type: string
        mandatory:
          type: boolean
        title:
          type: string
      required:
      - key
      - title
      - kind
      - mandatory
      - evidence_required
      - due_hours
      type: object
    CaseTaskInput:
      additionalProperties: false
      properties:
        assignee_id:
          format: uuid
          type: string
        case_id:
          format: uuid
          type: string
        depends_on:
          items:
            format: uuid
            type: string
          type: array
        due_at:
          format: date-time
          type: string
        evidence_required:
          type: boolean
        key:
          type: string
        kind:
          type: string
        mandatory:
          type: boolean
        title:
          type: string
      required:
      - case_id
      - key
      - title
      - kind
      - mandatory
      - evidence_required
      type: object
    CorrectedTransactionInput:
      additionalProperties: false
      properties:
        business_evidence: { $ref: "#/components/schemas/TransactionBusinessEvidence" }
        account_ref:
          type: string
        amount_minor:
          format: int64
          type: integer
        booking_ts:
          format: date-time
          type: string
        channel:
          type: string
        corridor_country:
          type: string
        counterparty_account:
          type: string
        counterparty_bank:
          type: string
        counterparty_name:
          type: string
        currency:
          type: string
        direction:
          type: string
        event_type:
          type: string
        external_ref:
          type: string
        lifecycle_reason:
          type: string
        narrative:
          type: string
        original_booking_ts:
          format: date-time
          type: string
        original_external_ref:
          type: string
        original_source:
          type: string
        value_date:
          format: date-time
          type: string
      required:
      - account_ref
      - external_ref
      - booking_ts
      - direction
      - amount_minor
      - currency
      type: object
    ExpectedActivity:
      additionalProperties: false
      properties:
        channels:
          items:
            type: string
          type: array
        countries:
          items:
            type: string
          type: array
        currency:
          type: string
        monthly_credit_minor:
          format: int64
          type: integer
        monthly_debit_minor:
          format: int64
          type: integer
        monthly_transaction_count:
          format: int64
          type: integer
      required:
      - currency
      - monthly_credit_minor
      - monthly_debit_minor
      - monthly_transaction_count
      type: object
    FXConversion:
      additionalProperties: false
      properties:
        as_of:
          format: date-time
          type: string
        base_currency:
          type: string
        input_minor:
          format: int64
          type: integer
        output_minor:
          format: int64
          type: integer
        payload_sha256:
          type: string
        quote_currency:
          type: string
        rate:
          $ref: '#/components/schemas/FXRate'
        reference_id:
          format: uuid
          type: string
        reference_version:
          format: int64
          type: integer
        source_sha256:
          pattern: ^[a-f0-9]{64}$
          type: string
      required:
      - reference_id
      - reference_version
      - payload_sha256
      - source_sha256
      - base_currency
      - quote_currency
      - input_minor
      - output_minor
      - rate
      - as_of
      type: object
    FXConversionInput:
      additionalProperties: false
      properties:
        amount_minor:
          format: int64
          type: integer
        as_of:
          format: date-time
          type: string
        base_currency:
          type: string
        quote_currency:
          type: string
        reference_id:
          format: uuid
          type: string
      required:
      - reference_id
      - base_currency
      - quote_currency
      - amount_minor
      - as_of
      type: object
    FXRate:
      additionalProperties: false
      properties:
        base_currency:
          type: string
        denominator:
          type: string
        numerator:
          type: string
        quote_currency:
          type: string
        rounding:
          type: string
      required:
      - base_currency
      - quote_currency
      - numerator
      - denominator
      - rounding
      type: object
    FilingClock:
      additionalProperties: false
      properties:
        basis:
          type: string
        business_days:
          format: int64
          type: integer
        calendar_from:
          type: string
        calendar_to:
          type: string
        cutoff_local:
          type: string
        decided_at:
          format: date-time
          type: string
        decided_by:
          format: uuid
          type: string
        effective_from:
          format: date-time
          type: string
        effective_to:
          format: date-time
          type: string
        event_type:
          type: string
        holidays:
          items:
            type: string
          type: array
        hours:
          format: int64
          type: integer
        id:
          format: uuid
          type: string
        key:
          type: string
        kind:
          type: string
        payload_sha256:
          type: string
        proposed_at:
          format: date-time
          type: string
        proposed_by:
          format: uuid
          type: string
        source_sha256:
          type: string
        source_uri:
          type: string
        status:
          type: string
        timezone:
          type: string
        version:
          format: int64
          type: integer
        weekend_days:
          items:
            format: int64
            type: integer
          type: array
      required:
      - id
      - key
      - kind
      - event_type
      - basis
      - timezone
      - effective_from
      - effective_to
      - source_uri
      - source_sha256
      - version
      - payload_sha256
      - status
      - proposed_by
      - proposed_at
      type: object
    FilingClockInput:
      additionalProperties: false
      properties:
        basis:
          type: string
        business_days:
          format: int64
          type: integer
        calendar_from:
          type: string
        calendar_to:
          type: string
        cutoff_local:
          type: string
        effective_from:
          format: date-time
          type: string
        effective_to:
          format: date-time
          type: string
        event_type:
          type: string
        holidays:
          items:
            type: string
          type: array
        hours:
          format: int64
          type: integer
        key:
          type: string
        kind:
          type: string
        source_sha256:
          type: string
        source_uri:
          type: string
        timezone:
          type: string
        weekend_days:
          items:
            format: int64
            type: integer
          type: array
      required:
      - key
      - kind
      - event_type
      - basis
      - timezone
      - effective_from
      - effective_to
      - source_uri
      - source_sha256
      type: object
    FilingObligation:
      additionalProperties: false
      properties:
        case_id:
          format: uuid
          type: string
        due_at:
          format: date-time
          type: string
        event_reference:
          type: string
        event_type:
          type: string
        id:
          format: uuid
          type: string
        kind:
          type: string
        met_at:
          format: date-time
          type: string
        met_late:
          type: boolean
        occurred_at:
          format: date-time
          type: string
        policy_version_id:
          format: uuid
          type: string
        recorded_at:
          format: date-time
          type: string
        recorded_by:
          format: uuid
          type: string
        report_id:
          format: uuid
          type: string
        status:
          type: string
      required:
      - id
      - policy_version_id
      - event_reference
      - occurred_at
      - kind
      - event_type
      - due_at
      - status
      - recorded_at
      - met_late
      type: object
    GeographyEntry:
      additionalProperties: false
      properties:
        classification:
          type: string
        country:
          type: string
        reason:
          type: string
      required:
      - country
      - classification
      - reason
      type: object
    KYCCompletion:
      additionalProperties: false
      properties:
        risk_assessment_id: {type: string, format: uuid}
        risk_reassessment_status: {type: string, enum: [assessed, unconfigured]}
        assessment:
          $ref: '#/components/schemas/ReviewAssessment'
        decided_at:
          format: date-time
          type: string
        decided_by:
          format: uuid
          type: string
        decision_reason:
          type: string
        evidence_document_ids:
          items:
            format: uuid
            type: string
          type: array
        id:
          format: uuid
          type: string
        next_review_on:
          format: date-time
          type: string
        outcome:
          type: string
        proposed_at:
          format: date-time
          type: string
        proposed_by:
          format: uuid
          type: string
        review_id:
          format: uuid
          type: string
        status:
          type: string
      required:
      - id
      - review_id
      - outcome
      - status
      - proposed_by
      - proposed_at
      - evidence_document_ids
      type: object
    KYCCompletionInput:
      additionalProperties: false
      properties:
        assessment:
          $ref: '#/components/schemas/ReviewAssessment'
        evidence_document_ids:
          items:
            format: uuid
            type: string
          type: array
        next_review_on:
          format: date-time
          type: string
        outcome:
          type: string
        review_id:
          format: uuid
          type: string
      required:
      - review_id
      - outcome
      - assessment
      - evidence_document_ids
      type: object
    KYCReview:
      additionalProperties: false
      properties:
        assignee_id:
          format: uuid
          type: string
        completed_at:
          format: date-time
          type: string
        completed_by:
          format: uuid
          type: string
        customer_display_name:
          description: Customer label returned through the ordinary authorized subject disclosure path on list and detail responses. Restricted or erased subjects are not disclosed; claim responses may omit this optional label.
          type: string
        customer_id:
          format: uuid
          type: string
        due_on:
          format: date-time
          type: string
        id:
          format: uuid
          type: string
        outcome:
          type: string
        reason:
          type: string
        started_at:
          format: date-time
          type: string
        status:
          type: string
      required:
      - id
      - customer_id
      - due_on
      - reason
      - status
      type: object
    ObligationInput:
      additionalProperties: false
      properties:
        case_id:
          format: uuid
          type: string
        event_reference:
          type: string
        occurred_at:
          format: date-time
          type: string
        policy_version_id:
          format: uuid
          type: string
      required:
      - policy_version_id
      - event_reference
      - occurred_at
      type: object
    QuarantineRecord:
      additionalProperties: false
      properties:
        batch_id:
          format: uuid
          type: string
        created_at:
          format: date-time
          type: string
        error:
          type: string
        id:
          format: uuid
          type: string
        line_no:
          format: int64
          type: integer
        raw:
          type: string
        resolution:
          $ref: '#/components/schemas/QuarantineResolution'
      required:
      - id
      - batch_id
      - line_no
      - raw
      - error
      - created_at
      type: object
    QuarantineResolution:
      additionalProperties: false
      properties:
        booking_ts:
          format: date-time
          type: string
        quarantine_id:
          format: uuid
          type: string
        reason_code:
          type: string
        resolved_at:
          format: date-time
          type: string
        resolved_by:
          format: uuid
          type: string
        transaction_id:
          format: uuid
          type: string
      required:
      - quarantine_id
      - transaction_id
      - booking_ts
      - reason_code
      - resolved_by
      - resolved_at
      type: object
    QuarantineResolutionInput:
      additionalProperties: false
      properties:
        corrected:
          $ref: '#/components/schemas/CorrectedTransactionInput'
        quarantine_id:
          format: uuid
          type: string
        reason_code:
          type: string
      required:
      - quarantine_id
      - reason_code
      - corrected
      type: object
    ReferenceInput:
      additionalProperties: false
      properties:
        as_of:
          format: date-time
          type: string
        geographies:
          items:
            $ref: '#/components/schemas/GeographyEntry'
          type: array
        key:
          type: string
        kind:
          type: string
        rates:
          items:
            $ref: '#/components/schemas/FXRate'
          type: array
        source_sha256:
          type: string
        source_uri:
          type: string
        valid_until:
          format: date-time
          type: string
      required:
      - kind
      - key
      - source_uri
      - source_sha256
      - as_of
      - valid_until
      type: object
    ReferenceVersion:
      additionalProperties: false
      properties:
        as_of:
          format: date-time
          type: string
        decided_at:
          format: date-time
          type: string
        decided_by:
          format: uuid
          type: string
        geographies:
          items:
            $ref: '#/components/schemas/GeographyEntry'
          type: array
        id:
          format: uuid
          type: string
        key:
          type: string
        kind:
          type: string
        payload_sha256:
          type: string
        proposed_at:
          format: date-time
          type: string
        proposed_by:
          format: uuid
          type: string
        rates:
          items:
            $ref: '#/components/schemas/FXRate'
          type: array
        source_sha256:
          type: string
        source_uri:
          type: string
        status:
          type: string
        valid_until:
          format: date-time
          type: string
        version:
          format: int64
          type: integer
      required:
      - id
      - kind
      - key
      - source_uri
      - source_sha256
      - as_of
      - valid_until
      - version
      - payload_sha256
      - status
      - proposed_by
      - proposed_at
      type: object
    ReviewAssessment:
      additionalProperties: false
      properties:
        checklist:
          additionalProperties:
            type: boolean
          type: object
        expected_activity:
          $ref: '#/components/schemas/ExpectedActivity'
        findings:
          type: string
        source_of_funds:
          type: string
        source_of_wealth:
          type: string
      required:
      - findings
      type: object
    SourceManifest:
      additionalProperties: false
      properties:
        latest_reconciliation:
          $ref: '#/components/schemas/SourceReconciliation'
        batch_id:
          format: uuid
          type: string
        expected_amounts:
          additionalProperties:
            format: int64
            type: integer
          type: object
        expected_at:
          format: date-time
          type: string
        expected_count:
          format: int64
          type: integer
        external_reference:
          type: string
        id:
          format: uuid
          type: string
        recorded_at:
          format: date-time
          type: string
        recorded_by:
          format: uuid
          type: string
        source:
          type: string
        source_sha256:
          type: string
        window_from:
          format: date-time
          type: string
        window_to:
          format: date-time
          type: string
      required:
      - id
      - source
      - external_reference
      - window_from
      - window_to
      - expected_at
      - expected_count
      - expected_amounts
      - source_sha256
      - recorded_by
      - recorded_at
      type: object
    SourceManifestInput:
      additionalProperties: false
      properties:
        batch_id:
          format: uuid
          type: string
        expected_amounts:
          additionalProperties:
            format: int64
            type: integer
          type: object
        expected_at:
          format: date-time
          type: string
        expected_count:
          format: int64
          type: integer
        external_reference:
          type: string
        source:
          type: string
        source_sha256:
          type: string
        window_from:
          format: date-time
          type: string
        window_to:
          format: date-time
          type: string
      required:
      - source
      - external_reference
      - window_from
      - window_to
      - expected_at
      - expected_count
      - expected_amounts
      - source_sha256
      type: object
    SourceReconciliation:
      additionalProperties: false
      properties:
        checked_at:
          format: date-time
          type: string
        id:
          format: uuid
          type: string
        manifest_id:
          format: uuid
          type: string
        observed_amounts:
          additionalProperties:
            format: int64
            type: integer
          type: object
        observed_count:
          format: int64
          type: integer
        status:
          type: string
        unresolved_quarantine:
          format: int64
          type: integer
      required:
      - id
      - manifest_id
      - status
      - observed_count
      - observed_amounts
      - unresolved_quarantine
      - checked_at
      type: object
    MaturityDecisionInput:
      type: object
      required:
      - decision
      properties:
        decision:
          type: string
          enum:
          - approve
          - reject
        reason:
          type: string
          maxLength: 8000
      additionalProperties: false
    CaseTaskCompletionInput:
      type: object
      required:
      - result
      - evidence_attachment_ids
      properties:
        result:
          type: string
          minLength: 1
          maxLength: 16000
        evidence_attachment_ids:
          type: array
          maxItems: 50
          uniqueItems: true
          items:
            type: string
            format: uuid
      additionalProperties: false
    KYCReviewPage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/KYCReview'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64
      additionalProperties: false
    KYCCompletionPage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/KYCCompletion'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64
      additionalProperties: false
    QuarantineRecordPage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/QuarantineRecord'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64
      additionalProperties: false
    SourceManifestPage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/SourceManifest'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64
      additionalProperties: false
    SourceReconciliationPage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/SourceReconciliation'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64
      additionalProperties: false
    CaseTaskPage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/CaseTask'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64
      additionalProperties: false
    CaseQualityReviewPage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/CaseQualityReview'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64
      additionalProperties: false
    CasePlaybookPage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/CasePlaybook'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64
      additionalProperties: false
    Notification:
      type: object
      additionalProperties: false
      required: [id, event_type, resource_type, resource_id, title, href, created_at]
      properties:
        id: { type: string, format: uuid }
        event_type: { type: string }
        resource_type: { type: string }
        resource_id: { type: string, format: uuid }
        title: { type: string }
        href: { type: string }
        created_at: { type: string, format: date-time }
        read_at: { type: string, format: date-time }
    NotificationPage:
      type: object
      additionalProperties: false
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: '#/components/schemas/Notification' }
        next_cursor: { $ref: '#/components/schemas/NextCursor' }
        truncated: { $ref: '#/components/schemas/Truncated' }
        truncation_reason: { $ref: '#/components/schemas/TruncationReason' }
        total_estimate: { $ref: '#/components/schemas/TotalEstimate' }
    NotificationPreferenceInput:
      type: object
      additionalProperties: false
      required: [in_app, email_mode, digest_hour_utc]
      properties:
        team_chat: { type: boolean, default: false }
        in_app: { type: boolean }
        email_mode: { type: string, enum: [off, daily] }
        digest_hour_utc: { type: integer, minimum: 0, maximum: 23 }
    NotificationPreferences:
      type: object
      additionalProperties: false
      required: [in_app, email_mode, digest_hour_utc, email_available]
      properties:
        team_chat: { type: boolean, default: false }
        in_app: { type: boolean }
        email_mode: { type: string, enum: [off, daily] }
        digest_hour_utc: { type: integer, minimum: 0, maximum: 23 }
        email_available: { type: boolean }

    WorkInboxItem:
      type: object
      required:
      - id
      - kind
      - label
      - href
      - priority
      - occurred_at
      properties:
        id:
          type: string
          format: uuid
        kind:
          type: string
          enum:
          - alert
          - case
          - kyc_review
          - approval
          - case_task
          - screening_hit
          - report
          - onboarding_application
        label:
          type: string
        href:
          type: string
        priority:
          type: string
        occurred_at:
          type: string
          format: date-time
        due_at:
          type: string
          format: date-time
        read_at:
          type: string
          format: date-time
    WorkInboxPage:
      type: object
      required:
      - items
      - generated_at
      - refresh_after_seconds
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/WorkInboxItem'
        next_cursor:
          $ref: '#/components/schemas/NextCursor'
        truncated:
          $ref: '#/components/schemas/Truncated'
        truncation_reason:
          $ref: '#/components/schemas/TruncationReason'
        total_estimate:
          $ref: '#/components/schemas/TotalEstimate'
        generated_at:
          type: string
          format: date-time
        refresh_after_seconds:
          type: integer
          minimum: 1

    WorkspaceDocument:
      type: object
      required:
      - id
      - kind
      - resource_key
      - revision
      - payload
      - updated_at
      - expires_at
      properties:
        id:
          type: string
          format: uuid
        kind:
          type: string
          enum:
          - onboarding
          - case_note
          - report_narrative
          - view
        resource_key:
          type: string
        revision:
          type: integer
          minimum: 1
        payload:
          type: object
          additionalProperties: true
        updated_at:
          type: string
          format: date-time
        expires_at:
          type: string
          format: date-time
    SearchResult:
      type: object
      required:
      - kind
      - id
      - label
      - description
      - href
      properties:
        kind:
          type: string
          enum:
          - customer
          - account
          - hit
          - case
          - report
          - alert
        id:
          type: string
          format: uuid
        label:
          type: string
        description:
          type: string
        href:
          type: string
    WorkspaceDocumentPage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/WorkspaceDocument'
        next_cursor:
          $ref: '#/components/schemas/NextCursor'
        truncated:
          $ref: '#/components/schemas/Truncated'
        truncation_reason:
          $ref: '#/components/schemas/TruncationReason'
        total_estimate:
          $ref: '#/components/schemas/TotalEstimate'
    SearchResultPage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/SearchResult'
        next_cursor:
          $ref: '#/components/schemas/NextCursor'
        truncated:
          $ref: '#/components/schemas/Truncated'
        truncation_reason:
          $ref: '#/components/schemas/TruncationReason'
        total_estimate:
          $ref: '#/components/schemas/TotalEstimate'

    Problem:
      type: object
      description: RFC 9457 problem detail. Every error response is one of these, including validation failures.
      required: [type, title, status]
      properties:
        type:
          type: string
          format: uri
          description: A stable, machine-readable problem type. Clients match on this, so it is part of the contract.
        title: { type: string }
        status: { type: integer }
        detail: { type: string }
        instance: { type: string }
        request_id:
          type: string
          description: Quote this to support; it appears in the logs and the audit trail.
        errors:
          type: array
          items:
            type: object
            required: [field, code, message]
            properties:
              field: { type: string }
              code: { type: string }
              message: { type: string }

    NextCursor:
      type: string
      description: |
        Opaque position to pass back through the cursor parameter documented by that
        collection (`cursor` for a top-level collection or its prefixed cursor for a
        compound workspace). Present only when more rows matched AND this collection can be
        resumed. Absent means one of two different things, and `truncated` says which:
        everything that matched is here, or there is more and this build cannot reach it.

    Truncated:
      type: boolean
      description: |
        True when more rows matched than were returned and no cursor could be issued, because
        the service behind this collection accepts a page size and no position.

        It exists so the gap is visible instead of invisible. Sixteen list endpoints read a
        raw `limit`, returned exactly that many rows and said nothing — so a bank with 3,000
        open alerts saw fifty, and an examiner asking "did you review every alert" got no
        defensible answer from a screen that had quietly stopped counting.

        A client must not treat this as "the end". Narrow the filters instead.

    TruncationReason:
      type: string
      description: |
        Why the remainder is unreachable, as a stable token. `service_cannot_resume` is the
        only value this build emits: the module's list method takes a limit and no cursor, and
        fixing it is a signature change in that module rather than in the API layer.

    TotalEstimate:
      type: integer
      format: int64
      description: |
        An optional planner estimate, explicitly not an exact count: COUNT(*) over a large
        filtered set costs more than the page itself. Nothing emits it yet.

    Me:
      type: object
      required: [user, tenant, roles, permissions, pending_approvals, dashboard, impersonating]
      properties:
        work_counts:
          type: object
          additionalProperties: {type: integer, format: int64, minimum: 0}
          description: Exact counts of work currently eligible for this caller, grouped by kind.
        user:
          type: object
          required: [id, email, display_name, mfa_present]
          properties:
            id: { type: string, format: uuid }
            email: { type: string }
            display_name: { type: string }
            mfa_present:
              type: boolean
              description: Whether this session evidenced a second factor, not whether the user has one enrolled.
        tenant:
          type: object
          required: [id, slug]
          properties:
            id: { type: string, format: uuid }
            slug: { type: string }
        roles:
          type: array
          items: { type: string }
        permissions:
          type: array
          items: { type: string }
        pending_approvals:
          type: integer
          format: int64
          description: Always present; zero when nothing awaits this caller.
        branding:
          description: |
            The tenant's `ui.branding` configuration document, applied as CSS custom
            properties. Null when the tenant has no override and no pack default resolves.

            Typed rather than `additionalProperties: true`: the untyped version compiled to
            `unknown` in the generated client, which the layout then passed to a function
            expecting a colour. The hand-written types declared a shape here that the spec
            never promised.
          oneOf:
            - type: "null"
            - $ref: "#/components/schemas/Branding"
        dashboard:
          description: |
            The resolved tenant `ui.dashboard` presentation document. Null only when neither a
            tenant override nor the shipped pack default resolves; clients must then use their
            built-in safe default. This closed vocabulary controls order, visibility and size
            only. It is never an authorisation grant, route, query or HTML surface.
          oneOf:
            - type: "null"
            - $ref: "#/components/schemas/DashboardConfig"
        impersonating:
          type: boolean
          description: True when a Veyndi operator is acting under a time-boxed support grant.
        impersonation_grant_id:
          description: |
            The grant this session runs under, or null for an ordinary session. The id rather
            than only the flag, because Q16 promises a regulator that impersonated sessions are
            DISTINGUISHABLE — a boolean says only "somebody", while the id joins this session to
            the reason, the reference and the operator on `GET /v1/iam/impersonation-grants` and
            to every audit row the session wrote.
          oneOf:
            - type: "null"
            - { type: string, format: uuid }

    Branding:
      type: object
      description: Per-tenant theming, delivered as configuration rather than a build (BRD §7.2, ADR-0005).
      required: [product_name, primary_color, accent_color]
      properties:
        product_name: { type: string }
        logo_url: { type: string }
        primary_color: { type: string, examples: ["#0F766E"] }
        accent_color: { type: string, examples: ["#F59E0B"] }
        surface_color: { type: string }
        report_footer:
          type: string
          maxLength: 300
          pattern: '^[^\x00-\x1F\x7F]*$'
          description: |
            Optional bounded plain-text footer for internal compliance-board JSON and CSV
            artifacts only. It is never inserted into statutory CTR, STR, CBN or SCUML
            XML/XSD payloads and does not imply PDF, letterhead or global report branding.

    DashboardConfig:
      type: object
      additionalProperties: false
      description: |
        Governed presentation preferences for the built-in dashboard. Runtime permissions are
        applied first, so this document can hide or rearrange an authorised widget but cannot
        reveal one the caller may not access.
      required: [widgets]
      properties:
        widgets:
          type: array
          minItems: 1
          maxItems: 4
          uniqueItems: true
          items:
            $ref: "#/components/schemas/DashboardWidget"

    DashboardWidget:
      type: object
      additionalProperties: false
      required: [key, enabled, size]
      properties:
        key:
          type: string
          enum: [book_overview, alert_queue, signals, approval_queue]
          description: A built-in display widget identifier, never an endpoint or query.
        enabled:
          type: boolean
        size:
          type: string
          enum: [half, full]

    Permission:
      type: object
      required: [key, module, action, description]
      properties:
        key: { type: string, examples: ["cases.case.close"] }
        module: { type: string }
        action: { type: string }
        description: { type: string }

    Role:
      type: object
      required: [id, key, name, is_system]
      properties:
        id: { type: string, format: uuid }
        key: { type: string }
        name: { type: string }
        description: { type: string }
        is_system:
          type: boolean
          description: Delivered by a content pack. Grantable but not editable, so a pack upgrade can correct it.
        source_pack: { type: string }
        permissions:
          type: array
          items: { type: string }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    User:
      type: object
      required: [id, email, display_name, status]
      properties:
        id: { type: string, format: uuid }
        email: { type: string }
        display_name: { type: string }
        status:
          type: string
          enum: [active, suspended, deactivated]
          description: There is no deleted state; audit rows reference the actor for at least five years.
        org_unit_id: { type: string, format: uuid }
        mfa_enrolled: { type: boolean }
        last_login_at: { type: string, format: date-time }
        roles:
          type: array
          items:
            type: object
            properties:
              id: { type: string, format: uuid }
              key: { type: string }
              name: { type: string }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    UserPage:
      type: object
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/User" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    ServiceCredential:
      type: object
      description: Safe metadata only. A digest and bearer can never appear in this shape.
      required: [id, issued_at]
      properties:
        id: { type: string, format: uuid }
        issued_at: { type: string, format: date-time }
        expires_at: { type: string, format: date-time }
        revoked_at: { type: string, format: date-time }
        last_used_at:
          type: string
          format: date-time
          description: Sampled at most once per fifteen-minute window, not one write per request.

    ServiceAccount:
      type: object
      required: [id, key, name, description, status, roles, credentials, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        key:
          type: string
          pattern: "^[a-z][a-z0-9_.-]{1,63}$"
          description: Stable across credential rotation.
        name: { type: string }
        description: { type: string }
        status: { type: string, enum: [active, suspended, revoked] }
        expires_at: { type: string, format: date-time }
        revoked_at: { type: string, format: date-time }
        last_used_at:
          type: string
          format: date-time
          description: Sampled operational metadata, not an exact per-request ledger.
        roles:
          type: array
          items:
            type: object
            required: [id, key, name]
            properties:
              id: { type: string, format: uuid }
              key: { type: string }
              name: { type: string }
        credentials:
          type: array
          items: { $ref: "#/components/schemas/ServiceCredential" }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    IssuedServiceAccount:
      type: object
      description: |
        Create/rotate response only. `credential` is the one plaintext copy and is not
        recoverable from later service-account reads.
      required: [account, credential_id, credential]
      properties:
        account: { $ref: "#/components/schemas/ServiceAccount" }
        credential_id: { type: string, format: uuid }
        credential:
          type: string
          pattern: "^bby_sa_v1\\."
          readOnly: true
          description: Copy immediately to the integration's secret manager.
        expires_at: { type: string, format: date-time }

    ServiceAccountCreate:
      type: object
      required: [key, name, role_ids]
      properties:
        key: { type: string, pattern: "^[a-z][a-z0-9_.-]{1,63}$" }
        name: { type: string, minLength: 1 }
        description: { type: string }
        role_ids:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string, format: uuid }
        expires_at: { type: string, format: date-time }
        credential_expires_at:
          type: string
          format: date-time
          description: Must not outlive the service account when both are present.

    ServiceAccountUpdate:
      type: object
      description: At least one property must be sent. Revocation uses the dedicated operation.
      minProperties: 1
      properties:
        name: { type: string, minLength: 1 }
        description: { type: string }
        status: { type: string, enum: [active, suspended] }
        expires_at: { type: string, format: date-time }
        clear_expires_at:
          type: boolean
          description: Send true instead of expires_at to remove an optional expiry.

    ServiceAccountCredentialRotate:
      type: object
      properties:
        expires_at: { type: string, format: date-time }

    ServiceAccountPage:
      type: object
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/ServiceAccount" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    TenantPage:
      type: object
      description: |
        Tenants. The platform-operator estate view is resumable, keyed on (created_at, id); the
        single-tenant view a `tenancy.tenant.read` holder gets returns exactly one row and
        carries no cursor.
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/Tenant" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    Tenant:
      type: object
      required: [id, slug, display_name, status]
      properties:
        id: { type: string, format: uuid }
        slug: { type: string }
        display_name: { type: string }
        status: { type: string, enum: [provisioning, active, suspended, closed] }
        deployment_mode: { type: string, enum: [saas, onprem] }
        isolation_strategy:
          type: string
          enum: [shared_schema]
          description: |
            The only database tenancy model this runtime implements: shared schema with FORCE
            RLS. A dedicated on-prem installation is deployment isolation, not a per-tenant schema.
        data_residency: { type: string }
        segment: { type: string }
        created_at: { type: string, format: date-time }

    UserUpdate:
      type: object
      description: |
        At least one of `status`, `org_unit_id` or `clear_org_unit` must be present. An empty
        patch is refused rather than recording an audit event saying nothing changed.
      properties:
        status:
          type: string
          enum: [active, suspended, deactivated]
        org_unit_id:
          type: string
          format: uuid
          description: Moves the user into this unit. Must name a unit in the same tenant.
        clear_org_unit:
          type: boolean
          description: |
            Detaches the user from any unit. A separate flag rather than a null `org_unit_id`,
            because JSON cannot otherwise distinguish "absent, leave it alone" from "explicitly
            none".

    OrgUnit:
      type: object
      required: [id, name, code, created_at]
      properties:
        id: { type: string, format: uuid }
        parent_id:
          type: string
          format: uuid
          description: Absent for a root unit. Detached automatically if the parent is removed.
        name: { type: string }
        code: { type: string, examples: ["HQ-COMP"] }
        created_at: { type: string, format: date-time }

    OrgUnitCreate:
      type: object
      required: [code, name]
      properties:
        code:
          type: string
          pattern: "^[A-Z0-9_-]{2,32}$"
          description: Uppercase; a unit code is printed on reports and read aloud in meetings.
        name: { type: string }
        parent_id: { type: string, format: uuid }

    OrgUnitPage:
      type: object
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/OrgUnit" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    ImpersonationGrant:
      type: object
      required: [id, platform_actor, reason_code, reason, granted_at, expires_at, use_count]
      properties:
        id: { type: string, format: uuid }
        platform_actor:
          type: string
          description: The authenticated operator who opened the session. Never taken from the request body.
        reason_code:
          type: string
          enum: [support_ticket, incident, migration, audit]
        reason:
          type: string
          description: At least 10 characters, enforced by a database CHECK as well as at the edge.
        reference:
          type: string
          description: The support ticket or incident number, when there is one.
        granted_at: { type: string, format: date-time }
        expires_at:
          type: string
          format: date-time
          description: At most 8 hours after the grant. A longer window is a standing key, not a session.
        revoked_at: { type: string, format: date-time }
        first_used_at: { type: string, format: date-time }
        last_used_at: { type: string, format: date-time }
        use_count:
          type: integer
          format: int32
          description: |
            Incremented in the same call that validates the grant, so an access cannot occur
            without leaving a trace.

    ImpersonationGrantRequest:
      type: object
      required: [reason_code, reason]
      properties:
        reason_code:
          type: string
          enum: [support_ticket, incident, migration, audit]
        reason:
          type: string
          minLength: 10
          description: What the tenant and their examiner read when they ask why Veyndi was in their data.
        reference: { type: string }
        duration_hours:
          type: integer
          minimum: 1
          maximum: 8
          description: Defaults to the 8-hour ceiling when absent.

    ImpersonationGrantPage:
      type: object
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/ImpersonationGrant" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    TenantCreate:
      type: object
      required: [slug, display_name]
      properties:
        slug:
          type: string
          pattern: "^[a-z0-9][a-z0-9-]{1,62}$"
          description: The subdomain. Immutable after creation; a reserved slug is refused.
        display_name: { type: string }
        segment: { type: string, enum: [bank, mfb, fintech, psp, dnfbp, regulator] }
        deployment_mode: { type: string, enum: [saas, onprem] }
        isolation_strategy:
          type: string
          enum: [shared_schema]
          default: shared_schema
          description: Any other value is refused; schema_per_tenant was legacy metadata with no runtime behind it.
        data_residency:
          type: string
          description: Defaults to NG. BRD §9 hosts the SaaS environment in Nigeria or a jurisdiction acceptable to CBN.

    TenantUpdate:
      type: object
      required: [display_name, segment, data_residency]
      properties:
        display_name: { type: string }
        segment: { type: string, enum: [bank, mfb, fintech, psp, dnfbp, regulator] }
        data_residency: { type: string }

    TenantStatusChange:
      type: object
      required: [status]
      properties:
        status: { type: string, enum: [provisioning, active, suspended, closed] }
        reason:
          type: string
          description: Required for anything but a resume. The audit row is the only place the why survives.

    CommercialOfferComponent:
      type: object
      required: [id, offer_version_id, component_key, display_name, component_type, billing_cadence, requires_external_licence, description, created_at]
      properties:
        id: { type: string, format: uuid }
        offer_version_id: { type: string, format: uuid }
        component_key: { type: string, pattern: "^[a-z][a-z0-9_.-]{1,63}$" }
        display_name: { type: string }
        component_type: { type: string, enum: [support_maintenance, addon, professional_service] }
        addon_type: { type: string, enum: [premium_sanctions, adverse_media, advanced_analytics, connector] }
        billing_cadence: { type: string, enum: [monthly, annual, one_time, not_applicable] }
        currency: { type: string, pattern: "^[A-Z]{3}$" }
        amount_minor: { type: integer, format: int64, minimum: 0 }
        requires_external_licence:
          type: boolean
          description: True means entitlement is not proof that a provider licence/feed/adapter is available.
        description: { type: string }
        created_at: { type: string, format: date-time }

    CommercialOfferComponentCreate:
      type: object
      required: [component_key, display_name, component_type, billing_cadence, requires_external_licence]
      properties:
        component_key: { type: string, pattern: "^[a-z][a-z0-9_.-]{1,63}$" }
        display_name: { type: string }
        component_type: { type: string, enum: [support_maintenance, addon, professional_service] }
        addon_type: { type: string, enum: [premium_sanctions, adverse_media, advanced_analytics, connector] }
        billing_cadence: { type: string, enum: [monthly, annual, one_time, not_applicable] }
        currency: { type: string, pattern: "^[A-Z]{3}$" }
        amount_minor: { type: integer, format: int64, minimum: 0 }
        requires_external_licence: { type: boolean }
        description: { type: string, maxLength: 4000 }

    CommercialOffer:
      type: object
      description: Immutable/versioned supplied terms. Missing money fields mean no price was supplied, not zero.
      required: [id, offer_key, version, display_name, deployment_mode, base_term_type, billing_cadence, available_from, source, notes, created_at, components]
      properties:
        id: { type: string, format: uuid }
        offer_key: { type: string }
        version: { type: integer, format: int32, minimum: 1 }
        display_name: { type: string }
        deployment_mode: { type: string, enum: [saas, onprem] }
        base_term_type: { type: string, enum: [saas_subscription, onprem_licence] }
        billing_cadence: { type: string, enum: [monthly, annual, one_time] }
        allowance_interval: { type: string, enum: [month, term] }
        transaction_allowance: { type: integer, format: int64, minimum: 0 }
        user_allowance: { type: integer, format: int64, minimum: 0 }
        currency: { type: string, pattern: "^[A-Z]{3}$" }
        base_amount_minor: { type: integer, format: int64, minimum: 0 }
        transaction_overage_minor: { type: integer, format: int64, minimum: 0 }
        user_overage_minor: { type: integer, format: int64, minimum: 0 }
        available_from: { type: string, format: date-time }
        available_until: { type: string, format: date-time }
        source: { type: string, description: Provenance for the supplied terms. }
        notes: { type: string }
        created_at: { type: string, format: date-time }
        components:
          type: array
          items: { $ref: "#/components/schemas/CommercialOfferComponent" }

    CommercialOfferCreate:
      type: object
      required: [offer_key, version, display_name, deployment_mode, base_term_type, billing_cadence, available_from, source, components]
      properties:
        offer_key: { type: string, pattern: "^[a-z][a-z0-9_.-]{1,63}$" }
        version: { type: integer, format: int32, minimum: 1 }
        display_name: { type: string }
        deployment_mode: { type: string, enum: [saas, onprem] }
        base_term_type: { type: string, enum: [saas_subscription, onprem_licence] }
        billing_cadence: { type: string, enum: [monthly, annual, one_time] }
        allowance_interval: { type: string, enum: [month, term] }
        transaction_allowance: { type: integer, format: int64, minimum: 0 }
        user_allowance: { type: integer, format: int64, minimum: 0 }
        currency: { type: string, pattern: "^[A-Z]{3}$" }
        base_amount_minor: { type: integer, format: int64, minimum: 0 }
        transaction_overage_minor: { type: integer, format: int64, minimum: 0 }
        user_overage_minor: { type: integer, format: int64, minimum: 0 }
        available_from: { type: string, format: date }
        available_until: { type: string, format: date }
        source: { type: string }
        notes: { type: string, maxLength: 4000 }
        components:
          type: array
          items: { $ref: "#/components/schemas/CommercialOfferComponentCreate" }

    CommercialAgreement:
      type: object
      required: [tenant_id, id, agreement_ref, status, renewal_mode, status_reason, revision, created_at, updated_at]
      properties:
        tenant_id: { type: string, format: uuid }
        id: { type: string, format: uuid }
        agreement_ref: { type: string }
        offer_version_id: { type: string, format: uuid }
        status: { type: string, enum: [provisioning, current, renewal_due, grace, past_due, disputed, ended, not_applicable] }
        renewal_mode: { type: string, enum: [manual, automatic, not_applicable] }
        term_start: { type: string, format: date-time, description: Inclusive half-open term start. }
        term_end: { type: string, format: date-time, description: Exclusive half-open term end. }
        grace_until: { type: string, format: date-time }
        billing_timezone: { type: string, examples: [Africa/Lagos] }
        status_reason: { type: string }
        revision: { type: integer, format: int64, minimum: 1 }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    CommercialAgreementCreate:
      type: object
      required: [agreement_ref, status, renewal_mode, status_reason]
      properties:
        agreement_ref: { type: string }
        offer_version_id: { type: string, format: uuid }
        status: { type: string, enum: [provisioning, current, not_applicable] }
        renewal_mode: { type: string, enum: [manual, automatic, not_applicable] }
        term_start: { type: string, format: date }
        term_end: { type: string, format: date }
        billing_timezone: { type: string, examples: [Africa/Lagos] }
        status_reason: { type: string, minLength: 1, maxLength: 2000 }
        entitled_component_ids:
          type: array
          uniqueItems: true
          items: { type: string, format: uuid }

    CommercialAgreementStatusChange:
      type: object
      required: [status, reason]
      properties:
        status: { type: string, enum: [current, renewal_due, grace, past_due, disputed, ended] }
        grace_until: { type: string, format: date }
        reason: { type: string, minLength: 1, maxLength: 2000 }

    CommercialEntitlement:
      type: object
      required: [agreement_id, component, evidence_status, entitled_at, operational_availability]
      properties:
        agreement_id: { type: string, format: uuid }
        component: { $ref: "#/components/schemas/CommercialOfferComponent" }
        evidence_status: { type: string, enum: [commercial_entitlement_only] }
        entitled_at: { type: string, format: date-time }
        operational_availability:
          type: string
          enum: [operational_availability_not_verified, external_licence_and_adapter_not_verified]

    CommercialAllowanceStatus:
      type: object
      required: [metric, coverage]
      properties:
        metric: { type: string, enum: [transaction.count, user.active] }
        allowance: { type: integer, format: int64, minimum: 0 }
        allowance_interval: { type: string, enum: [month, term] }
        recorded_value: { type: integer, format: int64, minimum: 0 }
        overage: { type: integer, format: int64, minimum: 0 }
        coverage:
          type: string
          enum: [allowance_not_configured, usage_unavailable, latest_closed_month, closed_term_periods_partial, bounded_history_incomplete]

    CommercialSummary:
      type: object
      description: Recorded commercial state only; never an invoice, payment or feed-licence assertion.
      required: [configured, entitlements, usage_periods, allowance_status, usage_coverage, warnings]
      properties:
        configured: { type: boolean }
        agreement: { $ref: "#/components/schemas/CommercialAgreement" }
        offer: { $ref: "#/components/schemas/CommercialOffer" }
        entitlements:
          type: array
          items: { $ref: "#/components/schemas/CommercialEntitlement" }
        usage_periods:
          type: array
          items: { $ref: "#/components/schemas/UsageMeasurement" }
        allowance_status:
          type: array
          items: { $ref: "#/components/schemas/CommercialAllowanceStatus" }
        usage_coverage:
          type: string
          enum: [commercial_agreement_not_configured, commercial_not_applicable, no_recorded_periods, recorded_periods_available, bounded_history_may_be_incomplete]
        warnings:
          type: array
          items: { type: string }

    CommercialHistory:
      type: object
      required: [agreement_id, revision, event_type, status, renewal_mode, reason, actor_type, actor_label, occurred_at]
      properties:
        agreement_id: { type: string, format: uuid }
        revision: { type: integer, format: int64, minimum: 1 }
        event_type: { type: string, enum: [created, status_changed] }
        offer_version_id: { type: string, format: uuid }
        status: { type: string, enum: [provisioning, current, renewal_due, grace, past_due, disputed, ended, not_applicable] }
        renewal_mode: { type: string, enum: [manual, automatic, not_applicable] }
        term_start: { type: string, format: date-time }
        term_end: { type: string, format: date-time }
        grace_until: { type: string, format: date-time }
        billing_timezone: { type: string }
        reason: { type: string }
        actor_id: { type: string, format: uuid }
        actor_type: { type: string, enum: [user, api_client, system, platform] }
        actor_label: { type: string }
        occurred_at: { type: string, format: date-time }

    CommercialOfferPage:
      type: object
      required: [items]
      properties:
        items: { type: array, items: { $ref: "#/components/schemas/CommercialOffer" } }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    CommercialHistoryPage:
      type: object
      required: [items]
      properties:
        items: { type: array, items: { $ref: "#/components/schemas/CommercialHistory" } }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    UsageMeasurement:
      type: object
      description: |
        One recorded number for one tenant, period and metric. Open rows are correctable; closed
        rows are immutable evidence. Optional rates may exist on a linked offer, but this row is
        still not an invoice or payment record.
      required: [id, period_start, period_end, metric, value, method, measured_at, state]
      properties:
        id: { type: string, format: uuid }
        period_start: { type: string, format: date-time }
        period_end:
          type: string
          format: date-time
          description: Exclusive. The window is half-open.
        metric:
          type: string
          enum: [transaction.count, user.active]
          description: |
            `transaction.count` counts transactions BOOKED in the period, not ingested in it — an
            end-of-day export uploaded on the 3rd carries transactions booked on the 1st.
            `user.active` counts distinct human actors in the audit chain, not distinct logins:
            `last_login_at` holds only the most recent login, so a month's figure would shrink
            every time somebody came back.
        value: { type: integer, format: int64 }
        method:
          type: string
          description: How the figure was arrived at, so a disputed number can be re-derived. Always "derived" today.
        measured_at: { type: string, format: date-time }
        state: { type: string, enum: [open, closed] }
        billing_timezone:
          type: string
          description: Present only for a closed local-calendar period.
        closed_at: { type: string, format: date-time }

    UsagePage:
      type: object
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/UsageMeasurement" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    ConfigSchema:
      type: object
      required: [key, version, title, category, json_schema, requires_approval]
      properties:
        key: { type: string }
        version: { type: integer }
        title: { type: string }
        description: { type: string }
        category: { type: string }
        json_schema:
          type: object
          additionalProperties: true
          description: The JSON Schema this key's payload must satisfy. The admin console renders its form from this.
        requires_approval: { type: boolean }
        go_type: { type: string }
        source_pack: { type: string }

    ConfigDocument:
      type: object
      required: [id, key, version, schema_version, payload, status, created_at]
      properties:
        id: { type: string, format: uuid }
        key: { type: string }
        version: { type: integer }
        schema_version: { type: integer }
        payload:
          type: object
          additionalProperties: true
        status: { type: string, enum: [draft, pending_approval, active, superseded, rejected] }
        effective_from: { type: string, format: date-time }
        effective_to: { type: string, format: date-time }
        note: { type: string }
        created_by: { type: string, format: uuid }
        approved_by: { type: string, format: uuid }
        approved_at: { type: string, format: date-time }
        created_at: { type: string, format: date-time }

    ResolvedConfig:
      type: object
      required: [key, payload, source]
      properties:
        key: { type: string }
        payload:
          type: object
          additionalProperties: true
        source:
          type: string
          enum: [tenant_override, pack_default]
          description: Which layer supplied this value.
        source_pack: { type: string, description: Historical default provenance when available }
        version: { type: integer }
        schema_version: { type: integer }
        effective_from: { type: string, format: date-time }
        approved_by: { type: string, format: uuid }

    ApprovalRequest:
      type: object
      required: [id, action_key, subject_type, subject_id, payload, payload_digest, status, maker_id, proposed_at]
      properties:
        id: { type: string, format: uuid }
        action_key: { type: string }
        subject_type: { type: string }
        subject_id:
          type: string
          description: |
            Digest-bound workflow subject. Empty when `payload_restricted=true`; an
            entry-add watchlist subject contains the protected external id and is therefore
            redacted with the payload.
        payload:
          type: object
          additionalProperties: true
          description: |
            The exact digest-bound proposal. For `watchlists.entry.edit`, callers without
            `watchlists.entry.read` receive only `{ "details_restricted": true }`; the raw
            watchlist record is never returned at this boundary.
        payload_restricted:
          type: boolean
          description: |
            Present and true only when an action-sensitive disclosure rule replaced the
            payload, subject identifier and free-text rationales. The client must render
            fixed restricted copy and must not render the payload object as proposal details.
        payload_digest:
          type: string
          description: |
            SHA-256 over the canonicalised payload, bound to the action and subject. The
            checker approves this specific digest, so a proposal altered after review
            cannot be applied.
        status: { type: string, enum: [pending, approved, rejected, withdrawn, expired] }
        maker_id: { type: string, format: uuid }
        maker_reason:
          type: string
          description: Empty when payload_restricted is true.
        proposed_at: { type: string, format: date-time }
        checker_id: { type: string, format: uuid }
        checker_reason:
          type: string
          description: Empty when payload_restricted is true.
        decided_at: { type: string, format: date-time }
        sla_due_at: { type: string, format: date-time }
        applied_at: { type: string, format: date-time }
        escalated_at: { type: string, format: date-time }
        escalated_to_role: { type: string }
        escalation_policy_digest:
          type: string
          pattern: "^[a-f0-9]{64}$"
          description: SHA-256 of the effective escalation policy captured at escalation time.

    SubjectDEKRotation:
      type: object
      description: Durable tenant-scoped cursor for one independently approved wrapper transition.
      required: [id, approval_request_id, source_key_id, target_key_id, status, processed_subjects, approved_at]
      properties:
        id: { type: string, format: uuid }
        approval_request_id: { type: string, format: uuid }
        source_key_id: { type: string }
        target_key_id: { type: string }
        status: { type: string, enum: [approved, running, completed] }
        processed_subjects: { type: integer, format: int64, minimum: 0 }
        approved_at: { type: string, format: date-time }
        started_at: { type: string, format: date-time }
        last_batch_at: { type: string, format: date-time }
        completed_at: { type: string, format: date-time }

    RootKeyRetirementDependencies:
      type: object
      description: 'Tenant-scoped dependency accounting only. Physical software-root removal
        is a

        process-wide operation and is not implemented by this API.

        '
      required:
      - tenant_id
      - key_id
      - active
      - wrapped_subject_deks
      - validation_evidence_deks
      - retention_archive_deks
      - workspace_document_deks
      - operational_envelope_deks
      - identifier_blind_indexes
      - audit_anchors
      - tenant_dependencies_clear
      - physical_retirement_supported
      - erasure_receipt_signatures
      properties:
        tenant_id:
          type: string
          format: uuid
        key_id:
          type: string
        active:
          type: boolean
        wrapped_subject_deks:
          type: integer
          format: int64
          minimum: 0
        validation_evidence_deks:
          type: integer
          format: int64
          minimum: 0
          description: Finalized or retryable validation-artifact envelopes still wrapped
            by this root identity.
        retention_archive_deks:
          type: integer
          format: int64
          minimum: 0
        workspace_document_deks:
          type: integer
          format: int64
          minimum: 0
        operational_envelope_deks:
          type: integer
          format: int64
          minimum: 0
          description: Retained webhook, idempotency, bulk-operation, board-commentary and AI envelopes that still require this root. Subject rewrap does not rewrap these records.
        identifier_blind_indexes:
          type: integer
          format: int64
          minimum: 0
        audit_anchors:
          type: integer
          format: int64
          minimum: 0
        tenant_dependencies_clear:
          type: boolean
          description: True only when this tenant has zero counted dependencies and the
            key is inactive; not an authorization to remove it globally.
        physical_retirement_supported:
          type: boolean
          enum:
          - false
          description: Always false in this build; no global retirement or provider-destruction
            workflow exists.
        erasure_receipt_signatures:
          type: integer
          format: int64
          minimum: 0
          description: Immutable destruction receipts still authenticated by this root
            identity.
    SubjectDEKRotationReadiness:
      type: object
      required: [rotation, phase, runnable, enumeration_complete, configuration_matches_approval,
                 source_write_barrier_installed, blockers, retirement_dependencies]
      properties:
        rotation: { $ref: "#/components/schemas/SubjectDEKRotation" }
        phase:
          type: string
          enum: [approved_awaiting_target_activation, ready, running, completed, blocked]
        runnable: { type: boolean }
        enumeration_complete:
          type: boolean
          description: False when the provider cannot prove it enumerated every configured root; run then refuses.
        configuration_matches_approval: { type: boolean }
        source_write_barrier_installed:
          type: boolean
          description: Always true for an approved rotation row; there is no cancel/unblock operation.
        active_key_id: { type: string }
        blockers:
          type: array
          items:
            type: string
            enum: [provider_root_enumeration_incomplete, approved_root_not_configured,
                   approved_root_identity_mismatch, target_root_not_active,
                   active_root_does_not_match_approved_target]
        retirement_dependencies: { $ref: "#/components/schemas/RootKeyRetirementDependencies" }

    ContentPack:
      type: object
      required: [id, name, version, verified, published_at, imported_at]
      properties:
        id: { type: string, format: uuid }
        name: { type: string }
        version: { type: string }
        min_app_version: { type: string }
        description: { type: string }
        sha256: { type: string }
        signing_key_id: { type: string }
        verified:
          type: boolean
          description: False for a pack installed with verification bypassed. Production refuses to load one.
        published_at: { type: string, format: date-time }
        imported_at: { type: string, format: date-time }

    PackInstallation:
      type: object
      required: [pack_id, pack_name, pack_version, state, installed_at]
      properties:
        pack_id: { type: string, format: uuid }
        pack_name: { type: string }
        pack_version: { type: string }
        state: { type: string, enum: [staged, active, superseded, rolled_back] }
        installed_by: { type: string, format: uuid }
        installed_at: { type: string, format: date-time }
        applied_diff:
          type: object
          additionalProperties: true
          description: The diff a human approved before this pack was applied.

    PackDiff:
      type: object
      required: [to_version, changes, added, modified, removed, conflicts_with_overrides]
      properties:
        from_version: { type: string }
        to_version: { type: string }
        added: { type: integer }
        modified: { type: integer }
        removed: { type: integer }
        conflicts_with_overrides:
          type: integer
          description: Changed defaults that sit underneath a tenant customisation.
        changes:
          type: array
          items:
            type: object
            required: [kind, key, type]
            properties:
              kind: { type: string }
              key: { type: string }
              type: { type: string, enum: [added, modified, removed, unchanged] }
              from: {}
              to: {}
              overridden_by_tenant: { type: boolean }

    AuditEvent:
      type: object
      required: [tenant_id, seq, id, occurred_at, actor_type, action, resource_type, outcome, digest]
      properties:
        tenant_id: { type: string, format: uuid }
        seq: { type: integer, format: int64, description: Per-tenant monotonic sequence. }
        id: { type: string, format: uuid }
        occurred_at: { type: string, format: date-time }
        actor_id: { type: string, format: uuid }
        actor_type: { type: string, enum: [user, system, platform, api_client] }
        actor_label:
          type: string
          description: Denormalised, so the row stays readable for five years even if the user is later deactivated.
        action: { type: string }
        resource_type: { type: string }
        resource_id: { type: string }
        outcome: { type: string, enum: [success, failure, denied] }
        before: {}
        after: {}
        metadata: {}
        request_id: { type: string }
        ip: { type: string }
        impersonation_grant_id:
          type: string
          format: uuid
          description: |
            The Veyndi support session this event was written under; absent for an ordinary
            one. Q16 promises a regulator that impersonated sessions are distinguishable, and
            the column has carried this since Phase 1 without being returned — so "what did
            the vendor do while they were in our data" could only be answered with database
            access. Join it to `GET /v1/iam/impersonation-grants` for the reason and operator.
        digest: { type: string }
        prev_digest: { type: string }

    AuditPage:
      type: object
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/AuditEvent" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    RetentionPolicy:
      type: object
      required:
        - resource_type
        - configured
        - coverage_state
        - compliance_state
        - subject_scoped
        - legal_hold
        - active_hold_count
        - version
      properties:
        resource_type:
          type: string
          enum:
            - alert_records
            - audit_events
            - case_records
            - configuration_history
            - customer_records
            - onboarding_evidence
            - privacy_records
            - regulatory_reports
            - screening_records
            - transaction_records
        retain_years:
          type: integer
          format: int32
          minimum: 5
          description: Absent when coverage_state is missing.
        configured: { type: boolean }
        coverage_state:
          type: string
          enum: [missing, covered]
        compliance_state:
          type: string
          enum: [non_compliant, compliant, held]
        subject_scoped:
          type: boolean
          description: Whether a subject legal hold conservatively governs this evidence family.
        legal_hold:
          type: boolean
          description: A fail-closed tenant summary, not a claim that every row is held.
        active_hold_count:
          type: integer
          format: int64
          minimum: 0
        version:
          type: integer
          format: int64
          minimum: 0
          description: Zero when no policy has been configured.
        updated_at: { type: string, format: date-time }

    RetentionPolicyPage:
      type: object
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/RetentionPolicy" }

    RetentionHistory:
      type: object
      required:
        - resource_type
        - version
        - retain_years
        - legal_hold
        - applied_by
        - approval_id
        - reason
        - applied_at
      properties:
        resource_type:
          type: string
          enum:
            - alert_records
            - audit_events
            - case_records
            - configuration_history
            - customer_records
            - onboarding_evidence
            - privacy_records
            - regulatory_reports
            - screening_records
            - transaction_records
        version: { type: integer, format: int64, minimum: 1 }
        retain_years: { type: integer, format: int32, minimum: 5 }
        legal_hold:
          type: boolean
          description: Hold summary captured when this version was applied.
        applied_by: { type: string, format: uuid }
        approval_id: { type: string, format: uuid }
        reason: { type: string, minLength: 1, maxLength: 2000 }
        applied_at: { type: string, format: date-time }

    RetentionHistoryPage:
      type: object
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/RetentionHistory" }

    RetentionChange:
      type: object
      required: [resource_type, retain_years, reason]
      properties:
        resource_type:
          type: string
          enum:
            - alert_records
            - audit_events
            - case_records
            - configuration_history
            - customer_records
            - onboarding_evidence
            - privacy_records
            - regulatory_reports
            - screening_records
            - transaction_records
        retain_years: { type: integer, format: int32, minimum: 5 }
        reason: { type: string, minLength: 1, maxLength: 2000 }

    RetentionProposal:
      type: object
      required: [change, approval]
      properties:
        change: { $ref: "#/components/schemas/RetentionChange" }
        approval: { $ref: "#/components/schemas/ApprovalRequest" }

    ChainStatus:
      type: object
      required: [tenant_id, valid, head_seq, verified_count, anchors_checked, anchors_valid, checked_at]
      properties:
        tenant_id: { type: string, format: uuid }
        valid: { type: boolean }
        head_seq: { type: integer, format: int64 }
        verified_count: { type: integer, format: int64 }
        broken_at_seq:
          type: integer
          format: int64
          description: The first sequence where verification failed.
        reason: { type: string }
        last_anchor_seq: { type: integer, format: int64 }
        last_anchor_at: { type: string, format: date-time }
        anchors_checked: { type: integer }
        anchors_valid: { type: boolean }
        checked_at: { type: string, format: date-time }

    # ------------------------------------------------------------- AML domain

    PrivacyHistory:
      type: object
      description: Append-only domain timeline entry; the hash-chained audit trail is extended separately.
      required: [id, record_type, record_id, action, status, metadata, occurred_at]
      properties:
        id: { type: string, format: uuid }
        record_type: { type: string, enum: [erasure, authority] }
        record_id: { type: string, format: uuid }
        action: { type: string }
        status: { type: string }
        actor_id: { type: string, format: uuid }
        reason: { type: string }
        metadata:
          type: object
          additionalProperties: true
        occurred_at: { type: string, format: date-time }

    ErasureRequestCreate:
      type: object
      required: [party_id, reason]
      properties:
        party_id: { type: string, format: uuid }
        reason: { type: string, minLength: 1 }
        received_at: { type: string, format: date-time }
        deadline_at: { type: string, format: date-time }

    ErasureRequest:
      type: object
      required: [id, reference, party_id, status, reason, received_at, requested_by,
                 approval_request_id, created_at, updated_at, policy_marker]
      properties:
        id: { type: string, format: uuid }
        reference: { type: string, examples: [ER-2026-01AB23CD] }
        party_id: { type: string, format: uuid }
        status: { type: string, enum: [pending_review, approved, refused, executed] }
        reason: { type: string }
        received_at: { type: string, format: date-time }
        deadline_at: { type: string, format: date-time }
        requested_by: { type: string, format: uuid }
        approval_request_id: { type: string, format: uuid }
        reviewed_by: { type: string, format: uuid }
        reviewed_at: { type: string, format: date-time }
        review_reason: { type: string }
        executed_by: { type: string, format: uuid }
        executed_at: { type: string, format: date-time }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        history:
          type: array
          items: { $ref: "#/components/schemas/PrivacyHistory" }
        policy_marker:
          type: string
          const: "NEEDS-COMPLIANCE-VALIDATION (Q5)"

    ErasureRequestPage:
      type: object
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/ErasureRequest" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }

    AuthorityRequestCreate:
      type: object
      required: [authority_name, external_reference, legal_basis_reference, description, subject_party_ids]
      properties:
        authority_name: { type: string, minLength: 1 }
        external_reference: { type: string, minLength: 1 }
        legal_basis_reference: { type: string, minLength: 1 }
        description: { type: string, minLength: 1 }
        received_at: { type: string, format: date-time }
        deadline_at: { type: string, format: date-time }
        period_from: { type: string, format: date }
        period_to: { type: string, format: date }
        subject_party_ids:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string, format: uuid }

    LegalHold:
      type: object
      required: [id, authority_request_id, party_id, status, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        authority_request_id: { type: string, format: uuid }
        party_id: { type: string, format: uuid }
        status: { type: string, enum: [pending, active, refused, release_pending, released] }
        activated_by: { type: string, format: uuid }
        activated_at: { type: string, format: date-time }
        released_by: { type: string, format: uuid }
        released_at: { type: string, format: date-time }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    AuthorityRequest:
      type: object
      required: [id, reference, authority_name, external_reference, legal_basis_reference,
                 description, status, received_at, requested_by, activation_approval_id,
                 created_at, updated_at, policy_marker]
      properties:
        id: { type: string, format: uuid }
        reference: { type: string, examples: [AR-2026-01AB23CD] }
        authority_name: { type: string }
        external_reference: { type: string }
        legal_basis_reference: { type: string }
        description: { type: string }
        status: { type: string, enum: [pending_review, active, refused, release_pending, released] }
        received_at: { type: string, format: date-time }
        deadline_at: { type: string, format: date-time }
        period_from: { type: string, format: date-time }
        period_to: { type: string, format: date-time }
        requested_by: { type: string, format: uuid }
        activation_approval_id: { type: string, format: uuid }
        reviewed_by: { type: string, format: uuid }
        reviewed_at: { type: string, format: date-time }
        review_reason: { type: string }
        release_requested_by: { type: string, format: uuid }
        release_requested_at: { type: string, format: date-time }
        release_reason: { type: string }
        release_approval_id: { type: string, format: uuid }
        released_by: { type: string, format: uuid }
        released_at: { type: string, format: date-time }
        release_decision_reason: { type: string }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        holds:
          type: array
          items: { $ref: "#/components/schemas/LegalHold" }
        history:
          type: array
          items: { $ref: "#/components/schemas/PrivacyHistory" }
        policy_marker:
          type: string
          const: "NEEDS-COMPLIANCE-VALIDATION (Q34)"

    AuthorityRequestPage:
      type: object
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/AuthorityRequest" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }

    PrivacySubjectStatus:
      type: object
      required: [party_id, privacy_state, active_hold_count, policy_marker]
      properties:
        party_id: { type: string, format: uuid }
        privacy_state: { type: string, enum: [normal, restricted, erased] }
        active_hold_count: { type: integer, format: int64, minimum: 0 }
        erasure_reference: { type: string }
        erasure_status: { type: string, enum: [pending_review, approved, refused, executed] }
        policy_marker:
          type: string
          enum:
            - "NEEDS-COMPLIANCE-VALIDATION (Q5)"
            - "NEEDS-COMPLIANCE-VALIDATION (Q34)"

    AuthorityEvidenceItem:
      additionalProperties: false
      properties:
        category:
          type: string
        count:
          format: int64
          type: integer
        scope:
          type: string
        sha256:
          type: string
        source:
          type: string
      required:
      - category
      - source
      - scope
      - count
      - sha256
      type: object
    AuthorityResponsePackage:
      type: object
      required: [id, authority_request_id, request_reference, generated_by, generated_at,
                 subject_party_ids, evidence, package_sha256, format, policy_marker]
      properties:
        id: { type: string, format: uuid }
        authority_request_id: { type: string, format: uuid }
        request_reference: { type: string }
        generated_by: { type: string, format: uuid }
        generated_at: { type: string, format: date-time }
        subject_party_ids:
          type: array
          items: { type: string, format: uuid }
        evidence:
          type: array
          items: { $ref: "#/components/schemas/AuthorityEvidenceItem" }
        package_sha256:
          type: string
          pattern: "^[a-f0-9]{64}$"
          description: SHA-256 of the canonical response manifest before this self-referential field is populated.
        format: { type: string, const: baobyte-neutral-evidence-manifest/v1 }
        policy_marker:
          type: string
          const: "NEEDS-COMPLIANCE-VALIDATION (Q34)"

    Customer:
      type: object
      required: [id, party_id, kyc_tier, segment, onboarding_status, edd_required, created_at]
      properties:
        id: { type: string, format: uuid }
        party_id: { type: string, format: uuid }
        display_name: { type: string }
        external_ref: { type: string }
        kyc_tier: { type: string, enum: [tier_1, tier_2, tier_3, corporate] }
        segment: { type: string }
        onboarding_status: { type: string, enum: [draft, pending_documents, pending_edd, pending_approval, active, rejected, exited] }
        risk_rating: { type: string, enum: [low, medium, high, prohibited] }
        risk_score: { type: number }
        risk_assessed_at: { type: string, format: date-time }
        next_review_at:
          type: string
          format: date-time
          description: Scheduled from the risk band, so a periodic review is a query rather than a reminder someone sets.
        edd_required: { type: boolean }
        edd_completed_at: { type: string, format: date-time }
        assigned_org_unit_id:
          type: string
          format: uuid
          description: |
            The branch or relationship team routed to this customer
            (POST /v1/customers/{customerID}/assign). Absent when unrouted. GET
            /v1/customers/{customerID} also resolves the unit's current name onto
            CustomerDetail.assigned_org_unit; this is the id alone, as carried on every
            Customer everywhere else it appears (the list, EDD completion, and so on).
        created_at: { type: string, format: date-time }

    CustomerAddress:
      type: object
      additionalProperties: false
      required: [line1, locality, country]
      properties:
        line1: { type: string, minLength: 1, maxLength: 256 }
        line2: { type: string, maxLength: 256 }
        locality: { type: string, minLength: 1, maxLength: 128 }
        lga:
          type: string
          maxLength: 128
          description: |
            Required with state when country is NG. Input may be the exact NBS source label,
            an explicitly curated constitutional alias, or the catalogue code; storage and
            subsequent reads use the canonical code.
        state:
          type: string
          maxLength: 128
          description: Required with lga when country is NG; canonical storage uses the NBS code.
        postal_code: { type: string, maxLength: 32 }
        country:
          type: string
          pattern: "^[A-Za-z]{2}$"
          description: Two-letter country code, normalised to uppercase.

    ProfileBeneficialOwnerChange:
      type: object
      additionalProperties: false
      description: |
        One DIRECT owner in a complete replacement register. Supply existing_party_id, or kind
        plus display_name. Identifier values, verification assertions, arbitrary party attributes
        and owns_party_id are intentionally unavailable here; use the dedicated ownership and
        identifier lifecycles for those higher-risk operations.
      properties:
        existing_party_id:
          type: string
          format: uuid
          description: Attach an existing party instead of creating another identity record.
        kind: { type: string, enum: [natural, legal] }
        display_name: { type: string, minLength: 1 }
        ownership_pct: { type: number, exclusiveMinimum: 0, maximum: 100 }
        control_type:
          type: string
          enum: [shareholding, voting_rights, board_control, significant_influence, other]
      oneOf:
        - title: Existing party
          type: object
          additionalProperties: false
          required: [existing_party_id]
          properties:
            existing_party_id:
              type: string
              format: uuid
              description: Attach an existing party instead of creating another identity record.
            ownership_pct: { type: number, exclusiveMinimum: 0, maximum: 100 }
            control_type:
              type: string
              enum: [shareholding, voting_rights, board_control, significant_influence, other]
        - title: New party
          type: object
          additionalProperties: false
          required: [kind, display_name]
          properties:
            kind: { type: string, enum: [natural, legal] }
            display_name: { type: string, minLength: 1 }
            ownership_pct: { type: number, exclusiveMinimum: 0, maximum: 100 }
            control_type:
              type: string
              enum: [shareholding, voting_rights, board_control, significant_influence, other]

    ProfileBeneficialOwnerPreview:
      type: object
      additionalProperties: false
      required: [kind, display_name, control_type, identity_source]
      properties:
        existing_party_id:
          type: string
          format: uuid
          description: Present when the proposal attaches an existing tenant-scoped party.
        kind: { type: string, enum: [natural, legal] }
        display_name: { type: string, minLength: 1 }
        ownership_pct: { type: number, exclusiveMinimum: 0, maximum: 100 }
        control_type:
          type: string
          enum: [shareholding, voting_rights, board_control, significant_influence, other]
        identity_source:
          type: string
          enum: [existing_party, proposed_new_party]
          description: |
            For `existing_party`, kind and display_name are resolved from that exact
            tenant-scoped party at preview time; they are not an ignored identity edit hidden in
            the proposal. For `proposed_new_party`, they are the encrypted proposed values.
      description: |
        One direct owner as a checker can review it. Unlike the write shape, an existing party is
        accompanied by its authoritative current kind and display name so the checker does not
        have to approve an opaque UUID. Identifier values, verification assertions and arbitrary
        attributes remain outside this preview.

    CustomerProfileChange:
      type: object
      additionalProperties: false
      minProperties: 1
      description: |
        Supported mutable CDD facts. Every supplied field is proposed through maker-checker,
        sealed under the subject DEK in immutable staging before the approval request is created,
        and applied only with re-screening, re-scoring and a risk-change review. The structured
        address remains subject-encrypted after approval; the other approved facts use their
        existing typed profile columns or party-attribute representation. Empty strings do not
        erase data; legal erasure is a separate hold-aware workflow.
      properties:
        address: { $ref: "#/components/schemas/CustomerAddress" }
        occupation: { type: string, minLength: 1, maxLength: 256, description: Natural persons only. }
        industry: { type: string, minLength: 1, maxLength: 256, description: Legal entities only. }
        country_of_residence: { type: string, pattern: "^[A-Za-z]{2}$" }
        nationality: { type: string, pattern: "^[A-Za-z]{2}$" }
        source_of_funds: { type: string, minLength: 1, maxLength: 512 }
        incorporation_date: { type: string, format: date, description: Legal entities only; cannot be in the future. }
        cash_intensive: { type: boolean, description: Legal entities only. }
        beneficial_owners:
          type: array
          minItems: 1
          maxItems: 100
          description: |
            Legal entities only. Replaces the active direct register while retaining prior edges
            as superseded history and invalidating verification that covered the old register.
          items: { $ref: "#/components/schemas/ProfileBeneficialOwnerChange" }

    CustomerProfileChangePreview:
      type: object
      additionalProperties: false
      required:
        [approval_id, customer_id, profile_change_id, profile_change_digest, changed_fields, profile]
      description: |
        Plaintext returned only by the explicit, audited checker-preview POST. The identifiers,
        ciphertext digest and field names are safe linkage metadata; `profile` is decrypted PII
        and must remain ephemeral client state.
      properties:
        approval_id: { type: string, format: uuid }
        customer_id: { type: string, format: uuid }
        profile_change_id: { type: string, format: uuid }
        profile_change_digest:
          type: string
          pattern: "^[0-9a-f]{64}$"
          description: SHA-256 of random-nonce AEAD ciphertext, never of the plaintext.
        changed_fields:
          type: array
          minItems: 1
          maxItems: 9
          uniqueItems: true
          items:
            type: string
            enum:
              [address, occupation, industry, country_of_residence, nationality,
               source_of_funds, incorporation_date, cash_intensive, beneficial_owners]
        profile: { $ref: "#/components/schemas/CustomerProfileChangePreviewValue" }

    CustomerProfileChangePreviewValue:
      type: object
      additionalProperties: false
      minProperties: 1
      description: |
        Decrypted proposed facts. This mirrors CustomerProfileChange except that referenced
        existing owners are resolved to a reviewable kind and display name without treating those
        reference fields as a proposed edit.
      properties:
        address: { $ref: "#/components/schemas/CustomerAddress" }
        occupation: { type: string }
        industry: { type: string }
        country_of_residence: { type: string }
        nationality: { type: string }
        source_of_funds: { type: string }
        incorporation_date: { type: string, format: date }
        cash_intensive: { type: boolean }
        beneficial_owners:
          type: array
          minItems: 1
          maxItems: 100
          items: { $ref: "#/components/schemas/ProfileBeneficialOwnerPreview" }

    CustomerProfile:
      type: object
      required: [customer_id, party_id, party_kind]
      properties:
        customer_id: { type: string, format: uuid }
        party_id: { type: string, format: uuid }
        party_kind: { type: string, enum: [natural, legal] }
        address: { $ref: "#/components/schemas/CustomerAddress" }
        legacy_address:
          type: string
          readOnly: true
          description: Older decrypted free-text address. Replace through a structured address correction.
        occupation: { type: string }
        industry: { type: string }
        country_of_residence: { type: string }
        nationality: { type: string }
        source_of_funds: { type: string }
        incorporation_date: { type: string, format: date }
        cash_intensive: { type: boolean }
        beneficial_owners:
          type: array
          items: { $ref: "#/components/schemas/BeneficialOwner" }

    Party:
      type: object
      required: [id, kind, display_name, privacy_state, created_at]
      properties:
        id: { type: string, format: uuid }
        kind: { type: string, enum: [natural, legal] }
        display_name: { type: string }
        privacy_state:
          type: string
          enum: [normal, restricted, erased]
          description: |
            `restricted` means an erasure request awaits decision. `erased` means the approved
            execution destroyed the subject key and redacted mutable onboarding PII while retained
            AML record skeletons and the audit chain were not rewritten.
            NEEDS-COMPLIANCE-VALIDATION (Q5): this technical state is not a legal interpretation
            of which records must be kept.
        names:
          type: array
          items: { $ref: "#/components/schemas/PartyName" }
        identifiers:
          type: array
          items: { $ref: "#/components/schemas/PartyIdentifier" }
        attributes:
          type: object
          additionalProperties: { type: string }
        created_at: { type: string, format: date-time }

    PartyName:
      type: object
      required: [id, type, full_name]
      properties:
        id: { type: string, format: uuid }
        type: { type: string, enum: [primary, alias, former, transliteration, trading] }
        full_name: { type: string }
        normalized:
          type: string
          description: The matcher's view of the name. Exposed because "why did that match?" is a fair question.

    PartyIdentifier:
      type: object
      required: [id, scheme, masked_hint]
      properties:
        id: { type: string, format: uuid }
        scheme: { type: string, enum: [BVN, NIN, CAC, TIN, PASSPORT, SCUML, DRIVERS_LICENCE, VOTERS_CARD, OTHER] }
        masked_hint:
          type: string
          description: |
            A display-ready masked value such as `****4821`, not a fragment to be
            reformatted by the caller. The full value requires a separate, audited reveal.
          examples: ["****4821"]
        value:
          type: string
          description: Present only on an explicit reveal, which writes a `pii.read` audit event.
        verified_at: { type: string, format: date-time }
        verified_by_source:
          type: string
          description: |
            Who or what produced `verified_at`: a named issuing authority (e.g. `NIBSS`) for a
            real verification, or a fixed, clearly-labelled sentinel when
            `verification_assurance` is `mock`. Absent when the identifier has not been
            verified (Q26).
        verification_assurance:
          type: string
          enum: [authoritative, mock]
          description: |
            Whether `verified_by_source` names a real authority or the deterministic mock used
            for demos and QA while no NIBSS/NIMC integration exists (Q26). Absent when the
            identifier has not been verified. A `mock` value must never be read as though a
            real provider had verified this identifier.

    RiskFactor:
      type: object
      required: [key, label, raw_value, matched_rule, factor_score, weight, contribution, source]
      properties:
        key: { type: string }
        label: { type: string }
        raw_value: { type: string }
        matched_rule:
          type: string
          description: Which value rule matched. `unmatched` means no rule and no catch-all applied.
        factor_score: { type: number }
        weight: { type: number }
        contribution:
          type: number
          description: The factor's share of the total. These sum to the score; a test asserts it.
        source:
          type: string
          enum: [party_attribute, missing]
          description: |
            `missing` means the input was absent. A factor silently omitted is
            indistinguishable from one that scored zero, and those are different facts.

    RiskAssessment:
      type: object
      required: [id, party_id, model_version_id, score, rating, triggers_edd, review_months, trigger, assessed_at, assessed_by_type]
      properties:
        id: { type: string, format: uuid }
        party_id: { type: string, format: uuid }
        customer_id: { type: string, format: uuid }
        model_version_id:
          type: string
          format: uuid
          description: Pinned, so re-reading today's configuration cannot change a historic rating.
        score: { type: number }
        rating: { type: string, enum: [low, medium, high, prohibited] }
        triggers_edd: { type: boolean }
        review_months: { type: integer }
        trigger:
          type: string
          # `event` was invented; the four it stood in for are real and were undocumented, so
          # a client could receive a trigger its own types could not represent.
          enum: [onboarding, periodic, profile_update, screening_hit, pep_change, behavioural, manual]
        trigger_ref: { type: string }
        factors:
          type: array
          items: { $ref: "#/components/schemas/RiskFactor" }
        assessed_at: { type: string, format: date-time }
        assessed_by:
          type: string
          format: uuid
          description: Authenticated human or service-account principal that caused the assessment; absent for system/platform work.
        assessed_by_type:
          type: string
          enum: [user, api_client, system, platform]
          description: Selects the principal table for assessed_by and distinguishes actorless system/platform assessments.

    BeneficialOwner:
      type: object
      required: [party_id, name, kind, control_type, depth]
      properties:
        party_id: { type: string, format: uuid }
        name: { type: string }
        kind: { type: string, enum: [natural, legal] }
        ownership_pct: { type: number, description: The direct stake in the immediately owned entity. }
        effective_pct:
          type: number
          description: The stake through the whole chain, which is what decides beneficial ownership.
        control_type: { type: string }
        depth: { type: integer, description: Hops from the root party. Resolution is capped at 10. }

    Account:
      type: object
      required: [id, customer_id, external_ref, product_type, currency, status]
      properties:
        id: { type: string, format: uuid }
        customer_id: { type: string, format: uuid }
        external_ref: { type: string }
        product_type: { type: string }
        currency: { type: string, minLength: 3, maxLength: 3 }
        status: { type: string, enum: [active, dormant, frozen, closed] }
        last_activity_at: { type: string, format: date-time }
        dormant_since: { type: string, format: date-time }

    CustomerDetail:
      type: object
      required: [customer, party, accounts]
      properties:
        customer: { $ref: "#/components/schemas/Customer" }
        party: { $ref: "#/components/schemas/Party" }
        accounts:
          type: array
          items: { $ref: "#/components/schemas/Account" }
        risk_assessment: { $ref: "#/components/schemas/RiskAssessment" }
        beneficial_owners:
          type: array
          items: { $ref: "#/components/schemas/BeneficialOwner" }
        corporate_profile:
          $ref: "#/components/schemas/CorporateProfile"
          description: |
            Present when, and only when, the party is a legal entity. Carries whether its
            beneficial-ownership register has been VERIFIED (`ubo_verified_at`, by
            `ubo_verification_method`, against `ubo_verification_reference`) rather than
            merely declared (`ubo_declared`) — the same three fields `ApplicationReview`
            already exposes while the application is pending. Until now they had no home on
            the customer's own profile, so a checker revisiting a corporate relationship
            after onboarding had no way to see "already verified on this date, by this
            method" without re-opening a decided application.
        screening_hits:
          type: array
          items: { $ref: "#/components/schemas/ScreeningHit" }
          description: |
            The sanctions and PEP hits recorded against this customer's party. A weighted risk
            score of 22 beside an open sanctions match is not a low-risk customer, and the two
            answers to "who is this" belong on one screen rather than two.

            ABSENT rather than empty when the caller does not hold `screening.hit.read`: an
            empty array asserts "screened, nothing on record", which is a different statement
            from "you may not know" and must not stand in for it. Clients test for the key, not
            its length.

            Newest first, capped at 50 and not resumable, across every decision state rather
            than only `pending`. The case workspace exposes the equivalent broader record as
            `CaseDetail.subject_screening_history.hits`; `CaseDetail.screening_hits` is the
            distinct, complete evidence set explicitly linked to that case.
        assigned_org_unit:
          type: object
          description: |
            The branch or relationship team this customer is routed to, with the unit's
            current name resolved alongside its id. Absent when unrouted.
          required: [id, name]
          properties:
            id: { type: string, format: uuid }
            name: { type: string }
        pending_application_id:
          type: string
          format: uuid
          description: |
            The customer's onboarding application still awaiting a decision, if any —
            readable at GET /v1/onboarding/applications/{applicationID}. Absent once the
            application has been decided, or if the customer has none outstanding.

    # --------------------------------------------------- CDD and onboarding

    CDDFormField:
      type: object
      description: One question on a CDD form, as `onboarding.cdd_forms` defines it.
      required: [key, label, type, required]
      properties:
        key:
          type: string
          description: |
            The answer key. It can only exist if a column, key or scheme already exists to hold
            it: the propose-time validator derives the permitted set from the database's own
            storage vocabulary, so a field with nowhere to go is refused before a checker is ever
            asked to approve it (ADR-0024). That is a real limit on BRD §7.2's no-code promise
            and it is the honest one — the alternative is a form that accepts answers it cannot
            save.
        label: { type: string }
        type:
          type: string
          description: |
            One of `text`, `date`, `select`, `number`, `boolean`, `identifier` or `address`.
            Not declared as an enum here because no database column governs it: the closed set
            lives in the content pack's registered JSON Schema, and an enum bound to nothing is
            how nine invented values reached the Phase 1 UI.
        required: { type: boolean }
        pii:
          type: boolean
          description: The answer is sealed under the subject's own key rather than stored in the clear (ADR-0019).
        options:
          type: array
          items: { type: string }
          description: The permitted answers for a `select` field.
        show_if:
          type: string
          description: |
            A CEL predicate over the answers so far; empty means always shown. It evaluates in a
            one-variable sandbox with no database, no clock and no helper functions — a predicate
            that decides whether to ask a question has no business reaching anything else. An
            answer to a field whose predicate does not hold is REFUSED rather than stored: a
            record showing something the customer never saw is worse than a missing field.

    CDDDocumentRequirement:
      type: object
      description: |
        A document the tier requires. NEEDS-COMPLIANCE-VALIDATION (Q32): the shipped lists read
        as researched because they are specific, and nobody has checked them against the circular
        in force. The lifecycle now enforces the configured list: required evidence must be
        uploaded, independently verified and unexpired before approval.
      required: [key, label, required]
      properties:
        key: { type: string }
        label: { type: string }
        required: { type: boolean }
        expires:
          type: boolean
          description: The document has a validity period, so a copy on file can go stale.

    CDDIdentifierRequirement:
      type: object
      description: |
        A requirement over identifier schemes that a per-field `required` flag cannot express.
        `any_of` requires at least one listed scheme; `all_of` requires every listed scheme.
        When `authoritative_verification` is true, capture satisfies submission but not
        relationship approval: approval requires electronic verification recorded with
        authoritative assurance. A demo/mock confirmation remains non-authoritative.
      required: [mode, schemes, authoritative_verification]
      properties:
        mode: { type: string, enum: [any_of, all_of] }
        schemes:
          type: array
          minItems: 1
          uniqueItems: true
          items:
            type: string
            enum: [BVN, NIN, CAC, TIN, PASSPORT, SCUML, DRIVERS_LICENCE, VOTERS_CARD, OTHER]
        authoritative_verification: { type: boolean }

    NigeriaLocationSource:
      type: object
      required: [publisher, study, study_reference_id, variable, catalogue_created_on,
                 catalogue_last_modified_on, url, metadata_url, constitution_url,
                 count_corroboration_url, notes]
      properties:
        publisher: { type: string }
        study: { type: string }
        study_reference_id: { type: string }
        variable: { type: string }
        catalogue_created_on: { type: string }
        catalogue_last_modified_on: { type: string }
        url: { type: string, format: uri }
        metadata_url: { type: string, format: uri }
        constitution_url: { type: string, format: uri }
        count_corroboration_url: { type: string, format: uri }
        notes:
          type: array
          items: { type: string }

    NigeriaSubdivision:
      type: object
      required: [code, source_label, aliases]
      properties:
        code: { type: string }
        source_label: { type: string }
        aliases:
          type: array
          items: { type: string }

    NigeriaState:
      type: object
      required: [code, source_label, aliases, subdivision_kind, subdivisions]
      properties:
        code: { type: string, pattern: "^[0-9]{2}$" }
        source_label: { type: string }
        aliases:
          type: array
          items: { type: string }
        subdivision_kind:
          type: string
          enum: [local_government_area, area_council]
        subdivisions:
          type: array
          items: { $ref: "#/components/schemas/NigeriaSubdivision" }

    NigeriaLocationCatalog:
      type: object
      required: [schema_version, country, dataset_sha256, source, states]
      properties:
        schema_version: { type: integer, enum: [1] }
        country: { type: string, enum: [NG] }
        dataset_sha256: { type: string, pattern: "^[a-f0-9]{64}$" }
        source: { $ref: "#/components/schemas/NigeriaLocationSource" }
        states:
          type: array
          minItems: 37
          maxItems: 37
          items: { $ref: "#/components/schemas/NigeriaState" }

    CDDForm:
      type: object
      description: The questions and documents in force for one customer type and tier.
      required: [customer_type, tier, party_kind, fields, documents]
      properties:
        customer_type: { type: string }
        tier:
          type: string
          enum: [tier_1, tier_2, tier_3, corporate]
          description: |
            Also the value recorded as the customer's KYC tier, which is why it is governed by
            `app.customer.kyc_tier` rather than being free text. The corporate tier key was
            renamed from `standard` for exactly this reason: a tier the customer table cannot
            store is a form nobody can complete (ADR-0024 §4).
        label: { type: string }
        party_kind:
          type: string
          enum: [natural, legal]
          description: Which kind of party this form creates. Derived from the customer type, not asked.
        fields:
          type: array
          items: { $ref: "#/components/schemas/CDDFormField" }
        documents:
          type: array
          items: { $ref: "#/components/schemas/CDDDocumentRequirement" }
        identifier_requirements:
          type: array
          items: { $ref: "#/components/schemas/CDDIdentifierRequirement" }
          description: |
            The identifier presence groups enforced at submission. For individual accounts the
            official CBN minimum is Tier 1 any of BVN/NIN and Tiers 2/3 all of BVN/NIN. These
            identifiers remain captured and unverified until the corresponding NIBSS/NIMC
            electronic check succeeds; approval refuses missing, unverified, or mock evidence.
        source:
          type: string
          description: |
            `pack_default` or `tenant_override`. Carried onto the stored application so a
            two-year-old submission can be re-rendered against the questions the customer
            actually answered.
        version: { type: integer }

    CDDApplication:
      type: object
      description: One submitted CDD form, kept verbatim against the form version in force.
      required: [id, customer_id, form_key, form_version, form_source, customer_type, kyc_tier, submitted_data, status, submitted_at, required_documents]
      properties:
        id: { type: string, format: uuid }
        customer_id: { type: string, format: uuid }
        form_key: { type: string }
        form_version: { type: integer }
        form_source: { type: string }
        customer_type: { type: string }
        kyc_tier: { type: string }
        submitted_data:
          type: object
          additionalProperties: true
          description: The answers exactly as they arrived.
        status: { type: string, enum: [submitted, under_review, approved, rejected] }
        submitted_by: { type: string, format: uuid }
        submitted_at: { type: string, format: date-time }
        required_documents:
          type: array
          description: Requirements snapshotted at submission, unaffected by later form changes.
          items: { $ref: "#/components/schemas/CDDDocumentRequirement" }
        review_started_by: { type: string, format: uuid }
        review_started_at: { type: string, format: date-time }
        decided_by: { type: string, format: uuid }
        decided_at: { type: string, format: date-time }
        decision_reason: { type: string }
        screening_request_id:
          type: string
          format: uuid
          description: The one onboarding screening run pinned to this application.
        risk_assessment_id:
          type: string
          format: uuid
          description: The immutable assessment supporting an approval.

    OnboardingDocument:
      type: object
      description: Immutable, encrypted evidence linked to one submitted application.
      required:
      - id
      - party_id
      - doc_type
      - sha256
      - filename
      - content_type
      - size_bytes
      - verification_status
      - uploaded_at
      properties:
        id:
          type: string
          format: uuid
        application_id:
          type: string
          format: uuid
          nullable: true
          description: Present for evidence linked to an onboarding application; absent
            for customer-only reassessment evidence.
        party_id:
          type: string
          format: uuid
        doc_type:
          type: string
        sha256:
          type: string
          pattern: ^[0-9a-f]{64}$
          description: Digest of the plaintext bytes, verified again on download.
        filename:
          type: string
        content_type:
          type: string
          enum:
          - application/pdf
          - image/jpeg
          - image/png
        size_bytes:
          type: integer
          format: int64
        verification_status:
          type: string
          enum:
          - pending
          - verified
          - rejected
          - expired
        uploaded_by:
          type: string
          format: uuid
        uploaded_at:
          type: string
          format: date-time
        verified_by:
          type: string
          format: uuid
        verified_at:
          type: string
          format: date-time
        verification_reason:
          type: string
        expires_at:
          type: string
          format: date
        review_id:
          type: string
          format: uuid
          description: The governed KYC reassessment that collected this evidence, when
            applicable.
    CorporateProfile:
      type: object
      description: |
        The corporate-only half of a legal party's record — the facts with no party-generic home.
        The registered name lives in `party_name` because screening reads it there, and the RC
        number lives in `party_identifier` because it must be encrypted with a blind index; a
        second plaintext home for either would bypass the boundary while reading like the home
        (ADR-0024 §5).
      required: [party_id, cash_intensive, ubo_declared]
      properties:
        party_id: { type: string, format: uuid }
        cash_intensive: { type: boolean }
        ubo_declared:
          type: boolean
          description: A beneficial-ownership register was captured. It does NOT record that anyone checked it.
        ubo_verified_at: { type: string, format: date-time }
        ubo_verification_method:
          type: string
          description: |
            How the register was checked: `cac_status_report`, `certified_ubo_register` or
            `board_resolution_and_id`. Not a database enum — what verification is allowed to mean
            is Q28, and freezing it in a CHECK would settle a legal question by schema.
        ubo_verification_reference:
          type: string
          description: The evidence reference. Required whenever a verification timestamp is set.

    ApplicationReview:
      type: object
      description: |
        A submitted application together with the identity data a checker needs to decide on it.
        Building one decrypts the subject's identifiers and writes a `pii.read` audit event.
      required: [application, customer, party, identifiers, documents]
      properties:
        application: { $ref: "#/components/schemas/CDDApplication" }
        customer: { $ref: "#/components/schemas/Customer" }
        party: { $ref: "#/components/schemas/Party" }
        identifiers:
          type: array
          description: Decrypted, in the clear. Empty for a subject whose key was destroyed under an erasure request.
          items: { $ref: "#/components/schemas/PartyIdentifier" }
        corporate_profile: { $ref: "#/components/schemas/CorporateProfile" }
        beneficial_owners:
          type: array
          items: { $ref: "#/components/schemas/BeneficialOwner" }
        documents:
          type: array
          items: { $ref: "#/components/schemas/OnboardingDocument" }
        outstanding_documents:
          type: array
          description: Required types that are not yet backed by verified, unexpired evidence.
          items: { $ref: "#/components/schemas/CDDDocumentRequirement" }
        screening:
          description: |
            What the watchlists said about this applicant, screened with `mode: onboarding` when
            the review was opened. This is where BRD §8.4's screening-at-onboarding actually
            happens: `POST /v1/customers` deliberately does not screen, because composing it
            there would hide a hit from the caller.

            Present only when the run succeeded. Mutually exclusive with
            `screening_unavailable`, and exactly one of the two is always present.
          allOf:
            - $ref: "#/components/schemas/ScreeningResult"
        screening_unavailable:
          type: string
          description: |
            Present INSTEAD of `screening` when the applicant was not screened, saying why in a
            sentence a compliance officer can act on — no published watchlist, the run exceeded
            the tenant's budget, the run failed, or the application has already been decided and
            reading it is not a control being exercised.

            It exists so that "not screened" can never be mistaken for "screened, clear". A
            review that quietly showed no hits because no screening happened is indistinguishable
            on screen from one that screened and found nothing, and the second is a clearance
            while the first is nothing at all. A screening failure does NOT block the review:
            the review approves nothing (no build admits a customer off the back of one), and
            refusing it would mean the control that exists — a human reading the decrypted
            identifiers — cannot be exercised because a control that does not exist yet is
            missing.

    ApplicationDecision:
      type: object
      required: [application, customer]
      properties:
        application: { $ref: "#/components/schemas/CDDApplication" }
        customer: { $ref: "#/components/schemas/Customer" }

    OnboardResult:
      type: object
      description: What the front office gets back from one CDD submission.
      required: [customer, party, application_id, form]
      properties:
        customer: { $ref: "#/components/schemas/Customer" }
        party: { $ref: "#/components/schemas/Party" }
        application_id:
          type: string
          format: uuid
          description: The stored verbatim submission, readable at /v1/onboarding/applications/{applicationID}.
        form: { $ref: "#/components/schemas/CDDForm" }
        outstanding_documents:
          type: array
          description: |
            The documents this tier requires. The customer starts in `pending_documents`, moves
            to `pending_approval` once each type is present, and cannot be approved until a
            different user has verified every object.
          items: { $ref: "#/components/schemas/CDDDocumentRequirement" }

    # ------------------------------------------------------------- Metrics

    MetricCell:
      type: object
      description: |
        One aggregate count. `value` is null EXACTLY when `suppressed` is true — not zero, because
        a suppressed cell and an empty cell mean opposite things to the person reading the screen,
        and a consumer that ignores the flag gets `null` rather than a plausible number.
      required: [key, value, suppressed]
      properties:
        key:
          type: string
          description: |
            Identifies the cell within its distribution: an alert status, an ageing band, a
            deadline horizon. Never a person, an account or a case reference.
        value:
          oneOf:
            - type: "null"
            - type: integer
              format: int64
        suppressed: { type: boolean }
        suppressed_by:
          type: string
          description: |
            Which rule removed the value. `small_cell` is the primary rule — a count of 1..4 is
            replaced by NULL inside the query, so the number never leaves the database.
            `complementary` means the cell was publishable in its own right and had to be
            withdrawn because publishing it would let a reader derive a suppressed neighbour by
            subtraction, which is one arithmetic step on a board slide. Not a database enum: it is
            computed per request (Q29).

    MetricCoverage:
      type: object
      description: |
        Whether a metric is being published at all, which has to be a separate question from what
        its value is. Without it every unwritten stream reports zero, and a zero on a compliance
        dashboard reads as good news.
      required: [stream, available, facts]
      properties:
        stream:
          type: string
          enum: [alert.outcome, case.lifecycle, filing.volume, filing.deadline, screening.outcome, risk.exposure]
        available:
          type: boolean
          description: False when no module has ever published this stream for this tenant.
        source_module:
          type: string
          description: Who publishes it, so an unavailable metric names who owes it.
        first_published_at: { type: string, format: date-time }
        last_published_at:
          type: string
          format: date-time
          description: |
            Returned with every aggregate, so a stream that stopped being published a fortnight
            ago does not read as a quiet fortnight.
        facts: { $ref: "#/components/schemas/MetricCell" }
        reason: { type: string, description: Why an unavailable stream is unavailable, in the words the screen should use. }

    MetricDistribution:
      type: object
      description: |
        Counts over one dimension, with the total they sum to. The total is carried rather than
        left to the caller to add up, because after suppression the cells no longer sum to it —
        that is the whole point — and a caller that adds the visible cells produces a total that
        is wrong in the direction of "fewer than there are".
      required: [metric, cells, total, as_of, coverage]
      properties:
        metric: { type: string }
        cells:
          type: array
          items: { $ref: "#/components/schemas/MetricCell" }
        total: { $ref: "#/components/schemas/MetricCell" }
        as_of: { type: string, format: date-time }
        coverage: { $ref: "#/components/schemas/MetricCoverage" }

    MetricRate:
      type: object
      description: A ratio of two suppressed counts, itself suppressed when either of them is.
      required: [metric, numerator, denominator, rate, suppressed, breakdown, from, to, coverage]
      properties:
        metric: { type: string }
        numerator: { $ref: "#/components/schemas/MetricCell" }
        denominator: { $ref: "#/components/schemas/MetricCell" }
        rate:
          oneOf:
            - type: "null"
            - type: number
          description: |
            Null when either component was suppressed, or when the denominator is zero. A rate
            published against a suppressed numerator discloses the numerator: 3% of a published
            100 is 3, and 3 was suppressed for a reason.
        suppressed: { type: boolean }
        breakdown:
          type: array
          description: Every closing disposition, not only the one in the numerator.
          items: { $ref: "#/components/schemas/MetricCell" }
        from: { type: string, format: date-time }
        to: { type: string, format: date-time }
        coverage: { $ref: "#/components/schemas/MetricCoverage" }

    MetricSeriesPoint:
      type: object
      required: [period_start, kind, status, count]
      properties:
        period_start: { type: string, format: date-time }
        kind: { type: string }
        status: { type: string }
        count: { $ref: "#/components/schemas/MetricCell" }

    MetricSeries:
      type: object
      description: "A volume time series: filings per period, by kind and status."
      required: [metric, grain, points, total, from, to, coverage]
      properties:
        metric: { type: string }
        grain:
          type: string
          description: |
            The period bucket this series was computed at — day, week, month, quarter or year.
            Governed by no database column: it is bound into `date_trunc` at query time, and the
            closed set is validated by the parameter on the operation.
        points:
          type: array
          items: { $ref: "#/components/schemas/MetricSeriesPoint" }
        total: { $ref: "#/components/schemas/MetricCell" }
        from: { type: string, format: date-time }
        to: { type: string, format: date-time }
        coverage: { $ref: "#/components/schemas/MetricCoverage" }

    MetricCoveragePage:
      type: object
      description: "Coverage per stream, complete: the stream list is a closed set in the analytics module."
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/MetricCoverage" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    ExecutiveRiskCell:
      type: object
      description: One current risk-rating intersection with a bounded, non-identifying label.
      required: [risk_rating, dimension_value, count]
      properties:
        risk_rating: { type: string, enum: [unrated, low, medium, high, prohibited] }
        dimension_value:
          type: string
          description: A bounded sector, two-letter geography/UNKNOWN, or KYC tier; never free text.
        count: { $ref: "#/components/schemas/MetricCell" }

    ExecutiveRiskMatrix:
      type: object
      description: The complete active customer book split by risk rating and one dimension.
      required: [metric, dimension, as_of, cells, total, coverage]
      properties:
        metric: { type: string, enum: [risk.exposure] }
        dimension: { type: string, enum: [sector, geography, kyc_tier] }
        as_of: { type: string, format: date-time }
        cells:
          type: array
          maxItems: 500
          items: { $ref: "#/components/schemas/ExecutiveRiskCell" }
        total: { $ref: "#/components/schemas/MetricCell" }
        coverage: { $ref: "#/components/schemas/MetricCoverage" }

    RiskProjectionCoverage:
      type: object
      description: |
        Comparison between analytics' projected active rows and onboarding's authoritative
        active-customer control total. Counts below five remain suppressed. If complete is false,
        the risk matrices are withheld rather than presented as a tenant-wide undercount.
      required: [available, complete, projected_active, authoritative_active]
      properties:
        available: { type: boolean }
        complete: { type: boolean }
        projected_active: { $ref: "#/components/schemas/MetricCell" }
        authoritative_active: { $ref: "#/components/schemas/MetricCell" }
        source_observed_at: { type: string, format: date-time }
        projection_observed_at: { type: string, format: date-time }
        reason: { type: string }

    ExecutiveDisclosure:
      type: object
      required: [small_cell_threshold, published_cells, primary_suppressed_cells,
                 complementary_suppressed_cells, labels_are_bounded, statement]
      properties:
        small_cell_threshold: { type: integer, format: int64, minimum: 5 }
        published_cells: { type: integer, minimum: 0 }
        primary_suppressed_cells: { type: integer, minimum: 0 }
        complementary_suppressed_cells: { type: integer, minimum: 0 }
        labels_are_bounded: { type: boolean }
        statement: { type: string }

    ExecutiveWindow:
      type: object
      description: Half-open filing window [from,to); it does not filter the current risk book.
      required: [from, to]
      properties:
        from: { type: string, format: date-time }
        to: { type: string, format: date-time }

    MetricHistory:
      type: object
      required: [metric, stream, from, to, available, prior_available, rows]
      properties:
        metric: { type: string, enum: [volume, funnel, productivity] }
        stream: { type: string }
        from: { type: string, format: date-time }
        to: { type: string, format: date-time }
        available: { type: boolean }
        prior_available: { type: boolean }
        coverage_from: { type: string, format: date-time }
        reason: { type: string }
        rows:
          type: array
          items: { $ref: "#/components/schemas/MetricHistoryRow" }
    MetricHistoryRow:
      type: object
      required: [key, value, prior_value, delta, suppressed]
      properties:
        category: { type: string }
        period_start: { type: string, format: date-time }
        prior_period_start: { type: string, format: date-time }
        key: { type: string }
        value: { type: [integer, "null"], format: int64 }
        prior_value: { type: [integer, "null"], format: int64 }
        delta: { type: [integer, "null"], format: int64 }
        suppressed: { type: boolean }
    ExecutiveAnalytics:
      type: object
      description: |
        Aggregate-only executive report. No property is a customer, party, account, case or
        source-record identifier. Current risk exposure and period filing metrics are deliberately
        distinguished so a cohort or historical claim cannot be inferred from current-state data.
      required: [schema, generated_at, risk_as_of, filing_window, grain, dimensions,
                 risk_exposure, filing_volumes, filing_deadlines, coverage, risk_projection,
                 disclosure, historical_risk_available]
      properties:
        history:
          type: array
          items: { $ref: "#/components/schemas/MetricHistory" }
        schema: { type: string, enum: [baobyte.executive-analytics.aggregate.v1] }
        generated_at: { type: string, format: date-time }
        risk_as_of: { type: string, format: date-time }
        filing_window: { $ref: "#/components/schemas/ExecutiveWindow" }
        grain: { type: string, enum: [day, week, month, quarter, year] }
        dimensions:
          type: array
          minItems: 1
          maxItems: 3
          uniqueItems: true
          items: { type: string, enum: [sector, geography, kyc_tier] }
        risk_exposure:
          type: array
          minItems: 1
          maxItems: 3
          items: { $ref: "#/components/schemas/ExecutiveRiskMatrix" }
        filing_volumes: { $ref: "#/components/schemas/MetricSeries" }
        filing_deadlines: { $ref: "#/components/schemas/MetricDistribution" }
        coverage:
          type: array
          items: { $ref: "#/components/schemas/MetricCoverage" }
        risk_projection: { $ref: "#/components/schemas/RiskProjectionCoverage" }
        disclosure: { $ref: "#/components/schemas/ExecutiveDisclosure" }
        historical_risk_available:
          type: boolean
          description: False for this current-state projection; no historical risk trend is implied.

    # ------------------------------------------------------------ Watchlists

    Watchlist:
      type: object
      description: An internal list header. The editable master; the screening index is a published snapshot of it.
      required: [id, key, name, kind, enabled, published_entry_count, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        key: { type: string }
        name: { type: string }
        kind:
          type: string
          enum: [internal_black, internal_grey]
          description: |
            A blacklist says "do not do business with this party"; a greylist says "do business
            and watch it". Different decisions, not two severities of one — and both surface as
            screening hits, so the analyst has to be able to tell them apart.
        description: { type: string }
        enabled: { type: boolean }
        published_version:
          type: string
          description: |
            What the screening index currently holds for this list, or absent if it has never been
            published. Kept here so "is screening current with the list?" is answerable without
            reading the screening module's tables.
        published_at: { type: string, format: date-time }
        published_entry_count: { type: integer }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    WatchlistEntry:
      type: object
      description: One live or removed row on an internal list. Removal is a soft delete, so a removed row is still readable.
      required: [id, list_id, external_id, entity_kind, primary_name, aliases, reason_code, reason, added_at]
      properties:
        id: { type: string, format: uuid }
        list_id: { type: string, format: uuid }
        external_id:
          type: string
          description: Stable within the list. Import matches on it, which makes re-importing a corrected file an update rather than a duplicate.
        entity_kind: { type: string, enum: [natural, legal, vessel, aircraft, unknown] }
        primary_name: { type: string }
        aliases:
          type: array
          items: { type: string }
        party_id:
          type: string
          format: uuid
          description: |
            Links the entry to the customer it is about (BRD §8.7.1) — this is *the customer we
            exited*, not a name that resembles them. It is what lets screening distinguish a
            self-match from a real one.
        reason_code: { type: string }
        reason: { type: string }
        date_of_birth: { type: string }
        nationality: { type: string }
        identifier: { type: string }
        added_by: { type: string, format: uuid }
        added_at: { type: string, format: date-time }
        expires_at: { type: string, format: date-time }
        removed_at: { type: string, format: date-time }
        removed_by: { type: string, format: uuid }
        removal_reason: { type: string }

    WatchlistPage:
      type: object
      description: "The internal lists a tenant maintains, complete."
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/Watchlist" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    WatchlistEntryPage:
      type: object
      description: |
        A bounded, resumable page of a list's entries in immutable descending UUIDv7 order.
        Follow next_cursor until absent to traverse all matches. Counts over items are page-scoped.
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/WatchlistEntry" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    WatchlistRowError:
      type: object
      description: One quarantined row, located precisely enough to fix the source file.
      required: [line_no, error]
      properties:
        line_no: { type: integer, format: int64 }
        raw: { type: string, description: The row exactly as it arrived. }
        error: { type: string }

    WatchlistRowErrorPage:
      type: object
      description: "The rows one import rejected, complete."
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/WatchlistRowError" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    WatchlistChangeApproval:
      type: object
      description: |
        A mandatory maker-checker watchlist change that was recorded but not applied. The
        request id links to the ordinary approval queue. Import failures are returned here
        because no reconciliation row exists until the approved import is actually applied.
      required: [request_id, action_key, op, list_key]
      properties:
        request_id: { type: string, format: uuid }
        action_key:
          type: string
          description: The configured workflow action; currently watchlists.entry.edit.
        op:
          type: string
          description: The held operation, currently entry.add, entry.remove or import.
        list_key: { type: string }
        failures:
          type: array
          description: Parsed import rows excluded from the digest-bound valid record set.
          items: { $ref: "#/components/schemas/WatchlistRowError" }

    WatchlistImportResult:
      type: object
      description: The reconciliation record for one bulk import (BRD §8.7.2).
      required: [import_id, list_key, status, received, added, updated, quarantined]
      properties:
        import_id: { type: string, format: uuid }
        list_key: { type: string }
        status:
          type: string
          enum: [running, completed, failed, partial]
          description: |
            `partial` means rows were quarantined. A green tick over a file that lost three names
            is the failure this whole design exists to avoid.
        received: { type: integer, format: int64 }
        added: { type: integer, format: int64 }
        updated: { type: integer, format: int64 }
        quarantined: { type: integer, format: int64 }
        failures:
          type: array
          description: The rejected rows, inline. The same set is readable later at /imports/{importID}/quarantine.
          items: { $ref: "#/components/schemas/WatchlistRowError" }

    WatchlistPublishResult:
      type: object
      required: [list_key, version, entry_count, published]
      properties:
        list_key: { type: string }
        version:
          type: string
          description: A timestamp plus a digest over the entry set. Every screening hit pins one.
        entry_count: { type: integer }
        published:
          type: boolean
          description: |
            False when the entry set was byte-identical to the live version and nothing was
            written. A version per save would make the version history useless for the one
            question it exists to answer.

    WatchlistSource:
      type: object
      description: A list's provider binding and refresh state (BRD §8.4.4, Q6).
      required: [id, list_key, provider, list_name, list_kind, list_source, enabled, interval_hours, last_status, next_due_at]
      properties:
        id: { type: string, format: uuid }
        list_key: { type: string }
        provider: { type: string, description: "The adapter id. None ships (Q6)." }
        list_name: { type: string }
        list_kind: { type: string, enum: [sanctions, pep, adverse_media] }
        list_source: { type: string, enum: [UN, OFAC, EU, UK_HMT, NFIU, CBN, NIGSAC, COMMERCIAL] }
        enabled: { type: boolean }
        settings:
          type: object
          additionalProperties: true
          description: The adapter's own configuration, opaque to this module.
        interval_hours: { type: integer }
        last_run_at: { type: string, format: date-time }
        last_version: { type: string }
        last_status: { type: string, enum: [never_run, succeeded, failed, skipped] }
        last_error: { type: string }
        next_due_at:
          type: string
          format: date-time
          description: |
            Written by the job, so a feed that is down backs off in one place rather than in every
            caller. Backoff on failure is one hour rather than the configured cadence, because a
            queue full of identical failures hides the next real one.

    WatchlistSourcePage:
      type: object
      description: "Configured provider bindings, complete."
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/WatchlistSource" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    WatchlistRefreshResult:
      type: object
      description: |
        One source's outcome from a refresh run. A refusal is reported here with `status: failed`
        rather than as an HTTP error, because the refusal is a fact about the feed that has just
        been recorded against the source — and a 5xx would roll back the record of why it failed.
      required: [list_key, provider, status, received, quarantined]
      properties:
        list_key: { type: string }
        provider: { type: string }
        status:
          type: string
          enum: [succeeded, failed, skipped]
          description: |
            `skipped` is a disabled source, which is the default state and is not an error: an
            installation with no licensed feed should not produce a permanently red queue.
        version: { type: string }
        received: { type: integer }
        quarantined: { type: integer }
        error:
          type: string
          description: |
            Expect "no provider is registered under that id" in every installation of this build.
            No sanctions, PEP or adverse-media adapter ships while Q6 is open.

    ScreeningResult:
      type: object
      description: |
        One screening run, self-contained: everything needed to explain later what was screened,
        against what, and what came back.

        It carries **no allow/deny field**, and that is the design rather than an omission. See
        `POST /v1/screening/runs` and open question Q7: the fail-open/fail-closed policy that
        would give such a field meaning is unbuilt and unsigned, and an `allow` nobody agreed to
        would make the absence of a hit read as a clearance.
      required: [request_id, subject_name, mode, hits, candidates_screened, latency, suppressed]
      properties:
        request_id:
          type: string
          format: uuid
          description: |
            The stored run. Every hit carries it, and a filing cites it years later to show which
            question was asked and when.
        subject_name: { type: string, description: The name as it was screened. }
        mode:
          type: string
          enum: [onboarding, ongoing, realtime, batch, adhoc]
          description: Why the run happened, as the caller declared it. Snapshotted onto the run.
        hits:
          type: array
          description: |
            Every candidate that reached the threshold after corroboration, each pinned to the
            watchlist version in force at match time. An empty array is an answer — "screened,
            nothing matched" — and is never `null`.
          items: { $ref: "#/components/schemas/ScreeningHit" }
        candidates_screened:
          type: integer
          description: How many index entries the run considered. The denominator behind `hits`.
        latency:
          type: integer
          format: int64
          description: |
            Wall-clock duration of the run in NANOSECONDS. Nanoseconds because this is Go's
            `time.Duration` serialised as itself rather than a converted figure — the same value
            the run row stores in milliseconds and the same one the tenant's `timeout_ms` budget
            is measured against. Divide by 1e6 for milliseconds.
        suppressed:
          type: integer
          description: |
            How many hits an approved suppression silenced. Reported rather than hidden: an
            analyst should know the system found something and that a human previously decided
            it was not this party.

    ScreeningHitOccurrence:
      type: object
      additionalProperties: false
      required: [request_id, hit_id, subject_name, mode, match_evidence, created_at]
      properties:
        request_id: { type: string, format: uuid }
        hit_id: { type: string, format: uuid }
        subject_name: { type: string }
        mode: { type: string, enum: [realtime, batch] }
        match_evidence: { type: object, additionalProperties: true }
        created_at: { type: string, format: date-time }
    ScreeningHitOccurrencePage:
      type: object
      additionalProperties: false
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: '#/components/schemas/ScreeningHitOccurrence' }
        next_cursor: { $ref: '#/components/schemas/NextCursor' }
        truncated: { $ref: '#/components/schemas/Truncated' }
        truncation_reason: { $ref: '#/components/schemas/TruncationReason' }
        total_estimate: { $ref: '#/components/schemas/TotalEstimate' }

    ScreeningHit:
      type: object
      required: [id, request_id, entry_id, version_id, watchlist_key, mode, score, algorithm, threshold, matched_name, subject_name, dob_match, nationality_match, identifier_match, adjusted_score, decision, created_at]
      properties:
        id: { type: string, format: uuid }
        request_id: { type: string, format: uuid }
        entry_id: { type: string, format: uuid }
        party_id:
          type: string
          format: uuid
          description: |
            The subject the screening run was about. Absent when the run named a free-text
            counterparty nobody holds a party record for, which is a real and ordinary state:
            a name on a payment can be screened long before anyone decides it is worth a row.
            Everything a confirmed match obliges — the KYC review, the re-score, the case
            opened over it — is addressed to a party, so its absence is what tells a client
            there is nothing to escalate against.
        version_id:
          type: string
          format: uuid
          description: |
            Pins the watchlist version, so "which list, as it stood when" is answerable
            about a filing made two years ago.
        watchlist_key: { type: string }
        mode:
          type: string
          enum: [onboarding, ongoing, realtime, batch, adhoc]
          description: |
            How the screening run that produced this hit was triggered. Two identical name
            matches mean different things depending on it — one raised at onboarding blocks an
            account opening, the same one raised by the nightly re-screen is a list change
            landing on an existing customer — and the queue cannot show that without it.
        watchlist_kind:
          type: string
          enum: [sanctions, pep, adverse_media, internal_black, internal_grey]
          description: |
            The obligation the hit carries, snapshotted at match time. A sanctions match is an
            asset freeze and a filing trigger, a PEP match is an enhanced-due-diligence
            trigger, and an internal greylist match means keep doing business and watch it.
            Three different legal duties, previously distinguishable only by decoding
            `watchlist_key` against the tenant's own list-naming convention.

            ABSENT on a hit raised before this was recorded. Snapshotted rather than joined
            because a list may be re-kinded, and the duty that applied is the one in force
            when the hit was raised.
        score: { type: number, description: The raw name-similarity score, before corroboration. }
        algorithm: { type: string }
        threshold: { type: number, description: The configured threshold in force at match time. }
        matched_name:
          type: string
          description: |
            Whichever recorded spelling actually scored. Frequently an alias or a
            transliteration rather than the name the list publishes — see
            `entry_primary_name` for that.
        matched_name_type:
          type: string
          enum: [primary, alias, former, transliteration, low_quality_alias]
          description: |
            Which KIND of recorded name scored. A hit on a `low_quality_alias` deserves less
            weight than one on the published primary name, and the two were previously
            reported identically. ABSENT on a hit raised before this was recorded.
        subject_name: { type: string }
        entry_external_id:
          type: string
          description: |
            The matched entry's identifier in the SOURCE list — a UN reference number, an OFAC
            SDN id, an internal list's own key — as it stood at match time. This is what a
            query to the list publisher quotes, and it is half of the suppression key.

            The next five fields are a SNAPSHOT of the listed party's identity, not a join.
            `entry_id` reaches the live row and it cannot be deleted while a hit references
            it, so a join would resolve — to the entry as the list holds it today. The point
            of pinning `version_id` is that a hit records the world as it stood when it
            matched: a delisting, a corrected programme or a withdrawn alias since must not
            silently rewrite the evidence behind a filing. All of them are ABSENT on a hit
            raised before the snapshot existed, and absent is the honest report — no backfill
            from the live entry was attempted, because a snapshot invented from today's list
            is worse than a missing one.
        entry_primary_name:
          type: string
          description: The listed party's primary name at match time, as distinct from the alias that scored.
        entry_entity_kind:
          type: string
          enum: [natural, legal, vessel, aircraft, unknown]
          description: Whether the listed party was a person, a company, a vessel or an aircraft. Not the same finding.
        entry_programs:
          type: array
          items: { type: string }
          description: |
            The designation programmes the entry was listed under at match time. An empty
            array is a real answer meaning the entry carried no programme; absent means the
            hit predates the snapshot.
        dob_match: { type: string, enum: [match, mismatch, unknown] }
        nationality_match: { type: string, enum: [match, mismatch, unknown] }
        identifier_match: { type: string, enum: [match, mismatch, unknown] }
        adjusted_score:
          type: number
          description: |
            The score after corroborating attributes. A name match with a mismatched date
            of birth is a weaker hit than the raw score suggests, and the queue should
            order by this rather than by string similarity.
        decision: { type: string, enum: [pending, true_positive, false_positive, suppressed] }
        decided_by:
          type: string
          format: uuid
          description: |
            The actor who cleared or confirmed the hit. Absent while the hit is pending, which
            is the only reason it is not required: "who cleared this sanctions match" is the
            first question an examiner asks, so a decided hit always carries it.
        decided_at:
          type: string
          format: date-time
          description: |
            When the decision was recorded, as the database timestamped it rather than as the
            caller observed it. Absent while pending, and always present alongside decided_by.
        decision_note: { type: string }
        created_at: { type: string, format: date-time }
        due_at:
          type: string
          format: date-time
          description: |
            When this match must have been reviewed by. Banded by adjusted_score from the
            tenant's screening.match review SLA at the moment the hit was raised, and stored
            rather than derived, so retuning the bands cannot rewrite the history of which
            reviews were late.

            Render this BESIDE the hit's age, never instead of it. They are different facts:
            an age says which hit has been ignored longest, a deadline says which one bites
            first, and they disagree constantly - a weak match from last week is older than a
            near-certain one from an hour ago and less urgent than it. Absent only on a hit
            that was already decided before this field existed.
        assigned_to:
          type: string
          format: uuid
          description: |
            The analyst who owns this review. Absent while nobody has taken it, which is what
            an "Unassigned" queue tile counts. Set by POST /v1/screening/hits/{hitID}/assign,
            which is self-assignment only.

    ScreeningEntryName:
      type: object
      description: |
        One recorded spelling of a listed party. `matched` marks the spelling that actually
        scored: an analyst looking at eleven aliases cannot otherwise tell which one produced
        the number they are being asked to act on.
      required: [type, full_name, matched]
      properties:
        type: { type: string, enum: [primary, alias, former, transliteration, low_quality_alias] }
        full_name: { type: string }
        matched: { type: boolean }

    ScreeningMatchedEntry:
      type: object
      description: |
        The watchlist entry a hit matched, AS THE LIST HOLDS IT NOW — deliberately distinct
        from the snapshot carried on the hit itself. Where the two disagree, that difference
        is evidence rather than an inconsistency, and a screen must say which it is showing.
      required: [id, external_id, entity_kind, primary_name, names, programs, attributes]
      properties:
        id: { type: string, format: uuid }
        external_id: { type: string }
        entity_kind: { type: string, enum: [natural, legal, vessel, aircraft, unknown] }
        primary_name: { type: string }
        names:
          type: array
          items: { $ref: "#/components/schemas/ScreeningEntryName" }
        programs:
          type: array
          items: { type: string }
        listed_on: { type: string, format: date }
        remarks: { type: string }
        attributes:
          type: object
          additionalProperties: { type: string }
          description: |
            The corroboration inputs the list carries — date_of_birth, year_of_birth,
            nationality, place_of_birth, address, identifier, position. These are the values
            the score adjustment was computed against, so showing them is what makes the
            arithmetic checkable rather than merely reported.

    ScreeningListVersion:
      type: object
      description: |
        The published watchlist version a hit is pinned to, with its list header. The version
        string and its publication date are the answer to "which list, as it stood when" — the
        first question an examiner asks about a filing.
      required: [id, watchlist_key, watchlist_name, watchlist_kind, source, version, state, entry_count]
      properties:
        id: { type: string, format: uuid }
        watchlist_key: { type: string }
        watchlist_name: { type: string }
        watchlist_kind: { type: string, enum: [sanctions, pep, adverse_media, internal_black, internal_grey] }
        source: { type: string, enum: [UN, OFAC, EU, UK_HMT, NFIU, CBN, NIGSAC, INTERNAL, COMMERCIAL] }
        version: { type: string }
        state:
          type: string
          enum: [loading, published, superseded, failed]
          description: |
            `superseded` is the normal state of an old hit's version and is not a fault: the
            list has been refreshed since. A screen saying so is what stops an analyst reading
            a two-year-old pin as a live one.
        entry_count: { type: integer }
        published_at: { type: string, format: date-time }

    ScreeningPolicy:
      type: object
      description: |
        The screening.match configuration document as it stood when a run happened, read back
        from the snapshot on the request row rather than from live configuration. Retuning a
        threshold must not retrospectively change the explanation of a decision taken under
        the old one.

        The corroboration terms ADJUST a score, they do not gate it. A strong name match with
        a contradicting date of birth is downgraded rather than discarded, because dates of
        birth are wrong in both directions often enough that discarding on them would suppress
        true hits (ADR-0015).
      required: [threshold, candidate_limit, dob_match_bonus, dob_mismatch_penalty, nationality_match_bonus, identifier_match_bonus]
      properties:
        threshold: { type: number, description: The adjusted score at or above which a candidate becomes a hit. }
        candidate_limit: { type: integer, description: How many index entries are scored per subject. The real-time path has a latency budget. }
        dob_match_bonus: { type: number }
        dob_mismatch_penalty: { type: number }
        nationality_match_bonus: { type: number }
        identifier_match_bonus: { type: number }
        lists:
          type: array
          nullable: true
          items: { type: string }
          description: Which watchlists participate. Empty or null means every enabled one.
        four_eyes_clear_above:
          type: number
          description: |
            The adjusted score at or above which CLEARING a hit as a false positive needed a
            second pair of eyes when this run happened. The SECONDARY predicate: a clearance on
            a sanctions-kind list is held at any score and this value does not apply to it.
            Above 1 means the band was disabled. Snapshotted with the rest of the policy, so
            "was a second reviewer required for this decision" stays answerable after the
            institution retunes it.
        timeout_ms:
          type: integer
          description: |
            The wall-clock budget one synchronous screening run was allowed, snapshotted with
            the rest of the policy. Per-tenant rather than a constant because Q7 requires the
            timeout on a synchronous screening decision to be the institution's own documented
            choice. It does not decide what happens when the budget is missed — fail-open
            versus fail-closed is the other half of Q7 and nothing here defaults it.
        review_sla_bands:
          type: array
          items:
            type: object
            required: [min_adjusted_score, hours]
            properties:
              min_adjusted_score: { type: number, description: Inclusive floor of the band. Bands match highest-floor-first, so declaration order carries no meaning. }
              hours: { type: integer, description: How long a pending hit in this band may sit unreviewed. }
          description: |
            How long a pending hit may sit unreviewed, by adjusted score. Snapshotted with the
            rest of the policy, so "which review window was in force when this hit was raised"
            is answerable from the stored request exactly as the threshold is — a retune must
            not rewrite the history of which reviews were late.

    ScreeningRun:
      type: object
      description: The screening request a hit came out of, with the policy in force when it ran.
      required: [id, subject_name, mode, policy, hit_count, requested_at]
      properties:
        id: { type: string, format: uuid }
        party_id:
          type: string
          format: uuid
          description: Absent when the run screened a free-text counterparty with no party row.
        subject_name: { type: string }
        mode: { type: string, enum: [onboarding, ongoing, realtime, batch, adhoc] }
        policy: { $ref: "#/components/schemas/ScreeningPolicy" }
        hit_count: { type: integer }
        latency_ms: { type: integer }
        requested_by: { type: string, format: uuid }
        requested_at: { type: string, format: date-time }

    ScreeningHitDetail:
      type: object
      description: |
        The hit workspace, as `getScreeningHit` returns it. See that operation for what each
        member is for and why they arrive together.

        `party` is optional and its absence is meaningful: the run screened a name with no
        party row behind it, or the party could not be read.
      required: [hit, entry, version, request]
      properties:
        hit: { $ref: "#/components/schemas/ScreeningHit" }
        entry: { $ref: "#/components/schemas/ScreeningMatchedEntry" }
        version: { $ref: "#/components/schemas/ScreeningListVersion" }
        request: { $ref: "#/components/schemas/ScreeningRun" }
        party: { $ref: "#/components/schemas/Party" }

    ScreeningDecision:
      type: object
      description: |
        What recording a decision on a screening hit actually did.

        Confirming a match against a sanctions list is the most filing-relevant single event
        this product records, and it used to return 204 — the decision row and one audit event,
        then nothing. The analyst opened a case by hand and retyped the subject, the list, the
        score and the watchlist version, which is where the evidential chain between the match
        and the filing broke.
      required: [hit]
      properties:
        hit: { $ref: "#/components/schemas/ScreeningHit" }
        customer_id:
          type: string
          format: uuid
          description: |
            The customer relationship behind the hit's subject, when there is one. Absent for a
            counterparty or a prospect, and its absence is why no KYC review was raised.
        kyc_review_id:
          type: string
          format: uuid
          description: |
            The review this confirmation raised, due today, reason `screening_hit`. Absent on a
            cleared hit, and absent on a confirmed one whenever `escalation_skipped` says why.
        assessment_id:
          type: string
          format: uuid
          description: The risk assessment written with trigger `screening_hit` and this hit as its trigger reference.
        risk_rating:
          type: string
          description: The rating that assessment produced. Recorded against the party; the customer's own denormalised rating is not overwritten from here.
        escalation_skipped:
          type: array
          items: { type: string }
          description: |
            Every consequence that did not follow, and why, in prose an analyst can act on.
            These are ordinary states rather than failures — no party behind the hit, no
            customer behind the party, a review already outstanding, no active risk model — and
            each one changes what the person who confirmed the match should do next. Empty on a
            cleared hit, which obliges nothing.

    Rule:
      type: object
      required: [id, key, typology, name]
      properties:
        id: { type: string, format: uuid }
        key: { type: string }
        typology: { type: string }
        name: { type: string }
        description: { type: string }
        source_pack: { type: string }

    RuleVersion:
      type: object
      required: [id, rule_id, rule_key, typology, version, window_hours, window_scope, aggregates, expression, params_key, severity, status]
      properties:
        id: { type: string, format: uuid }
        rule_id: { type: string, format: uuid }
        rule_key: { type: string }
        typology: { type: string }
        version: { type: integer }
        window_hours: { type: integer }
        window_scope:
          type: string
          # `customer` was invented. The column has always allowed exactly these three, and a
          # client typed against the old list could ask for a scope the database refuses.
          enum: [account, party, counterparty]
        aggregates:
          type: array
          items: { type: string }
          description: A closed vocabulary. A new aggregate is a new indexed query shape, so it is a code change.
        expression:
          type: string
          description: A CEL predicate over the window aggregates and named parameters.
        params_key:
          type: string
          enum: [monitoring.thresholds]
          description: |
            Thresholds are never literals in the expression. They resolve from this
            closed configuration key, which is what lets a compliance administrator retune
            a rule without a deploy while keeping simulation and production on one source
            (ADR-0016).
        params_segment:
          type: string
          maxLength: 0
          deprecated: true
          description: Must be omitted or empty. The customer's segment is selected per transaction.
        severity: { type: string, enum: [low, medium, high, critical] }
        condition_tree:
          type: object
          additionalProperties: true
          description: |
            The tree the rule builder edits, alongside the CEL it emits (ADR-0028). Both are
            stored: the expression is what the engine runs and must not be recompiled from a
            tree on the hot path, and the tree is what an administrator edits and must not be
            guessed at from the text.

            ABSENT is a real state, not a missing value. An expression using a construct the
            tree cannot represent — a macro, a function call, arithmetic nested more than one
            level — has no tree, and the builder declines to open it rather than rendering an
            approximation it would re-emit over the author's rule on save.
        activation_version:
          type: integer
          description: |
            The CEL variable set this expression was compiled against. Activation is refused
            when it does not match the running build, so a change to the field vocabulary is a
            loud failure rather than a silent behaviour change (ADR-0007 § Amendment).
        status:
          type: string
          enum: [draft, pending_approval, simulated, active, retired]
          description: |
            `simulated` is a rule version being evaluated against history without raising
            alerts, which is how a threshold change is assessed before it reaches
            production traffic (ADR-0016).
        inventory_version_id:
          type: string
          format: uuid
          description: Exact immutable inventory pin; absence on legacy history is a visible governance gap.

    RuleVersionDraft:
      type: object
      description: |
        The declarative half of a rule (ADR-0016) plus its predicate. The tenant chooses the
        window and the aggregates from a fixed vocabulary; they never write a query.
      required: [typology, window_hours, window_scope, severity]
      properties:
        typology:
          type: string
          enum: [structuring, rapid_movement, dormant_reactivation, high_risk_corridor, velocity, threshold, custom, counterparty_diversification, corridor_dispersion, round_number_activity, high_risk_customer_volume, bidirectional_low_value_turnover, pos_round_activity, agent_cash_structuring, ussd_mule_fanin, nip_mule_fanout, wallet_pass_through, mobile_fast_turnover, bdc_corridor_layering, fx_counterparty_dispersion, crypto_onramp_turnover, salary_channel_outflow, loan_channel_turnover, npo_small_value_dispersal, domestic_pep_flows, foreign_pep_flows, rca_corridor_flows, trade_corridor_dispersion, imto_recipient_diversity, new_relationship_fanin, dormant_cash_reactivation, low_tier_large_turnover, weekly_credit_acceleration, monthly_credit_acceleration, weekly_debit_acceleration, monthly_debit_acceleration, cash_heavy_turnover, gambling_round_flows, extractive_corridor_flows, legal_entity_fanout, retail_multicorridor, shared_counterparty_collection, shared_phone_accounts, loan_back_relationship, trade_value_mismatch, imto_value_mismatch]
        window_hours:
          type: integer
          minimum: 1
          maximum: 8760
          description: |
            Capped at a year. A window longer than the retention of the transactions it
            aggregates would silently narrow as the oldest rows aged out, which makes a rule
            change behaviour with no change to the rule.
        window_scope: { type: string, enum: [account, party, counterparty] }
        aggregates:
          type: array
          items: { type: string }
        severity: { type: string, enum: [low, medium, high, critical] }
        condition_tree:
          type: object
          additionalProperties: true
          description: What the builder posts. Compiled to CEL deterministically (ADR-0028).
        expression:
          type: string
          description: |
            What an expert posts. Supplying both this and `condition_tree` is allowed and
            checked: a pair that disagree is refused.
        params_key:
          type: string
          enum: [monitoring.thresholds]
        params_segment:
          type: string
          maxLength: 0
          deprecated: true
          description: Must be omitted or empty. The customer's segment is selected per transaction.

    RuleVocabularyField:
      type: object
      description: One thing a monitoring rule may name (ADR-0028).
      required: [path, namespace, name, kind, unit, label, doc, operators]
      properties:
        path:
          type: string
          description: The qualified name as it appears in an expression, e.g. `txn.amount_minor`.
        namespace: { type: string, enum: [txn, agg, customer, profile, peer] }
        name: { type: string }
        kind:
          type: string
          enum: [int, string]
          description: |
            Every count and every money amount is `int`. Money is int64 minor units (ADR-0010);
            there is no float money in this vocabulary and there must never be one.
        unit:
          type: string
          description: |
            What the number means — `minor_units`, `count`, `days`, `iso4217`, `iso3166`,
            `enumeration`, or empty. An amount and a day count are both integers, and confusing
            them is how a seven-day window becomes a seven-kobo threshold.
        label: { type: string }
        doc:
          type: string
          description: What the value means and, where it matters, what it does NOT mean.
        values:
          type: array
          items: { type: string }
          description: |
            The permitted values where the set is closed, so a builder offers a select rather
            than a free-text box a typo can enter. Absent means the set is open.
        operators:
          type: array
          items: { type: string, enum: [eq, ne, gt, gte, lt, lte] }
          description: |
            Ordering comparisons are not offered on string fields. `customer.risk_rating > 'low'`
            compiles in CEL and compares lexicographically, so 'prohibited' sorts below 'low' —
            an ordering that reads like risk severity and is alphabetical.

    RuleVocabularyGroup:
      type: object
      required: [namespace, fields]
      properties:
        namespace: { type: string }
        fields:
          type: array
          items: { $ref: "#/components/schemas/RuleVocabularyField" }

    RuleSimulationHit:
      additionalProperties: false
      properties:
        account_id:
          format: uuid
          type: string
        aggregates:
          additionalProperties: false
          properties:
            credit_count:
              format: int64
              type: integer
            credit_minor:
              format: int64
              type: integer
            currency:
              type: string
            debit_count:
              format: int64
              type: integer
            debit_minor:
              format: int64
              type: integer
            profile:
              $ref: '#/components/schemas/ActivityBaseline'

            peer:
              $ref: '#/components/schemas/ActivityBaseline'
            counterparty_bank: {type: string, description: Bank namespace of a bank-qualified counterparty window.}
            counterparty_source: {type: string, description: Source-local namespace when the bank is unknown; never merged with a known bank or another source.}
            profile_credit:
              $ref: '#/components/schemas/ActivityBaseline'
            peer_credit:
              $ref: '#/components/schemas/ActivityBaseline'
            profile_debit:
              $ref: '#/components/schemas/ActivityBaseline'
            peer_debit:
              $ref: '#/components/schemas/ActivityBaseline'

            cash_minor:
              type: integer
            channel_minor:
              type: integer
            round_amount_count:
              type: integer
            network_neighbour_count: {type: integer, format: int64}
            shared_device_count: {type: integer, format: int64}
            loan_back_minor: {type: integer, format: int64}
            loan_back_count: {type: integer, format: int64}
            trade_value_mismatch_minor: {type: integer, format: int64}
            trade_value_mismatch_count: {type: integer, format: int64}
            imto_value_mismatch_minor: {type: integer, format: int64}
            imto_value_mismatch_count: {type: integer, format: int64}
            business_evidence:
              type: array
              items: { $ref: "#/components/schemas/BusinessEvidenceReference" }
            business_evidence_truncated: {type: boolean}
            shared_phone_account_count: {type: integer, format: int64}
            shared_phone_count: {type: integer, format: int64}
            shared_beneficiary_count: {type: integer, format: int64}
            fan_in_count:
              type: integer
            fan_out_count:
              type: integer
            credit_7d_minor:
              type: integer
            debit_7d_minor:
              type: integer
            credit_30d_minor:
              type: integer
            debit_30d_minor:
              type: integer
            credit_90d_minor:
              type: integer
            debit_90d_minor:
              type: integer
            outflow_bps:
              type: integer
            distinct_corridors:
              format: int64
              type: integer
            distinct_counterparties:
              format: int64
              type: integer
            lifecycle_adjusted_count:
              format: int64
              type: integer
            max_minor:
              format: int64
              type: integer
            raw_sum_minor:
              format: int64
              type: integer
            raw_txn_count:
              format: int64
              type: integer
            sum_minor:
              format: int64
              type: integer
            txn_count:
              format: int64
              type: integer
          required:
          - currency
          - txn_count
          - sum_minor
          - max_minor
          - credit_minor
          - debit_minor
          - credit_count
          - debit_count
          - distinct_counterparties
          - distinct_corridors
          - raw_txn_count
          - raw_sum_minor
          - lifecycle_adjusted_count
          type: object
        amount_minor:
          format: int64
          type: integer
        booking_ts:
          format: date-time
          type: string
        currency:
          type: string
        customer_id:
          format: uuid
          type: string
        geography:
          $ref: '#/components/schemas/GeographyEvidence'
        resolved_params:
          additionalProperties: true
          type: object
        transaction_id:
          format: uuid
          type: string
        window_from:
          format: date-time
          type: string
        window_to:
          format: date-time
          type: string
      required:
      - transaction_id
      - account_id
      - booking_ts
      - amount_minor
      - currency
      - window_from
      - window_to
      - aggregates
      - resolved_params
      type: object
    RuleSimulationSkip:
      additionalProperties: false
      properties:
        reason:
          type: string
        transaction_id:
          format: uuid
          type: string
      required:
      - transaction_id
      - reason
      type: object
    RuleSimulation:
      additionalProperties: false
      properties:
        alerts_would_raise:
          format: int64
          type: integer
        distinct_subjects:
          format: int64
          type: integer
        duration_ms:
          format: int64
          type: integer
        id:
          format: uuid
          type: string
        max_transactions:
          format: int64
          type: integer
        parameter_snapshot:
          additionalProperties:
            additionalProperties: true
            type: object
          type: object
        ran_at:
          format: date-time
          type: string
        rule_key:
          type: string
        rule_version_id:
          format: uuid
          type: string
        safety_metadata_recorded:
          type: boolean
        sample:
          items:
            $ref: '#/components/schemas/RuleSimulationHit'
          type: array
        sample_limit:
          format: int64
          type: integer
        skipped:
          items:
            $ref: '#/components/schemas/RuleSimulationSkip'
          type: array
        skipped_count:
          format: int64
          type: integer
        transactions_scanned:
          format: int64
          type: integer
        truncated:
          type: boolean
        window_from:
          format: date-time
          type: string
        window_to:
          format: date-time
          type: string
      required:
      - id
      - rule_version_id
      - window_from
      - window_to
      - transactions_scanned
      - alerts_would_raise
      - distinct_subjects
      - sample
      - truncated
      - safety_metadata_recorded
      - skipped_count
      - max_transactions
      - sample_limit
      - ran_at
      - duration_ms
      type: object
    InventoryEvidence:
      type: object
      required: [type, reference, digest, validator, produced_at]
      properties:
        type:
          type: string
          enum:
            - independent_validation_report
            - backtesting_results
            - data_quality_assessment
            - model_risk_approval
            - performance_monitoring
        reference:
          type: string
          format: uuid
          pattern: "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
          description: Canonical UUIDv7 of a finalized encrypted validation-evidence artifact.
        digest:
          type: string
          pattern: "^[0-9a-f]{64}$"
          description: SHA-256 digest binding the referenced evidence bytes.
        validator: { type: string, minLength: 1, maxLength: 200 }
        produced_at: { type: string, format: date }

    InventoryMetadata:
      type: object
      required:
        - owner
        - purpose
        - risk_coverage
        - typology_coverage
        - regulatory_rationale
        - data_inputs
        - assumptions
        - features
        - dependencies
        - limitations
        - validation_status
        - activation_policy
        - validation_evidence
        - next_review_date
      properties:
        owner: { type: string, minLength: 1, maxLength: 200 }
        purpose: { type: string, minLength: 1, maxLength: 4000 }
        risk_coverage:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string, enum: [ML, TF, PF] }
        typology_coverage:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string, minLength: 1 }
        regulatory_rationale: { type: string, minLength: 1, maxLength: 8000 }
        data_inputs:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string, minLength: 1 }
        assumptions:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string, minLength: 1 }
        features:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string, minLength: 1 }
        dependencies:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string, minLength: 1 }
        limitations:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string, minLength: 1 }
        validation_status:
          type: string
          enum: [not_validated, in_progress, conditionally_validated, validated, failed]
        activation_policy:
          type: string
          enum: [blocked, controlled_use, production]
          description: |
            `controlled_use` is metadata only because this build has no separate shadow engine.
            `production` requires validated/conditionally-validated status plus exact finalized
            encrypted artifact references whose finalized bytes, audit receipt and digest are
            integrity-authenticated relationally. This does not independently attest the
            validation conclusion. `blocked` cannot deploy.
        validation_evidence:
          type: array
          maxItems: 50
          items: { $ref: "#/components/schemas/InventoryEvidence" }
        next_review_date: { type: string, format: date }

    ValidationEvidenceArtifact:
      type: object
      required: [id, filename, content_type, size_bytes, sha256, handling_method,
        verifier_name, verifier_version, verified_at, uploaded_by, uploaded_at,
        finalized_by, finalized_at]
      properties:
        id:
          type: string
          format: uuid
          description: Caller-owned UUIDv7 idempotency identity.
        filename: { type: string, minLength: 1, maxLength: 255 }
        content_type: { type: string, enum: [application/json, text/plain, application/pdf] }
        size_bytes: { type: integer, format: int64, minimum: 1, maximum: 10485760 }
        sha256: { type: string, pattern: "^[0-9a-f]{64}$" }
        handling_method: { type: string, enum: [structural, malware_scan] }
        verifier_name:
          type: string
          description: Structural validator or malware-scanner engine; not an independent model validator.
        verifier_version: { type: string }
        signature_version: { type: string }
        verified_at: { type: string, format: date-time }
        uploaded_by: { type: string, format: uuid }
        uploaded_at: { type: string, format: date-time }
        finalized_by: { type: string, format: uuid }
        finalized_at: { type: string, format: date-time }

    ValidationEvidenceArtifactPage:
      type: object
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/ValidationEvidenceArtifact" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }

    ValidationEvidenceRecoveryRequest:
      type: object
      additionalProperties: false
      required: [reason]
      properties:
        reason:
          type: string
          minLength: 1
          maxLength: 1000
          description: Operational reason stored in the immutable recovery audit event.

    PendingValidationEvidence:
      type: object
      required: [id, filename, content_type, size_bytes, sha256, handling_method,
        uploaded_by, uploaded_at, pending_seconds, state]
      properties:
        id: { type: string, format: uuid }
        filename: { type: string, minLength: 1, maxLength: 255 }
        content_type: { type: string, enum: [application/json, text/plain, application/pdf] }
        size_bytes: { type: integer, format: int64, minimum: 1, maximum: 10485760 }
        sha256: { type: string, pattern: "^[0-9a-f]{64}$" }
        handling_method: { type: string, enum: [structural, malware_scan] }
        uploaded_by: { type: string, format: uuid }
        uploaded_at: { type: string, format: date-time }
        pending_seconds: { type: integer, format: int64, minimum: 0 }
        state:
          type: string
          enum: [awaiting_object_finalization, awaiting_audit_commit]
          description: Fail-visible stage preventing this intent from being linked to production inventory.

    PendingValidationEvidencePage:
      type: object
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/PendingValidationEvidence" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }

    ModelInventoryVersion:
      type: object
      required:
        - id
        - asset_type
        - asset_key
        - inventory_version
        - artifact_digest
        - evidence_integrity_verified
        - owner
        - purpose
        - risk_coverage
        - typology_coverage
        - regulatory_rationale
        - data_inputs
        - assumptions
        - features
        - dependencies
        - limitations
        - validation_status
        - activation_policy
        - validation_evidence
        - next_review_date
        - approval_source
        - approved_at
        - record_digest
        - created_at
      properties:
        id: { type: string, format: uuid }
        asset_type: { type: string, enum: [monitoring_rule, risk_model, genai_model] }
        asset_key: { type: string }
        inventory_version: { type: integer, minimum: 1 }
        rule_version_id: { type: string, format: uuid }
        artifact_digest: { type: string, pattern: "^[0-9a-f]{64}$" }
        evidence_integrity_verified:
          type: boolean
          description: |
            Server-derived proof that every cited artifact is finalized, authenticated and
            digest-bound. It does not independently attest the validation conclusion.
        parameter_config_digest: { type: string, pattern: "^[0-9a-f]{64}$" }
        parameter_config_source:
          type: string
          enum: [tenant_override, pack_default]
          description: Exact effective parameter source, bound together with its immutable identity and digest.
        parameter_config_document_id: { type: string, format: uuid }
        parameter_config_pack_id:
          type: string
          format: uuid
          description: Exact tenant pack installation supplying the governed default.
        owner: { type: string, minLength: 1, maxLength: 200 }
        purpose: { type: string, minLength: 1, maxLength: 4000 }
        risk_coverage:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string, enum: [ML, TF, PF] }
        typology_coverage:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string, minLength: 1 }
        regulatory_rationale: { type: string, minLength: 1, maxLength: 8000 }
        data_inputs:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string, minLength: 1 }
        assumptions:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string, minLength: 1 }
        features:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string, minLength: 1 }
        dependencies:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string, minLength: 1 }
        limitations:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string, minLength: 1 }
        validation_status:
          type: string
          enum: [not_validated, in_progress, conditionally_validated, validated, failed]
        activation_policy:
          type: string
          enum: [blocked, controlled_use, production]
        validation_evidence:
          type: array
          maxItems: 50
          items: { $ref: "#/components/schemas/InventoryEvidence" }
        next_review_date: { type: string, format: date }
        approval_source: { type: string, enum: [workflow, content_pack] }
        approval_request_id: { type: string, format: uuid }
        source_pack_id: { type: string, format: uuid }
        proposed_by: { type: string, format: uuid }
        approved_by: { type: string, format: uuid }
        approved_at: { type: string, format: date-time }
        record_digest: { type: string, pattern: "^[0-9a-f]{64}$" }
        created_at: { type: string, format: date-time }

    ModelInventoryCoverage:
      type: object
      required: [asset_type, asset_key, deployed_version, state]
      properties:
        asset_type: { type: string, enum: [monitoring_rule, risk_model, genai_model] }
        asset_key: { type: string }
        deployed_version: { type: integer, minimum: 1 }
        inventory: { $ref: "#/components/schemas/ModelInventoryVersion" }
        state: { type: string, enum: [current, due_soon, stale, failed, drifted, evidence_integrity_unverified, missing] }
        days_until_review: { type: integer }

    ModelInventoryResponse:
      type: object
      required: [items, coverage, deployments, history_limit, validation_policy]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/ModelInventoryVersion" }
        coverage:
          type: array
          items: { $ref: "#/components/schemas/ModelInventoryCoverage" }
        deployments:
          type: array
          items: { $ref: "#/components/schemas/ModelInventoryDeployment" }
        history_limit: { type: integer, enum: [50] }
        inventory_next_cursor: { $ref: "#/components/schemas/NextCursor" }
        deployment_next_cursor: { $ref: "#/components/schemas/NextCursor" }
        coverage_next_cursor: { $ref: "#/components/schemas/NextCursor" }
        validation_policy:
          type: object
          additionalProperties: { type: string }

    ModelInventoryProposal:
      type: object
      required: [asset_type, asset_key, inventory, reason]
      properties:
        asset_type: { type: string, enum: [monitoring_rule, risk_model, genai_model] }
        asset_key: { type: string }
        rule_version_id: { type: string, format: uuid }
        artifact_digest:
          type: string
          readOnly: true
          pattern: "^[0-9a-f]{64}$"
          description: Server-populated exact executable digest persisted in the approval payload.
        parameter_config_digest:
          type: string
          readOnly: true
          pattern: "^[0-9a-f]{64}$"
          description: Server-populated effective or pending parameter-document digest.
        parameter_config_source:
          type: string
          readOnly: true
          enum: [tenant_override, pack_default]
          description: Server-populated exact parameter source kind persisted in the approval payload.
        parameter_config_document_id:
          type: string
          format: uuid
          description: Optional pending monitoring.thresholds document this inventory anticipates.
        parameter_config_pack_id:
          type: string
          format: uuid
          readOnly: true
          description: Server-populated tenant pack installation id when the effective source is a pack default.
        genai_model_definition: { $ref: "#/components/schemas/GenAIModelDefinition" }
        risk_model_definition:
          type: object
          additionalProperties: true
        inventory: { $ref: "#/components/schemas/InventoryMetadata" }
        reason: { type: string, minLength: 1 }

    ModelInventoryDeployment:
      type: object
      required: [id, event_type, deployed_asset_version,
        change_approval_request_id, deployed_by, deployed_at]
      properties:
        id: { type: string, format: uuid }
        inventory_version_id: { type: string, format: uuid }
        rule_version_id: { type: string, format: uuid }
        risk_model_version_id: { type: string, format: uuid }
        event_type:
          type: string
          enum: [activated, deactivated, inventory_attached, legacy_gap_closed]
          description: |
            `inventory_attached` remediates a legacy active artifact whose original activation
            time is unknown; it never rewrites that history as if activation happened now.
            `legacy_gap_closed` records an unpinned pre-inventory active artifact leaving
            service under an exact governed change; `inventory_version_id` is intentionally
            absent and no original activation time or inventory identity is invented.
        deployed_asset_version: { type: integer, minimum: 1 }
        engine_activation_version: { type: integer, minimum: 1 }
        parameter_config_digest: { type: string, pattern: "^[0-9a-f]{64}$" }
        parameter_config_source: { type: string, enum: [tenant_override, pack_default] }
        parameter_config_document_id: { type: string, format: uuid }
        parameter_config_pack_id: { type: string, format: uuid }
        change_approval_request_id: { type: string, format: uuid }
        deployed_by: { type: string, format: uuid }
        deployed_at: { type: string, format: date-time }

    ModelInventoryVersionPage:
      type: object
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/ModelInventoryVersion" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    RuleInventoryCandidate:
      type: object
      required: [rule_version_id, asset_key, rule_name, version, status, created_at]
      properties:
        rule_version_id: { type: string, format: uuid }
        asset_key: { type: string }
        rule_name: { type: string }
        version: { type: integer, minimum: 1 }
        status: { type: string, enum: [draft, pending_approval, simulated, active, retired] }
        created_at: { type: string, format: date-time }

    RuleInventoryCandidatePage:
      type: object
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/RuleInventoryCandidate" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    ModelInventoryDeploymentPage:
      type: object
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/ModelInventoryDeployment" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    ModelInventoryCoveragePage:
      type: object
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/ModelInventoryCoverage" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    RiskModel:
      type: object
      description: |
        An activated risk-scoring model version, as it was snapshotted at activation. Not as
        configuration reads today: an assessment pins the version it was scored under.
      required: [id, version, status, definition, activated_at]
      properties:
        id: { type: string, format: uuid }
        version: { type: integer }
        status: { type: string, enum: [active, superseded] }
        definition:
          type: object
          additionalProperties: true
        activated_at: { type: string, format: date-time }
        inventory_version_id:
          type: string
          format: uuid
          description: Exact immutable inventory pin; absence identifies a legacy governance gap.

    Alert:
      type: object
      required: [id, correlation_key, group_count, rule_version_id, rule_key, typology, severity, score, priority, status, opened_at]
      properties:
        id: { type: string, format: uuid }
        correlation_key:
          type: string
          description: |
            The de-duplication key. A repeat of the same behaviour joins the existing group
            rather than creating a second alert, which is what keeps a queue triageable
            (ADR-0017).
        group_id: { type: string, format: uuid }
        group_count: { type: integer, description: How many alerts share this correlation key. A duplicate never vanishes; it increments this. }
        rule_version_id: { type: string, format: uuid }
        rule_key: { type: string }
        typology: { type: string }
        subject_party_id: { type: string, format: uuid }
        subject_name: { type: string }
        subject_account_id: { type: string, format: uuid }
        subject_customer_id: { type: string, format: uuid }
        severity: { type: string, enum: [low, medium, high, critical] }
        score: { type: number }
        priority: { type: string, enum: [p1, p2, p3, p4] }
        status: { type: string, enum: [open, assigned, in_review, escalated, closed_false_positive, closed_actioned, merged] }
        assignee_id: { type: string, format: uuid }
        sla_due_at: { type: string, format: date-time }
        case_id: { type: string, format: uuid }
        opened_at: { type: string, format: date-time }
        closed_at: { type: string, format: date-time }
        close_reason: { type: string }

    AlertPage:
      type: object
      description: |
        The triage queue, one row per correlation group (ADR-0017). Resumable, keyed on
        (priority rank, opened_at, id) — the same three keys the ordering uses, in the same
        directions.

        One property of the grouping, stated because a client walking the queue will meet it:
        a new alert joining an EXISTING group can change that group's representative and so its
        position in the ordering. A brand new group is placed correctly. That is the cost of
        collapsing 47 occurrences into one row, not a defect in the cursor.
      required: [items, total_count, backlog]
      properties:
        total_count:
          type: integer
          format: int64
          minimum: 0
          description: Exact matching total before the cursor, from the same database snapshot
            as the page.
        backlog:
          type: object
          required:
          - total
          - overdue
          - unassigned
          - escalated
          properties:
            total:
              type: integer
              format: int64
              minimum: 0
            overdue:
              type: integer
              format: int64
              minimum: 0
            unassigned:
              type: integer
              format: int64
              minimum: 0
            escalated:
              type: integer
              format: int64
              minimum: 0
        items:
          type: array
          items: { $ref: "#/components/schemas/Alert" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    EvaluationTrace:
      type: object
      required: [alert_id, rule_version, expression, resolved_params, window_from, window_to, window_scope, aggregates, evaluated_at]
      properties:
        alert_id: { type: string, format: uuid }
        rule_version: { type: integer }
        expression: { type: string }
        resolved_params:
          type: object
          additionalProperties: true
          description: |
            The parameter values as they stood at evaluation time. Recorded rather than
            looked up, because the thresholds will have been retuned by the time anyone
            asks why this alert fired.
        window_from: { type: string, format: date-time }
        window_to: { type: string, format: date-time }
        window_scope: { type: string }
        aggregates:
          type: object
          additionalProperties: true
        activation:
          type: object
          additionalProperties: true
          description: The complete variable binding the predicate saw, so the evaluation can be replayed exactly.
        evaluated_at: { type: string, format: date-time }

    Transaction:
      type: object
      required: [id, booking_ts, account_id, external_ref, direction, amount_minor, currency, channel, event_type]
      properties:
        id: { type: string, format: uuid }
        booking_ts: { type: string, format: date-time }
        account_id: { type: string, format: uuid }
        external_ref: { type: string }
        direction: { type: string, enum: [credit, debit] }
        amount_minor:
          type: integer
          format: int64
          description: |
            Minor units. Always an integer, never a decimal string and never a float:
            ₦4,400,000.00 is 440000000, and no arithmetic in this system ever sees a float.
        currency: { type: string, minLength: 3, maxLength: 3 }
        channel: { type: string }
        counterparty_name: { type: string }
        counterparty_account: { type: string }
        corridor_country: { type: string, minLength: 2, maxLength: 2 }
        narrative: { type: string }
        event_type:
          type: string
          enum: [posted, reversal, correction, cancellation, chargeback]
          description: "`posted` for an ordinary transaction, otherwise the immutable lifecycle event type."
        original_transaction_id:
          type: string
          format: uuid
          description: Exact predecessor UUID; present for every non-posted event.
        original_booking_ts:
          type: string
          format: date-time
          description: Exact predecessor partition key; present for every non-posted event.
        lifecycle_reason:
          type: string
          maxLength: 500
        lifecycle_recorded_at:
          type: string
          format: date-time
          description: Server-owned arrival time, preserving evidence of late-arriving events.
        ctr_disposition:
          type: string
          enum: [no_report_impact, new_report_required, amendment_required, withdrawal_review_required, cancellation_review_required]
          description: Actionable automatic-CTR impact for a lifecycle event; never a delivery claim.
        affected_report_id:
          type: string
          format: uuid
          description: Immutable prior automatic CTR requiring review, amendment, withdrawal or cancellation handling.
        resulting_report_id:
          type: string
          format: uuid
          description: New correction-derived draft/validation-failed CTR, when the effective corrected amount is reportable.
        screened_at: { type: string, format: date-time }
        counterparty_screening:
          $ref: "#/components/schemas/CounterpartyScreening"

    CounterpartyScreening:
      type: object
      description: |
        Immutable transaction-ingest disposition. `completed` pins the screening request and
        hit count; `not_applicable` explicitly records that no counterparty name was supplied.
        Absence means the transaction predates migration 00034 and is unavailable coverage,
        never a zero-hit result.
      required: [status, hit_count]
      properties:
        status: { type: string, enum: [completed, not_applicable] }
        request_id: { type: string, format: uuid }
        hit_count: { type: integer, minimum: 0 }
        reason: { type: string, enum: [counterparty_name_absent] }

    Case:
      type: object
      required: [id, reference, title, status, priority, opened_at]
      properties:
        id: { type: string, format: uuid }
        reference: { type: string, examples: [CASE-2026-0001] }
        title: { type: string }
        summary: { type: string }
        subject_party_id: { type: string, format: uuid }
        subject_customer_id: { type: string, format: uuid }
        subject_name: { type: string }
        status: { type: string, enum: [open, investigating, pending_approval, closed_no_action, closed_reported, reopened] }
        priority: { type: string, enum: [p1, p2, p3, p4] }
        assignee_id: { type: string, format: uuid }
        sla_due_at: { type: string, format: date-time }
        opened_at: { type: string, format: date-time }
        opened_by: { type: string, format: uuid }
        closed_at: { type: string, format: date-time }
        closed_by: { type: string, format: uuid }
        approved_by:
          type: string
          format: uuid
          description: Always different from `closed_by`. A database CHECK enforces it.
        outcome: { type: string, enum: [false_positive, no_suspicion, str_filed, ctr_filed, escalated_externally, customer_exited] }

    CaseSummary:
      type: object
      additionalProperties: false
      description: |
        Metadata-only caseload-register row. It intentionally cannot carry a title, summary,
        subject/customer identifier or name, outcome, assignee, or any actor id. Fetching the
        investigation workspace requires `cases.case_content.read`.
      required: [id, reference, status, priority, opened_at]
      properties:
        id: { type: string, format: uuid }
        reference: { type: string, examples: [CASE-2026-0001] }
        status: { type: string, enum: [open, investigating, pending_approval, closed_no_action, closed_reported, reopened] }
        priority: { type: string, enum: [p1, p2, p3, p4] }
        sla_due_at: { type: string, format: date-time }
        opened_at: { type: string, format: date-time }
        closed_at: { type: string, format: date-time }

    CasePage:
      type: object
      description: |
        Metadata-safe investigation register, highest priority first. Resumable, keyed on
        (priority rank, opened_at, id). Rich case content is never embedded in this envelope.
      required: [items, total_count]
      properties:
        total_count:
          type: integer
          format: int64
          minimum: 0
          description: Exact matching total before the cursor, from the same database snapshot
            as the page.
        items:
          type: array
          items: { $ref: "#/components/schemas/CaseSummary" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    LinkedAlert:
      type: object
      required: [id, rule_key, typology, severity, score, priority, status, opened_at]
      properties:
        id: { type: string, format: uuid }
        rule_key: { type: string }
        typology: { type: string }
        severity: { type: string }
        score: { type: number }
        priority: { type: string }
        status: { type: string }
        opened_at: { type: string, format: date-time }

    CaseNote:
      type: object
      required: [id, body, author_id, created_at]
      properties:
        id: { type: string, format: uuid }
        body:
          type: string
          description: |
            Encrypted at rest under the subject's key, because notes routinely quote
            identity data. Append-only: a note that can be edited afterwards is not
            evidence of anything.
        author_id: { type: string, format: uuid }
        created_at: { type: string, format: date-time }

    CaseEvent:
      type: object
      required: [id, kind, occurred_at]
      properties:
        id: { type: string, format: uuid }
        kind: { type: string }
        detail: {}
        actor_id: { type: string, format: uuid }
        occurred_at: { type: string, format: date-time }

    CaseAttachment:
      type: object
      required: [id, case_id, filename, content_type, size_bytes, sha256, uploaded_at]
      properties:
        id: { type: string, format: uuid }
        case_id: { type: string, format: uuid }
        filename:
          type: string
          description: Decrypted display name. The object store never receives it.
        content_type: { type: string, enum: [application/pdf, image/jpeg, image/png, text/plain] }
        size_bytes: { type: integer, format: int64, minimum: 1, maximum: 20971520 }
        sha256: { type: string, pattern: "^[a-f0-9]{64}$" }
        uploaded_by: { type: string, format: uuid }
        uploaded_at: { type: string, format: date-time }

    CaseLinkedAlertPage:
      type: object
      description: |
        Immutable case-linked alert provenance, newest UUIDv7 link first. At most 200 rows;
        overflow is explicit and cannot be resumed through this endpoint.
      required: [items]
      properties:
        items:
          type: array
          maxItems: 200
          items: { $ref: "#/components/schemas/LinkedAlert" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }

    CaseLinkedScreeningHitPage:
      type: object
      description: |
        Immutable case-linked screening provenance, newest UUIDv7 link first. At most 200
        rows; overflow is explicit and cannot be resumed through this endpoint.
      required: [items]
      properties:
        items:
          type: array
          maxItems: 200
          items: { $ref: "#/components/schemas/ScreeningHit" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }

    CaseAttachmentPage:
      type: object
      description: |
        Decrypted metadata for immutable attachments, newest first. At most 200 rows; overflow
        is explicit and cannot be resumed through this endpoint.
      required: [items]
      properties:
        items:
          type: array
          maxItems: 200
          items: { $ref: "#/components/schemas/CaseAttachment" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }

    CaseAssignment:
      type: object
      required: [case_id, case_status]
      properties:
        case_id: { type: string, format: uuid }
        queue_id: { type: string, format: uuid }
        queue_name: { type: string }
        org_unit_id: { type: string, format: uuid }
        assignee_id: { type: string, format: uuid }
        case_status: { type: string, enum: [open, investigating, pending_approval, closed_no_action, closed_reported, reopened] }

    CaseQueueInput:
      type: object
      required: [name, org_unit_id, eligible_role_keys, priorities]
      properties:
        name: { type: string, minLength: 1, maxLength: 120 }
        org_unit_id: { type: string, format: uuid }
        eligible_role_keys:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string, pattern: "^[a-z][a-z0-9_]{1,63}$" }
        priorities:
          type: array
          uniqueItems: true
          items: { type: string, enum: [p1, p2, p3, p4] }

    CaseQueue:
      type: object
      required: [id, name, org_unit_id, eligible_role_keys, priorities, state, created_by, updated_by, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        name: { type: string, minLength: 1, maxLength: 120 }
        org_unit_id: { type: string, format: uuid }
        eligible_role_keys:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string, pattern: "^[a-z][a-z0-9_]{1,63}$" }
        priorities:
          type: array
          uniqueItems: true
          items: { type: string, enum: [p1, p2, p3, p4] }
        state: { type: string, enum: [active, retired] }
        created_by: { type: string, format: uuid }
        updated_by: { type: string, format: uuid }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        retired_at: { type: string, format: date-time }

    EligibleCaseAssignee:
      type: object
      required: [id, display_name]
      properties:
        id: { type: string, format: uuid }
        display_name: { type: string }

    CaseTransactionEvidence:
      type: object
      required: [transaction, source_alert_ids, screening_coverage]
      properties:
        transaction: { $ref: "#/components/schemas/Transaction" }
        source_alert_ids:
          type: array
          minItems: 1
          uniqueItems: true
          items: { type: string, format: uuid }
        screening_coverage:
          type: string
          enum: [available, unavailable_pre_counterparty_linkage]
        counterparty_screening: { $ref: "#/components/schemas/CounterpartyScreening" }

    CaseTransactionHistory:
      type: object
      description: |
        Alert-linked transactions deduplicated by immutable transaction id and booking time.
        This filing-provenance view deliberately stops at 200 distinct transactions;
        `truncated`, `source_alerts_evaluated` and `source_alerts_truncated` make both bounds
        explicit. Traverse
        `subject_transaction_history` for resumable subject activity within its echoed
        half-open window when account fan-out is within that endpoint's declared boundary.
      required: [items, source_alerts_evaluated, source_alerts_truncated, truncated]
      properties:
        items:
          type: array
          maxItems: 200
          items: { $ref: "#/components/schemas/CaseTransactionEvidence" }
        source_alerts_evaluated: { type: integer, minimum: 0, maximum: 200 }
        source_alerts_truncated:
          type: boolean
          description: True when the case links more alerts than the bounded evidence query evaluated.
        truncated: { type: boolean }

    SubjectAlertHistory:
      type: object
      description: |
        Every individual current and prior alert for the canonical case party, not the
        correlation-group representative used by the triage queue. Newest first by
        `(opened_at,id)` and independently resumable through `subject_alerts_cursor`.
      required: [items, coverage, limit, truncated]
      properties:
        items:
          type: array
          maxItems: 200
          items: { $ref: "#/components/schemas/Alert" }
        coverage: { type: string, enum: [available, unavailable_no_subject] }
        limit: { type: integer, minimum: 1, maximum: 200 }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated:
          type: boolean
          description: Retained for compatibility; resumable pages issue `next_cursor` instead.

    SubjectTransactionEvidence:
      type: object
      required: [transaction, screening_coverage]
      properties:
        transaction: { $ref: "#/components/schemas/Transaction" }
        screening_coverage:
          type: string
          enum: [available, unavailable_pre_counterparty_linkage]
        counterparty_screening: { $ref: "#/components/schemas/CounterpartyScreening" }

    SubjectTransactionHistory:
      type: object
      description: |
        Activity across every account belonging to the canonical customer, in the half-open
        `[from,to)` window, newest first by `(booking_ts,id)`. `account_count` and coverage
        distinguish no customer relationship, no accounts and no activity. Counterparty
        screening is joined in this one page query; missing legacy linkage is unavailable
        coverage, never an inferred zero. Resume with `subject_transactions_cursor` while
        resubmitting the exact echoed `from` and `to` instants. The synchronous k-way merge
        reads at most 200 accounts. More accounts returns `unavailable_account_limit`, an empty
        item set and `account_count_truncated: true`, never partial activity.
      required: [items, coverage, from, to, account_count, account_count_truncated, limit, truncated]
      properties:
        items:
          type: array
          maxItems: 200
          items: { $ref: "#/components/schemas/SubjectTransactionEvidence" }
        coverage:
          type: string
          enum: [available, available_no_accounts, unavailable_no_subject, unavailable_no_customer_relationship, unavailable_account_limit]
        from: { type: string, format: date-time }
        to: { type: string, format: date-time }
        account_count: { type: integer, minimum: 0, maximum: 200 }
        account_count_truncated:
          type: boolean
          description: True means at least 201 accounts exist and no partial activity was returned.
        limit: { type: integer, minimum: 1, maximum: 200 }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated:
          type: boolean
          description: Retained for compatibility; resumable pages issue `next_cursor` instead.

    SubjectScreeningRunHistory:
      type: object
      description: |
        Includes zero-hit runs, which cannot be reconstructed from hit rows. Newest first by
        `(requested_at,id)` and independently resumable through `subject_screening_runs_cursor`.
      required: [items, coverage, limit, truncated]
      properties:
        items:
          type: array
          maxItems: 200
          items: { $ref: "#/components/schemas/ScreeningRun" }
        coverage: { type: string, enum: [available, unavailable_no_subject] }
        limit: { type: integer, minimum: 1, maximum: 200 }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated:
          type: boolean
          description: Retained for compatibility; resumable pages issue `next_cursor` instead.

    SubjectScreeningHitHistory:
      type: object
      description: |
        All prior hit dispositions for the subject, including pending, confirmed, cleared and
        suppressed. Newest first by `(created_at,id)` and independently resumable through
        `subject_screening_hits_cursor`.
      required: [items, coverage, limit, truncated]
      properties:
        items:
          type: array
          maxItems: 200
          items: { $ref: "#/components/schemas/ScreeningHit" }
        coverage: { type: string, enum: [available, unavailable_no_subject] }
        limit: { type: integer, minimum: 1, maximum: 200 }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated:
          type: boolean
          description: Retained for compatibility; resumable pages issue `next_cursor` instead.

    SubjectScreeningHistory:
      type: object
      required: [runs, hits]
      properties:
        runs: { $ref: "#/components/schemas/SubjectScreeningRunHistory" }
        hits: { $ref: "#/components/schemas/SubjectScreeningHitHistory" }

    CaseDetail:
      type: object
      description: |
        The case workspace. Every child collection has an envelope. Notes, events and subject
        histories are independently cursor-resumable. Immutable linked alerts, screening hits
        and attachments are hard-capped at 200 with explicit truncation; their index-bounded
        reads never scan/materialise an unbounded case and never present a slice as complete.

        Every bounded child is independently resumable through its own prefixed cursor:
        `notes_cursor`, `events_cursor`, `subject_alerts_cursor`,
        `subject_transactions_cursor`, `subject_screening_runs_cursor` and
        `subject_screening_hits_cursor`. A single `cursor` would apply one collection's sort
        key to a different collection and return plausible but wrong evidence.
      required: [case, alerts, screening_hits, events, notes, assignment]
      properties:
        case: { $ref: "#/components/schemas/Case" }
        alerts: { $ref: "#/components/schemas/CaseLinkedAlertPage" }
        events: { $ref: "#/components/schemas/CaseEventPage" }
        notes: { $ref: "#/components/schemas/CaseNotePage" }
        assignment: { $ref: "#/components/schemas/CaseAssignment" }
        attachments:
          allOf:
            - { $ref: "#/components/schemas/CaseAttachmentPage" }
          description: |
            Present only with `cases.evidence.read`; absence means the caller was not granted
            access, not that the case has no attachments.
        transactions:
          allOf:
            - { $ref: "#/components/schemas/CaseTransactionHistory" }
          description: |
            Present only with `cases.evidence.read`. Counterparty screening coverage is explicit
            so pre-linkage history never becomes a misleading zero-hit result.
        subject_alert_history:
          allOf:
            - { $ref: "#/components/schemas/SubjectAlertHistory" }
          description: |
            Present only with `monitoring.alert.read`; absence is a permission refusal, not an
            empty history. Separate from `alerts`, which is the case-linked evidence set.
        subject_transaction_history:
          allOf:
            - { $ref: "#/components/schemas/SubjectTransactionHistory" }
          description: |
            Present only with `cases.evidence.read`; absence is a permission refusal. Separate
            from `transactions`, which contains only alert-linked filing provenance.
        subject_screening_history:
          allOf:
            - { $ref: "#/components/schemas/SubjectScreeningHistory" }
          description: |
            Present only with `screening.hit.read`; absence is a permission refusal. Run and
            hit histories have independent cursors so zero-hit screening and prior disposition
            outcomes are both reconstructable.
        screening_hits:
          allOf:
            - { $ref: "#/components/schemas/CaseLinkedScreeningHitPage" }
          description: |
            Screening hits explicitly linked to this case as filing provenance. The bounded
            envelope is always present; when `screening.hit.read` or
            `onboarding.customer.read` is absent, sensitive hit/subject fields are blanked while
            the existence and decision shape remain visible. Broader party screening belongs in
            `subject_screening_history`, whose permission/coverage semantics are independent.

    PermissionPage:
      type: object
      description: "The permission catalogue, complete: it is delivered by content pack and bounded by the code that enforces it."
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/Permission" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    RolePage:
      type: object
      description: "A tenant's roles, complete."
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/Role" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    ConfigSchemaPage:
      type: object
      description: "The configurable surface, complete: whatever the installed packs register."
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/ConfigSchema" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    ConfigDocumentPage:
      type: object
      description: |
        Version history for one configuration key. Resumable, keyed on the version number
        alone: UNIQUE (tenant_id, key, version) makes it a total order, so this is the one
        collection in the API whose cursor carries no id tiebreaker.
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/ConfigDocument" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    ApprovalRequestPage:
      type: object
      description: |
        Approval requests, newest first. Resumable, keyed on (proposed_at, id). The id half is
        load-bearing: a content-pack install proposes many requests in one transaction under a
        single now(), so proposed_at alone names no position.
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/ApprovalRequest" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    ContentPackPage:
      type: object
      description: "Imported content packs, complete."
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/ContentPack" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    PackInstallationPage:
      type: object
      description: "This tenant's installation history, complete — a truncated history proves nothing about which regulatory content was in force when."
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/PackInstallation" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    CustomerPage:
      type: object
      description: "The customer book. Resumable: the cursor is the last customer id on the page."
      required: [items, total_count]
      properties:
        total_count:
          type: integer
          format: int64
          minimum: 0
          description: Exact matching total before the cursor, from the same database snapshot
            as the page.
        items:
          type: array
          items: { $ref: "#/components/schemas/Customer" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    ScreeningHitPage:
      type: object
      description: |
        Screening hits, newest first. Resumable, keyed on (created_at, id). A batch screening
        run writes every hit in one transaction, so created_at is shared across them and the id
        tiebreaker is what orders the page.
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/ScreeningHit" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    RiskAssessmentPage:
      type: object
      description: |
        One party's rating history, newest first. Resumable, keyed on (assessed_at, id): a
        periodic re-score can run over a whole book in one transaction, so assessed_at is
        shared across every assessment it writes and the id tiebreaker is what orders the page.
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/RiskAssessment" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    ReportPage:
      type: object
      description: |
        The filing register, newest first. Resumable, keyed on (generated_at, id). This is the
        metadata-safe collection an examiner or executive reads end to end, so a page boundary
        that silently ended the list would be the most consequential truncation in the API.
        Rich filing content is never embedded in this envelope.
      required: [items, total_count]
      properties:
        total_count:
          type: integer
          format: int64
          minimum: 0
          description: Exact matching total before the cursor, from the same database snapshot
            as the page.
        items:
          type: array
          items: { $ref: "#/components/schemas/ReportSummary" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    CTRLifecycleReviewPage:
      type: object
      description: |
        Immutable automatic-CTR lifecycle effects, newest first and resumable on
        (recorded_at, transaction_id). This is a review queue, not a resolution ledger.
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/CTRLifecycleReviewRecord" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    RulePage:
      type: object
      description: "The monitoring rule library, complete."
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/Rule" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    RuleVersionPage:
      type: object
      description: "The rule versions in force, complete."
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/RuleVersion" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    CaseEventPage:
      type: object
      description: "A case's timeline, 50 per page by default. Resumable with `events_cursor` on GET /v1/cases/{caseID}, keyed on (occurred_at, id)."
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/CaseEvent" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    CaseNotePage:
      type: object
      description: "A case's notes, 50 per page by default. Resumable with `notes_cursor` on GET /v1/cases/{caseID}, keyed on (created_at, id)."
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/CaseNote" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    TransactionIngestResult:
      type: object
      description: |
        The outcome of a real-time ingest. Deliberately NOT a payment decision: there is no
        `decision` field, because the per-tenant fail-open / fail-closed policy and timeout of
        open question Q7 are not built, and an endpoint that answered `allow` would imply a
        policy nobody has signed.
      required: [external_ref, source, duplicate, evaluated, alerts, alerts_raised, latency_ms]
      properties:
        transaction:
          description: |
            The stored transaction. Absent on a replay: the conflicting insert returns no row,
            so the service cannot hand back what is already stored without a second query it
            does not make. Absent is honest; a nil identifier would not be.
          $ref: "#/components/schemas/Transaction"
        external_ref: { type: string }
        source: { type: string }
        duplicate:
          type: boolean
          description: |
            True when this exact (source, external_ref, booking_ts) was already stored, so
            nothing was written and no rules were re-run. A success, not an error — a retrying
            rail must be able to tell "already have it" from "rejected".
        evaluated:
          type: boolean
          description: |
            False on a replay. A rule that did not run is not a rule that ran and found
            nothing, and the difference is what an examiner asks about.
        alerts:
          type: array
          items: { $ref: "#/components/schemas/Alert" }
        alerts_raised: { type: integer }
        latency_ms:
          type: integer
          format: int64
          description: |
            Server-side handling time for this request. Returned because BRD §9's sub-2-second
            budget is only meaningful if the caller can see it being met, and because a rail
            deciding whether to keep calling needs its own evidence.

    IngestBatchResult:
      type: object
      description: |
        The per-file reconciliation record of ADR-0014 — the proof an operations team can
        query that an export was consumed exactly once, including its exact digest and durable
        chunk progress.
      required: [batch_id, source, status, records_received, records_inserted, records_duplicate,
                 records_quarantined, alerts_raised, duration_ms, skipped_rules, processing_mode,
                 chunk_size, chunks_committed, file_bytes, atomic, resumable]
      properties:
        batch_id: { type: string, format: uuid }
        source: { type: string }
        filename: { type: string }
        file_sha256:
          type: string
          pattern: "^[0-9a-f]{64}$"
          description: SHA-256 of the exact complete upload bytes.
        file_bytes: { type: integer, format: int64, minimum: 0 }
        processing_mode: { type: string, enum: [chunked] }
        chunk_size: { type: integer, minimum: 1 }
        chunks_committed:
          type: integer
          format: int64
          minimum: 0
          description: Data/quarantine chunks committed together with their progress counters.
        status:
          type: string
          description: |
            `completed`, `partial` or `failed`. `partial` means every row was handled but
            something was quarantined or a rule could not be evaluated — a file whose records
            all ingested but against which a rule never ran is not a completed monitoring run,
            and calling it one is how a blind spot stays invisible.

            Not declared as an enum here, and that is a gap rather than a style: the values are
            governed by a CHECK on app.ingest_batch.status, and binding a spec enum to a
            constraint requires an entry in the integration suite's binding table, which this
            change could not add. Documented so the next person adds the binding rather than
            inventing values.
        records_received: { type: integer, format: int64 }
        records_inserted: { type: integer, format: int64 }
        records_duplicate:
          type: integer
          format: int64
          description: Rows that conflicted on their idempotency identity. A re-sent export is all duplicates.
        records_quarantined:
          type: integer
          format: int64
          description: |
            Rows held with their line number and parse error rather than dropped or made
            fatal. A file with 40,000 good rows and 3 bad ones ingests 40,000 and reports 3.
        alerts_raised: { type: integer, format: int64 }
        duration_ms: { type: integer, format: int64 }
        skipped_rules:
          type: array
          description: |
            Rules that could not be evaluated, and why — "412 records were not evaluated by the
            structuring rule because they are in USD and your thresholds are in NGN". A rule
            that did not run is not a rule that found nothing.
          items:
            type: object
            required: [rule_key, reason, records]
            properties:
              rule_key: { type: string }
              reason: { type: string }
              records: { type: integer, format: int64 }
        atomic:
          type: boolean
          description: |
            Always false for this endpoint. Each bounded chunk and its reconciliation counters
            share a commit boundary; earlier chunks remain durable if a later one fails.
        resumable:
          type: boolean
          description: |
            Always true for replay-based recovery. Re-send the same bytes with the same source:
            committed rows deduplicate and processing continues into the uncommitted suffix.
            This does not mean an HTTP upload can restart at an arbitrary byte offset.
        notes:
          type: array
          items: { type: string }
          description: Addressed to the operator reading this response, not to a developer.

    ValidationResult:
      type: object
      required: [valid, validator, validator_version, schema_language, document_sha256, proof_sha256]
      properties:
        valid: { type: boolean }
        errors:
          type: array
          items: { type: string }
        validator:
          type: string
          description: |
            What actually checked the document. `structural-not-xsd` means well-formedness,
            required-field and unknown-element checks only — not schema validation. It says
            so in every response precisely so nobody can mistake one for the other (Q17).
        validator_version: { type: string }
        schema_language: { type: string, enum: [none, xsd] }
        schema_language_version:
          type: string
          description: Empty for structural-only placeholders; `1.0` for the installed XSD engine.
        schema_sha256:
          type: string
          pattern: "^[a-f0-9]{64}$"
          description: Digest of the exact XSD bytes; absent for structural-only placeholders.
        document_sha256: { type: string, pattern: "^[a-f0-9]{64}$" }
        proof_sha256:
          type: string
          pattern: "^[a-f0-9]{64}$"
          description: Binds schema digest, document digest, validator identity/language and outcome.

    ReportSchema:
      type: object
      required: [kind, schema_version, format, authoritative, source, notes,
                 schema_language, schema_language_version, validator, validator_version]
      properties:
        kind: { type: string, enum: [STR, CTR, SCUML, CBN_RETURN, BOARD] }
        schema_version: { type: string, minLength: 1 }
        format: { type: string, enum: [xml, csv, json, pdf] }
        authoritative:
          type: boolean
          description: True only when the exact XSD compiled under the recorded real validator.
        source: { type: string }
        notes: { type: string }
        schema_language: { type: string, enum: [none, xsd] }
        schema_language_version: { type: string }
        schema_sha256: { type: string, pattern: "^[a-f0-9]{64}$" }
        validator: { type: string }
        validator_version: { type: string }

    ReportSchemaPage:
      type: object
      description: Installed regulatory schema descriptors, complete for the requested page.
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/ReportSchema" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    FieldTrace:
      type: object
      required: [target, expression, value, required]
      properties:
        target: { type: string, description: The element path in the rendered document. }
        expression: { type: string, description: The CEL expression over the canonical model that produced it. }
        value: { type: string }
        required: { type: boolean }

    FilingDeadline:
      type: object
      required: [id, kind, due_at, status, created_at]
      properties:
        id: { type: string, format: uuid }
        kind: { type: string, enum: [STR, CTR, SCUML, CBN_RETURN, BOARD] }
        report_id: { type: string, format: uuid }
        case_id: { type: string, format: uuid }
        due_at: { type: string, format: date-time }
        status: { type: string, enum: [pending, met, breached, waived] }
        met_at: { type: string, format: date-time }
        created_at: { type: string, format: date-time }

    ExternalSubmissionInput:
      type: object
      additionalProperties: false
      required: [external_reference, filed_at]
      properties:
        external_reference:
          type: string
          minLength: 1
          maxLength: 256
          description: |
            A reference actually obtained from the authorised external filing channel. It
            is not generated by Veyndi and becomes immutable once recorded.
        filed_at:
          type: string
          format: date-time
          description: |
            When the external filing actually occurred. It cannot precede internal approval
            or be in the future; it becomes the report's submitted_at value.

    ReportSubmissionEvidence:
      type: object
      required: [method, external_reference, filed_at, recorded_at, recorded_by, payload_sha256, schema_sha256]
      properties:
        method:
          type: string
          enum: [manual_external_filing, electronic_channel]
          description: |
            The filing occurred outside this platform and a human recorded the resulting
            evidence. This value does not claim an automated regulator integration.
        external_reference: { type: string, minLength: 1, maxLength: 256 }
        filed_at: { type: string, format: date-time }
        recorded_at: { type: string, format: date-time }
        recorded_by:
          type: string
          format: uuid
          description: Authenticated human who recorded the externally obtained evidence.
        payload_sha256:
          type: string
          pattern: "^[a-f0-9]{64}$"
          description: Digest of the exact immutable exported bytes that were validated.
        schema_sha256:
          type: string
          pattern: "^[a-f0-9]{64}$"
          description: Digest of the exact authoritative XSD pinned to the report.

    ReportSummary:
      type: object
      additionalProperties: false
      description: |
        Metadata-only filing-register row. It intentionally cannot carry a case/party id,
        validation errors, actors, external references, source keys, free text, payload/schema
        digests, field traces or rendered content. Fetching those requires
        `reporting.report_content.read` on report detail.
      required: [id, reference, kind, status, schema_authoritative, validation_valid, validator, generated_at]
      properties:
        id: { type: string, format: uuid }
        reference: { type: string, examples: [STR-2026-0001] }
        kind: { type: string, enum: [STR, CTR, SCUML, CBN_RETURN, BOARD] }
        status: { type: string, enum: [draft, validation_failed, in_review, approved, submitted, acknowledged, rejected] }
        schema_authoritative:
          type: boolean
          description: False means a placeholder schema was used and submission is forbidden.
        validation_valid:
          type: boolean
          description: Validation outcome only; error text is detail content and is never listed.
        validator:
          type: string
          description: Fixed validator implementation identifier, never a document-derived value.
        generated_at: { type: string, format: date-time }

    CTRLifecycleReviewRecord:
      type: object
      additionalProperties: false
      description: |
        Append-only record of how one canonical financial lifecycle event affected automatic
        CTR reporting. Linked report statuses are current workflow states. No field asserts
        assignment, completed review, external amendment/withdrawal, or regulator delivery.
      required: [transaction_id, transaction_booking_ts, event_type,
                 original_transaction_id, original_booking_ts, reason, disposition,
                 action_required, recorded_at]
      properties:
        transaction_id: { type: string, format: uuid }
        transaction_booking_ts: { type: string, format: date-time }
        event_type: { type: string, enum: [reversal, correction, cancellation, chargeback] }
        original_transaction_id: { type: string, format: uuid }
        original_booking_ts: { type: string, format: date-time }
        reason: { type: string, minLength: 1, maxLength: 500 }
        disposition:
          type: string
          enum: [no_report_impact, new_report_required, amendment_required,
                 withdrawal_review_required, cancellation_review_required]
        action_required: { type: boolean }
        prior_report_id: { type: string, format: uuid }
        prior_report_status:
          type: string
          enum: [draft, validation_failed, in_review, approved, submitted, acknowledged, rejected]
        resulting_report_id: { type: string, format: uuid }
        resulting_report_status:
          type: string
          enum: [draft, validation_failed, in_review, approved, submitted, acknowledged, rejected]
        recorded_at: { type: string, format: date-time }

    Report:
      type: object
      required: [id, reference, kind, status, schema_authoritative, validation, generated_at]
      properties:
        id: { type: string, format: uuid }
        reference: { type: string, examples: [STR-2026-0001] }
        kind: { type: string, enum: [STR, CTR, SCUML, CBN_RETURN, BOARD] }
        case_id: { type: string, format: uuid }
        subject_party_id: { type: string, format: uuid }
        period_from: { type: string, format: date-time }
        period_to: { type: string, format: date-time }
        status: { type: string, enum: [draft, validation_failed, in_review, approved, submitted, acknowledged, rejected] }
        schema_authoritative:
          type: boolean
          description: |
            False means the report was generated against a PLACEHOLDER schema and must not
            be filed. Copied onto the report at generation rather than looked up, so the
            document carries the honesty of its own provenance. Submission is refused at
            three layers when this is false (Q1).
        validation: { $ref: "#/components/schemas/ValidationResult" }
        generated_at: { type: string, format: date-time }
        generated_by: { type: string, format: uuid }
        approved_by:
          type: string
          format: uuid
          description: Always different from `generated_by`. A database CHECK enforces it.
        approved_at: { type: string, format: date-time }
        submitted_at:
          type: string
          format: date-time
          description: Actual external filing time copied from immutable submission evidence.
        submission: { $ref: "#/components/schemas/ReportSubmissionEvidence" }
        acknowledged_at: { type: string, format: date-time }
        rejected_at: { type: string, format: date-time }
        external_ack_ref: { type: string }
        status_reason: { type: string }
        source_event_key:
          type: string
          description: Immutable source event for machine-generated reports; unique per tenant and kind.
        deadline: { $ref: "#/components/schemas/FilingDeadline" }
        payload_format: { type: string, enum: [xml, csv, json, pdf] }
        payload_sha256: { type: string, pattern: "^[a-f0-9]{64}$" }

    ReportDetail:
      type: object
      required: [report, document, traces]
      properties:
        report: { $ref: "#/components/schemas/Report" }
        document:
          type: string
          description: The rendered filing, exactly as it would be transmitted.
        traces:
          type: array
          items: { $ref: "#/components/schemas/FieldTrace" }
          description: |
            One entry per field, with the expression that produced it. This is what lets a
            reviewer answer "where did this number come from" without reading the mapping.

    ReportRecurrenceRule:
      type: object
      description: |
        A recurrence in an explicit IANA timezone and tenant wall clock. Weekly weekday is ISO
        Monday=1 through Sunday=7. A monthly day beyond the end of a month uses that month's
        last day without changing the configured day for later months. A skipped DST time uses
        the first valid instant after the gap; a repeated time uses its first occurrence.
      required: [recurrence, timezone, local_delivery_time]
      properties:
        recurrence: { type: string, enum: [daily, weekly, monthly] }
        timezone:
          type: string
          minLength: 1
          maxLength: 100
          examples: [Africa/Lagos]
          description: An installed IANA timezone name; fixed numeric offsets are refused.
        local_delivery_time:
          type: string
          pattern: "^(?:[01][0-9]|2[0-3]):[0-5][0-9]$"
          examples: ["08:30"]
          description: Local 24-hour HH:MM delivery time in `timezone`.
        weekday:
          type: integer
          minimum: 1
          maximum: 7
          description: Required only for weekly recurrence; Monday=1 and Sunday=7.
        day_of_month:
          type: integer
          minimum: 1
          maximum: 31
          description: Required only for monthly recurrence; clamped independently per month.

    ReportWindow:
      type: object
      description: A reproducible half-open reporting window, `[from,to)`.
      required: [from, to]
      properties:
        from: { type: string, format: date-time }
        to: { type: string, format: date-time }

    ReportBoardSection:
      type: object
      required: [key, enabled]
      properties:
        key:
          type: string
          enum: [coverage, alert_false_positive_rate, screening_false_positive_rate,
                 case_ageing, screening_hit_ageing, sla_breaches, filing_deadlines,
                 filing_volumes]
        enabled: { type: boolean }
        label:
          type: string
          maxLength: 120
          description: Optional plain-text label; HTML, URLs and control characters are refused.

    ReportBoardLayout:
      type: object
      required: [key, name, sections]
      properties:
        key: { type: string, pattern: "^[a-z][a-z0-9_-]{0,39}$" }
        name: { type: string, minLength: 1, maxLength: 120 }
        title: { type: string, maxLength: 160 }
        subtitle: { type: string, maxLength: 240 }
        sections:
          type: array
          minItems: 1
          maxItems: 8
          items: { $ref: "#/components/schemas/ReportBoardSection" }

    ReportBoardLayoutSnapshot:
      type: object
      description: Canonical immutable layout and provenance captured when the run was created.
      required: [layout, sha256, source, schema_version, document_version]
      properties:
        layout: { $ref: "#/components/schemas/ReportBoardLayout" }
        sha256: { type: string, pattern: "^[a-f0-9]{64}$" }
        source: { type: string, enum: [pack_default, tenant_override, legacy_standard] }
        schema_version: { type: integer, minimum: 1 }
        document_version: { type: integer, minimum: 0 }

    ReportBoardLayoutPage:
      type: object
      description: The complete bounded layout catalogue (at most twelve layouts).
      required: [items]
      properties:
        items:
          type: array
          maxItems: 12
          items: { $ref: "#/components/schemas/ReportBoardLayout" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    ReportScheduleInput:
      type: object
      required: [name, report_kind, format, layout_key, rule, recipient_user_ids]
      properties:
        name: { type: string, minLength: 1, maxLength: 120 }
        report_kind:
          type: string
          enum: [compliance_board]
          description: Internal disclosure-controlled aggregate board pack; never a filing.
        format: { type: string, enum: [json, csv, pdf, xlsx] }
        layout_key:
          type: string
          pattern: "^[a-z][a-z0-9_-]{0,39}$"
          description: A key returned by `GET /v1/report-board-layouts`.
        rule: { $ref: "#/components/schemas/ReportRecurrenceRule" }
        recipient_user_ids:
          type: array
          minItems: 1
          maxItems: 100
          uniqueItems: true
          items: { type: string, format: uuid }
          description: |
            Current users in this tenant. Email addresses are resolved at delivery and are not
            copied into the schedule or immutable run ledger.

    ReportSchedule:
      type: object
      required: [id, name, report_kind, format, layout_key, rule, state, recipient_user_ids, created_by,
                 updated_by, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        name: { type: string }
        report_kind: { type: string, enum: [compliance_board] }
        format: { type: string, enum: [json, csv, pdf, xlsx] }
        layout_key:
          type: string
          pattern: "^[a-z][a-z0-9_-]{0,39}$"
          description: Layout selected for future occurrences.
        rule: { $ref: "#/components/schemas/ReportRecurrenceRule" }
        state: { type: string, enum: [active, paused, retired] }
        next_run_at:
          type: string
          format: date-time
          description: Present only while active.
        recipient_user_ids:
          type: array
          items: { type: string, format: uuid }
          description: Tenant user identifiers, never email addresses.
        created_by: { type: string, format: uuid }
        updated_by: { type: string, format: uuid }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        paused_at: { type: string, format: date-time }
        retired_at: { type: string, format: date-time }

    ReportSchedulePage:
      type: object
      description: A cursor-paged schedule register in the selected server order; limit is bounded at200 and defaults to50.
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/ReportSchedule" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    ReportRun:
      type: object
      description: |
        One immutable schedule occurrence. `(schedule_id, scheduled_for)` is unique. Artifact
        metadata identifies write-once bytes; recipient addresses and artifact bodies are not
        present in this JSON response.
      required: [id, schedule_id, scheduled_for, window, report_kind, format, layout, status,
                 attempt_count, message_id, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        schedule_id: { type: string, format: uuid }
        scheduled_for: { type: string, format: date-time }
        window: { $ref: "#/components/schemas/ReportWindow" }
        report_kind: { type: string, enum: [compliance_board] }
        format: { type: string, enum: [json, csv, pdf, xlsx] }
        layout: { $ref: "#/components/schemas/ReportBoardLayoutSnapshot" }
        status:
          type: string
          enum: [queued, generating, generated, sending, sent, failed, delivery_not_configured]
        attempt_count: { type: integer, minimum: 0 }
        result:
          type: object
          additionalProperties: true
          description: Privacy-safe generation and delivery metadata; never an artifact body or address.
        error_code:
          type: string
          description: A closed, privacy-safe operational code; never an SMTP relay response.
        error_message:
          type: string
          description: A fixed privacy-safe message; never a recipient or relay response.
        artifact_sha256: { type: string, pattern: "^[a-f0-9]{64}$" }
        artifact_filename: { type: string }
        content_type: { type: string, enum: [application/json, text/csv, application/pdf, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet] }
        message_id:
          type: string
          description: Deterministic idempotency identifier supplied to the SMTP relay.
        requested_by: { type: string, format: uuid }
        generated_at: { type: string, format: date-time }
        delivery_started_at: { type: string, format: date-time }
        sent_at: { type: string, format: date-time }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    ReportRunRequestResult:
      type: object
      required: [run, created]
      properties:
        run: { $ref: "#/components/schemas/ReportRun" }
        created:
          type: boolean
          description: False when the unique occurrence already existed.

    ReportRunPage:
      type: object
      description: A bounded run ledger, newest occurrence first; currently at most 100.
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/ReportRun" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    ReportRunEvent:
      type: object
      description: An append-only generation, delivery or download transition.
      required: [id, run_id, attempt, status, occurred_at]
      properties:
        id: { type: string, format: uuid }
        run_id: { type: string, format: uuid }
        attempt: { type: integer, minimum: 0 }
        status:
          type: string
          enum: [queued, generating, generated, sending, sent, failed, delivery_not_configured, downloaded]
        result:
          type: object
          additionalProperties: true
          description: Privacy-safe transition metadata.
        error_code: { type: string }
        error_message: { type: string }
        occurred_at: { type: string, format: date-time }

    ReportRunEventPage:
      type: object
      description: The complete append-only transition ledger for one run.
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: "#/components/schemas/ReportRunEvent" }
        next_cursor: { $ref: "#/components/schemas/NextCursor" }
        truncated: { $ref: "#/components/schemas/Truncated" }
        truncation_reason: { $ref: "#/components/schemas/TruncationReason" }
        total_estimate: { $ref: "#/components/schemas/TotalEstimate" }

    ReportPreviewInput:
      type: object
      description: Build an on-demand aggregate artifact without scheduling or email delivery.
      required: [report_kind, format, layout_key, window]
      properties:
        commentary_id: { type: string, format: uuid, description: Export the exact approved frozen snapshot; period and layout must match. }
        report_kind: { type: string, enum: [compliance_board] }
        format: { type: string, enum: [json, csv, pdf, xlsx] }
        layout_key:
          type: string
          pattern: "^[a-z][a-z0-9_-]{0,39}$"
        window: { $ref: "#/components/schemas/ReportWindow" }

    EntityIdentity:
      additionalProperties: false
      properties:
        enabled:
          type: boolean
        jurisdiction:
          type: string
        legal_name:
          type: string
        nfiu_id:
          type: string
        registration_reference:
          type: string
      required:
      - enabled
      - nfiu_id
      - legal_name
      - registration_reference
      - jurisdiction
      type: object
    ExpectedActivityBaseline:
      additionalProperties: false
      properties:
        activity:
          $ref: '#/components/schemas/ExpectedActivity'
        approved_at:
          format: date-time
          type: string
        approved_by:
          format: uuid
          type: string
        completion_id:
          format: uuid
          type: string
        customer_id:
          format: uuid
          type: string
      required:
      - customer_id
      - completion_id
      - activity
      - approved_by
      - approved_at
      type: object
    IngestBatchSummary:
      additionalProperties: false
      properties:
        finished_at:
          format: date-time
          type: string
        id:
          format: uuid
          type: string
        records_duplicate:
          format: int64
          type: integer
        records_inserted:
          format: int64
          type: integer
        records_quarantined:
          format: int64
          type: integer
        records_received:
          format: int64
          type: integer
        source:
          type: string
        started_at:
          format: date-time
          type: string
        status:
          type: string
        unresolved_quarantine:
          format: int64
          type: integer
      required:
      - id
      - source
      - status
      - records_received
      - records_inserted
      - records_duplicate
      - records_quarantined
      - unresolved_quarantine
      - started_at
      type: object
    NetworkObservationInput:
      type: object
      additionalProperties: false
      required: [kind, value, source_code, source_reference, observed_at]
      properties:
        kind: {type: string, enum: [bvn, nin, phone, address, email, device, beneficiary]}
        value: {type: string, minLength: 1, maxLength: 1000, description: 'Phone requires E.164. Beneficiary is bank|account. Values are tenant-HMAC indexed and never returned.'}
        source_code: {type: string, pattern: '^[a-zA-Z0-9_.:-]{1,80}$'}
        source_reference: {type: string, minLength: 1, maxLength: 1000}
        observed_at: {type: string, format: date-time}
    NetworkObservation:
      type: object
      additionalProperties: false
      required: [id, party_id, kind, source_code, confidence, observed_at, recorded_at]
      properties:
        id: {type: string, format: uuid}
        party_id: {type: string, format: uuid}
        kind: {type: string}
        source_code: {type: string}
        confidence: {type: number, format: double}
        observed_at: {type: string, format: date-time}
        recorded_at: {type: string, format: date-time}
    NetworkNode:
      type: object
      additionalProperties: false
      required: [party_id, name, kind, depth]
      properties:
        party_id: {type: string, format: uuid}
        name: {type: string}
        kind: {type: string}
        depth: {type: integer, format: int64}
    NetworkLink:
      type: object
      additionalProperties: false
      required: [id, left_party_id, right_party_id, kind, confidence, left_observation_id, right_observation_id, observed_at]
      properties:
        id: {type: string, format: uuid}
        left_party_id: {type: string, format: uuid}
        right_party_id: {type: string, format: uuid}
        kind: {type: string}
        confidence: {type: number, format: double}
        left_observation_id: {type: string, format: uuid}
        right_observation_id: {type: string, format: uuid}
        observed_at: {type: string, format: date-time}
    PartyNetwork:
      type: object
      additionalProperties: false
      required: [root_party_id, as_of, nodes, links, cycles, truncated, cycle_search_truncated, max_depth, limitations]
      properties:
        root_party_id: {type: string, format: uuid}
        as_of: {type: string, format: date-time}
        nodes:
          type: array
          items: {$ref: '#/components/schemas/NetworkNode'}
        links:
          type: array
          items: {$ref: '#/components/schemas/NetworkLink'}
        cycles:
          type: array
          items:
            type: array
            items: {type: string, format: uuid}
        truncated: {type: boolean}
        cycle_search_truncated: {type: boolean}
        max_depth: {type: integer, format: int64}
        limitations:
          type: array
          items: {type: string}
    OwnershipGraph:
      additionalProperties: false
      properties:
        as_of:
          format: date-time
          type: string
        complete:
          type: boolean
        edges:
          items:
            $ref: '#/components/schemas/OwnershipLink'
          type: array
        issues:
          items:
            $ref: '#/components/schemas/OwnershipIssue'
          type: array
        max_depth:
          format: int64
          type: integer
        max_edges:
          format: int64
          type: integer
        max_nodes:
          format: int64
          type: integer
        nodes:
          items:
            $ref: '#/components/schemas/OwnershipNode'
          type: array
        root_party_id:
          format: uuid
          type: string
      required:
      - root_party_id
      - as_of
      - nodes
      - edges
      - complete
      - issues
      - max_depth
      - max_nodes
      - max_edges
      type: object
    OwnershipIssue:
      additionalProperties: false
      properties:
        kind:
          type: string
        party_ids:
          items:
            format: uuid
            type: string
          type: array
      required:
      - kind
      - party_ids
      type: object
    OwnershipNode:
      additionalProperties: false
      properties:
        depth:
          format: int64
          type: integer
        effective_pct:
          type: string
        kind:
          type: string
        name:
          type: string
        party_id:
          format: uuid
          type: string
      required:
      - party_id
      - name
      - kind
      - depth
      type: object
    ObligationReportInput:
      type: object
      required:
      - report_id
      properties:
        report_id:
          type: string
          format: uuid
      additionalProperties: false
    IngestBatchSummaryPage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/IngestBatchSummary'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64
      additionalProperties: false
    ReferenceVersionPage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/ReferenceVersion'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64
      additionalProperties: false
    FilingClockPage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/FilingClock'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64
      additionalProperties: false
    FilingObligationPage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/FilingObligation'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64
      additionalProperties: false
    FilingProviderProvenance:
      type: object
      additionalProperties: false
      properties:
        capability:
          type: string
        provider:
          type: string
        version:
          type: string
        assurance:
          type: string
        authority:
          type: string
        answered_at:
          type: string
          format: date-time
      required:
      - capability
      - provider
      - version
      - assurance
      - answered_at
    FilingChannelReceipt:
      type: object
      additionalProperties: false
      properties:
        purpose:
          type: string
          enum:
          - supplement
          - amendment
        original_report_id:
          type: string
          format: uuid
        original_receipt_id:
          type: string
        supplement_id:
          type: string
          format: uuid
        id:
          type: string
        report_id:
          type: string
        status:
          type: string
          enum:
          - queued
          - accepted
          - rejected
        payload_sha256:
          type: string
        schema_sha256:
          type: string
        received_at:
          type: string
          format: date-time
        reason_code:
          type: string
        provenance:
          $ref: '#/components/schemas/FilingProviderProvenance'
      required:
      - id
      - report_id
      - status
      - payload_sha256
      - schema_sha256
      - received_at
      - provenance
    ReportDeliveryAttempt:
      type: object
      additionalProperties: false
      properties:
        supplement:
          $ref: '#/components/schemas/DeliverySupplement'
        id:
          type: string
          format: uuid
        report_id:
          type: string
          format: uuid
        idempotency_key:
          type: string
        payload_sha256:
          type: string
        schema_sha256:
          type: string
        status:
          type: string
          enum:
          - pending
          - unavailable
          - queued
          - accepted
          - rejected
        assurance:
          type: string
          enum:
          - fixture
          - authoritative
        receipt:
          $ref: '#/components/schemas/FilingChannelReceipt'
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
        recovery:
          $ref: '#/components/schemas/DeliveryRecovery'
      required:
      - id
      - report_id
      - idempotency_key
      - payload_sha256
      - schema_sha256
      - status
      - assurance
      - created_at
      - updated_at
    ReportDeliveryAttemptPage:
      type: object
      additionalProperties: false
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/ReportDeliveryAttempt'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
      required:
      - items
    RetentionDispositionArchive:
      additionalProperties: false
      properties:
        ciphertext_sha256:
          type: string
        format:
          type: string
        manifest_sha256:
          type: string
        verified_at:
          format: date-time
          type: string
      required:
      - format
      - manifest_sha256
      - ciphertext_sha256
      - verified_at
      type: object
    RetentionDispositionDecision:
      additionalProperties: false
      properties:
        approved:
          type: boolean
        checker:
          format: uuid
          type: string
        decided_at:
          format: date-time
          type: string
        reason:
          type: string
      required:
      - approved
      - reason
      - checker
      - decided_at
      type: object
    RetentionDispositionDecisionInput:
      additionalProperties: false
      properties:
        approved:
          type: boolean
        reason:
          type: string
      required:
      - approved
      - reason
      type: object
    RetentionDispositionInput:
      additionalProperties: false
      properties:
        lifecycle_reference:
          type: string
        relationship_ended_at:
          format: date-time
          type: string
      required:
      - relationship_ended_at
      - lifecycle_reference
      type: object
    RetentionDispositionPlan:
      additionalProperties: false
      properties:
        archive:
          $ref: '#/components/schemas/RetentionDispositionArchive'
        created_at:
          format: date-time
          type: string
        decision:
          $ref: '#/components/schemas/RetentionDispositionDecision'
        erasure_id:
          format: uuid
          type: string
        executed_at:
          format: date-time
          type: string
        id:
          format: uuid
          type: string
        maker:
          format: uuid
          type: string
        preview:
          $ref: '#/components/schemas/RetentionDispositionPreview'
      required:
      - id
      - erasure_id
      - maker
      - created_at
      - preview
      - archive
      type: object
    RetentionDispositionPreview:
      additionalProperties: false
      properties:
        archive_semantics:
          type: string
        blocking_reasons:
          items:
            type: string
          type: array
        earliest_disposition_at:
          format: date-time
          type: string
        eligible:
          type: boolean
        erasure_id:
          format: uuid
          type: string
        evaluated_at:
          format: date-time
          type: string
        evidence:
          items:
            $ref: '#/components/schemas/AuthorityEvidenceItem'
          type: array
        lifecycle:
          $ref: '#/components/schemas/RetentionDispositionInput'
        party_id:
          format: uuid
          type: string
        policies:
          items:
            $ref: '#/components/schemas/RetentionPolicyVersion'
          type: array
        policy_marker:
          type: string
        retention_anchor:
          format: date-time
          type: string
        snapshot_sha256:
          type: string
      required:
      - erasure_id
      - party_id
      - lifecycle
      - evaluated_at
      - retention_anchor
      - earliest_disposition_at
      - policies
      - evidence
      - eligible
      - blocking_reasons
      - snapshot_sha256
      - archive_semantics
      - policy_marker
      type: object
    RetentionPolicyVersion:
      additionalProperties: false
      properties:
        configured:
          type: boolean
        legal_hold:
          type: boolean
        resource_type:
          type: string
        retain_years:
          format: int64
          type: integer
        version:
          format: int64
          type: integer
      required:
      - resource_type
      - configured
      - retain_years
      - version
      - legal_hold
      type: object
    DeliveryRecoveryInput:
      type: object
      additionalProperties: false
      required:
      - replacement_report_id
      - reason_code
      properties:
        replacement_report_id:
          type: string
          format: uuid
        reason_code:
          type: string
          enum:
          - corrected_mapping
          - provider_rejection
          - updated_facts
          - corrected_schema
    DeliveryRecovery:
      type: object
      additionalProperties: false
      required:
      - attempt_id
      - replacement_report_id
      - reason_code
      - recorded_at
      properties:
        attempt_id:
          type: string
          format: uuid
        replacement_report_id:
          type: string
          format: uuid
        reason_code:
          type: string
        recorded_at:
          type: string
          format: date-time
    FilingEvent:
      additionalProperties: false
      properties:
        case_id:
          format: uuid
          type: string
        event_reference:
          type: string
        event_type:
          type: string
        kind:
          type: string
        occurred_at:
          format: date-time
          type: string
      required:
      - kind
      - event_type
      - event_reference
      - occurred_at
      type: object
    GeographyEvidence:
      additionalProperties: false
      properties:
        as_of:
          format: date-time
          type: string
        classification:
          type: string
        country:
          type: string
        payload_sha256:
          type: string
        reason:
          type: string
        reference_id:
          format: uuid
          type: string
        reference_version:
          format: int64
          type: integer
        source_sha256:
          type: string
      required:
      - reference_id
      - reference_version
      - payload_sha256
      - source_sha256
      - as_of
      - country
      - classification
      - reason
      type: object
    OutcomeReview:
      additionalProperties: false
      properties:
        rule_key: {type: string}
        cases: {type: integer, format: int64}
        case_linked_alerts: {type: integer, format: int64}
        str_cases: {type: integer, format: int64}
        alert_case_conversion: {type: number}
        case_str_conversion: {type: number}
        conversion_as_of: {type: string, format: date-time}
        conversion_available: {type: boolean}
        actioned:
          format: int64
          type: integer
        alerts:
          format: int64
          type: integer
        confidence_lower:
          type: number
        confidence_upper:
          type: number
        created_at:
          format: date-time
          type: string
        created_by:
          format: uuid
          type: string
        false_positive:
          format: int64
          type: integer
        false_positive_rate:
          type: number
        false_positive_target:
          type: number
        id:
          format: uuid
          type: string
        limitations:
          items:
            type: string
          type: array
        max_alerts:
          format: int64
          type: integer
        minimum_samples:
          format: int64
          type: integer
        reviewed:
          format: int64
          type: integer
        rule_version_id:
          format: uuid
          type: string
        segment:
          type: string
        signal:
          type: string
        truncated:
          type: boolean
        unreviewed:
          format: int64
          type: integer
        window_from:
          format: date-time
          type: string
        window_to:
          format: date-time
          type: string
      required:
      - id
      - rule_version_id
      - window_from
      - window_to
      - minimum_samples
      - false_positive_target
      - alerts
      - reviewed
      - false_positive
      - actioned
      - unreviewed
      - signal
      - truncated
      - max_alerts
      - limitations
      - created_by
      - created_at
      type: object
    OutcomeReviewInput:
      additionalProperties: false
      properties:
        false_positive_target:
          type: number
        minimum_samples:
          format: int64
          type: integer
        rule_version_id:
          format: uuid
          type: string
        segment:
          type: string
        window_from:
          format: date-time
          type: string
        window_to:
          format: date-time
          type: string
      required:
      - rule_version_id
      - window_from
      - window_to
      - minimum_samples
      - false_positive_target
      type: object
    SuspicionInput:
      additionalProperties: false
      properties:
        identified_at:
          format: date-time
          type: string
        rationale:
          type: string
      required:
      - identified_at
      - rationale
      type: object
    SuspicionRecognition:
      additionalProperties: false
      properties:
        case_id:
          format: uuid
          type: string
        coverage:
          $ref: '#/components/schemas/TriggerCoverage'
        identified_at:
          format: date-time
          type: string
        recorded_at:
          format: date-time
          type: string
        recorded_by:
          format: uuid
          type: string
      required:
      - case_id
      - identified_at
      - recorded_by
      - recorded_at
      - coverage
      type: object
    TriggerCoverage:
      additionalProperties: false
      properties:
        issues:
          type: array
          items:
            type: object
            additionalProperties: false
            required: [policy_version_id, policy_key, reason, action]
            properties:
              policy_version_id: {type: string, format: uuid}
              policy_key: {type: string}
              reason: {type: string, enum: [calendar_gap]}
              action: {type: string}
        event_id:
          format: uuid
          type: string
        event_reference:
          type: string
        event_type:
          type: string
        kind:
          type: string
        obligation_ids:
          items:
            format: uuid
            type: string
          type: array
        occurred_at:
          format: date-time
          type: string
        status:
          type: string
      required:
      - kind
      - event_id
      - event_type
      - event_reference
      - occurred_at
      - status
      - obligation_ids
      type: object
    OutcomeReviewPage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/OutcomeReview'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64
      additionalProperties: false
    TemplateParameter:
      additionalProperties: false
      properties:
        key:
          type: string
        kind:
          type: string
        purpose:
          type: string
      required:
      - key
      - kind
      - purpose
      type: object

    TypologyCatalogue:
      additionalProperties: false
      properties:
        templates:
          items:
            $ref: '#/components/schemas/TypologyTemplate'
          type: array
      required:
      - templates
      type: object

    TypologyDraft:
      additionalProperties: false
      properties:
        activation_policy:
          type: string
        governance_requirements:
          items:
            type: string
          type: array
        required_parameters:
          items:
            $ref: '#/components/schemas/TemplateParameter'
          type: array
        rule:
          $ref: '#/components/schemas/Rule'
        template_key:
          type: string
        version:
          $ref: '#/components/schemas/RuleVersion'
      required:
      - template_key
      - rule
      - version
      - activation_policy
      - required_parameters
      - governance_requirements
      type: object

    TypologyDraftInput:
      additionalProperties: false
      properties:
        description:
          type: string
        name:
          type: string
        rule_key:
          type: string
        window_hours:
          format: int64
          type: integer
      required:
      - rule_key
      - name
      type: object

    TypologyTemplate:
      additionalProperties: false
      properties:
        activation_policy:
          type: string
        aggregates:
          items:
            type: string
          type: array
        assumptions:
          items:
            type: string
          type: array
        description:
          type: string
        expression:
          type: string
        key:
          type: string
        limitations:
          items:
            type: string
          type: array
        name:
          type: string
        parameters:
          items:
            $ref: '#/components/schemas/TemplateParameter'
          type: array
        window_hours:
          format: int64
          type: integer
        window_scope:
          type: string
      required:
      - key
      - name
      - description
      - expression
      - window_hours
      - window_scope
      - aggregates
      - parameters
      - assumptions
      - limitations
      - activation_policy
      type: object


    ExpectedFeedInput:
      type: object
      required:
      - source
      - name
      - owner_id
      - first_window_at
      - window_seconds
      - grace_seconds
      - expected_count
      - expected_amounts
      properties:
        source:
          type: string
          minLength: 1
          maxLength: 120
        name:
          type: string
          minLength: 1
          maxLength: 200
        owner_id:
          type: string
          format: uuid
        first_window_at:
          type: string
          format: date-time
        window_seconds:
          type: integer
          minimum: 600
          maximum: 86400
        grace_seconds:
          type: integer
          minimum: 0
          maximum: 604800
        expected_count:
          type: integer
          format: int64
          minimum: 1
        expected_amounts:
          type: object
          additionalProperties:
            type: integer
            format: int64
            minimum: 0
    ExpectedFeed:
      type: object
      required:
      - source
      - name
      - owner_id
      - first_window_at
      - window_seconds
      - grace_seconds
      - expected_count
      - expected_amounts
      - id
      - maker_id
      - status
      - created_at
      - next_window_at
      properties:
        source:
          type: string
          minLength: 1
          maxLength: 120
        name:
          type: string
          minLength: 1
          maxLength: 200
        owner_id:
          type: string
          format: uuid
        first_window_at:
          type: string
          format: date-time
        window_seconds:
          type: integer
          minimum: 600
          maximum: 86400
        grace_seconds:
          type: integer
          minimum: 0
          maximum: 604800
        expected_count:
          type: integer
          format: int64
          minimum: 1
        expected_amounts:
          type: object
          additionalProperties:
            type: integer
            format: int64
            minimum: 0
        id:
          type: string
          format: uuid
        maker_id:
          type: string
          format: uuid
        checker_id:
          type: string
          format: uuid
        status:
          type: string
          enum:
          - proposed
          - approved
          - rejected
          - disabled
        created_at:
          type: string
          format: date-time
        decided_at:
          type: string
          format: date-time
        next_window_at:
          type: string
          format: date-time

    ExpectedFeedWindow:
      type: object
      required:
      - id
      - definition_id
      - source
      - name
      - owner_id
      - window_from
      - window_to
      - due_at
      - expected_count
      - expected_amounts
      - observed_count
      - observed_amounts
      - status
      - created_at
      properties:
        id:
          type: string
          format: uuid
        definition_id:
          type: string
          format: uuid
        source:
          type: string
        name:
          type: string
        owner_id:
          type: string
          format: uuid
        window_from:
          type: string
          format: date-time
        window_to:
          type: string
          format: date-time
        due_at:
          type: string
          format: date-time
        expected_count:
          type: integer
          format: int64
          minimum: 0
        expected_amounts:
          type: object
          additionalProperties:
            type: integer
            format: int64
            minimum: 0
        observed_count:
          type: integer
          format: int64
          minimum: 0
        observed_amounts:
          type: object
          additionalProperties:
            type: integer
            format: int64
            minimum: 0
        status:
          type: string
          enum:
          - pending
          - matched
          - missing_feed
          - variance
        checked_at:
          type: string
          format: date-time
        created_at:
          type: string
          format: date-time

    ExpectedFeedPage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/ExpectedFeed'
        next_cursor:
          type: string
    ExpectedFeedWindowPage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/ExpectedFeedWindow'
        next_cursor:
          type: string

    DeliverySupplementInput:
      type: object
      additionalProperties: false
      required:
      - supplement_report_id
      - purpose
      - reason_code
      properties:
        supplement_report_id:
          type: string
          format: uuid
        purpose:
          type: string
          enum:
          - supplement
          - amendment
        reason_code:
          type: string
          enum:
          - additional_information
          - updated_facts
          - corrected_mapping
          - corrected_schema
    DeliverySupplement:
      type: object
      required:
      - id
      - original_attempt_id
      - original_report_id
      - original_receipt_id
      - payload_sha256
      - status
      - proposed_by
      - proposed_at
      - supplement_report_id
      - purpose
      - reason_code
      properties:
        artifact_maker_id:
          type: string
          format: uuid
        supplement_report_id:
          type: string
          format: uuid
        purpose:
          type: string
          enum:
          - supplement
          - amendment
        reason_code:
          type: string
          enum:
          - additional_information
          - updated_facts
          - corrected_mapping
          - corrected_schema
        id:
          type: string
          format: uuid
        original_attempt_id:
          type: string
          format: uuid
        original_report_id:
          type: string
          format: uuid
        original_receipt_id:
          type: string
        payload_sha256:
          type: string
          pattern: ^[a-f0-9]{64}$
        status:
          type: string
          enum:
          - proposed
          - approved
          - rejected
        proposed_by:
          type: string
          format: uuid
        proposed_at:
          type: string
          format: date-time
        decided_by:
          type: string
          format: uuid
        decided_at:
          type: string
          format: date-time
    DeliverySupplementPage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/DeliverySupplement'
        next_cursor:
          type: string
    FilingEventCoveragePage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/TriggerCoverage'
        next_cursor:
          type: string
    ExpectedFeedOwner:
      type: object
      required:
      - id
      - display_name
      properties:
        id:
          type: string
          format: uuid
        display_name:
          type: string
    ExpectedFeedOwnerPage:
      type: object
      required:
      - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/ExpectedFeedOwner'
        next_cursor:
          type: string

    DestructionReceipt:
      type: object
      required:
      - format
      - tenant_id
      - erasure_id
      - party_id
      - plan_id
      - executed_at
      - executed_by
      - snapshot_sha256
      - archive_sha256
      - signing_key_id
      - mac
      properties:
        format:
          type: string
        tenant_id:
          type: string
          format: uuid
        erasure_id:
          type: string
          format: uuid
        party_id:
          type: string
          format: uuid
        plan_id:
          type: string
          format: uuid
        executed_at:
          type: string
          format: date-time
        executed_by:
          type: string
          format: uuid
        snapshot_sha256:
          type: string
        archive_sha256:
          type: string
        signing_key_id:
          type: string
        mac:
          type: string

    RetainedDestructionReceipt:
      type: object
      required:
      - receipt
      - object_reference
      - sha256
      - independently_retained
      properties:
        receipt:
          $ref: '#/components/schemas/DestructionReceipt'
        object_reference:
          type: string
        sha256:
          type: string
        independently_retained:
          type: boolean

    CaseQualityReview:
      additionalProperties: false
      properties:
        case_id:
          format: uuid
          type: string
        findings:
          type: string
        id:
          format: uuid
          type: string
        outcome:
          type: string
        remediation_assignee_id:
          format: uuid
          type: string
        remediation_due_at:
          format: date-time
          type: string
        remediation_task_id:
          format: uuid
          type: string
        reviewed_at:
          format: date-time
          type: string
        reviewer_id:
          format: uuid
          type: string
        sample_id:
          format: uuid
          type: string
        score:
          type: integer
      required:
      - id
      - case_id
      - score
      - outcome
      - findings
      - reviewer_id
      - reviewed_at
      type: object

    CaseQualityReviewInput:
      additionalProperties: false
      properties:
        case_id:
          format: uuid
          type: string
        findings:
          type: string
        outcome:
          type: string
        remediation_assignee_id:
          format: uuid
          type: string
        remediation_due_at:
          format: date-time
          type: string
        sample_id:
          format: uuid
          type: string
        score:
          type: integer
      required:
      - case_id
      - score
      - outcome
      - findings
      type: object

    CaseTask:
      additionalProperties: false
      properties:
        assignee_id:
          format: uuid
          type: string
        case_id:
          format: uuid
          type: string
        completed_at:
          format: date-time
          type: string
        completed_by:
          format: uuid
          type: string
        created_at:
          format: date-time
          type: string
        created_by:
          format: uuid
          type: string
        depends_on:
          items:
            format: uuid
            type: string
          type: array
        due_at:
          format: date-time
          type: string
        evidence_attachment_ids:
          items:
            format: uuid
            type: string
          type: array
        evidence_required:
          type: boolean
        id:
          format: uuid
          type: string
        key:
          type: string
        kind:
          type: string
        mandatory:
          type: boolean
        playbook_version_id:
          format: uuid
          type: string
        remediation_accepted_at:
          format: date-time
          type: string
        remediation_accepted_by:
          format: uuid
          type: string
        result:
          type: string
        status:
          type: string
        title:
          type: string
      required:
      - id
      - case_id
      - key
      - title
      - kind
      - mandatory
      - evidence_required
      - status
      - evidence_attachment_ids
      - created_by
      - created_at
      type: object

    LinkedOwnershipAccount:
      additionalProperties: false
      properties:
        created_at:
          format: date-time
          type: string
        currency:
          type: string
        customer_id:
          format: uuid
          type: string
        external_reference:
          type: string
        id:
          format: uuid
          type: string
        party_id:
          format: uuid
          type: string
        product_type:
          type: string
      required:
      - id
      - party_id
      - customer_id
      - external_reference
      - currency
      - product_type
      - created_at
      type: object

    LinkedOwnershipActivity:
      additionalProperties: false
      properties:
        account_id:
          format: uuid
          type: string
        amount_minor:
          type: integer
        booking_ts:
          format: date-time
          type: string
        channel:
          type: string
        counterparty_party_id:
          format: uuid
          type: string
        currency:
          type: string
        customer_id:
          format: uuid
          type: string
        direction:
          type: string
        external_reference:
          type: string
        id:
          format: uuid
          type: string
        party_id:
          format: uuid
          type: string
        relation:
          type: string
          enum:
          - owned_account
          - counterparty
      required:
      - id
      - booking_ts
      - account_id
      - customer_id
      - party_id
      - external_reference
      - direction
      - amount_minor
      - currency
      - channel
      - relation
      type: object

    OwnershipLink:
      additionalProperties: false
      properties:
        control_type:
          type: string
        effective_from:
          format: date-time
          type: string
        effective_to:
          format: date-time
          type: string
        evidence:
          items:
            $ref: '#/components/schemas/RelationshipEvidence'
          type: array
        id:
          format: uuid
          type: string
        owned_party_id:
          format: uuid
          type: string
        owner_party_id:
          format: uuid
          type: string
        ownership_pct:
          type: string
        recorded_at:
          format: date-time
          type: string
        snapshot_id:
          format: uuid
          type: string
        snapshot_sha256:
          type: string
        snapshot_version:
          type: integer
        source_kind:
          type: string
        verification_method:
          type: string
        verification_reference_sha256:
          type: string
        verified_at:
          format: date-time
          type: string
      required:
      - id
      - owner_party_id
      - owned_party_id
      - control_type
      - effective_from
      - evidence
      type: object

    OwnershipSnapshot:
      additionalProperties: false
      properties:
        edge_id:
          format: uuid
          type: string
        id:
          format: uuid
          type: string
        link:
          $ref: '#/components/schemas/OwnershipLink'
        recorded_at:
          format: date-time
          type: string
        snapshot_sha256:
          type: string
        source_kind:
          type: string
          enum:
          - declaration
          - edge_change
          - verification
          - legacy_snapshot
        version:
          type: integer
      required:
      - id
      - edge_id
      - version
      - source_kind
      - snapshot_sha256
      - recorded_at
      - link
      type: object

    RelationshipEvidence:
      additionalProperties: false
      properties:
        document_id:
          format: uuid
          type: string
        document_sha256:
          type: string
        edge_id:
          format: uuid
          type: string
        id:
          format: uuid
          type: string
        recorded_at:
          format: date-time
          type: string
        recorded_by:
          format: uuid
          type: string
      required:
      - id
      - edge_id
      - document_id
      - document_sha256
      - recorded_by
      - recorded_at
      type: object

    RemediationAcceptance:
      additionalProperties: false
      properties:
        accepted_at:
          format: date-time
          type: string
        accepted_by:
          format: uuid
          type: string
        findings:
          type: string
        task_id:
          format: uuid
          type: string
      required:
      - task_id
      - accepted_by
      - accepted_at
      - findings
      type: object

    RemediationAssignee:
      additionalProperties: false
      properties:
        created_at:
          format: date-time
          type: string
        display_name:
          type: string
        id:
          format: uuid
          type: string
      required:
      - id
      - display_name
      - created_at
      type: object

    ReviewAssignee:
      additionalProperties: false
      properties:
        created_at:
          format: date-time
          type: string
        display_name:
          type: string
        id:
          format: uuid
          type: string
      required:
      - id
      - display_name
      - created_at
      type: object

    ReviewAssignmentInput:
      additionalProperties: false
      properties:
        assignee_id:
          format: uuid
          type: string
        reason:
          type: string
      required:
      - assignee_id
      - reason
      type: object

    ReviewEvidenceGap:
      additionalProperties: false
      properties:
        key:
          type: string
        kind:
          type: string
        request_id:
          format: uuid
          type: string
      required:
      - kind
      - key
      type: object

    ReviewEvidenceRequest:
      additionalProperties: false
      properties:
        description:
          type: string
        document_id:
          format: uuid
          type: string
        document_kind:
          type: string
        due_at:
          format: date-time
          type: string
        fulfilled_at:
          format: date-time
          type: string
        fulfilled_by:
          format: uuid
          type: string
        id:
          format: uuid
          type: string
        requested_at:
          format: date-time
          type: string
        requested_by:
          format: uuid
          type: string
        review_id:
          format: uuid
          type: string
        status:
          type: string
          enum:
          - requested
          - fulfilled
      required:
      - id
      - review_id
      - document_kind
      - description
      - due_at
      - status
      - requested_by
      - requested_at
      type: object

    ReviewEvidenceRequestInput:
      additionalProperties: false
      properties:
        description:
          type: string
        document_kind:
          type: string
        due_at:
          format: date-time
          type: string
      required:
      - document_kind
      - description
      - due_at
      type: object

    ReviewRequirementInput:
      additionalProperties: false
      properties:
        effective_from:
          format: date-time
          type: string
        effective_to:
          format: date-time
          type: string
        evidence_max_age_days:
          type: integer
        key:
          type: string
        next_review_months:
          type: integer
        reason:
          type: string
        require_source_of_funds:
          type: boolean
        require_source_of_wealth:
          type: boolean
        required_checks:
          items:
            type: string
          type: array
        required_document_kinds:
          items:
            type: string
          type: array
        trust_kind:
          type: string
          enum:
          - institution_reviewed
          - synthetic_rehearsal
          description: Rehearsal definitions cannot satisfy the required production governance
            gate.
      required:
      - key
      - reason
      - required_checks
      - required_document_kinds
      - require_source_of_funds
      - require_source_of_wealth
      - evidence_max_age_days
      - next_review_months
      - effective_from
      - effective_to
      - trust_kind
      type: object

    ReviewRequirementVersion:
      additionalProperties: false
      properties:
        decided_at:
          format: date-time
          type: string
        decided_by:
          format: uuid
          type: string
        effective_from:
          format: date-time
          type: string
        effective_to:
          format: date-time
          type: string
        evidence_max_age_days:
          type: integer
        id:
          format: uuid
          type: string
        key:
          type: string
        next_review_months:
          type: integer
        payload_sha256:
          type: string
        proposed_at:
          format: date-time
          type: string
        proposed_by:
          format: uuid
          type: string
        reason:
          type: string
        require_source_of_funds:
          type: boolean
        require_source_of_wealth:
          type: boolean
        required_checks:
          items:
            type: string
          type: array
        required_document_kinds:
          items:
            type: string
          type: array
        status:
          type: string
          enum:
          - pending
          - approved
          - rejected
        version:
          type: integer
        trust_kind:
          type: string
          enum:
          - institution_reviewed
          - synthetic_rehearsal
          description: Rehearsal definitions cannot satisfy the required production governance
            gate.
      required:
      - id
      - key
      - reason
      - required_checks
      - required_document_kinds
      - require_source_of_funds
      - require_source_of_wealth
      - evidence_max_age_days
      - next_review_months
      - effective_from
      - effective_to
      - version
      - status
      - payload_sha256
      - proposed_by
      - proposed_at
      - trust_kind
      type: object

    ReviewRequirements:
      additionalProperties: false
      properties:
        pinned_at:
          format: date-time
          type: string
        requirement:
          $ref: '#/components/schemas/ReviewRequirementVersion'
        review_id:
          format: uuid
          type: string
        status:
          type: string
          enum:
          - pinned
          - unconfigured
      required:
      - review_id
      - status
      type: object

    SamplingPlan:
      additionalProperties: false
      properties:
        decided_at:
          format: date-time
          type: string
        decided_by:
          format: uuid
          type: string
        id:
          format: uuid
          type: string
        key:
          type: string
        outcome:
          type: string
        payload_sha256:
          type: string
        proposed_at:
          format: date-time
          type: string
        proposed_by:
          format: uuid
          type: string
        remediation_due_hours:
          type: integer
        review_due_hours:
          type: integer
        sample_size:
          type: integer
        status:
          type: string
          enum:
          - pending
          - approved
          - rejected
        version:
          type: integer
      required:
      - id
      - key
      - sample_size
      - review_due_hours
      - remediation_due_hours
      - version
      - status
      - payload_sha256
      - proposed_by
      - proposed_at
      type: object

    SamplingPlanInput:
      additionalProperties: false
      properties:
        key:
          type: string
        outcome:
          type: string
        remediation_due_hours:
          type: integer
        review_due_hours:
          type: integer
        sample_size:
          type: integer
      required:
      - key
      - sample_size
      - review_due_hours
      - remediation_due_hours
      type: object

    SamplingRun:
      additionalProperties: false
      properties:
        cohort_count:
          type: integer
        cohort_sha256:
          type: string
        created_at:
          format: date-time
          type: string
        created_by:
          format: uuid
          type: string
        external_reference:
          type: string
        id:
          format: uuid
          type: string
        plan_id:
          format: uuid
          type: string
        selected_count:
          type: integer
        window_from:
          format: date-time
          type: string
        window_to:
          format: date-time
          type: string
      required:
      - id
      - plan_id
      - external_reference
      - window_from
      - window_to
      - cohort_count
      - cohort_sha256
      - selected_count
      - created_by
      - created_at
      type: object

    SamplingRunInput:
      additionalProperties: false
      properties:
        external_reference:
          type: string
        plan_id:
          format: uuid
          type: string
        window_from:
          format: date-time
          type: string
        window_to:
          format: date-time
          type: string
      required:
      - plan_id
      - external_reference
      - window_from
      - window_to
      type: object

    SupervisorSample:
      additionalProperties: false
      properties:
        assignee_id:
          format: uuid
          type: string
        case_id:
          format: uuid
          type: string
        case_reference:
          type: string
        claimed_at:
          format: date-time
          type: string
        due_at:
          format: date-time
          type: string
        id:
          format: uuid
          type: string
        quality_review_id:
          format: uuid
          type: string
        run_id:
          format: uuid
          type: string
        selection_rank:
          type: integer
        status:
          type: string
          enum:
          - pending
          - overdue
          - reviewed
      required:
      - id
      - run_id
      - case_id
      - case_reference
      - due_at
      - selection_rank
      - status
      type: object

    DocumentReferenceInput:
      type: object
      required:
      - document_id
      properties:
        document_id:
          type: string
          format: uuid
      additionalProperties: false

    RemediationAcceptanceInput:
      type: object
      required:
      - findings
      properties:
        findings:
          type: string
          minLength: 1
          maxLength: 20000
      additionalProperties: false

    EmptyInput:
      type: object
      additionalProperties: false

    ReviewRequirementVersionPage:
      type: object
      required:
      - items
      additionalProperties: false
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/ReviewRequirementVersion'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64

    ReviewAssigneePage:
      type: object
      required:
      - items
      additionalProperties: false
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/ReviewAssignee'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64

    ReviewEvidenceRequestPage:
      type: object
      required:
      - items
      additionalProperties: false
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/ReviewEvidenceRequest'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64

    SamplingPlanPage:
      type: object
      required:
      - items
      additionalProperties: false
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/SamplingPlan'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64

    SamplingRunPage:
      type: object
      required:
      - items
      additionalProperties: false
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/SamplingRun'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64

    SupervisorSamplePage:
      type: object
      required:
      - items
      additionalProperties: false
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/SupervisorSample'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64

    RemediationAssigneePage:
      type: object
      required:
      - items
      additionalProperties: false
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/RemediationAssignee'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64

    OwnershipSnapshotPage:
      type: object
      required:
      - items
      additionalProperties: false
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/OwnershipSnapshot'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64

    OnboardingDocumentPage:
      type: object
      required:
      - items
      additionalProperties: false
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/OnboardingDocument'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64

    LinkedOwnershipAccountPage:
      type: object
      required:
      - items
      additionalProperties: false
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/LinkedOwnershipAccount'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64

    LinkedOwnershipActivityPage:
      type: object
      required:
      - items
      additionalProperties: false
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/LinkedOwnershipActivity'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64

    ExecutableScenario:
      additionalProperties: false
      properties:
        aggregates:
          $ref: '#/components/schemas/WindowAggregates'
        expected_alert:
          type: boolean
        key:
          type: string
        segment:
          type: string
        subject:
          $ref: '#/components/schemas/ScenarioSubject'
      required:
      - key
      - segment
      - expected_alert
      - subject
      - aggregates
      type: object

    FXDecision:
      additionalProperties: false
      properties:
        conversion:
          $ref: '#/components/schemas/FXConversion'
        id:
          format: uuid
          type: string
        purpose:
          type: string
          enum:
          - threshold_calibration
          - report_preparation
          - case_analysis
          - operational_calculation
        recorded_at:
          format: date-time
          type: string
        recorded_by:
          format: uuid
          type: string
      required:
      - id
      - purpose
      - conversion
      - recorded_by
      - recorded_at
      type: object

    FXDecisionInput:
      additionalProperties: false
      properties:
        amount_minor:
          type: integer
        as_of:
          format: date-time
          type: string
        base_currency:
          type: string
        purpose:
          type: string
          enum:
          - threshold_calibration
          - report_preparation
          - case_analysis
          - operational_calculation
        quote_currency:
          type: string
        reference_id:
          format: uuid
          type: string
      required:
      - reference_id
      - base_currency
      - quote_currency
      - amount_minor
      - as_of
      - purpose
      type: object

    PairedResult:
      additionalProperties: false
      properties:
        account_id:
          format: uuid
          type: string
        baseline_aggregates:
          $ref: '#/components/schemas/WindowAggregates'
        baseline_alert:
          type: boolean
        baseline_geography:
          $ref: '#/components/schemas/GeographyEvidence'
        baseline_parameters:
          additionalProperties: {}
          type: object
        candidate_aggregates:
          $ref: '#/components/schemas/WindowAggregates'
        candidate_alert:
          type: boolean
        candidate_geography:
          $ref: '#/components/schemas/GeographyEvidence'
        candidate_parameters:
          additionalProperties: {}
          type: object
        expected_alert:
          type: boolean
        segment:
          type: string
        subject:
          $ref: '#/components/schemas/ScenarioSubject'
        transaction_id:
          format: uuid
          type: string
      required:
      - transaction_id
      - account_id
      - expected_alert
      - baseline_alert
      - candidate_alert
      - subject
      - segment
      - baseline_aggregates
      - candidate_aggregates
      - baseline_parameters
      - candidate_parameters
      type: object

    QualityMetrics:
      additionalProperties: false
      properties:
        alerts:
          type: integer
        distinct_alert_subjects:
          type: integer
        false_negative:
          type: integer
        false_positive:
          type: integer
        false_positive_rate:
          type: number
        precision:
          type: number
        recall:
          type: number
        true_negative:
          type: integer
        true_positive:
          type: integer
      required:
      - true_positive
      - false_positive
      - true_negative
      - false_negative
      - alerts
      - precision
      - recall
      - false_positive_rate
      - distinct_alert_subjects
      type: object

    ReferenceDependency:
      additionalProperties: false
      properties:
        key:
          type: string
        kind:
          type: string
        payload_sha256:
          type: string
        reference_id:
          format: uuid
          type: string
        source_sha256:
          type: string
        version:
          type: integer
      required:
      - reference_id
      - kind
      - key
      - version
      - payload_sha256
      - source_sha256
      type: object

    RuleAssurance:
      additionalProperties: false
      properties:
        artifact_sha256:
          type: string
        candidate_version_id:
          format: uuid
          type: string
        comparison_id:
          format: uuid
          type: string
        dataset_id:
          format: uuid
          type: string
        eligible:
          type: boolean
        parameter_sha256:
          type: string
        reasons:
          items:
            type: string
          type: array
        reference_dependency_sha256:
          type: string
        required:
          type: boolean
        scenario_suite_id:
          format: uuid
          type: string
      required:
      - candidate_version_id
      - required
      - eligible
      - reasons
      - artifact_sha256
      - parameter_sha256
      - reference_dependency_sha256
      type: object

    RuleComparison:
      additionalProperties: false
      properties:
        baseline:
          $ref: '#/components/schemas/QualityMetrics'
        baseline_artifact_sha256:
          type: string
        baseline_basis:
          type: string
        baseline_version_id:
          format: uuid
          type: string
        candidate:
          $ref: '#/components/schemas/QualityMetrics'
        candidate_artifact_sha256:
          type: string
        candidate_version_id:
          format: uuid
          type: string
        dataset_id:
          format: uuid
          type: string
        dataset_sha256:
          type: string
        decided_at:
          format: date-time
          type: string
        decided_by:
          format: uuid
          type: string
        failures:
          items:
            type: string
          type: array
        id:
          format: uuid
          type: string
        maximum_alert_count:
          type: integer
          format: int64
          minimum: 0
          maximum: 5000
          description: Required positive absolute workload budget when baseline_version_id is omitted for a new typology.
        maximum_alert_increase_percent:
          type: number
          minimum: 0
          maximum: 100
        maximum_false_positive_rate:
          type: number
          minimum: 0
          maximum: 1
          exclusiveMaximum: true
        minimum_recall:
          type: number
          minimum: 0
          exclusiveMinimum: true
          maximum: 1
        parameter_sha256:
          type: string
        passed:
          type: boolean
        proposed_at:
          format: date-time
          type: string
        proposed_by:
          format: uuid
          type: string
        reference_dependencies:
          items:
            $ref: '#/components/schemas/ReferenceDependency'
          type: array
        reference_dependency_sha256:
          type: string
        results:
          items:
            $ref: '#/components/schemas/PairedResult'
          type: array
        scenario_suite_id:
          format: uuid
          type: string
        scenario_suite_sha256:
          type: string
        status:
          type: string
          enum:
          - pending
          - approved
          - rejected
        workload_basis:
          type: string
      required:
      - reference_dependencies
      - baseline_basis
      - id
      - dataset_id
      - scenario_suite_id
      - baseline_version_id
      - candidate_version_id
      - minimum_recall
      - maximum_false_positive_rate
      - maximum_alert_increase_percent
      - dataset_sha256
      - scenario_suite_sha256
      - baseline_artifact_sha256
      - candidate_artifact_sha256
      - parameter_sha256
      - reference_dependency_sha256
      - baseline
      - candidate
      - results
      - passed
      - failures
      - workload_basis
      - status
      - proposed_by
      - proposed_at
      type: object

    RuleComparisonInput:
      additionalProperties: false
      properties:
        baseline_version_id:
          description: Omit only for a new typology with no active or retired version.
          format: uuid
          type: string
        candidate_version_id:
          format: uuid
          type: string
        dataset_id:
          format: uuid
          type: string
        maximum_alert_count:
          type: integer
          format: int64
          minimum: 0
          maximum: 5000
          description: Required positive absolute workload budget when baseline_version_id is omitted for a new typology.
        maximum_alert_increase_percent:
          type: number
          minimum: 0
          maximum: 100
        maximum_false_positive_rate:
          type: number
          minimum: 0
          maximum: 1
          exclusiveMaximum: true
        minimum_recall:
          type: number
          minimum: 0
          exclusiveMinimum: true
          maximum: 1
        scenario_suite_id:
          format: uuid
          type: string
      required:
      - dataset_id
      - scenario_suite_id
      - candidate_version_id
      - minimum_recall
      - maximum_false_positive_rate
      - maximum_alert_increase_percent
      type: object

    RuleComparisonSummary:
      additionalProperties: false
      properties:
        baseline:
          $ref: '#/components/schemas/QualityMetrics'
        baseline_version_id:
          format: uuid
          type: string
        candidate:
          $ref: '#/components/schemas/QualityMetrics'
        candidate_version_id:
          format: uuid
          type: string
        dataset_id:
          format: uuid
          type: string
        decided_at:
          format: date-time
          type: string
        decided_by:
          format: uuid
          type: string
        failures:
          items:
            type: string
          type: array
        id:
          format: uuid
          type: string
        maximum_alert_count:
          type: integer
          format: int64
          minimum: 0
          maximum: 5000
          description: Required positive absolute workload budget when baseline_version_id is omitted for a new typology.
        maximum_alert_increase_percent:
          type: number
          minimum: 0
          maximum: 100
        maximum_false_positive_rate:
          type: number
          minimum: 0
          maximum: 1
          exclusiveMaximum: true
        minimum_recall:
          type: number
          minimum: 0
          exclusiveMinimum: true
          maximum: 1
        passed:
          type: boolean
        proposed_at:
          format: date-time
          type: string
        proposed_by:
          format: uuid
          type: string
        scenario_suite_id:
          format: uuid
          type: string
        status:
          type: string
          enum:
          - pending
          - approved
          - rejected
        workload_basis:
          type: string
      required:
      - id
      - dataset_id
      - scenario_suite_id
      - baseline_version_id
      - candidate_version_id
      - minimum_recall
      - maximum_false_positive_rate
      - maximum_alert_increase_percent
      - baseline
      - candidate
      - passed
      - failures
      - workload_basis
      - status
      - proposed_by
      - proposed_at
      type: object

    ScenarioResult:
      additionalProperties: false
      properties:
        actual_alert:
          type: boolean
        error:
          type: string
        expected_alert:
          type: boolean
        geography:
          $ref: '#/components/schemas/GeographyEvidence'
        key:
          type: string
        parameters:
          additionalProperties: {}
          type: object
        passed:
          type: boolean
      required:
      - key
      - expected_alert
      - actual_alert
      - passed
      - parameters
      type: object

    ScenarioSubject:
      additionalProperties: false
      properties:
        customer_type: {type: string, maxLength: 200}
        customer_industry: {type: string, maxLength: 200}
        customer_pep_status: {type: string, maxLength: 200}
        customer_kyc_tier: {type: string, maxLength: 200}
        relationship_age_days: {type: integer, format: int64, minimum: 0}
        account_dormant_days:
          type: integer
        amount_minor:
          type: integer
        booking_ts:
          format: date-time
          type: string
        channel:
          type: string
        corridor_country:
          type: string
        currency:
          type: string
        customer_risk:
          type: string
        direction:
          type: string
        event_type:
          type: string
      required:
      - booking_ts
      - event_type
      - direction
      - amount_minor
      - currency
      - channel
      - corridor_country
      - customer_risk
      - account_dormant_days
      type: object

    ScenarioSuite:
      additionalProperties: false
      properties:
        artifact_sha256:
          type: string
        candidate_version_id:
          format: uuid
          type: string
        decided_at:
          format: date-time
          type: string
        decided_by:
          format: uuid
          type: string
        id:
          format: uuid
          type: string
        key:
          type: string
        parameter_sha256:
          type: string
        passed:
          type: boolean
        payload_sha256:
          type: string
        proposed_at:
          format: date-time
          type: string
        proposed_by:
          format: uuid
          type: string
        reference_dependencies:
          items:
            $ref: '#/components/schemas/ReferenceDependency'
          type: array
        reference_dependency_sha256:
          type: string
        results:
          items:
            $ref: '#/components/schemas/ScenarioResult'
          type: array
        scenarios:
          items:
            $ref: '#/components/schemas/ExecutableScenario'
          type: array
          minItems: 2
          maxItems: 100
        status:
          type: string
          enum:
          - pending
          - approved
          - rejected
        trust_kind:
          type: string
          enum:
          - institution_reviewed
          - synthetic_rehearsal
      required:
      - reference_dependencies
      - id
      - key
      - candidate_version_id
      - trust_kind
      - scenarios
      - payload_sha256
      - artifact_sha256
      - parameter_sha256
      - reference_dependency_sha256
      - results
      - passed
      - status
      - proposed_by
      - proposed_at
      type: object

    ScenarioSuiteInput:
      additionalProperties: false
      properties:
        candidate_version_id:
          format: uuid
          type: string
        key:
          type: string
        scenarios:
          items:
            $ref: '#/components/schemas/ExecutableScenario'
          type: array
          minItems: 2
          maxItems: 100
        trust_kind:
          type: string
          enum:
          - institution_reviewed
          - synthetic_rehearsal
      required:
      - key
      - candidate_version_id
      - trust_kind
      - scenarios
      type: object

    ScenarioSuiteSummary:
      additionalProperties: false
      properties:
        artifact_sha256:
          type: string
        candidate_version_id:
          format: uuid
          type: string
        decided_at:
          format: date-time
          type: string
        decided_by:
          format: uuid
          type: string
        id:
          format: uuid
          type: string
        key:
          type: string
        parameter_sha256:
          type: string
        passed:
          type: boolean
        payload_sha256:
          type: string
        proposed_at:
          format: date-time
          type: string
        proposed_by:
          format: uuid
          type: string
        reference_dependency_sha256:
          type: string
        scenario_count:
          type: integer
        status:
          type: string
          enum:
          - pending
          - approved
          - rejected
        trust_kind:
          type: string
          enum:
          - institution_reviewed
          - synthetic_rehearsal
      required:
      - id
      - key
      - candidate_version_id
      - trust_kind
      - scenario_count
      - artifact_sha256
      - parameter_sha256
      - reference_dependency_sha256
      - payload_sha256
      - passed
      - status
      - proposed_by
      - proposed_at
      type: object

    ValidationDataset:
      additionalProperties: false
      properties:
        decided_at:
          format: date-time
          type: string
        decided_by:
          format: uuid
          type: string
        id:
          format: uuid
          type: string
        key:
          type: string
        labels:
          items:
            $ref: '#/components/schemas/ValidationLabel'
          type: array
          minItems: 30
          maxItems: 5000
        negative_count:
          type: integer
        payload_sha256:
          type: string
        positive_count:
          type: integer
        proposed_at:
          format: date-time
          type: string
        proposed_by:
          format: uuid
          type: string
        source_sha256:
          type: string
        source_uri:
          type: string
          format: uri
        status:
          type: string
          enum:
          - pending
          - approved
          - rejected
        trust_kind:
          type: string
          enum:
          - institution_reviewed
          - synthetic_rehearsal
        version:
          type: integer
        window_from:
          format: date-time
          type: string
        window_to:
          format: date-time
          type: string
      required:
      - id
      - key
      - trust_kind
      - source_uri
      - source_sha256
      - window_from
      - window_to
      - labels
      - version
      - payload_sha256
      - positive_count
      - negative_count
      - status
      - proposed_by
      - proposed_at
      type: object

    ValidationDatasetInput:
      additionalProperties: false
      properties:
        key:
          type: string
        labels:
          items:
            $ref: '#/components/schemas/ValidationLabel'
          type: array
          minItems: 30
          maxItems: 5000
        source_sha256:
          type: string
        source_uri:
          type: string
          format: uri
        trust_kind:
          type: string
          enum:
          - institution_reviewed
          - synthetic_rehearsal
        window_from:
          format: date-time
          type: string
        window_to:
          format: date-time
          type: string
      required:
      - key
      - trust_kind
      - source_uri
      - source_sha256
      - window_from
      - window_to
      - labels
      type: object

    ValidationDatasetSummary:
      additionalProperties: false
      properties:
        decided_at:
          format: date-time
          type: string
        decided_by:
          format: uuid
          type: string
        id:
          format: uuid
          type: string
        key:
          type: string
        negative_count:
          type: integer
        payload_sha256:
          type: string
        positive_count:
          type: integer
        proposed_at:
          format: date-time
          type: string
        proposed_by:
          format: uuid
          type: string
        source_sha256:
          type: string
        source_uri:
          type: string
        status:
          type: string
          enum:
          - pending
          - approved
          - rejected
        trust_kind:
          type: string
          enum:
          - institution_reviewed
          - synthetic_rehearsal
        version:
          type: integer
        window_from:
          format: date-time
          type: string
        window_to:
          format: date-time
          type: string
      required:
      - id
      - key
      - version
      - trust_kind
      - source_uri
      - source_sha256
      - payload_sha256
      - window_from
      - window_to
      - positive_count
      - negative_count
      - status
      - proposed_by
      - proposed_at
      type: object

    ValidationLabel:
      additionalProperties: false
      properties:
        booking_ts:
          format: date-time
          type: string
        expected_alert:
          type: boolean
        transaction_id:
          format: uuid
          type: string
      required:
      - transaction_id
      - booking_ts
      - expected_alert
      type: object

    ValidationSubjectReference:
      additionalProperties: false
      properties:
        account_id:
          format: uuid
          type: string
        amount_minor:
          type: integer
        booking_ts:
          format: date-time
          type: string
        currency:
          type: string
        customer_id:
          format: uuid
          type: string
        direction:
          type: string
        external_reference:
          type: string
        id:
          format: uuid
          type: string
      required:
      - id
      - external_reference
      - booking_ts
      - account_id
      - customer_id
      - direction
      - amount_minor
      - currency
      type: object

    WindowAggregates:
      additionalProperties: false
      properties:
        credit_count:
          type: integer
        credit_minor:
          type: integer
        currency:
          type: string
        debit_count:
          type: integer
        debit_minor:
          type: integer
        profile:
          $ref: '#/components/schemas/ActivityBaseline'

        peer:
          $ref: '#/components/schemas/ActivityBaseline'
        counterparty_bank: {type: string, description: Bank namespace of a bank-qualified counterparty window.}
        counterparty_source: {type: string, description: Source-local namespace when the bank is unknown; never merged with a known bank or another source.}
        profile_credit:
          $ref: '#/components/schemas/ActivityBaseline'
        peer_credit:
          $ref: '#/components/schemas/ActivityBaseline'
        profile_debit:
          $ref: '#/components/schemas/ActivityBaseline'
        peer_debit:
          $ref: '#/components/schemas/ActivityBaseline'

        cash_minor:
          type: integer
        channel_minor:
          type: integer
        round_amount_count:
          type: integer
        network_neighbour_count: {type: integer, format: int64}
        shared_device_count: {type: integer, format: int64}
        loan_back_minor: {type: integer, format: int64}
        loan_back_count: {type: integer, format: int64}
        trade_value_mismatch_minor: {type: integer, format: int64}
        trade_value_mismatch_count: {type: integer, format: int64}
        imto_value_mismatch_minor: {type: integer, format: int64}
        imto_value_mismatch_count: {type: integer, format: int64}
        business_evidence:
          type: array
          items: { $ref: "#/components/schemas/BusinessEvidenceReference" }
        business_evidence_truncated: {type: boolean}
        shared_phone_account_count: {type: integer, format: int64}
        shared_phone_count: {type: integer, format: int64}
        shared_beneficiary_count: {type: integer, format: int64}
        fan_in_count:
          type: integer
        fan_out_count:
          type: integer
        credit_7d_minor:
          type: integer
        debit_7d_minor:
          type: integer
        credit_30d_minor:
          type: integer
        debit_30d_minor:
          type: integer
        credit_90d_minor:
          type: integer
        debit_90d_minor:
          type: integer
        outflow_bps:
          type: integer
        distinct_corridors:
          type: integer
        distinct_counterparties:
          type: integer
        lifecycle_adjusted_count:
          type: integer
        max_minor:
          type: integer
        raw_sum_minor:
          type: integer
        raw_txn_count:
          type: integer
        sum_minor:
          type: integer
        txn_count:
          type: integer
      required:
      - currency
      - txn_count
      - sum_minor
      - max_minor
      - credit_minor
      - debit_minor
      - credit_count
      - debit_count
      - distinct_counterparties
      - distinct_corridors
      - raw_txn_count
      - raw_sum_minor
      - lifecycle_adjusted_count
      type: object

    ValidationDatasetSummaryPage:
      type: object
      required:
      - items
      additionalProperties: false
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/ValidationDatasetSummary'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64

    ScenarioSuiteSummaryPage:
      type: object
      required:
      - items
      additionalProperties: false
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/ScenarioSuiteSummary'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64

    RuleComparisonSummaryPage:
      type: object
      required:
      - items
      additionalProperties: false
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/RuleComparisonSummary'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64

    ValidationSubjectReferencePage:
      type: object
      required:
      - items
      additionalProperties: false
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/ValidationSubjectReference'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64

    FXDecisionPage:
      type: object
      required:
      - items
      additionalProperties: false
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/FXDecision'
        next_cursor:
          type: string
        truncated:
          type: boolean
        truncation_reason:
          type: string
        total_estimate:
          type: integer
          format: int64
    RuleOutcomeInput:
      type: object
      additionalProperties: false
      properties:
        rule_key:
          type: string
        window_from:
          type: string
          format: date-time
        window_to:
          type: string
          format: date-time
        segment:
          type: string
        minimum_samples:
          type: integer
          format: int64
        false_positive_target:
          type: number
      required:
      - rule_key
      - window_from
      - window_to
      - minimum_samples
      - false_positive_target
    RuleOutcomeRollup:
      type: object
      additionalProperties: false
      properties:
        rule_key:
          type: string
        window_from:
          type: string
          format: date-time
        window_to:
          type: string
          format: date-time
        segment:
          type: string
        minimum_samples:
          type: integer
          format: int64
        false_positive_target:
          type: number
        id:
          type: string
          format: uuid
        versions:
          type: array
          items:
            $ref: '#/components/schemas/OutcomeReview'
        created_at:
          type: string
          format: date-time
        false_positive_rate:
          type: number
        alerts:
          type: integer
          format: int64
        reviewed:
          type: integer
          format: int64
        false_positive:
          type: integer
          format: int64
        actioned:
          type: integer
          format: int64
        cases:
          type: integer
          format: int64
        case_linked_alerts:
          type: integer
          format: int64
        str_cases:
          type: integer
          format: int64
      required:
      - rule_key
      - window_from
      - window_to
      - minimum_samples
      - false_positive_target
      - id
      - versions
      - created_at
      - alerts
      - reviewed
      - false_positive
      - actioned
      - cases
      - case_linked_alerts
      - str_cases

    TransactionBusinessEvidence:
      type: object
      additionalProperties: false
      description: |
        Source-attested business evidence for this exact payment, immutable at ingest.
        The document reference and digest identify the upstream assertion, not independent
        verification. Loan collateral debits and disbursement credits require a lender
        counterparty_bank and counterparty_account and common source/agreement reference. Settlement declared
        amounts must be positive expected allocations for this exact payment in its own
        currency, after upstream fee/FX allocation; whole invoice or send amounts must not
        be substituted. Only posted and correction events may carry evidence.
      required: [kind, agreement_ref, evidence_ref, evidence_sha256]
      properties:
        kind: {type: string, enum: [loan_collateral_transfer, loan_disbursement, trade_settlement, imto_settlement]}
        agreement_ref: {type: string, minLength: 1, maxLength: 128}
        evidence_ref: {type: string, minLength: 1, maxLength: 128}
        evidence_sha256: {type: string, pattern: '^[a-f0-9]{64}$'}
        declared_amount_minor: {type: integer, format: int64, minimum: 1, maximum: 18446744073709551}
        declared_currency: {type: string, pattern: '^[A-Z]{3}$'}
    BusinessEvidenceReference:
      type: object
      additionalProperties: false
      required: [transaction_id, booking_ts, source, kind, agreement_ref, evidence_ref, evidence_sha256, amount_minor, currency]
      properties:
        counterparty_account: {type: string}
        counterparty_bank: {type: string}
        transaction_id: {type: string, format: uuid}
        booking_ts: {type: string, format: date-time}
        source: {type: string}
        kind: {type: string}
        agreement_ref: {type: string}
        evidence_ref: {type: string}
        evidence_sha256: {type: string, pattern: '^[a-f0-9]{64}$'}
        amount_minor: {type: integer, format: int64}
        currency: {type: string}
        declared_amount_minor: {type: integer, format: int64}
        declared_currency: {type: string}
