CREATE TABLE IF NOT EXISTS admission_operations (
    operation_id TEXT NOT NULL PRIMARY KEY
        CHECK (length(operation_id) = 64 AND operation_id NOT GLOB '*[^0-9a-f]*'),
    request_namespace_digest TEXT NOT NULL
        CHECK (length(request_namespace_digest) = 64
               AND request_namespace_digest NOT GLOB '*[^0-9a-f]*'),
    request_id TEXT NOT NULL CHECK (length(request_id) BETWEEN 1 AND 512),
    operation_json BLOB NOT NULL CHECK (length(operation_json) BETWEEN 1 AND 262144),
    state TEXT NOT NULL CHECK (state IN (
        'prepared', 'broker_attempt_registered', 'approval_required',
        'budget_authorized', 'approval_reserved', 'ready_to_dispatch',
        'capture_pending', 'dispatch_committed', 'finalizing', 'completed',
        'compensated_before_dispatch', 'not_accepted_after_dispatch_commit',
        'outcome_unknown_after_dispatch', 'mutation_ready', 'mutation_submitted',
        'economic_mutation_applied', 'economic_mutation_not_applied'
    )),
    terminal INTEGER NOT NULL CHECK (terminal IN (0, 1)),
    coordinator_lease_epoch INTEGER NOT NULL CHECK (coordinator_lease_epoch > 0),
    version INTEGER NOT NULL CHECK (version > 0),
    created_at_unix_ms INTEGER NOT NULL CHECK (created_at_unix_ms > 0),
    updated_at_unix_ms INTEGER NOT NULL
        CHECK (updated_at_unix_ms >= created_at_unix_ms),
    recovery_claimant_id TEXT,
    recovery_coordinator_lease_id TEXT,
    recovery_coordinator_lease_epoch INTEGER,
    recovery_claimed_version INTEGER,
    recovery_expires_at_unix_ms INTEGER,
    recovery_store_uuid TEXT,
    recovery_store_lease_id TEXT,
    recovery_store_owner_epoch INTEGER,
    CHECK (
        (recovery_claimant_id IS NULL
         AND recovery_coordinator_lease_id IS NULL
         AND recovery_coordinator_lease_epoch IS NULL
         AND recovery_claimed_version IS NULL
         AND recovery_expires_at_unix_ms IS NULL
         AND recovery_store_uuid IS NULL
         AND recovery_store_lease_id IS NULL
         AND recovery_store_owner_epoch IS NULL)
        OR
        (length(recovery_claimant_id) BETWEEN 1 AND 512
         AND length(recovery_coordinator_lease_id) BETWEEN 1 AND 512
         AND recovery_coordinator_lease_epoch > 0
         AND recovery_claimed_version > 0
         AND recovery_expires_at_unix_ms > 0
         AND recovery_store_uuid <> ''
         AND recovery_store_lease_id <> ''
         AND recovery_store_owner_epoch > 0)
    )
);

CREATE UNIQUE INDEX IF NOT EXISTS admission_operations_replay_key
    ON admission_operations(request_namespace_digest, request_id);

CREATE INDEX IF NOT EXISTS admission_operations_recovery
    ON admission_operations(
        terminal, recovery_expires_at_unix_ms, updated_at_unix_ms, operation_id
    );

CREATE TABLE IF NOT EXISTS admission_operation_commit_meta (
    singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
    head_sequence INTEGER NOT NULL CHECK (head_sequence >= 0),
    head_chain_digest TEXT NOT NULL CHECK (
        length(head_chain_digest) = 64
        AND head_chain_digest NOT GLOB '*[^0-9a-f]*'
    ),
    trusted_time_high_water_unix_ms INTEGER NOT NULL
        CHECK (trusted_time_high_water_unix_ms >= 0)
);

INSERT INTO admission_operation_commit_meta (
    singleton, head_sequence, head_chain_digest,
    trusted_time_high_water_unix_ms
)
VALUES (
    1, 0,
    '0000000000000000000000000000000000000000000000000000000000000000',
    0
)
ON CONFLICT(singleton) DO NOTHING;

CREATE TABLE IF NOT EXISTS admission_operation_commits (
    commit_sequence INTEGER PRIMARY KEY CHECK (commit_sequence > 0),
    operation_id TEXT NOT NULL,
    operation_version INTEGER NOT NULL CHECK (operation_version > 0),
    mutation_kind TEXT NOT NULL CHECK (
        mutation_kind IN (
            'begin', 'compare_and_swap', 'recovery_claim', 'participant_update',
            'channel_reservation_finalized'
        )
    ),
    operation_digest TEXT NOT NULL
        CHECK (length(operation_digest) = 64
               AND operation_digest NOT GLOB '*[^0-9a-f]*'),
    recovery_claim_digest TEXT CHECK (
        recovery_claim_digest IS NULL
        OR (length(recovery_claim_digest) = 64
            AND recovery_claim_digest NOT GLOB '*[^0-9a-f]*')
    ),
    participant_digest TEXT CHECK (
        participant_digest IS NULL
        OR (length(participant_digest) = 64
            AND participant_digest NOT GLOB '*[^0-9a-f]*')
    ),
    previous_chain_digest TEXT NOT NULL CHECK (
        length(previous_chain_digest) = 64
        AND previous_chain_digest NOT GLOB '*[^0-9a-f]*'
    ),
    chain_digest TEXT NOT NULL CHECK (
        length(chain_digest) = 64
        AND chain_digest NOT GLOB '*[^0-9a-f]*'
    ),
    store_uuid TEXT NOT NULL CHECK (store_uuid <> ''),
    store_lease_id TEXT NOT NULL CHECK (store_lease_id <> ''),
    store_owner_epoch INTEGER NOT NULL CHECK (store_owner_epoch > 0),
    recorded_at_unix_ms INTEGER NOT NULL CHECK (recorded_at_unix_ms > 0),
    FOREIGN KEY (operation_id) REFERENCES admission_operations(operation_id),
    FOREIGN KEY (store_uuid, store_owner_epoch)
        REFERENCES chio_serving_leases(store_uuid, owner_epoch),
    CHECK (
        (mutation_kind = 'begin'
         AND recovery_claim_digest IS NULL)
        OR (mutation_kind = 'recovery_claim'
            AND recovery_claim_digest IS NOT NULL
            AND participant_digest IS NULL)
        OR (mutation_kind = 'compare_and_swap'
            AND recovery_claim_digest IS NOT NULL)
        OR (mutation_kind = 'participant_update'
            AND recovery_claim_digest IS NOT NULL
            AND participant_digest IS NOT NULL)
        OR (mutation_kind = 'channel_reservation_finalized'
            AND recovery_claim_digest IS NOT NULL
            AND participant_digest IS NOT NULL)
    )
);

CREATE INDEX IF NOT EXISTS admission_operation_commits_operation
    ON admission_operation_commits(operation_id, commit_sequence);
END;
END;
END;
END;
END;
END;
END;
END;

CREATE TABLE IF NOT EXISTS threshold_approval_proposals (
    proposal_id TEXT NOT NULL PRIMARY KEY CHECK (length(proposal_id) BETWEEN 1 AND 512),
    operation_id TEXT NOT NULL UNIQUE,
    request_id TEXT NOT NULL CHECK (length(request_id) BETWEEN 1 AND 512),
    governed_intent_hash TEXT NOT NULL CHECK (
        length(governed_intent_hash) = 64
        AND governed_intent_hash NOT GLOB '*[^0-9a-f]*'
    ),
    subject_fingerprint TEXT NOT NULL CHECK (subject_fingerprint <> ''),
    authorizing_capability_digest TEXT NOT NULL CHECK (
        length(authorizing_capability_digest) = 64
        AND authorizing_capability_digest NOT GLOB '*[^0-9a-f]*'
    ),
    policy_hash TEXT NOT NULL CHECK (
        length(policy_hash) = 64 AND policy_hash NOT GLOB '*[^0-9a-f]*'
    ),
    threshold INTEGER NOT NULL CHECK (threshold > 0),
    eligible_set_digest TEXT NOT NULL CHECK (
        length(eligible_set_digest) = 64
        AND eligible_set_digest NOT GLOB '*[^0-9a-f]*'
    ),
    proposal_created_at INTEGER NOT NULL CHECK (proposal_created_at >= 0),
    proposal_deadline INTEGER NOT NULL CHECK (proposal_deadline > proposal_created_at),
    proposal_hash TEXT NOT NULL UNIQUE CHECK (
        length(proposal_hash) = 64 AND proposal_hash NOT GLOB '*[^0-9a-f]*'
    ),
    approval_set_hash TEXT NOT NULL UNIQUE CHECK (
        length(approval_set_hash) = 64
        AND approval_set_hash NOT GLOB '*[^0-9a-f]*'
    ),
    proposal_json BLOB NOT NULL CHECK (length(proposal_json) BETWEEN 1 AND 262144),
    state TEXT NOT NULL CHECK (state IN ('reserved', 'committed', 'cancelled')),
    reserved_at_unix_ms INTEGER NOT NULL CHECK (reserved_at_unix_ms > 0),
    updated_at_unix_ms INTEGER NOT NULL CHECK (updated_at_unix_ms >= reserved_at_unix_ms),
    FOREIGN KEY (operation_id) REFERENCES admission_operations(operation_id)
);

CREATE TABLE IF NOT EXISTS threshold_approval_tokens (
    proposal_id TEXT NOT NULL,
    token_id TEXT NOT NULL CHECK (length(token_id) BETWEEN 1 AND 512),
    approver_fingerprint TEXT NOT NULL CHECK (approver_fingerprint <> ''),
    canonical_token_digest TEXT NOT NULL UNIQUE CHECK (
        length(canonical_token_digest) = 64
        AND canonical_token_digest NOT GLOB '*[^0-9a-f]*'
    ),
    token_json BLOB NOT NULL CHECK (length(token_json) BETWEEN 1 AND 262144),
    PRIMARY KEY (proposal_id, token_id),
    UNIQUE (proposal_id, approver_fingerprint),
    UNIQUE (proposal_id, canonical_token_digest),
    FOREIGN KEY (proposal_id) REFERENCES threshold_approval_proposals(proposal_id)
);
END;
END;
END;
END;
END;
END;

CREATE TRIGGER IF NOT EXISTS admission_operations_commit_threshold_approval
AFTER UPDATE OF state ON admission_operations
WHEN NEW.state IN (
    'dispatch_committed', 'finalizing', 'completed',
    'not_accepted_after_dispatch_commit', 'outcome_unknown_after_dispatch'
)
BEGIN
    UPDATE threshold_approval_proposals
    SET state = 'committed', updated_at_unix_ms = NEW.updated_at_unix_ms
    WHERE operation_id = NEW.operation_id AND state = 'reserved';
END;

CREATE TRIGGER IF NOT EXISTS admission_operations_cancel_threshold_approval
AFTER UPDATE OF state ON admission_operations
WHEN NEW.state = 'compensated_before_dispatch'
BEGIN
    UPDATE threshold_approval_proposals
    SET state = 'cancelled', updated_at_unix_ms = NEW.updated_at_unix_ms
    WHERE operation_id = NEW.operation_id AND state = 'reserved';
END;

CREATE TABLE IF NOT EXISTS admission_operation_terminal_projections (
    operation_id TEXT NOT NULL PRIMARY KEY,
    source_operation_version INTEGER NOT NULL CHECK (source_operation_version > 0),
    terminal_operation_version INTEGER NOT NULL CHECK (
        terminal_operation_version = source_operation_version + 1
    ),
    terminal_state TEXT NOT NULL CHECK (terminal_state IN (
        'completed', 'compensated_before_dispatch',
        'not_accepted_after_dispatch_commit', 'outcome_unknown_after_dispatch',
        'economic_mutation_applied', 'economic_mutation_not_applied'
    )),
    projection_body_digest TEXT NOT NULL CHECK (
        length(projection_body_digest) = 64
        AND projection_body_digest NOT GLOB '*[^0-9a-f]*'
    ),
    projection_digest TEXT NOT NULL CHECK (
        length(projection_digest) = 64
        AND projection_digest NOT GLOB '*[^0-9a-f]*'
    ),
    projection_json BLOB NOT NULL CHECK (
        length(projection_json) BETWEEN 1 AND 4194304
    ),
    manifest_json BLOB NOT NULL CHECK (
        length(manifest_json) BETWEEN 1 AND 262144
    ),
    record_count INTEGER NOT NULL CHECK (record_count BETWEEN 1 AND 32),
    committed_at_unix_ms INTEGER NOT NULL CHECK (committed_at_unix_ms > 0),
    store_uuid TEXT NOT NULL CHECK (store_uuid <> ''),
    store_lease_id TEXT NOT NULL CHECK (store_lease_id <> ''),
    store_owner_epoch INTEGER NOT NULL CHECK (store_owner_epoch > 0),
    FOREIGN KEY (operation_id) REFERENCES admission_operations(operation_id),
    FOREIGN KEY (store_uuid, store_owner_epoch)
        REFERENCES chio_serving_leases(store_uuid, owner_epoch)
);
END;
END;
END;

CREATE TABLE IF NOT EXISTS admission_operation_terminal_records (
    operation_id TEXT NOT NULL,
    record_kind TEXT NOT NULL CHECK (record_kind IN (
        'receipt', 'incident', 'tool_outcome', 'payment_terminal',
        'authorization_consumption', 'outcome_eligibility',
        'observation_attempt_zero', 'obligation', 'release_proof',
        'channel_terminal', 'economic_mutation_result', 'mutation_audit'
    )),
    record_id TEXT NOT NULL CHECK (length(record_id) BETWEEN 1 AND 512),
    record_digest TEXT NOT NULL CHECK (
        length(record_digest) = 64
        AND record_digest NOT GLOB '*[^0-9a-f]*'
    ),
    record_json BLOB NOT NULL CHECK (length(record_json) BETWEEN 1 AND 1048576),
    PRIMARY KEY (operation_id, record_kind, record_id),
    UNIQUE (record_kind, record_id),
    FOREIGN KEY (operation_id)
        REFERENCES admission_operation_terminal_projections(operation_id)
);

CREATE INDEX IF NOT EXISTS admission_operation_terminal_records_kind
    ON admission_operation_terminal_records(record_kind, operation_id);
END;
END;

CREATE TABLE IF NOT EXISTS obligation_atoms (
    obligation_id TEXT NOT NULL PRIMARY KEY CHECK (
        length(obligation_id) = 64
        AND obligation_id NOT GLOB '*[^0-9a-f]*'
    ),
    operation_id TEXT NOT NULL UNIQUE,
    atom_digest TEXT NOT NULL UNIQUE CHECK (
        length(atom_digest) = 64
        AND atom_digest NOT GLOB '*[^0-9a-f]*'
    ),
    source_receipt_id TEXT NOT NULL UNIQUE CHECK (
        length(source_receipt_id) BETWEEN 1 AND 512
    ),
    source_receipt_digest TEXT NOT NULL UNIQUE CHECK (
        length(source_receipt_digest) = 64
        AND source_receipt_digest NOT GLOB '*[^0-9a-f]*'
    ),
    atom_json BLOB NOT NULL CHECK (length(atom_json) BETWEEN 1 AND 1048576),
    committed_at_unix_ms INTEGER NOT NULL CHECK (committed_at_unix_ms > 0),
    store_uuid TEXT NOT NULL CHECK (store_uuid <> ''),
    store_lease_id TEXT NOT NULL CHECK (store_lease_id <> ''),
    store_owner_epoch INTEGER NOT NULL CHECK (store_owner_epoch > 0),
    UNIQUE (obligation_id, atom_digest),
    FOREIGN KEY (operation_id)
        REFERENCES admission_operation_terminal_projections(operation_id),
    FOREIGN KEY (store_uuid, store_owner_epoch)
        REFERENCES chio_serving_leases(store_uuid, owner_epoch)
);
END;
END;
END;

CREATE TABLE IF NOT EXISTS obligation_disposition_records (
    obligation_id TEXT NOT NULL,
    version INTEGER NOT NULL CHECK (version > 0),
    lifecycle_fence INTEGER NOT NULL CHECK (lifecycle_fence = version),
    atom_digest TEXT NOT NULL CHECK (
        length(atom_digest) = 64
        AND atom_digest NOT GLOB '*[^0-9a-f]*'
    ),
    disposition_digest TEXT NOT NULL UNIQUE CHECK (
        length(disposition_digest) = 64
        AND disposition_digest NOT GLOB '*[^0-9a-f]*'
    ),
    operation_id TEXT NOT NULL,
    record_json BLOB NOT NULL CHECK (length(record_json) BETWEEN 1 AND 1048576),
    committed_at_unix_ms INTEGER NOT NULL CHECK (committed_at_unix_ms > 0),
    store_uuid TEXT NOT NULL CHECK (store_uuid <> ''),
    store_lease_id TEXT NOT NULL CHECK (store_lease_id <> ''),
    store_owner_epoch INTEGER NOT NULL CHECK (store_owner_epoch > 0),
    PRIMARY KEY (obligation_id, version),
    FOREIGN KEY (obligation_id, atom_digest)
        REFERENCES obligation_atoms(obligation_id, atom_digest),
    FOREIGN KEY (operation_id)
        REFERENCES admission_operations(operation_id),
    FOREIGN KEY (store_uuid, store_owner_epoch)
        REFERENCES chio_serving_leases(store_uuid, owner_epoch)
);

CREATE INDEX IF NOT EXISTS obligation_disposition_records_operation
    ON obligation_disposition_records(operation_id, obligation_id, version);
END;
END;
END;

CREATE TABLE IF NOT EXISTS obligation_settlement_lifecycle_records (
    obligation_id TEXT NOT NULL,
    version INTEGER NOT NULL CHECK (version > 0),
    lifecycle_fence INTEGER NOT NULL CHECK (lifecycle_fence = version),
    atom_digest TEXT NOT NULL CHECK (
        length(atom_digest) = 64
        AND atom_digest NOT GLOB '*[^0-9a-f]*'
    ),
    lifecycle_digest TEXT NOT NULL UNIQUE CHECK (
        length(lifecycle_digest) = 64
        AND lifecycle_digest NOT GLOB '*[^0-9a-f]*'
    ),
    operation_id TEXT NOT NULL,
    record_json BLOB NOT NULL CHECK (length(record_json) BETWEEN 1 AND 1048576),
    committed_at_unix_ms INTEGER NOT NULL CHECK (committed_at_unix_ms > 0),
    store_uuid TEXT NOT NULL CHECK (store_uuid <> ''),
    store_lease_id TEXT NOT NULL CHECK (store_lease_id <> ''),
    store_owner_epoch INTEGER NOT NULL CHECK (store_owner_epoch > 0),
    PRIMARY KEY (obligation_id, version),
    FOREIGN KEY (obligation_id, atom_digest)
        REFERENCES obligation_atoms(obligation_id, atom_digest),
    FOREIGN KEY (operation_id)
        REFERENCES admission_operations(operation_id),
    FOREIGN KEY (store_uuid, store_owner_epoch)
        REFERENCES chio_serving_leases(store_uuid, owner_epoch)
);

CREATE INDEX IF NOT EXISTS obligation_settlement_lifecycle_records_operation
    ON obligation_settlement_lifecycle_records(operation_id, obligation_id, version);
END;
END;
END;

CREATE TABLE IF NOT EXISTS obligation_head_commits (
    obligation_id TEXT NOT NULL,
    head_sequence INTEGER NOT NULL CHECK (head_sequence > 0),
    previous_head_digest TEXT NOT NULL CHECK (
        length(previous_head_digest) = 64
        AND previous_head_digest NOT GLOB '*[^0-9a-f]*'
    ),
    head_digest TEXT NOT NULL CHECK (
        length(head_digest) = 64
        AND head_digest NOT GLOB '*[^0-9a-f]*'
    ),
    atom_digest TEXT NOT NULL CHECK (
        length(atom_digest) = 64
        AND atom_digest NOT GLOB '*[^0-9a-f]*'
    ),
    disposition_version INTEGER NOT NULL CHECK (disposition_version > 0),
    disposition_lifecycle_fence INTEGER NOT NULL CHECK (
        disposition_lifecycle_fence = disposition_version
    ),
    disposition_digest TEXT NOT NULL CHECK (
        length(disposition_digest) = 64
        AND disposition_digest NOT GLOB '*[^0-9a-f]*'
    ),
    settlement_version INTEGER NOT NULL CHECK (settlement_version > 0),
    settlement_lifecycle_fence INTEGER NOT NULL CHECK (
        settlement_lifecycle_fence = settlement_version
    ),
    settlement_lifecycle_digest TEXT NOT NULL CHECK (
        length(settlement_lifecycle_digest) = 64
        AND settlement_lifecycle_digest NOT GLOB '*[^0-9a-f]*'
    ),
    snapshot_version INTEGER NOT NULL CHECK (snapshot_version > 0),
    resource_fence INTEGER NOT NULL CHECK (resource_fence > 0),
    source_kind TEXT NOT NULL CHECK (source_kind IN (
        'initial_projection', 'disposition_transition', 'settlement_lifecycle'
    )),
    source_operation_id TEXT NOT NULL,
    participant_digest TEXT CHECK (
        participant_digest IS NULL
        OR (length(participant_digest) = 64
            AND participant_digest NOT GLOB '*[^0-9a-f]*')
    ),
    participant_commit_sequence INTEGER CHECK (
        participant_commit_sequence IS NULL OR participant_commit_sequence > 0
    ),
    committed_at_unix_ms INTEGER NOT NULL CHECK (committed_at_unix_ms > 0),
    store_uuid TEXT NOT NULL CHECK (store_uuid <> ''),
    store_lease_id TEXT NOT NULL CHECK (store_lease_id <> ''),
    store_owner_epoch INTEGER NOT NULL CHECK (store_owner_epoch > 0),
    PRIMARY KEY (obligation_id, head_sequence),
    UNIQUE (obligation_id, head_digest),
    UNIQUE (obligation_id, head_sequence, head_digest),
    CHECK ((participant_digest IS NULL) = (participant_commit_sequence IS NULL)),
    FOREIGN KEY (obligation_id, atom_digest)
        REFERENCES obligation_atoms(obligation_id, atom_digest),
    FOREIGN KEY (obligation_id, disposition_version)
        REFERENCES obligation_disposition_records(obligation_id, version),
    FOREIGN KEY (obligation_id, settlement_version)
        REFERENCES obligation_settlement_lifecycle_records(obligation_id, version),
    FOREIGN KEY (source_operation_id)
        REFERENCES admission_operations(operation_id),
    FOREIGN KEY (participant_commit_sequence)
        REFERENCES admission_operation_commits(commit_sequence),
    FOREIGN KEY (store_uuid, store_owner_epoch)
        REFERENCES chio_serving_leases(store_uuid, owner_epoch)
);

CREATE INDEX IF NOT EXISTS obligation_head_commits_operation
    ON obligation_head_commits(source_operation_id, obligation_id, head_sequence);

CREATE UNIQUE INDEX IF NOT EXISTS obligation_head_commits_participant
    ON obligation_head_commits(participant_commit_sequence)
    WHERE participant_commit_sequence IS NOT NULL;

CREATE UNIQUE INDEX IF NOT EXISTS obligation_head_commits_source_operation
    ON obligation_head_commits(source_operation_id)
    WHERE source_kind <> 'initial_projection';
END;
END;
END;
END;
END;

CREATE TABLE IF NOT EXISTS obligation_heads (
    obligation_id TEXT NOT NULL PRIMARY KEY,
    head_sequence INTEGER NOT NULL CHECK (head_sequence > 0),
    head_digest TEXT NOT NULL CHECK (
        length(head_digest) = 64
        AND head_digest NOT GLOB '*[^0-9a-f]*'
    ),
    atom_digest TEXT NOT NULL CHECK (
        length(atom_digest) = 64
        AND atom_digest NOT GLOB '*[^0-9a-f]*'
    ),
    disposition_version INTEGER NOT NULL CHECK (disposition_version > 0),
    disposition_lifecycle_fence INTEGER NOT NULL CHECK (
        disposition_lifecycle_fence = disposition_version
    ),
    settlement_version INTEGER NOT NULL CHECK (settlement_version > 0),
    settlement_lifecycle_fence INTEGER NOT NULL CHECK (
        settlement_lifecycle_fence = settlement_version
    ),
    snapshot_version INTEGER NOT NULL CHECK (snapshot_version > 0),
    resource_fence INTEGER NOT NULL CHECK (resource_fence > 0),
    updated_at_unix_ms INTEGER NOT NULL CHECK (updated_at_unix_ms > 0),
    store_uuid TEXT NOT NULL CHECK (store_uuid <> ''),
    store_lease_id TEXT NOT NULL CHECK (store_lease_id <> ''),
    store_owner_epoch INTEGER NOT NULL CHECK (store_owner_epoch > 0),
    FOREIGN KEY (obligation_id, head_sequence, head_digest)
        REFERENCES obligation_head_commits(obligation_id, head_sequence, head_digest),
    FOREIGN KEY (obligation_id, atom_digest)
        REFERENCES obligation_atoms(obligation_id, atom_digest),
    FOREIGN KEY (obligation_id, disposition_version)
        REFERENCES obligation_disposition_records(obligation_id, version),
    FOREIGN KEY (obligation_id, settlement_version)
        REFERENCES obligation_settlement_lifecycle_records(obligation_id, version),
    FOREIGN KEY (store_uuid, store_owner_epoch)
        REFERENCES chio_serving_leases(store_uuid, owner_epoch)
);
END;
END;
END;
END;
END;

CREATE TABLE IF NOT EXISTS factor_assignment_authority_sets (
    generation INTEGER NOT NULL PRIMARY KEY CHECK (generation > 0),
    active_set_digest TEXT NOT NULL CHECK (
        length(active_set_digest) = 64
        AND active_set_digest NOT GLOB '*[^0-9a-f]*'
    ),
    previous_active_set_digest TEXT CHECK (
        previous_active_set_digest IS NULL
        OR (length(previous_active_set_digest) = 64
            AND previous_active_set_digest NOT GLOB '*[^0-9a-f]*')
    ),
    activated_at_unix_ms INTEGER NOT NULL CHECK (activated_at_unix_ms > 0),
    store_uuid TEXT NOT NULL CHECK (store_uuid <> ''),
    store_lease_id TEXT NOT NULL CHECK (store_lease_id <> ''),
    store_owner_epoch INTEGER NOT NULL CHECK (store_owner_epoch > 0),
    UNIQUE (generation, active_set_digest),
    FOREIGN KEY (store_uuid, store_owner_epoch)
        REFERENCES chio_serving_leases(store_uuid, owner_epoch)
);
END;
END;
END;
END;
END;
END;
END;
END;
END;
END;
END;
END;
END;

CREATE TABLE IF NOT EXISTS admission_operation_observer_attempts (
    operation_id TEXT NOT NULL PRIMARY KEY,
    receipt_id TEXT NOT NULL UNIQUE CHECK (length(receipt_id) BETWEEN 1 AND 512),
    work_state TEXT NOT NULL CHECK (work_state IN (
        'pending', 'claimed', 'completed', 'failed'
    )),
    attempts INTEGER NOT NULL CHECK (attempts >= 0),
    next_visible_at_unix_ms INTEGER NOT NULL CHECK (next_visible_at_unix_ms > 0),
    row_version INTEGER NOT NULL CHECK (row_version >= 0),
    last_error TEXT CHECK (last_error IS NULL OR length(last_error) BETWEEN 1 AND 2048),
    record_digest TEXT NOT NULL CHECK (
        length(record_digest) = 64
        AND record_digest NOT GLOB '*[^0-9a-f]*'
    ),
    record_json BLOB NOT NULL CHECK (length(record_json) BETWEEN 1 AND 1048576),
    created_at_unix_ms INTEGER NOT NULL CHECK (created_at_unix_ms > 0),
    updated_at_unix_ms INTEGER NOT NULL CHECK (
        updated_at_unix_ms >= created_at_unix_ms
    ),
    store_uuid TEXT NOT NULL CHECK (store_uuid <> ''),
    store_lease_id TEXT NOT NULL CHECK (store_lease_id <> ''),
    store_owner_epoch INTEGER NOT NULL CHECK (store_owner_epoch > 0),
    FOREIGN KEY (operation_id)
        REFERENCES admission_operation_terminal_projections(operation_id),
    FOREIGN KEY (store_uuid, store_owner_epoch)
        REFERENCES chio_serving_leases(store_uuid, owner_epoch)
);

CREATE INDEX IF NOT EXISTS admission_operation_observer_attempts_ready
    ON admission_operation_observer_attempts(
        work_state, next_visible_at_unix_ms, operation_id
    );
END;
END;
END;
END;
END;

CREATE TABLE IF NOT EXISTS credit_exposure_accounts (
    debtor_id TEXT NOT NULL CHECK (length(debtor_id) BETWEEN 1 AND 512),
    scope_digest TEXT NOT NULL CHECK (
        length(scope_digest) = 64
        AND scope_digest = lower(scope_digest)
        AND scope_digest NOT GLOB '*[^0-9a-f]*'
    ),
    currency TEXT NOT NULL CHECK (length(currency) BETWEEN 1 AND 32),
    open_units INTEGER NOT NULL CHECK (open_units BETWEEN 0 AND 9007199254740991),
    reserved_units INTEGER NOT NULL CHECK (reserved_units BETWEEN 0 AND 9007199254740991),
    effective_ceiling_units INTEGER NOT NULL CHECK (
        effective_ceiling_units BETWEEN 1 AND 9007199254740991
    ),
    authority_configuration_digest TEXT NOT NULL CHECK (
        length(authority_configuration_digest) = 64
        AND authority_configuration_digest = lower(authority_configuration_digest)
        AND authority_configuration_digest NOT GLOB '*[^0-9a-f]*'
    ),
    authority_set_digest TEXT NOT NULL CHECK (
        length(authority_set_digest) = 64
        AND authority_set_digest = lower(authority_set_digest)
        AND authority_set_digest NOT GLOB '*[^0-9a-f]*'
    ),
    authority_evidence_digest TEXT NOT NULL CHECK (
        length(authority_evidence_digest) = 64
        AND authority_evidence_digest = lower(authority_evidence_digest)
        AND authority_evidence_digest NOT GLOB '*[^0-9a-f]*'
    ),
    authority_expires_at_unix_seconds INTEGER NOT NULL CHECK (
        authority_expires_at_unix_seconds BETWEEN 1 AND 9007199254740991
    ),
    account_version INTEGER NOT NULL CHECK (account_version BETWEEN 1 AND 9007199254740991),
    resource_fence INTEGER NOT NULL CHECK (resource_fence BETWEEN 1 AND 9007199254740991),
    updated_at_unix_ms INTEGER NOT NULL CHECK (
        updated_at_unix_ms BETWEEN 1 AND 9007199254740991
    ),
    store_uuid TEXT NOT NULL CHECK (store_uuid <> ''),
    store_lease_id TEXT NOT NULL CHECK (store_lease_id <> ''),
    store_owner_epoch INTEGER NOT NULL CHECK (store_owner_epoch > 0),
    PRIMARY KEY (debtor_id, scope_digest, currency),
    CHECK (open_units <= effective_ceiling_units - reserved_units),
    CHECK (account_version = resource_fence),
    FOREIGN KEY (store_uuid, store_owner_epoch)
        REFERENCES chio_serving_leases(store_uuid, owner_epoch)
);
END;
END;
END;
END;

CREATE TABLE IF NOT EXISTS credit_exposure_reservations (
    operation_id TEXT NOT NULL PRIMARY KEY,
    reservation_digest TEXT NOT NULL UNIQUE CHECK (
        length(reservation_digest) = 64
        AND reservation_digest = lower(reservation_digest)
        AND reservation_digest NOT GLOB '*[^0-9a-f]*'
    ),
    debtor_id TEXT NOT NULL,
    scope_digest TEXT NOT NULL,
    currency TEXT NOT NULL,
    action_nonce TEXT NOT NULL CHECK (length(action_nonce) BETWEEN 1 AND 512),
    amount_units INTEGER NOT NULL CHECK (amount_units BETWEEN 1 AND 9007199254740991),
    source_account_version INTEGER NOT NULL CHECK (
        source_account_version BETWEEN 1 AND 9007199254740991
    ),
    source_resource_fence INTEGER NOT NULL CHECK (
        source_resource_fence BETWEEN 1 AND 9007199254740991
    ),
    reserved_account_version INTEGER NOT NULL CHECK (
        reserved_account_version BETWEEN 1 AND 9007199254740991
    ),
    reserved_resource_fence INTEGER NOT NULL CHECK (
        reserved_resource_fence BETWEEN 1 AND 9007199254740991
    ),
    reservation_json BLOB NOT NULL CHECK (length(reservation_json) > 0),
    reserved_at_unix_ms INTEGER NOT NULL CHECK (
        reserved_at_unix_ms BETWEEN 1 AND 9007199254740991
    ),
    store_uuid TEXT NOT NULL CHECK (store_uuid <> ''),
    store_lease_id TEXT NOT NULL CHECK (store_lease_id <> ''),
    store_owner_epoch INTEGER NOT NULL CHECK (store_owner_epoch > 0),
    UNIQUE (debtor_id, scope_digest, currency, action_nonce),
    UNIQUE (operation_id, reservation_digest),
    CHECK (source_account_version = source_resource_fence),
    CHECK (reserved_account_version = reserved_resource_fence),
    CHECK (reserved_account_version = source_account_version + 1),
    FOREIGN KEY (operation_id) REFERENCES admission_operations(operation_id),
    FOREIGN KEY (debtor_id, scope_digest, currency)
        REFERENCES credit_exposure_accounts(debtor_id, scope_digest, currency),
    FOREIGN KEY (store_uuid, store_owner_epoch)
        REFERENCES chio_serving_leases(store_uuid, owner_epoch)
);
END;
END;
END;
END;

CREATE TABLE IF NOT EXISTS credit_exposure_terminal_transitions (
    operation_id TEXT NOT NULL PRIMARY KEY,
    reservation_digest TEXT NOT NULL,
    terminal_state TEXT NOT NULL CHECK (
        terminal_state IN ('committed', 'released_before_dispatch', 'outcome_unknown')
    ),
    admission_terminal_state TEXT NOT NULL CHECK (
        admission_terminal_state IN (
            'completed', 'compensated_before_dispatch',
            'not_accepted_after_dispatch_commit', 'outcome_unknown_after_dispatch'
        )
    ),
    projection_digest TEXT NOT NULL CHECK (
        length(projection_digest) = 64
        AND projection_digest = lower(projection_digest)
        AND projection_digest NOT GLOB '*[^0-9a-f]*'
    ),
    obligation_id TEXT,
    account_version INTEGER NOT NULL CHECK (account_version BETWEEN 1 AND 9007199254740991),
    resource_fence INTEGER NOT NULL CHECK (resource_fence BETWEEN 1 AND 9007199254740991),
    transition_json BLOB NOT NULL CHECK (length(transition_json) > 0),
    transitioned_at_unix_ms INTEGER NOT NULL CHECK (
        transitioned_at_unix_ms BETWEEN 1 AND 9007199254740991
    ),
    store_uuid TEXT NOT NULL CHECK (store_uuid <> ''),
    store_lease_id TEXT NOT NULL CHECK (store_lease_id <> ''),
    store_owner_epoch INTEGER NOT NULL CHECK (store_owner_epoch > 0),
    CHECK ((terminal_state = 'committed') = (obligation_id IS NOT NULL)),
    CHECK (account_version = resource_fence),
    FOREIGN KEY (operation_id, reservation_digest)
        REFERENCES credit_exposure_reservations(operation_id, reservation_digest),
    FOREIGN KEY (store_uuid, store_owner_epoch)
        REFERENCES chio_serving_leases(store_uuid, owner_epoch)
);
END;
END;
END;
END;
