-- Machine traffic monetization decision model
-- Schema version: 1.1.0 | Reference date: 2026-08-02 | Engine: SQLite 3.37+
-- Companion: ../20-machine-traffic-monetization-and-agent-payments.md
--
-- Run only on a new/disposable database:
--   sqlite3 -bail :memory: < indie-developer-playbook/research/20-machine-traffic-monetization-model.sql
--
-- Every actor, request, resource, amount, timestamp, provider, wallet, bank
-- reference, and result in this file is fully synthetic. Opaque hashes are
-- synthetic pointers; they do not prove identity, consent, provenance, rights,
-- payment finality, or anonymity. Raw IP addresses, user-agent strings, names,
-- emails, prompts, content, payment credentials, wallet secrets, and customer
-- payloads do not belong in this model.
--
-- Interpretation boundary
-- - HTTP 402 is a challenge state, not revenue, buyer demand, authorization,
--   settlement, entitlement, delivery, cash, or retained contribution.
-- - A claimed bot name or user-agent is not verified identity.
-- - TEST and REAL are separate accounting environments. This compact reference
--   folds SYNTHETIC and SANDBOX into TEST, and LIMITED_LIVE and LIVE into REAL.
--   A production ledger must retain the original environment in addition to
--   this accounting_environment mapping. TEST facts never enter REAL economics.
-- - UNKNOWN, N/A, and FAILED are categorical states. Numeric 0 is reserved for
--   measured counts/values/coverage or absence readouts, never a row-result enum.
-- - occurred_at, recorded_at, outcome_cutoff_at, snapshot_as_of, and maturity_at
--   are separate clocks. Late facts may change a later snapshot but never
--   rewrite an earlier decision.
-- - Payment authorization, settlement, reversal, entitlement, delivery, bank
--   cash, variable cost, and founder time are immutable facts.
-- - A 2xx delivery is not an accepted outcome. Contribution eligibility needs
--   a first-party, exact request+delivery acceptance fact that has itself
--   matured by the decision snapshot. Acceptance may be recorded after its
--   maturity_at; it enters only snapshots at or after its recorded_at.
-- - An HTTP 402 response may contain challenge-document bytes, but it must
--   withhold all protected-resource bytes. Those byte classes are distinct.
-- - Challenge and payment proof records contain only opaque hashes/scope codes.
--   The server-issued expected tuple and proof-presented tuple must match, and
--   every proof is single-use. The authoritative offer fixes network,
--   recipient, version, amount, and asset. Raw payloads, payment secrets, and
--   credentials are deliberately not modeled. Challenge expiry is derived
--   from expires_at; terminal pre-authorization expiry/failure belongs in the
--   immutable payment lifecycle rather than a mutable challenge state.
-- - A one-shot delivery needs a grant valid when delivery occurred and no later
--   REVOKED event, refund, or reversal by the snapshot. Natural expiry after a
--   valid delivery does not erase that historical delivery. Current policy at
--   decision time is a separate expansion gate.
-- - BYTE_RESOURCE deliveries require positive bytes. TOOL_ACTION deliveries
--   use ACTION_RESULT and may validly return a 2xx status with zero bytes.
-- - Cash is expressed in contract base-currency micros. Gross must equal the
--   authoritative offer value; any FX adjustment carries an explicit basis,
--   and each payment/component tuple is idempotent independent of any supplied
--   commercial-owner label. Multiple same-type provider subcomponents must be
--   authoritatively aggregated upstream in this compact model; changing owner
--   never creates a new component identity.
-- - Economics here covers per-request paid access only. License value, referral
--   value, and cannibalization are not modeled. A reason-coded N/A contributes
--   numeric zero, while the broader/inclusive-profit result remains UNKNOWN and
--   is never presented as comprehensive profit.
-- - Positive bank/wallet cash is admitted only for fully contribution-eligible
--   accepted units. Negative refunds/reversals and incremental variable/founder
--   costs are deducted for the entire mature verified-eligible cohort, including
--   abandoned, paid-undelivered, delivered-not-accepted, and failed units.
-- - EXPAND means one bounded next cohort. It requires current evidence, verified
--   identity, rights and risk PASS, complete delivery/cash reconciliation, and
--   positive mature contribution. It is not universal rollout authority.

PRAGMA foreign_keys = ON;
PRAGMA recursive_triggers = ON;
PRAGMA trusted_schema = OFF;
BEGIN IMMEDIATE;

-- ---------------------------------------------------------------------------
-- Schema and immutable source evidence
-- ---------------------------------------------------------------------------

CREATE TABLE schema_registry (
  schema_id INTEGER PRIMARY KEY CHECK (schema_id=1),
  schema_name TEXT NOT NULL UNIQUE
    CHECK (schema_name='machine_traffic_monetization'),
  schema_version TEXT NOT NULL CHECK (schema_version='1.1.0'),
  engine_floor TEXT NOT NULL CHECK (engine_floor='SQLite 3.37+'),
  applied_at TEXT NOT NULL CHECK (datetime(applied_at) IS NOT NULL),
  data_policy_code TEXT NOT NULL CHECK (
    data_policy_code='SYNTHETIC_ONLY_NO_RAW_PII_OR_SECRETS'
  )
) STRICT;

CREATE TABLE model_setting (
  singleton_id INTEGER PRIMARY KEY CHECK (singleton_id=1),
  reference_time TEXT NOT NULL CHECK (datetime(reference_time) IS NOT NULL),
  default_snapshot_as_of TEXT NOT NULL
    CHECK (datetime(default_snapshot_as_of) IS NOT NULL),
  base_currency TEXT NOT NULL CHECK (
    length(base_currency)=3 AND base_currency=upper(base_currency)
  ),
  founder_rate_micros_per_minute INTEGER NOT NULL
    CHECK (founder_rate_micros_per_minute>0),
  source_staleness_hours INTEGER NOT NULL
    CHECK (source_staleness_hours BETWEEN 1 AND 8760),
  bounded_output_limit INTEGER NOT NULL
    CHECK (bounded_output_limit BETWEEN 1 AND 200),
  CHECK (datetime(default_snapshot_as_of)<=datetime(reference_time))
) STRICT;

CREATE TABLE evidence_record (
  evidence_id TEXT PRIMARY KEY,
  evidence_class TEXT NOT NULL CHECK (evidence_class IN (
    'E0_INFERENCE','E1_MANUAL_OBSERVATION','E2_VERSIONED_CONFIG',
    'E3_VERIFIED_PROVIDER_EVENT','E4_FIRST_PARTY_AUTHORITATIVE',
    'E5_BANK_WALLET_OR_CUSTOMER_AUTHORITATIVE'
  )),
  evidence_rank INTEGER NOT NULL CHECK (evidence_rank BETWEEN 0 AND 5),
  evidence_domain TEXT NOT NULL CHECK (evidence_domain IN (
    'SOURCE','CONTRACT','RESOURCE','POLICY','IDENTITY','REQUEST','OFFER',
    'CHALLENGE','PAYMENT','ENTITLEMENT','DELIVERY','ACCEPTED_OUTCOME','CASH',
    'COST','RISK','DECISION'
  )),
  environment TEXT NOT NULL CHECK (environment IN ('TEST','REAL')),
  source_system_code TEXT NOT NULL,
  source_object_ref_hash TEXT NOT NULL CHECK (
    length(source_object_ref_hash)=64
    AND source_object_ref_hash=lower(source_object_ref_hash)
    AND source_object_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  payload_ref_hash TEXT NOT NULL CHECK (
    length(payload_ref_hash)=64
    AND payload_ref_hash=lower(payload_ref_hash)
    AND payload_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  occurred_at TEXT NOT NULL CHECK (datetime(occurred_at) IS NOT NULL),
  recorded_at TEXT NOT NULL CHECK (datetime(recorded_at) IS NOT NULL),
  supersedes_evidence_id TEXT,
  data_class_code TEXT NOT NULL CHECK (
    data_class_code='SYNTHETIC_OPAQUE_REFERENCE_ONLY'
  ),
  CHECK (datetime(occurred_at)<=datetime(recorded_at)),
  CHECK (
    (evidence_class='E0_INFERENCE' AND evidence_rank=0)
    OR (evidence_class='E1_MANUAL_OBSERVATION' AND evidence_rank=1)
    OR (evidence_class='E2_VERSIONED_CONFIG' AND evidence_rank=2)
    OR (evidence_class='E3_VERIFIED_PROVIDER_EVENT' AND evidence_rank=3)
    OR (evidence_class='E4_FIRST_PARTY_AUTHORITATIVE' AND evidence_rank=4)
    OR (evidence_class='E5_BANK_WALLET_OR_CUSTOMER_AUTHORITATIVE'
        AND evidence_rank=5)
  ),
  FOREIGN KEY (supersedes_evidence_id) REFERENCES evidence_record(evidence_id)
) STRICT;

CREATE TABLE source_snapshot (
  source_snapshot_id TEXT PRIMARY KEY,
  provider_code TEXT NOT NULL,
  program_code TEXT NOT NULL,
  program_status TEXT NOT NULL CHECK (program_status IN (
    'CURRENT','PREVIEW','INVITE_ONLY','DEPRECATED','UNKNOWN','FAILED'
  )),
  seller_eligibility_state TEXT NOT NULL CHECK (seller_eligibility_state IN (
    'OBSERVED','UNKNOWN','N/A','FAILED'
  )),
  buyer_support_state TEXT NOT NULL CHECK (buyer_support_state IN (
    'OBSERVED','UNKNOWN','N/A','FAILED'
  )),
  exact_version TEXT NOT NULL,
  effective_at TEXT NOT NULL CHECK (datetime(effective_at) IS NOT NULL),
  checked_at TEXT NOT NULL CHECK (datetime(checked_at) IS NOT NULL),
  stale_after TEXT NOT NULL CHECK (datetime(stale_after) IS NOT NULL),
  source_url_ref_hash TEXT NOT NULL CHECK (
    length(source_url_ref_hash)=64
    AND source_url_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  evidence_id TEXT NOT NULL UNIQUE,
  CHECK (datetime(effective_at)<=datetime(checked_at)),
  CHECK (datetime(checked_at)<datetime(stale_after)),
  FOREIGN KEY (evidence_id) REFERENCES evidence_record(evidence_id)
) STRICT;

CREATE TABLE machine_access_contract (
  machine_access_contract_id TEXT PRIMARY KEY,
  contract_family_id TEXT NOT NULL,
  contract_version INTEGER NOT NULL CHECK (contract_version>=1),
  supersedes_contract_id TEXT,
  environment TEXT NOT NULL CHECK (environment IN ('TEST','REAL')),
  source_snapshot_id TEXT NOT NULL,
  contract_state TEXT NOT NULL CHECK (contract_state IN (
    'ACTIVE','PAUSED','CLOSED'
  )),
  observation_state TEXT NOT NULL CHECK (observation_state IN (
    'OBSERVED','UNKNOWN','N/A','FAILED'
  )),
  decision_owner_code TEXT NOT NULL,
  actor_scope_code TEXT NOT NULL,
  resource_scope_code TEXT NOT NULL,
  primary_metric_code TEXT NOT NULL
    CHECK (primary_metric_code='MATURED_INCREMENTAL_MACHINE_CONTRIBUTION'),
  base_currency TEXT NOT NULL CHECK (
    length(base_currency)=3 AND base_currency=upper(base_currency)
  ),
  maximum_cash_exposure_micros INTEGER NOT NULL
    CHECK (maximum_cash_exposure_micros>=0),
  maximum_founder_minutes INTEGER NOT NULL CHECK (maximum_founder_minutes>=0),
  enrollment_starts_at TEXT NOT NULL CHECK (datetime(enrollment_starts_at) IS NOT NULL),
  outcome_cutoff_at TEXT NOT NULL CHECK (datetime(outcome_cutoff_at) IS NOT NULL),
  maturity_at TEXT NOT NULL CHECK (datetime(maturity_at) IS NOT NULL),
  decision_due_at TEXT NOT NULL CHECK (datetime(decision_due_at) IS NOT NULL),
  evidence_id TEXT NOT NULL UNIQUE,
  UNIQUE (contract_family_id,contract_version),
  CHECK (datetime(enrollment_starts_at)<datetime(outcome_cutoff_at)),
  CHECK (datetime(outcome_cutoff_at)<=datetime(maturity_at)),
  CHECK (datetime(maturity_at)<=datetime(decision_due_at)),
  CHECK (
    (contract_version=1 AND supersedes_contract_id IS NULL)
    OR (contract_version>1 AND supersedes_contract_id IS NOT NULL)
  ),
  FOREIGN KEY (supersedes_contract_id)
    REFERENCES machine_access_contract(machine_access_contract_id),
  FOREIGN KEY (source_snapshot_id) REFERENCES source_snapshot(source_snapshot_id),
  FOREIGN KEY (evidence_id) REFERENCES evidence_record(evidence_id)
) STRICT;

CREATE TABLE resource_contract (
  resource_contract_id TEXT PRIMARY KEY,
  machine_access_contract_id TEXT NOT NULL,
  resource_class_code TEXT NOT NULL CHECK (resource_class_code IN (
    'PUBLIC_MARKETING','PREMIUM_CONTENT','API_COMPUTE','TOOL_ACTION',
    'CUSTOMER_DATA'
  )),
  resource_revision TEXT NOT NULL,
  rights_state TEXT NOT NULL CHECK (rights_state IN (
    'PASS','UNKNOWN','N/A','FAILED'
  )),
  human_access_expected INTEGER NOT NULL CHECK (human_access_expected IN (0,1)),
  search_access_expected INTEGER NOT NULL CHECK (search_access_expected IN (0,1)),
  content_ref_hash TEXT NOT NULL CHECK (
    length(content_ref_hash)=64 AND content_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  evidence_id TEXT NOT NULL UNIQUE,
  UNIQUE (machine_access_contract_id,resource_revision),
  FOREIGN KEY (machine_access_contract_id)
    REFERENCES machine_access_contract(machine_access_contract_id),
  FOREIGN KEY (evidence_id) REFERENCES evidence_record(evidence_id)
) STRICT;

CREATE TABLE traffic_policy_version (
  traffic_policy_id TEXT PRIMARY KEY,
  machine_access_contract_id TEXT NOT NULL,
  resource_contract_id TEXT NOT NULL,
  actor_class_code TEXT NOT NULL CHECK (actor_class_code IN (
    'HUMAN_BROWSER','SEARCH_INDEXER','AI_SEARCH_RETRIEVAL','AI_TRAINING',
    'USER_TRIGGERED_AGENT','AUTHENTICATED_API_CLIENT','UNKNOWN_AUTOMATION',
    'MALICIOUS_ABUSE'
  )),
  policy_version INTEGER NOT NULL CHECK (policy_version>=1),
  supersedes_policy_id TEXT,
  action_mode_code TEXT NOT NULL CHECK (action_mode_code IN (
    'MEASURE_ONLY','ALLOW_FREE','RATE_LIMIT','SECURITY_CHALLENGE','BLOCK',
    'CONTRACT_LICENSE','AUTHENTICATED_API','HTTP_402','SERVE_ENTITLED','PAUSE'
  )),
  identity_required INTEGER NOT NULL CHECK (identity_required IN (0,1)),
  chargeable INTEGER NOT NULL CHECK (chargeable IN (0,1)),
  effective_from TEXT NOT NULL CHECK (datetime(effective_from) IS NOT NULL),
  effective_until TEXT CHECK (
    effective_until IS NULL OR datetime(effective_until) IS NOT NULL
  ),
  evidence_id TEXT NOT NULL UNIQUE,
  UNIQUE (resource_contract_id,actor_class_code,policy_version),
  CHECK (
    (policy_version=1 AND supersedes_policy_id IS NULL)
    OR (policy_version>1 AND supersedes_policy_id IS NOT NULL)
  ),
  CHECK (effective_until IS NULL OR datetime(effective_from)<datetime(effective_until)),
  CHECK (
    (chargeable=1 AND action_mode_code IN (
      'CONTRACT_LICENSE','AUTHENTICATED_API','HTTP_402','SERVE_ENTITLED'))
    OR (chargeable=0 AND action_mode_code IN (
      'MEASURE_ONLY','ALLOW_FREE','RATE_LIMIT','SECURITY_CHALLENGE','BLOCK',
      'PAUSE'))
  ),
  FOREIGN KEY (machine_access_contract_id)
    REFERENCES machine_access_contract(machine_access_contract_id),
  FOREIGN KEY (resource_contract_id) REFERENCES resource_contract(resource_contract_id),
  FOREIGN KEY (supersedes_policy_id) REFERENCES traffic_policy_version(traffic_policy_id),
  FOREIGN KEY (evidence_id) REFERENCES evidence_record(evidence_id)
) STRICT;

CREATE TABLE actor_identity_observation (
  identity_observation_id TEXT PRIMARY KEY,
  machine_access_contract_id TEXT NOT NULL,
  actor_ref_hash TEXT NOT NULL CHECK (
    length(actor_ref_hash)=64 AND actor_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  claimed_actor_class_code TEXT NOT NULL CHECK (claimed_actor_class_code IN (
    'HUMAN_BROWSER','SEARCH_INDEXER','AI_SEARCH_RETRIEVAL','AI_TRAINING',
    'USER_TRIGGERED_AGENT','AUTHENTICATED_API_CLIENT','UNKNOWN_AUTOMATION',
    'MALICIOUS_ABUSE'
  )),
  verified_actor_class_code TEXT CHECK (
    verified_actor_class_code IS NULL OR verified_actor_class_code IN (
      'HUMAN_BROWSER','SEARCH_INDEXER','AI_SEARCH_RETRIEVAL','AI_TRAINING',
      'USER_TRIGGERED_AGENT','AUTHENTICATED_API_CLIENT','UNKNOWN_AUTOMATION',
      'MALICIOUS_ABUSE'
    )
  ),
  verification_state TEXT NOT NULL CHECK (verification_state IN (
    'VERIFIED','UNKNOWN','N/A','FAILED'
  )),
  verification_method_code TEXT NOT NULL CHECK (verification_method_code IN (
    'NONE','USER_AGENT_ONLY','PROVIDER_VERIFIED_BOT','SIGNED_REQUEST',
    'AUTHENTICATED_ACCOUNT','NETWORK_AND_RDNS','MULTI_SIGNAL'
  )),
  confidence_milli INTEGER NOT NULL CHECK (confidence_milli BETWEEN 0 AND 1000),
  occurred_at TEXT NOT NULL CHECK (datetime(occurred_at) IS NOT NULL),
  recorded_at TEXT NOT NULL CHECK (datetime(recorded_at) IS NOT NULL),
  valid_until TEXT NOT NULL CHECK (datetime(valid_until) IS NOT NULL),
  evidence_id TEXT NOT NULL UNIQUE,
  CHECK (datetime(occurred_at)<=datetime(recorded_at)),
  CHECK (datetime(recorded_at)<datetime(valid_until)),
  CHECK (
    (verification_state='VERIFIED' AND verified_actor_class_code IS NOT NULL
      AND confidence_milli>0)
    OR (verification_state<>'VERIFIED' AND verified_actor_class_code IS NULL)
  ),
  FOREIGN KEY (machine_access_contract_id)
    REFERENCES machine_access_contract(machine_access_contract_id),
  FOREIGN KEY (evidence_id) REFERENCES evidence_record(evidence_id)
) STRICT;

CREATE TABLE request_observation (
  request_id TEXT PRIMARY KEY,
  machine_access_contract_id TEXT NOT NULL,
  resource_contract_id TEXT NOT NULL,
  traffic_policy_id TEXT NOT NULL,
  identity_observation_id TEXT NOT NULL,
  environment TEXT NOT NULL CHECK (environment IN ('TEST','REAL')),
  request_ref_hash TEXT NOT NULL UNIQUE CHECK (
    length(request_ref_hash)=64 AND request_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  network_scope_code TEXT NOT NULL CHECK (
    length(network_scope_code) BETWEEN 1 AND 64
    AND network_scope_code=upper(network_scope_code)
    AND network_scope_code NOT GLOB '*[^A-Z0-9_:-]*'
  ),
  recipient_ref_hash TEXT NOT NULL CHECK (
    length(recipient_ref_hash)=64
    AND recipient_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  request_method_code TEXT NOT NULL CHECK (request_method_code IN (
    'GET','HEAD','POST','PUT','PATCH','DELETE'
  )),
  canonical_target_ref_hash TEXT NOT NULL CHECK (
    length(canonical_target_ref_hash)=64
    AND canonical_target_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  request_body_digest_hash TEXT NOT NULL CHECK (
    length(request_body_digest_hash)=64
    AND request_body_digest_hash NOT GLOB '*[^0-9a-f]*'
  ),
  classification_state TEXT NOT NULL CHECK (classification_state IN (
    'OBSERVED','UNKNOWN','N/A','FAILED'
  )),
  applied_action_mode_code TEXT NOT NULL CHECK (applied_action_mode_code IN (
    'MEASURE_ONLY','ALLOW_FREE','RATE_LIMIT','SECURITY_CHALLENGE','BLOCK',
    'CONTRACT_LICENSE','AUTHENTICATED_API','HTTP_402','SERVE_ENTITLED','PAUSE'
  )),
  response_status INTEGER NOT NULL CHECK (response_status BETWEEN 100 AND 599),
  protected_resource_bytes INTEGER NOT NULL CHECK (protected_resource_bytes>=0),
  challenge_document_bytes INTEGER NOT NULL CHECK (challenge_document_bytes>=0),
  occurred_at TEXT NOT NULL CHECK (datetime(occurred_at) IS NOT NULL),
  recorded_at TEXT NOT NULL CHECK (datetime(recorded_at) IS NOT NULL),
  outcome_cutoff_at TEXT NOT NULL CHECK (datetime(outcome_cutoff_at) IS NOT NULL),
  maturity_at TEXT NOT NULL CHECK (datetime(maturity_at) IS NOT NULL),
  evidence_id TEXT NOT NULL UNIQUE,
  CHECK (datetime(occurred_at)<=datetime(recorded_at)),
  CHECK (datetime(occurred_at)<=datetime(outcome_cutoff_at)),
  CHECK (datetime(outcome_cutoff_at)<=datetime(maturity_at)),
  CHECK (
    (applied_action_mode_code='HTTP_402' AND protected_resource_bytes=0
      AND challenge_document_bytes>0)
    OR (applied_action_mode_code<>'HTTP_402' AND challenge_document_bytes=0)
  ),
  FOREIGN KEY (machine_access_contract_id)
    REFERENCES machine_access_contract(machine_access_contract_id),
  FOREIGN KEY (resource_contract_id) REFERENCES resource_contract(resource_contract_id),
  FOREIGN KEY (traffic_policy_id) REFERENCES traffic_policy_version(traffic_policy_id),
  FOREIGN KEY (identity_observation_id)
    REFERENCES actor_identity_observation(identity_observation_id),
  FOREIGN KEY (evidence_id) REFERENCES evidence_record(evidence_id)
) STRICT;

CREATE TABLE payment_offer_version (
  payment_offer_id TEXT PRIMARY KEY,
  offer_family_id TEXT NOT NULL,
  offer_version INTEGER NOT NULL CHECK (offer_version>=1),
  supersedes_offer_id TEXT,
  machine_access_contract_id TEXT NOT NULL,
  resource_contract_id TEXT NOT NULL,
  offer_state TEXT NOT NULL CHECK (offer_state IN (
    'CURRENT','UNKNOWN','N/A','FAILED','EXPIRED'
  )),
  rail_code TEXT NOT NULL,
  asset_code TEXT NOT NULL,
  amount_atomic INTEGER NOT NULL CHECK (amount_atomic>0),
  base_currency_value_micros INTEGER NOT NULL
    CHECK (base_currency_value_micros>0),
  settlement_requirement_code TEXT NOT NULL CHECK (settlement_requirement_code IN (
    'AUTHORITATIVE_SETTLEMENT','CONTRACT_CREDIT'
  )),
  network_scope_code TEXT NOT NULL CHECK (
    length(network_scope_code) BETWEEN 1 AND 64
    AND network_scope_code=upper(network_scope_code)
    AND network_scope_code NOT GLOB '*[^A-Z0-9_:-]*'
  ),
  recipient_ref_hash TEXT NOT NULL CHECK (
    length(recipient_ref_hash)=64
    AND recipient_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  entitlement_scope_ref_hash TEXT NOT NULL CHECK (
    length(entitlement_scope_ref_hash)=64
    AND entitlement_scope_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  effective_from TEXT NOT NULL CHECK (datetime(effective_from) IS NOT NULL),
  expires_at TEXT NOT NULL CHECK (datetime(expires_at) IS NOT NULL),
  evidence_id TEXT NOT NULL UNIQUE,
  UNIQUE (offer_family_id,offer_version),
  CHECK (datetime(effective_from)<datetime(expires_at)),
  CHECK (
    (offer_version=1 AND supersedes_offer_id IS NULL)
    OR (offer_version>1 AND supersedes_offer_id IS NOT NULL)
  ),
  FOREIGN KEY (supersedes_offer_id) REFERENCES payment_offer_version(payment_offer_id),
  FOREIGN KEY (machine_access_contract_id)
    REFERENCES machine_access_contract(machine_access_contract_id),
  FOREIGN KEY (resource_contract_id) REFERENCES resource_contract(resource_contract_id),
  FOREIGN KEY (evidence_id) REFERENCES evidence_record(evidence_id)
) STRICT;

CREATE TABLE challenge_receipt (
  challenge_id TEXT PRIMARY KEY,
  request_id TEXT NOT NULL UNIQUE,
  machine_access_contract_id TEXT NOT NULL,
  payment_offer_id TEXT NOT NULL,
  environment TEXT NOT NULL CHECK (environment IN ('TEST','REAL')),
  challenge_state TEXT NOT NULL CHECK (challenge_state IN (
    'ISSUED','UNKNOWN','N/A','FAILED'
  )),
  response_status INTEGER NOT NULL CHECK (response_status=402),
  nonce_ref_hash TEXT NOT NULL UNIQUE CHECK (
    length(nonce_ref_hash)=64 AND nonce_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  idempotency_ref_hash TEXT NOT NULL UNIQUE CHECK (
    length(idempotency_ref_hash)=64
    AND idempotency_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  network_scope_code TEXT NOT NULL CHECK (
    length(network_scope_code) BETWEEN 1 AND 64
    AND network_scope_code=upper(network_scope_code)
    AND network_scope_code NOT GLOB '*[^A-Z0-9_:-]*'
  ),
  recipient_ref_hash TEXT NOT NULL CHECK (
    length(recipient_ref_hash)=64
    AND recipient_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  principal_ref_hash TEXT NOT NULL CHECK (
    length(principal_ref_hash)=64
    AND principal_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  purpose_scope_code TEXT NOT NULL CHECK (purpose_scope_code IN (
    'RESOURCE_ACCESS','CONTRACT_LICENSE','AUTHENTICATED_API'
  )),
  rights_scope_ref_hash TEXT NOT NULL CHECK (
    length(rights_scope_ref_hash)=64
    AND rights_scope_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  entitlement_scope_ref_hash TEXT NOT NULL CHECK (
    length(entitlement_scope_ref_hash)=64
    AND entitlement_scope_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  request_method_code TEXT NOT NULL CHECK (request_method_code IN (
    'GET','HEAD','POST','PUT','PATCH','DELETE'
  )),
  canonical_target_ref_hash TEXT NOT NULL CHECK (
    length(canonical_target_ref_hash)=64
    AND canonical_target_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  request_body_digest_hash TEXT NOT NULL CHECK (
    length(request_body_digest_hash)=64
    AND request_body_digest_hash NOT GLOB '*[^0-9a-f]*'
  ),
  server_expected_tuple_hash TEXT NOT NULL UNIQUE CHECK (
    length(server_expected_tuple_hash)=64
    AND server_expected_tuple_hash NOT GLOB '*[^0-9a-f]*'
  ),
  challenge_artifact_hash TEXT NOT NULL UNIQUE CHECK (
    length(challenge_artifact_hash)=64
    AND challenge_artifact_hash NOT GLOB '*[^0-9a-f]*'
  ),
  amount_atomic INTEGER NOT NULL CHECK (amount_atomic>0),
  asset_code TEXT NOT NULL,
  issued_at TEXT NOT NULL CHECK (datetime(issued_at) IS NOT NULL),
  expires_at TEXT NOT NULL CHECK (datetime(expires_at) IS NOT NULL),
  recorded_at TEXT NOT NULL CHECK (datetime(recorded_at) IS NOT NULL),
  evidence_id TEXT NOT NULL UNIQUE,
  CHECK (datetime(issued_at)<=datetime(recorded_at)),
  CHECK (datetime(recorded_at)<datetime(expires_at)),
  FOREIGN KEY (request_id) REFERENCES request_observation(request_id),
  FOREIGN KEY (machine_access_contract_id)
    REFERENCES machine_access_contract(machine_access_contract_id),
  FOREIGN KEY (payment_offer_id) REFERENCES payment_offer_version(payment_offer_id),
  FOREIGN KEY (evidence_id) REFERENCES evidence_record(evidence_id)
) STRICT;

CREATE TABLE payment_proof (
  payment_proof_id TEXT PRIMARY KEY,
  proof_covered_request_id TEXT NOT NULL,
  proof_covered_challenge_id TEXT NOT NULL,
  payment_offer_id TEXT NOT NULL,
  payment_offer_version INTEGER NOT NULL CHECK (payment_offer_version>=1),
  amount_atomic INTEGER NOT NULL CHECK (amount_atomic>0),
  asset_code TEXT NOT NULL,
  environment TEXT NOT NULL CHECK (environment IN ('TEST','REAL')),
  network_scope_code TEXT NOT NULL CHECK (
    length(network_scope_code) BETWEEN 1 AND 64
    AND network_scope_code=upper(network_scope_code)
    AND network_scope_code NOT GLOB '*[^A-Z0-9_:-]*'
  ),
  recipient_ref_hash TEXT NOT NULL CHECK (
    length(recipient_ref_hash)=64
    AND recipient_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  principal_ref_hash TEXT NOT NULL CHECK (
    length(principal_ref_hash)=64
    AND principal_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  purpose_scope_code TEXT NOT NULL CHECK (purpose_scope_code IN (
    'RESOURCE_ACCESS','CONTRACT_LICENSE','AUTHENTICATED_API'
  )),
  rights_scope_ref_hash TEXT NOT NULL CHECK (
    length(rights_scope_ref_hash)=64
    AND rights_scope_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  entitlement_scope_ref_hash TEXT NOT NULL CHECK (
    length(entitlement_scope_ref_hash)=64
    AND entitlement_scope_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  request_method_code TEXT NOT NULL CHECK (request_method_code IN (
    'GET','HEAD','POST','PUT','PATCH','DELETE'
  )),
  canonical_target_ref_hash TEXT NOT NULL CHECK (
    length(canonical_target_ref_hash)=64
    AND canonical_target_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  request_body_digest_hash TEXT NOT NULL CHECK (
    length(request_body_digest_hash)=64
    AND request_body_digest_hash NOT GLOB '*[^0-9a-f]*'
  ),
  presented_tuple_hash TEXT NOT NULL CHECK (
    length(presented_tuple_hash)=64
    AND presented_tuple_hash NOT GLOB '*[^0-9a-f]*'
  ),
  proof_artifact_hash TEXT NOT NULL UNIQUE CHECK (
    length(proof_artifact_hash)=64
    AND proof_artifact_hash NOT GLOB '*[^0-9a-f]*'
  ),
  verification_state TEXT NOT NULL CHECK (verification_state='VERIFIED'),
  verified_at TEXT NOT NULL CHECK (datetime(verified_at) IS NOT NULL),
  recorded_at TEXT NOT NULL CHECK (datetime(recorded_at) IS NOT NULL),
  evidence_id TEXT NOT NULL UNIQUE,
  CHECK (datetime(verified_at)<=datetime(recorded_at)),
  FOREIGN KEY (proof_covered_request_id)
    REFERENCES request_observation(request_id),
  FOREIGN KEY (proof_covered_challenge_id)
    REFERENCES challenge_receipt(challenge_id),
  FOREIGN KEY (payment_offer_id)
    REFERENCES payment_offer_version(payment_offer_id),
  FOREIGN KEY (evidence_id) REFERENCES evidence_record(evidence_id)
) STRICT;

CREATE TABLE payment_event (
  payment_event_id TEXT PRIMARY KEY,
  challenge_id TEXT NOT NULL,
  request_id TEXT NOT NULL,
  machine_access_contract_id TEXT NOT NULL,
  payment_proof_id TEXT UNIQUE,
  event_sequence INTEGER NOT NULL CHECK (event_sequence>=1),
  predecessor_payment_event_id TEXT,
  event_type_code TEXT NOT NULL CHECK (event_type_code IN (
    'AUTHORIZATION','SETTLEMENT','REVERSAL','REFUND','FAILURE','EXPIRY'
  )),
  event_state TEXT NOT NULL CHECK (event_state IN (
    'OBSERVED','UNKNOWN','N/A','FAILED'
  )),
  environment TEXT NOT NULL CHECK (environment IN ('TEST','REAL')),
  external_transaction_ref_hash TEXT NOT NULL CHECK (
    length(external_transaction_ref_hash)=64
    AND external_transaction_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  amount_atomic INTEGER NOT NULL CHECK (amount_atomic>0),
  asset_code TEXT NOT NULL,
  proof_verification_state TEXT NOT NULL CHECK (proof_verification_state IN (
    'VERIFIED','UNKNOWN','N/A','FAILED'
  )),
  occurred_at TEXT NOT NULL CHECK (datetime(occurred_at) IS NOT NULL),
  recorded_at TEXT NOT NULL CHECK (datetime(recorded_at) IS NOT NULL),
  evidence_id TEXT NOT NULL UNIQUE,
  UNIQUE (challenge_id,event_sequence),
  UNIQUE (environment,external_transaction_ref_hash,event_type_code),
  CHECK (datetime(occurred_at)<=datetime(recorded_at)),
  CHECK (
    (event_sequence=1 AND predecessor_payment_event_id IS NULL)
    OR (event_sequence>1 AND predecessor_payment_event_id IS NOT NULL)
  ),
  CHECK (
    (event_type_code='AUTHORIZATION' AND payment_proof_id IS NOT NULL
      AND proof_verification_state='VERIFIED')
    OR (event_type_code<>'AUTHORIZATION' AND payment_proof_id IS NULL
      AND proof_verification_state='N/A')
  ),
  FOREIGN KEY (challenge_id) REFERENCES challenge_receipt(challenge_id),
  FOREIGN KEY (request_id) REFERENCES request_observation(request_id),
  FOREIGN KEY (machine_access_contract_id)
    REFERENCES machine_access_contract(machine_access_contract_id),
  FOREIGN KEY (payment_proof_id) REFERENCES payment_proof(payment_proof_id),
  FOREIGN KEY (predecessor_payment_event_id)
    REFERENCES payment_event(payment_event_id),
  FOREIGN KEY (evidence_id) REFERENCES evidence_record(evidence_id)
) STRICT;

CREATE TABLE entitlement_event (
  entitlement_event_id TEXT PRIMARY KEY,
  request_id TEXT NOT NULL,
  machine_access_contract_id TEXT NOT NULL,
  entitlement_ref_hash TEXT NOT NULL CHECK (
    length(entitlement_ref_hash)=64
    AND entitlement_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  event_sequence INTEGER NOT NULL CHECK (event_sequence>=1),
  predecessor_entitlement_event_id TEXT,
  entitlement_state TEXT NOT NULL CHECK (entitlement_state IN (
    'GRANTED','REVOKED','UNKNOWN','N/A','FAILED'
  )),
  source_kind_code TEXT NOT NULL CHECK (source_kind_code IN (
    'PAYMENT_SETTLEMENT','CONTRACT_LICENSE','AUTHENTICATED_API'
  )),
  source_payment_event_id TEXT,
  environment TEXT NOT NULL CHECK (environment IN ('TEST','REAL')),
  valid_from TEXT NOT NULL CHECK (datetime(valid_from) IS NOT NULL),
  valid_until TEXT NOT NULL CHECK (datetime(valid_until) IS NOT NULL),
  occurred_at TEXT NOT NULL CHECK (datetime(occurred_at) IS NOT NULL),
  recorded_at TEXT NOT NULL CHECK (datetime(recorded_at) IS NOT NULL),
  evidence_id TEXT NOT NULL UNIQUE,
  UNIQUE (entitlement_ref_hash,event_sequence),
  CHECK (datetime(valid_from)<datetime(valid_until)),
  CHECK (datetime(occurred_at)<=datetime(recorded_at)),
  CHECK (
    (event_sequence=1 AND predecessor_entitlement_event_id IS NULL)
    OR (event_sequence>1 AND predecessor_entitlement_event_id IS NOT NULL)
  ),
  FOREIGN KEY (request_id) REFERENCES request_observation(request_id),
  FOREIGN KEY (machine_access_contract_id)
    REFERENCES machine_access_contract(machine_access_contract_id),
  FOREIGN KEY (predecessor_entitlement_event_id)
    REFERENCES entitlement_event(entitlement_event_id),
  FOREIGN KEY (source_payment_event_id) REFERENCES payment_event(payment_event_id),
  FOREIGN KEY (evidence_id) REFERENCES evidence_record(evidence_id)
) STRICT;

CREATE TABLE delivery_event (
  delivery_event_id TEXT PRIMARY KEY,
  request_id TEXT NOT NULL,
  machine_access_contract_id TEXT NOT NULL,
  entitlement_event_id TEXT,
  delivery_kind_code TEXT NOT NULL CHECK (delivery_kind_code IN (
    'BYTE_RESOURCE','ACTION_RESULT'
  )),
  delivery_state TEXT NOT NULL CHECK (delivery_state IN (
    'DELIVERED','UNKNOWN','N/A','FAILED'
  )),
  environment TEXT NOT NULL CHECK (environment IN ('TEST','REAL')),
  response_status INTEGER NOT NULL CHECK (response_status BETWEEN 100 AND 599),
  delivered_bytes INTEGER NOT NULL CHECK (delivered_bytes>=0),
  delivery_ref_hash TEXT NOT NULL UNIQUE CHECK (
    length(delivery_ref_hash)=64 AND delivery_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  idempotency_ref_hash TEXT NOT NULL UNIQUE CHECK (
    length(idempotency_ref_hash)=64
    AND idempotency_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  occurred_at TEXT NOT NULL CHECK (datetime(occurred_at) IS NOT NULL),
  recorded_at TEXT NOT NULL CHECK (datetime(recorded_at) IS NOT NULL),
  evidence_id TEXT NOT NULL UNIQUE,
  CHECK (datetime(occurred_at)<=datetime(recorded_at)),
  CHECK (
    (delivery_state='DELIVERED' AND response_status BETWEEN 200 AND 299
      AND ((delivery_kind_code='BYTE_RESOURCE' AND delivered_bytes>0)
        OR delivery_kind_code='ACTION_RESULT'))
    OR (delivery_state<>'DELIVERED')
  ),
  FOREIGN KEY (request_id) REFERENCES request_observation(request_id),
  FOREIGN KEY (machine_access_contract_id)
    REFERENCES machine_access_contract(machine_access_contract_id),
  FOREIGN KEY (entitlement_event_id)
    REFERENCES entitlement_event(entitlement_event_id),
  FOREIGN KEY (evidence_id) REFERENCES evidence_record(evidence_id)
) STRICT;

CREATE UNIQUE INDEX one_delivered_event_per_entitlement
ON delivery_event(entitlement_event_id)
WHERE delivery_state='DELIVERED' AND entitlement_event_id IS NOT NULL;

CREATE TABLE accepted_outcome_event (
  accepted_outcome_event_id TEXT PRIMARY KEY,
  request_id TEXT NOT NULL,
  delivery_event_id TEXT NOT NULL,
  machine_access_contract_id TEXT NOT NULL,
  event_sequence INTEGER NOT NULL CHECK (event_sequence>=1),
  predecessor_accepted_outcome_event_id TEXT,
  environment TEXT NOT NULL CHECK (environment IN ('TEST','REAL')),
  outcome_state TEXT NOT NULL CHECK (outcome_state IN (
    'ACCEPTED','REJECTED','UNKNOWN','N/A','FAILED'
  )),
  acceptance_ref_hash TEXT NOT NULL UNIQUE CHECK (
    length(acceptance_ref_hash)=64
    AND acceptance_ref_hash NOT GLOB '*[^0-9a-f]*'
  ),
  occurred_at TEXT NOT NULL CHECK (datetime(occurred_at) IS NOT NULL),
  recorded_at TEXT NOT NULL CHECK (datetime(recorded_at) IS NOT NULL),
  maturity_at TEXT NOT NULL CHECK (datetime(maturity_at) IS NOT NULL),
  evidence_id TEXT NOT NULL UNIQUE,
  UNIQUE (delivery_event_id,event_sequence),
  CHECK (datetime(occurred_at)<=datetime(recorded_at)),
  CHECK (
    (event_sequence=1 AND predecessor_accepted_outcome_event_id IS NULL)
    OR (event_sequence>1 AND predecessor_accepted_outcome_event_id IS NOT NULL)
  ),
  FOREIGN KEY (request_id) REFERENCES request_observation(request_id),
  FOREIGN KEY (delivery_event_id) REFERENCES delivery_event(delivery_event_id),
  FOREIGN KEY (machine_access_contract_id)
    REFERENCES machine_access_contract(machine_access_contract_id),
  FOREIGN KEY (predecessor_accepted_outcome_event_id)
    REFERENCES accepted_outcome_event(accepted_outcome_event_id),
  FOREIGN KEY (evidence_id) REFERENCES evidence_record(evidence_id)
) STRICT;

CREATE TABLE cash_bridge_line (
  cash_line_id TEXT PRIMARY KEY,
  machine_access_contract_id TEXT NOT NULL,
  request_id TEXT NOT NULL,
  payment_event_id TEXT NOT NULL,
  commercial_owner_key TEXT NOT NULL,
  line_type_code TEXT NOT NULL CHECK (line_type_code IN (
    'GROSS_SETTLED','RAIL_FEE','TAX_WITHHELD','BANK_OR_WALLET_RECEIPT',
    'REFUND','REVERSAL','FX_ADJUSTMENT'
  )),
  amount_base_micros INTEGER NOT NULL CHECK (amount_base_micros<>0),
  base_currency TEXT NOT NULL CHECK (
    length(base_currency)=3 AND base_currency=upper(base_currency)
  ),
  fx_policy_code TEXT NOT NULL CHECK (fx_policy_code IN (
    'BASE_CURRENCY_NO_FX','FX_ADJUSTMENT_TO_BASE'
  )),
  fx_basis_ref_hash TEXT CHECK (
    fx_basis_ref_hash IS NULL OR (
      length(fx_basis_ref_hash)=64
      AND fx_basis_ref_hash NOT GLOB '*[^0-9a-f]*')
  ),
  environment TEXT NOT NULL CHECK (environment IN ('TEST','REAL')),
  authority_code TEXT NOT NULL CHECK (authority_code IN (
    'PROVIDER_LEDGER','CONTROLLED_WALLET','BANK_STATEMENT','ACCOUNTING_BRIDGE'
  )),
  occurred_at TEXT NOT NULL CHECK (datetime(occurred_at) IS NOT NULL),
  recorded_at TEXT NOT NULL CHECK (datetime(recorded_at) IS NOT NULL),
  evidence_id TEXT NOT NULL UNIQUE,
  CHECK (datetime(occurred_at)<=datetime(recorded_at)),
  CHECK (
    (line_type_code IN ('GROSS_SETTLED','BANK_OR_WALLET_RECEIPT')
      AND amount_base_micros>0)
    OR (line_type_code IN ('RAIL_FEE','TAX_WITHHELD','REFUND','REVERSAL')
      AND amount_base_micros<0)
    OR (line_type_code='FX_ADJUSTMENT')
  ),
  CHECK (
    (line_type_code='FX_ADJUSTMENT'
      AND fx_policy_code='FX_ADJUSTMENT_TO_BASE'
      AND fx_basis_ref_hash IS NOT NULL)
    OR (line_type_code<>'FX_ADJUSTMENT'
      AND fx_policy_code='BASE_CURRENCY_NO_FX'
      AND fx_basis_ref_hash IS NULL)
  ),
  FOREIGN KEY (machine_access_contract_id)
    REFERENCES machine_access_contract(machine_access_contract_id),
  FOREIGN KEY (request_id) REFERENCES request_observation(request_id),
  FOREIGN KEY (payment_event_id) REFERENCES payment_event(payment_event_id),
  FOREIGN KEY (evidence_id) REFERENCES evidence_record(evidence_id)
) STRICT;

CREATE UNIQUE INDEX one_cash_component_per_payment
ON cash_bridge_line(payment_event_id,line_type_code);

CREATE TABLE cost_event (
  cost_event_id TEXT PRIMARY KEY,
  machine_access_contract_id TEXT NOT NULL,
  request_id TEXT NOT NULL,
  cost_type_code TEXT NOT NULL CHECK (cost_type_code IN (
    'ORIGIN','EGRESS','COMPUTE','SUPPORT','FOUNDER_TIME'
  )),
  cash_cost_base_micros INTEGER NOT NULL CHECK (cash_cost_base_micros>=0),
  founder_minutes INTEGER NOT NULL CHECK (founder_minutes>=0),
  environment TEXT NOT NULL CHECK (environment IN ('TEST','REAL')),
  occurred_at TEXT NOT NULL CHECK (datetime(occurred_at) IS NOT NULL),
  recorded_at TEXT NOT NULL CHECK (datetime(recorded_at) IS NOT NULL),
  evidence_id TEXT NOT NULL UNIQUE,
  CHECK (datetime(occurred_at)<=datetime(recorded_at)),
  CHECK (
    (cost_type_code='FOUNDER_TIME' AND founder_minutes>0
      AND cash_cost_base_micros=0)
    OR (cost_type_code<>'FOUNDER_TIME' AND founder_minutes=0)
  ),
  FOREIGN KEY (machine_access_contract_id)
    REFERENCES machine_access_contract(machine_access_contract_id),
  FOREIGN KEY (request_id) REFERENCES request_observation(request_id),
  FOREIGN KEY (evidence_id) REFERENCES evidence_record(evidence_id)
) STRICT;

CREATE TABLE risk_review (
  risk_review_id TEXT PRIMARY KEY,
  machine_access_contract_id TEXT NOT NULL,
  review_sequence INTEGER NOT NULL CHECK (review_sequence>=1),
  predecessor_risk_review_id TEXT,
  rights_state TEXT NOT NULL CHECK (rights_state IN ('PASS','UNKNOWN','N/A','FAILED')),
  security_state TEXT NOT NULL CHECK (security_state IN ('PASS','UNKNOWN','N/A','FAILED')),
  privacy_state TEXT NOT NULL CHECK (privacy_state IN ('PASS','UNKNOWN','N/A','FAILED')),
  tax_payment_state TEXT NOT NULL CHECK (tax_payment_state IN ('PASS','UNKNOWN','N/A','FAILED')),
  human_search_guardrail_state TEXT NOT NULL
    CHECK (human_search_guardrail_state IN ('PASS','UNKNOWN','N/A','FAILED')),
  overall_state TEXT NOT NULL CHECK (overall_state IN ('PASS','UNKNOWN','N/A','FAILED')),
  reviewed_at TEXT NOT NULL CHECK (datetime(reviewed_at) IS NOT NULL),
  recorded_at TEXT NOT NULL CHECK (datetime(recorded_at) IS NOT NULL),
  evidence_id TEXT NOT NULL UNIQUE,
  UNIQUE (machine_access_contract_id,review_sequence),
  CHECK (datetime(reviewed_at)<=datetime(recorded_at)),
  CHECK (
    (review_sequence=1 AND predecessor_risk_review_id IS NULL)
    OR (review_sequence>1 AND predecessor_risk_review_id IS NOT NULL)
  ),
  CHECK (
    (overall_state='PASS' AND rights_state='PASS' AND security_state='PASS'
      AND privacy_state='PASS' AND tax_payment_state='PASS'
      AND human_search_guardrail_state='PASS')
    OR (overall_state='FAILED' AND 'FAILED' IN (
      rights_state,security_state,privacy_state,tax_payment_state,
      human_search_guardrail_state))
    OR (overall_state='UNKNOWN' AND 'FAILED' NOT IN (
      rights_state,security_state,privacy_state,tax_payment_state,
      human_search_guardrail_state)
      AND 'UNKNOWN' IN (rights_state,security_state,privacy_state,
                        tax_payment_state,human_search_guardrail_state))
    OR (overall_state='N/A' AND rights_state='N/A' AND security_state='N/A'
      AND privacy_state='N/A' AND tax_payment_state='N/A'
      AND human_search_guardrail_state='N/A')
  ),
  FOREIGN KEY (machine_access_contract_id)
    REFERENCES machine_access_contract(machine_access_contract_id),
  FOREIGN KEY (predecessor_risk_review_id) REFERENCES risk_review(risk_review_id),
  FOREIGN KEY (evidence_id) REFERENCES evidence_record(evidence_id)
) STRICT;

CREATE TABLE decision_snapshot (
  decision_snapshot_id TEXT PRIMARY KEY,
  machine_access_contract_id TEXT NOT NULL,
  decision_sequence INTEGER NOT NULL CHECK (decision_sequence>=1),
  predecessor_decision_snapshot_id TEXT,
  decision_state TEXT NOT NULL CHECK (decision_state IN (
    'STOP','PAUSE','UNKNOWN','INCONCLUSIVE','CHANGE','MAINTAIN','EXPAND'
  )),
  action_mode_code TEXT NOT NULL CHECK (action_mode_code IN (
    'MEASURE_ONLY','ALLOW_FREE','RATE_LIMIT','SECURITY_CHALLENGE','BLOCK',
    'CONTRACT_LICENSE','AUTHENTICATED_API','HTTP_402','SERVE_ENTITLED','PAUSE'
  )),
  risk_review_id TEXT NOT NULL,
  evidence_cutoff_at TEXT NOT NULL CHECK (datetime(evidence_cutoff_at) IS NOT NULL),
  snapshot_as_of TEXT NOT NULL CHECK (datetime(snapshot_as_of) IS NOT NULL),
  maturity_at TEXT NOT NULL CHECK (datetime(maturity_at) IS NOT NULL),
  mature_request_n INTEGER NOT NULL CHECK (mature_request_n>=0),
  verified_request_n INTEGER NOT NULL CHECK (verified_request_n>=0),
  verified_eligible_request_n INTEGER NOT NULL
    CHECK (verified_eligible_request_n>=0),
  rights_risk_pass_request_n INTEGER NOT NULL
    CHECK (rights_risk_pass_request_n>=0),
  challenged_request_n INTEGER NOT NULL CHECK (challenged_request_n>=0),
  authorized_request_n INTEGER NOT NULL CHECK (authorized_request_n>=0),
  payment_proof_verified_request_n INTEGER NOT NULL
    CHECK (payment_proof_verified_request_n>=0),
  settled_request_n INTEGER NOT NULL CHECK (settled_request_n>=0),
  entitled_request_n INTEGER NOT NULL CHECK (entitled_request_n>=0),
  not_revoked_entitlement_request_n INTEGER NOT NULL
    CHECK (not_revoked_entitlement_request_n>=0),
  delivered_request_n INTEGER NOT NULL CHECK (delivered_request_n>=0),
  accepted_request_n INTEGER NOT NULL CHECK (accepted_request_n>=0),
  cash_reconciled_request_n INTEGER NOT NULL
    CHECK (cash_reconciled_request_n>=0),
  contribution_eligible_request_n INTEGER NOT NULL
    CHECK (contribution_eligible_request_n>=0),
  reversed_request_n INTEGER NOT NULL CHECK (reversed_request_n>=0),
  bank_or_wallet_cash_micros INTEGER NOT NULL,
  cash_cost_micros INTEGER NOT NULL CHECK (cash_cost_micros>=0),
  founder_minutes INTEGER NOT NULL CHECK (founder_minutes>=0),
  founder_time_cost_micros INTEGER NOT NULL CHECK (founder_time_cost_micros>=0),
  matured_incremental_machine_contribution_micros INTEGER NOT NULL,
  decided_at TEXT NOT NULL CHECK (datetime(decided_at) IS NOT NULL),
  evidence_id TEXT NOT NULL UNIQUE,
  UNIQUE (machine_access_contract_id,decision_sequence),
  CHECK (datetime(evidence_cutoff_at)=datetime(snapshot_as_of)),
  CHECK (datetime(snapshot_as_of)<=datetime(decided_at)),
  CHECK (datetime(maturity_at)<=datetime(snapshot_as_of)),
  CHECK (datetime(maturity_at)<=datetime(decided_at)),
  CHECK (
    (decision_sequence=1 AND predecessor_decision_snapshot_id IS NULL)
    OR (decision_sequence>1 AND predecessor_decision_snapshot_id IS NOT NULL)
  ),
  FOREIGN KEY (machine_access_contract_id)
    REFERENCES machine_access_contract(machine_access_contract_id),
  FOREIGN KEY (predecessor_decision_snapshot_id)
    REFERENCES decision_snapshot(decision_snapshot_id),
  FOREIGN KEY (risk_review_id) REFERENCES risk_review(risk_review_id),
  FOREIGN KEY (evidence_id) REFERENCES evidence_record(evidence_id)
) STRICT;

-- Probe harness. Invalid mutations are sent through the same semantic trigger
-- as production inserts. An active probe records the rejection and uses
-- RAISE(IGNORE), so sqlite3 -bail can continue. Outside a probe the same rule
-- raises ABORT.
CREATE TABLE negative_probe_context (
  singleton_id INTEGER PRIMARY KEY CHECK (singleton_id=1),
  probe_id TEXT NOT NULL UNIQUE,
  expected_rule_code TEXT NOT NULL
) STRICT;

CREATE TABLE negative_probe_result (
  probe_id TEXT PRIMARY KEY,
  expected_rule_code TEXT NOT NULL,
  observed_rule_code TEXT NOT NULL,
  status TEXT NOT NULL CHECK (status IN ('PASS','FAIL')),
  target_table TEXT NOT NULL,
  recorded_at TEXT NOT NULL CHECK (datetime(recorded_at) IS NOT NULL)
) STRICT;

-- ---------------------------------------------------------------------------
-- Semantic guards
-- ---------------------------------------------------------------------------
-- Minimum positive-state evidence authority:
-- SOURCE/CONTRACT/POLICY/OFFER >=E2; IDENTITY verified and PAYMENT lifecycle
-- >=E3; REQUEST observed >=E3; RESOURCE rights PASS, ENTITLEMENT granted,
-- DELIVERY delivered, ACCEPTED_OUTCOME accepted, RISK, and DECISION >=E4;
-- CASH >=E3 and bank/wallet receipt >=E5; COST >=E3. Every stage must use its
-- exact evidence_domain and the same TEST/REAL environment as its contract.

CREATE TRIGGER evidence_predecessor_guard
BEFORE INSERT ON evidence_record
WHEN NEW.supersedes_evidence_id IS NOT NULL
BEGIN
  SELECT RAISE(ABORT,'evidence predecessor must be earlier and same-domain')
  WHERE NOT EXISTS (
    SELECT 1 FROM evidence_record p
    WHERE p.evidence_id=NEW.supersedes_evidence_id
      AND p.evidence_domain=NEW.evidence_domain
      AND datetime(p.recorded_at)<datetime(NEW.recorded_at)
  );
END;

CREATE TRIGGER source_semantic_guard
BEFORE INSERT ON source_snapshot
BEGIN
  SELECT RAISE(ABORT,'source snapshot requires SOURCE E2+ evidence')
  WHERE NOT EXISTS (
    SELECT 1 FROM evidence_record e
    WHERE e.evidence_id=NEW.evidence_id
      AND e.evidence_domain='SOURCE' AND e.evidence_rank>=2
  );
END;

CREATE TRIGGER contract_semantic_guard
BEFORE INSERT ON machine_access_contract
BEGIN
  SELECT RAISE(ABORT,'contract evidence environment mismatch')
  WHERE NOT EXISTS (
    SELECT 1 FROM evidence_record e
    WHERE e.evidence_id=NEW.evidence_id
      AND e.environment=NEW.environment
      AND e.evidence_domain='CONTRACT' AND e.evidence_rank>=2);
  SELECT RAISE(ABORT,'source evidence environment must match contract')
  WHERE NOT EXISTS (
    SELECT 1 FROM source_snapshot s
    JOIN evidence_record e USING (evidence_id)
    WHERE s.source_snapshot_id=NEW.source_snapshot_id
      AND e.environment=NEW.environment
      AND e.evidence_domain='SOURCE' AND e.evidence_rank>=2);
  SELECT RAISE(ABORT,'contract currency must match model base currency')
  WHERE NEW.base_currency<>(SELECT base_currency FROM model_setting
                            WHERE singleton_id=1);
  SELECT RAISE(ABORT,'REAL contract requires current eligible source snapshot')
  WHERE NEW.environment='REAL' AND NOT EXISTS (
    SELECT 1 FROM source_snapshot s
    WHERE s.source_snapshot_id=NEW.source_snapshot_id
      AND s.program_status='CURRENT'
      AND s.seller_eligibility_state='OBSERVED'
      AND datetime(s.stale_after)>=datetime(NEW.decision_due_at)
  );
  SELECT RAISE(ABORT,'contract after v1 requires exact prior family version')
  WHERE NEW.contract_version>1 AND NOT EXISTS (
    SELECT 1 FROM machine_access_contract p
    WHERE p.machine_access_contract_id=NEW.supersedes_contract_id
      AND p.contract_family_id=NEW.contract_family_id
      AND p.contract_version=NEW.contract_version-1
  );
END;

CREATE TRIGGER resource_semantic_guard
BEFORE INSERT ON resource_contract
BEGIN
  INSERT INTO negative_probe_result
  SELECT c.probe_id,c.expected_rule_code,'REAL_CHARGEABLE_RIGHTS_REQUIRED',
         CASE WHEN c.expected_rule_code='REAL_CHARGEABLE_RIGHTS_REQUIRED'
              THEN 'PASS' ELSE 'FAIL' END,
         'resource_contract',datetime('now')
  FROM negative_probe_context c
  JOIN machine_access_contract m
    ON m.machine_access_contract_id=NEW.machine_access_contract_id
  WHERE m.environment='REAL'
    AND NEW.resource_class_code IN (
      'PREMIUM_CONTENT','API_COMPUTE','TOOL_ACTION','CUSTOMER_DATA')
    AND NEW.rights_state<>'PASS';
  SELECT CASE WHEN EXISTS (SELECT 1 FROM negative_probe_context)
    AND EXISTS (
      SELECT 1 FROM machine_access_contract m
      WHERE m.machine_access_contract_id=NEW.machine_access_contract_id
        AND m.environment='REAL'
        AND NEW.resource_class_code IN (
          'PREMIUM_CONTENT','API_COMPUTE','TOOL_ACTION','CUSTOMER_DATA')
        AND NEW.rights_state<>'PASS')
    THEN RAISE(IGNORE) END;
  SELECT RAISE(ABORT,'REAL chargeable resource requires rights PASS')
  WHERE EXISTS (
    SELECT 1 FROM machine_access_contract m
    WHERE m.machine_access_contract_id=NEW.machine_access_contract_id
      AND m.environment='REAL'
      AND NEW.resource_class_code IN (
        'PREMIUM_CONTENT','API_COMPUTE','TOOL_ACTION','CUSTOMER_DATA')
      AND NEW.rights_state<>'PASS'
  );
  SELECT RAISE(ABORT,'resource evidence must belong to same environment')
  WHERE NOT EXISTS (
    SELECT 1 FROM evidence_record e
    JOIN machine_access_contract m
      ON m.machine_access_contract_id=NEW.machine_access_contract_id
    WHERE e.evidence_id=NEW.evidence_id
      AND e.environment=m.environment
      AND e.evidence_domain='RESOURCE'
      AND e.evidence_rank>=CASE WHEN NEW.rights_state='PASS' THEN 4 ELSE 2 END);
END;

CREATE TRIGGER policy_semantic_guard
BEFORE INSERT ON traffic_policy_version
BEGIN
  SELECT RAISE(ABORT,'policy resource and contract scope mismatch')
  WHERE NOT EXISTS (
    SELECT 1 FROM resource_contract r
    WHERE r.resource_contract_id=NEW.resource_contract_id
      AND r.machine_access_contract_id=NEW.machine_access_contract_id
  );
  SELECT RAISE(ABORT,'human and search policies cannot be made chargeable here')
  WHERE NEW.actor_class_code IN ('HUMAN_BROWSER','SEARCH_INDEXER')
    AND (NEW.chargeable=1 OR NEW.action_mode_code IN (
      'CONTRACT_LICENSE','AUTHENTICATED_API','HTTP_402','SERVE_ENTITLED'));
  SELECT RAISE(ABORT,'chargeable policy requires verified identity')
  WHERE NEW.chargeable=1 AND NEW.identity_required<>1;
  SELECT RAISE(ABORT,'policy must start inside contract enrollment window')
  WHERE NOT EXISTS (
    SELECT 1 FROM machine_access_contract m
    WHERE m.machine_access_contract_id=NEW.machine_access_contract_id
      AND datetime(NEW.effective_from)>=datetime(m.enrollment_starts_at)
      AND datetime(NEW.effective_from)<=datetime(m.outcome_cutoff_at)
  );
  SELECT RAISE(ABORT,'policy after v1 requires exact prior scope version')
  WHERE NEW.policy_version>1 AND NOT EXISTS (
    SELECT 1 FROM traffic_policy_version p
    WHERE p.traffic_policy_id=NEW.supersedes_policy_id
      AND p.resource_contract_id=NEW.resource_contract_id
      AND p.actor_class_code=NEW.actor_class_code
      AND p.policy_version=NEW.policy_version-1
  );
  SELECT RAISE(ABORT,'policy requires same-environment POLICY E2+ evidence')
  WHERE NOT EXISTS (
    SELECT 1 FROM evidence_record e
    JOIN machine_access_contract m
      ON m.machine_access_contract_id=NEW.machine_access_contract_id
    WHERE e.evidence_id=NEW.evidence_id AND e.environment=m.environment
      AND e.evidence_domain='POLICY' AND e.evidence_rank>=2);
END;

CREATE TRIGGER identity_semantic_guard
BEFORE INSERT ON actor_identity_observation
BEGIN
  INSERT INTO negative_probe_result
  SELECT c.probe_id,c.expected_rule_code,'USER_AGENT_NOT_IDENTITY',
         CASE WHEN c.expected_rule_code='USER_AGENT_NOT_IDENTITY'
              THEN 'PASS' ELSE 'FAIL' END,
         'actor_identity_observation',datetime('now')
  FROM negative_probe_context c
  WHERE NEW.verification_state='VERIFIED'
    AND NEW.verification_method_code IN ('NONE','USER_AGENT_ONLY');
  SELECT CASE WHEN EXISTS (SELECT 1 FROM negative_probe_context)
    AND NEW.verification_state='VERIFIED'
    AND NEW.verification_method_code IN ('NONE','USER_AGENT_ONLY')
    THEN RAISE(IGNORE) END;
  SELECT RAISE(ABORT,'user-agent alone cannot verify machine identity')
  WHERE NEW.verification_state='VERIFIED'
    AND NEW.verification_method_code IN ('NONE','USER_AGENT_ONLY');
  SELECT RAISE(ABORT,'verified actor class must match claimed class')
  WHERE NEW.verification_state='VERIFIED'
    AND NEW.verified_actor_class_code<>NEW.claimed_actor_class_code;
  SELECT RAISE(ABORT,'identity evidence environment mismatch')
  WHERE NOT EXISTS (
    SELECT 1 FROM evidence_record e
    JOIN machine_access_contract m
      ON m.machine_access_contract_id=NEW.machine_access_contract_id
    WHERE e.evidence_id=NEW.evidence_id AND e.environment=m.environment
      AND e.evidence_domain='IDENTITY'
      AND e.evidence_rank>=CASE WHEN NEW.verification_state='VERIFIED'
                                THEN 3 ELSE 1 END);
END;

CREATE TRIGGER request_semantic_guard
BEFORE INSERT ON request_observation
BEGIN
  INSERT INTO negative_probe_result
  SELECT c.probe_id,c.expected_rule_code,'POLICY_ACTION_EXACT',
         CASE WHEN c.expected_rule_code='POLICY_ACTION_EXACT'
              THEN 'PASS' ELSE 'FAIL' END,
         'request_observation',datetime('now')
  FROM negative_probe_context c
  WHERE NOT EXISTS (
    SELECT 1 FROM traffic_policy_version p
    WHERE p.traffic_policy_id=NEW.traffic_policy_id
      AND p.action_mode_code=NEW.applied_action_mode_code
  );
  SELECT CASE WHEN EXISTS (SELECT 1 FROM negative_probe_context)
    AND NOT EXISTS (
      SELECT 1 FROM traffic_policy_version p
      WHERE p.traffic_policy_id=NEW.traffic_policy_id
        AND p.action_mode_code=NEW.applied_action_mode_code)
    THEN RAISE(IGNORE) END;
  SELECT RAISE(ABORT,'request action must match exact policy revision')
  WHERE NOT EXISTS (
    SELECT 1 FROM traffic_policy_version p
    WHERE p.traffic_policy_id=NEW.traffic_policy_id
      AND p.action_mode_code=NEW.applied_action_mode_code
  );
  SELECT RAISE(ABORT,'request contract/resource/policy/identity scope mismatch')
  WHERE NOT EXISTS (
    SELECT 1
    FROM machine_access_contract m
    JOIN resource_contract r
      ON r.machine_access_contract_id=m.machine_access_contract_id
    JOIN traffic_policy_version p
      ON p.machine_access_contract_id=m.machine_access_contract_id
     AND p.resource_contract_id=r.resource_contract_id
    JOIN actor_identity_observation i
      ON i.machine_access_contract_id=m.machine_access_contract_id
    WHERE m.machine_access_contract_id=NEW.machine_access_contract_id
      AND r.resource_contract_id=NEW.resource_contract_id
      AND p.traffic_policy_id=NEW.traffic_policy_id
      AND i.identity_observation_id=NEW.identity_observation_id
      AND m.environment=NEW.environment
      AND datetime(i.occurred_at)<=datetime(NEW.occurred_at)
      AND datetime(i.recorded_at)<=datetime(NEW.occurred_at)
      AND p.actor_class_code=coalesce(i.verified_actor_class_code,
                                      i.claimed_actor_class_code)
      AND datetime(NEW.occurred_at)>=datetime(m.enrollment_starts_at)
      AND datetime(NEW.occurred_at)<=datetime(m.outcome_cutoff_at)
      AND datetime(NEW.occurred_at)>=datetime(p.effective_from)
      AND (p.effective_until IS NULL
           OR datetime(NEW.occurred_at)<datetime(p.effective_until))
  );
  SELECT RAISE(ABORT,'identity-required request lacks current verified identity')
  WHERE EXISTS (
    SELECT 1 FROM traffic_policy_version p
    WHERE p.traffic_policy_id=NEW.traffic_policy_id AND p.identity_required=1
  ) AND NOT EXISTS (
    SELECT 1 FROM actor_identity_observation i
    WHERE i.identity_observation_id=NEW.identity_observation_id
      AND i.verification_state='VERIFIED'
      AND datetime(NEW.occurred_at)<=datetime(i.valid_until)
  );
  SELECT RAISE(ABORT,'HTTP 402 must withhold resource and may emit challenge document')
  WHERE NEW.applied_action_mode_code='HTTP_402'
    AND (NEW.response_status<>402 OR NEW.protected_resource_bytes<>0
      OR NEW.challenge_document_bytes<=0);
  SELECT RAISE(ABORT,'rate-limit and block response status mismatch')
  WHERE (NEW.applied_action_mode_code='RATE_LIMIT' AND NEW.response_status<>429)
     OR (NEW.applied_action_mode_code='BLOCK' AND NEW.response_status<>403);
  SELECT RAISE(ABORT,'request clocks must stay inside contract clocks')
  WHERE NOT EXISTS (
    SELECT 1 FROM machine_access_contract m
    WHERE m.machine_access_contract_id=NEW.machine_access_contract_id
      AND datetime(NEW.outcome_cutoff_at)<=datetime(m.outcome_cutoff_at)
      AND datetime(NEW.maturity_at)<=datetime(m.maturity_at)
  );
  SELECT RAISE(ABORT,'request requires same-environment REQUEST evidence')
  WHERE NOT EXISTS (
    SELECT 1 FROM evidence_record e
    WHERE e.evidence_id=NEW.evidence_id AND e.environment=NEW.environment
      AND e.evidence_domain='REQUEST'
      AND e.evidence_rank>=CASE WHEN NEW.classification_state='OBSERVED'
                                THEN 3 ELSE 1 END);
END;

CREATE TRIGGER offer_semantic_guard
BEFORE INSERT ON payment_offer_version
BEGIN
  SELECT RAISE(ABORT,'offer resource and contract scope mismatch')
  WHERE NOT EXISTS (
    SELECT 1 FROM resource_contract r
    WHERE r.resource_contract_id=NEW.resource_contract_id
      AND r.machine_access_contract_id=NEW.machine_access_contract_id
      AND r.rights_state='PASS'
  );
  SELECT RAISE(ABORT,'offer after v1 requires exact prior family version')
  WHERE NEW.offer_version>1 AND NOT EXISTS (
    SELECT 1 FROM payment_offer_version p
    WHERE p.payment_offer_id=NEW.supersedes_offer_id
      AND p.offer_family_id=NEW.offer_family_id
      AND p.offer_version=NEW.offer_version-1
  );
  SELECT RAISE(ABORT,'offer requires same-environment OFFER E2+ evidence')
  WHERE NOT EXISTS (
    SELECT 1 FROM evidence_record e
    JOIN machine_access_contract m
      ON m.machine_access_contract_id=NEW.machine_access_contract_id
    WHERE e.evidence_id=NEW.evidence_id AND e.environment=m.environment
      AND e.evidence_domain='OFFER' AND e.evidence_rank>=2);
END;

CREATE TRIGGER challenge_semantic_guard
BEFORE INSERT ON challenge_receipt
BEGIN
  INSERT INTO negative_probe_result
  SELECT c.probe_id,c.expected_rule_code,'NONCE_AND_IDEMPOTENCY_UNIQUE',
         CASE WHEN c.expected_rule_code='NONCE_AND_IDEMPOTENCY_UNIQUE'
              THEN 'PASS' ELSE 'FAIL' END,
         'challenge_receipt',datetime('now')
  FROM negative_probe_context c
  WHERE EXISTS (
    SELECT 1 FROM challenge_receipt x
    WHERE x.nonce_ref_hash=NEW.nonce_ref_hash
       OR x.idempotency_ref_hash=NEW.idempotency_ref_hash
  );
  SELECT CASE WHEN EXISTS (SELECT 1 FROM negative_probe_context)
    AND EXISTS (
      SELECT 1 FROM challenge_receipt x
      WHERE x.nonce_ref_hash=NEW.nonce_ref_hash
         OR x.idempotency_ref_hash=NEW.idempotency_ref_hash)
    THEN RAISE(IGNORE) END;
  SELECT RAISE(ABORT,'challenge nonce and idempotency key cannot be reused')
  WHERE EXISTS (
    SELECT 1 FROM challenge_receipt x
    WHERE x.nonce_ref_hash=NEW.nonce_ref_hash
       OR x.idempotency_ref_hash=NEW.idempotency_ref_hash
  );
  SELECT RAISE(ABORT,'challenge requires matching HTTP 402 request and offer')
  WHERE NOT EXISTS (
    SELECT 1
    FROM request_observation r
    JOIN actor_identity_observation i
      ON i.identity_observation_id=r.identity_observation_id
    JOIN resource_contract rc
      ON rc.resource_contract_id=r.resource_contract_id
    JOIN payment_offer_version o
      ON o.machine_access_contract_id=r.machine_access_contract_id
     AND o.resource_contract_id=r.resource_contract_id
    WHERE r.request_id=NEW.request_id
      AND r.machine_access_contract_id=NEW.machine_access_contract_id
      AND r.applied_action_mode_code='HTTP_402'
      AND r.response_status=402
      AND r.environment=NEW.environment
      AND datetime(r.occurred_at)<=datetime(NEW.issued_at)
      AND datetime(r.recorded_at)<=datetime(NEW.recorded_at)
      AND o.payment_offer_id=NEW.payment_offer_id
      AND o.offer_state='CURRENT'
      AND o.amount_atomic=NEW.amount_atomic
      AND o.asset_code=NEW.asset_code
      AND o.network_scope_code=NEW.network_scope_code
      AND o.recipient_ref_hash=NEW.recipient_ref_hash
      AND r.network_scope_code=NEW.network_scope_code
      AND r.recipient_ref_hash=NEW.recipient_ref_hash
      AND i.actor_ref_hash=NEW.principal_ref_hash
      AND NEW.purpose_scope_code='RESOURCE_ACCESS'
      AND rc.content_ref_hash=NEW.rights_scope_ref_hash
      AND o.entitlement_scope_ref_hash=NEW.entitlement_scope_ref_hash
      AND r.request_method_code=NEW.request_method_code
      AND r.canonical_target_ref_hash=NEW.canonical_target_ref_hash
      AND r.request_body_digest_hash=NEW.request_body_digest_hash
      AND datetime(NEW.issued_at)>=datetime(o.effective_from)
      AND datetime(NEW.expires_at)<=datetime(o.expires_at)
  );
  SELECT RAISE(ABORT,'challenge requires authoritative same-environment evidence')
  WHERE NOT EXISTS (
    SELECT 1 FROM evidence_record e
    WHERE e.evidence_id=NEW.evidence_id
      AND e.evidence_domain='CHALLENGE'
      AND e.evidence_rank>=4
      AND e.environment=NEW.environment
  );
END;

CREATE TRIGGER payment_proof_semantic_guard
BEFORE INSERT ON payment_proof
BEGIN
  INSERT INTO negative_probe_result
  SELECT c.probe_id,c.expected_rule_code,
         CASE
           WHEN NOT EXISTS (
             SELECT 1 FROM challenge_receipt h
             WHERE h.challenge_id=NEW.proof_covered_challenge_id
               AND h.request_id=NEW.proof_covered_request_id)
             THEN 'PROOF_COVERAGE_EXACT'
           WHEN NOT EXISTS (
             SELECT 1 FROM challenge_receipt h
             JOIN payment_offer_version o ON o.payment_offer_id=h.payment_offer_id
             WHERE h.challenge_id=NEW.proof_covered_challenge_id
               AND o.payment_offer_id=NEW.payment_offer_id
               AND o.offer_version=NEW.payment_offer_version
               AND h.amount_atomic=NEW.amount_atomic
               AND h.asset_code=NEW.asset_code
               AND o.amount_atomic=NEW.amount_atomic
               AND o.asset_code=NEW.asset_code)
             THEN 'PROOF_OFFER_BINDING'
           WHEN NEW.network_scope_code<>(
             SELECT h.network_scope_code FROM challenge_receipt h
             WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             THEN 'PROOF_NETWORK_BINDING'
           WHEN NEW.recipient_ref_hash<>(
             SELECT h.recipient_ref_hash FROM challenge_receipt h
             WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             THEN 'PROOF_RECIPIENT_BINDING'
           WHEN NEW.principal_ref_hash<>(
             SELECT h.principal_ref_hash FROM challenge_receipt h
             WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             THEN 'PROOF_PRINCIPAL_BINDING'
           WHEN NEW.purpose_scope_code<>(
                  SELECT h.purpose_scope_code FROM challenge_receipt h
                  WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             OR NEW.rights_scope_ref_hash<>(
                  SELECT h.rights_scope_ref_hash FROM challenge_receipt h
                  WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             OR NEW.entitlement_scope_ref_hash<>(
                  SELECT h.entitlement_scope_ref_hash FROM challenge_receipt h
                  WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             OR NEW.request_method_code<>(
                  SELECT h.request_method_code FROM challenge_receipt h
                  WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             OR NEW.canonical_target_ref_hash<>(
                  SELECT h.canonical_target_ref_hash FROM challenge_receipt h
                  WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             THEN 'PROOF_RESOURCE_BINDING'
           WHEN NEW.request_body_digest_hash<>(
             SELECT h.request_body_digest_hash FROM challenge_receipt h
             WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             THEN 'PROOF_BODY_BINDING'
           WHEN NEW.presented_tuple_hash<>(
             SELECT h.server_expected_tuple_hash FROM challenge_receipt h
             WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             THEN 'EXPECTED_PRESENTED_TUPLE_EQUALITY'
           ELSE 'PROOF_VERIFICATION_AUTHORITATIVE'
         END,
         CASE WHEN c.expected_rule_code=CASE
           WHEN NOT EXISTS (
             SELECT 1 FROM challenge_receipt h
             WHERE h.challenge_id=NEW.proof_covered_challenge_id
               AND h.request_id=NEW.proof_covered_request_id)
             THEN 'PROOF_COVERAGE_EXACT'
           WHEN NOT EXISTS (
             SELECT 1 FROM challenge_receipt h
             JOIN payment_offer_version o ON o.payment_offer_id=h.payment_offer_id
             WHERE h.challenge_id=NEW.proof_covered_challenge_id
               AND o.payment_offer_id=NEW.payment_offer_id
               AND o.offer_version=NEW.payment_offer_version
               AND h.amount_atomic=NEW.amount_atomic
               AND h.asset_code=NEW.asset_code
               AND o.amount_atomic=NEW.amount_atomic
               AND o.asset_code=NEW.asset_code)
             THEN 'PROOF_OFFER_BINDING'
           WHEN NEW.network_scope_code<>(
             SELECT h.network_scope_code FROM challenge_receipt h
             WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             THEN 'PROOF_NETWORK_BINDING'
           WHEN NEW.recipient_ref_hash<>(
             SELECT h.recipient_ref_hash FROM challenge_receipt h
             WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             THEN 'PROOF_RECIPIENT_BINDING'
           WHEN NEW.principal_ref_hash<>(
             SELECT h.principal_ref_hash FROM challenge_receipt h
             WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             THEN 'PROOF_PRINCIPAL_BINDING'
           WHEN NEW.purpose_scope_code<>(
                  SELECT h.purpose_scope_code FROM challenge_receipt h
                  WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             OR NEW.rights_scope_ref_hash<>(
                  SELECT h.rights_scope_ref_hash FROM challenge_receipt h
                  WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             OR NEW.entitlement_scope_ref_hash<>(
                  SELECT h.entitlement_scope_ref_hash FROM challenge_receipt h
                  WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             OR NEW.request_method_code<>(
                  SELECT h.request_method_code FROM challenge_receipt h
                  WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             OR NEW.canonical_target_ref_hash<>(
                  SELECT h.canonical_target_ref_hash FROM challenge_receipt h
                  WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             THEN 'PROOF_RESOURCE_BINDING'
           WHEN NEW.request_body_digest_hash<>(
             SELECT h.request_body_digest_hash FROM challenge_receipt h
             WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             THEN 'PROOF_BODY_BINDING'
           WHEN NEW.presented_tuple_hash<>(
             SELECT h.server_expected_tuple_hash FROM challenge_receipt h
             WHERE h.challenge_id=NEW.proof_covered_challenge_id)
             THEN 'EXPECTED_PRESENTED_TUPLE_EQUALITY'
           ELSE 'PROOF_VERIFICATION_AUTHORITATIVE' END
         THEN 'PASS' ELSE 'FAIL' END,
         'payment_proof',datetime('now')
  FROM negative_probe_context c
  WHERE NOT EXISTS (
    SELECT 1 FROM challenge_receipt h
    JOIN payment_offer_version o ON o.payment_offer_id=h.payment_offer_id
    JOIN evidence_record e ON e.evidence_id=NEW.evidence_id
    WHERE h.challenge_id=NEW.proof_covered_challenge_id
      AND h.request_id=NEW.proof_covered_request_id
      AND o.payment_offer_id=NEW.payment_offer_id
      AND o.offer_version=NEW.payment_offer_version
      AND h.amount_atomic=NEW.amount_atomic
      AND h.asset_code=NEW.asset_code
      AND o.amount_atomic=NEW.amount_atomic
      AND o.asset_code=NEW.asset_code
      AND o.network_scope_code=NEW.network_scope_code
      AND o.recipient_ref_hash=NEW.recipient_ref_hash
      AND h.environment=NEW.environment
      AND h.network_scope_code=NEW.network_scope_code
      AND h.recipient_ref_hash=NEW.recipient_ref_hash
      AND h.principal_ref_hash=NEW.principal_ref_hash
      AND h.purpose_scope_code=NEW.purpose_scope_code
      AND h.rights_scope_ref_hash=NEW.rights_scope_ref_hash
      AND h.entitlement_scope_ref_hash=NEW.entitlement_scope_ref_hash
      AND h.request_method_code=NEW.request_method_code
      AND h.canonical_target_ref_hash=NEW.canonical_target_ref_hash
      AND h.request_body_digest_hash=NEW.request_body_digest_hash
      AND h.server_expected_tuple_hash=NEW.presented_tuple_hash
      AND h.challenge_state='ISSUED'
      AND datetime(h.issued_at)<=datetime(NEW.verified_at)
      AND datetime(h.recorded_at)<=datetime(NEW.verified_at)
      AND datetime(NEW.verified_at)<datetime(h.expires_at)
      AND NEW.verification_state='VERIFIED'
      AND e.evidence_domain='PAYMENT' AND e.evidence_rank>=3
      AND e.environment=NEW.environment
  );
  SELECT CASE WHEN EXISTS (SELECT 1 FROM negative_probe_context)
    AND NOT EXISTS (
      SELECT 1 FROM challenge_receipt h
      JOIN payment_offer_version o ON o.payment_offer_id=h.payment_offer_id
      JOIN evidence_record e ON e.evidence_id=NEW.evidence_id
      WHERE h.challenge_id=NEW.proof_covered_challenge_id
        AND h.request_id=NEW.proof_covered_request_id
        AND o.payment_offer_id=NEW.payment_offer_id
        AND o.offer_version=NEW.payment_offer_version
        AND h.amount_atomic=NEW.amount_atomic
        AND h.asset_code=NEW.asset_code
        AND o.amount_atomic=NEW.amount_atomic
        AND o.asset_code=NEW.asset_code
        AND o.network_scope_code=NEW.network_scope_code
        AND o.recipient_ref_hash=NEW.recipient_ref_hash
        AND h.environment=NEW.environment
        AND h.network_scope_code=NEW.network_scope_code
        AND h.recipient_ref_hash=NEW.recipient_ref_hash
        AND h.principal_ref_hash=NEW.principal_ref_hash
        AND h.purpose_scope_code=NEW.purpose_scope_code
        AND h.rights_scope_ref_hash=NEW.rights_scope_ref_hash
        AND h.entitlement_scope_ref_hash=NEW.entitlement_scope_ref_hash
        AND h.request_method_code=NEW.request_method_code
        AND h.canonical_target_ref_hash=NEW.canonical_target_ref_hash
        AND h.request_body_digest_hash=NEW.request_body_digest_hash
        AND h.server_expected_tuple_hash=NEW.presented_tuple_hash
        AND h.challenge_state='ISSUED'
        AND datetime(h.issued_at)<=datetime(NEW.verified_at)
        AND datetime(h.recorded_at)<=datetime(NEW.verified_at)
        AND datetime(NEW.verified_at)<datetime(h.expires_at)
        AND NEW.verification_state='VERIFIED'
        AND e.evidence_domain='PAYMENT' AND e.evidence_rank>=3
        AND e.environment=NEW.environment)
    THEN RAISE(IGNORE) END;
  SELECT RAISE(ABORT,'payment proof must match the exact authoritative challenge tuple')
  WHERE NOT EXISTS (
    SELECT 1 FROM challenge_receipt h
    JOIN payment_offer_version o ON o.payment_offer_id=h.payment_offer_id
    JOIN evidence_record e ON e.evidence_id=NEW.evidence_id
    WHERE h.challenge_id=NEW.proof_covered_challenge_id
      AND h.request_id=NEW.proof_covered_request_id
      AND o.payment_offer_id=NEW.payment_offer_id
      AND o.offer_version=NEW.payment_offer_version
      AND h.amount_atomic=NEW.amount_atomic
      AND h.asset_code=NEW.asset_code
      AND o.amount_atomic=NEW.amount_atomic
      AND o.asset_code=NEW.asset_code
      AND o.network_scope_code=NEW.network_scope_code
      AND o.recipient_ref_hash=NEW.recipient_ref_hash
      AND h.environment=NEW.environment
      AND h.network_scope_code=NEW.network_scope_code
      AND h.recipient_ref_hash=NEW.recipient_ref_hash
      AND h.principal_ref_hash=NEW.principal_ref_hash
      AND h.purpose_scope_code=NEW.purpose_scope_code
      AND h.rights_scope_ref_hash=NEW.rights_scope_ref_hash
      AND h.entitlement_scope_ref_hash=NEW.entitlement_scope_ref_hash
      AND h.request_method_code=NEW.request_method_code
      AND h.canonical_target_ref_hash=NEW.canonical_target_ref_hash
      AND h.request_body_digest_hash=NEW.request_body_digest_hash
      AND h.server_expected_tuple_hash=NEW.presented_tuple_hash
      AND h.challenge_state='ISSUED'
      AND datetime(h.issued_at)<=datetime(NEW.verified_at)
      AND datetime(h.recorded_at)<=datetime(NEW.verified_at)
      AND datetime(NEW.verified_at)<datetime(h.expires_at)
      AND NEW.verification_state='VERIFIED'
      AND e.evidence_domain='PAYMENT' AND e.evidence_rank>=3
      AND e.environment=NEW.environment
  );
END;

CREATE TRIGGER payment_semantic_guard
BEFORE INSERT ON payment_event
BEGIN
  INSERT INTO negative_probe_result
  SELECT c.probe_id,c.expected_rule_code,
         CASE
           WHEN NEW.event_type_code='SETTLEMENT' AND NEW.event_sequence=1
             THEN 'SETTLEMENT_REQUIRES_AUTHORIZATION'
           WHEN NOT EXISTS (
             SELECT 1 FROM challenge_receipt h
             WHERE h.challenge_id=NEW.challenge_id
               AND h.amount_atomic=NEW.amount_atomic
               AND h.asset_code=NEW.asset_code)
             THEN 'PAYMENT_MUST_MATCH_OFFER'
           WHEN EXISTS (
             SELECT 1 FROM payment_event x
             WHERE x.payment_proof_id=NEW.payment_proof_id)
             THEN 'PROOF_SINGLE_USE'
           ELSE 'PAYMENT_PREDECESSOR_EXACT'
         END,
         CASE WHEN c.expected_rule_code=CASE
           WHEN NEW.event_type_code='SETTLEMENT' AND NEW.event_sequence=1
             THEN 'SETTLEMENT_REQUIRES_AUTHORIZATION'
           WHEN NOT EXISTS (
             SELECT 1 FROM challenge_receipt h
             WHERE h.challenge_id=NEW.challenge_id
               AND h.amount_atomic=NEW.amount_atomic
               AND h.asset_code=NEW.asset_code)
             THEN 'PAYMENT_MUST_MATCH_OFFER'
           WHEN EXISTS (
             SELECT 1 FROM payment_event x
             WHERE x.payment_proof_id=NEW.payment_proof_id)
             THEN 'PROOF_SINGLE_USE'
           ELSE 'PAYMENT_PREDECESSOR_EXACT' END
         THEN 'PASS' ELSE 'FAIL' END,
         'payment_event',datetime('now')
  FROM negative_probe_context c
  WHERE (NEW.event_type_code='SETTLEMENT' AND NEW.event_sequence=1)
     OR NOT EXISTS (
       SELECT 1 FROM challenge_receipt h
       WHERE h.challenge_id=NEW.challenge_id
         AND h.amount_atomic=NEW.amount_atomic
         AND h.asset_code=NEW.asset_code)
     OR EXISTS (
       SELECT 1 FROM payment_event x
       WHERE x.payment_proof_id=NEW.payment_proof_id)
     OR (NEW.event_sequence>1 AND NOT EXISTS (
       SELECT 1 FROM payment_event p
       WHERE p.payment_event_id=NEW.predecessor_payment_event_id
         AND p.challenge_id=NEW.challenge_id
         AND p.request_id=NEW.request_id
         AND p.machine_access_contract_id=NEW.machine_access_contract_id
         AND p.event_sequence=NEW.event_sequence-1));
  SELECT CASE WHEN EXISTS (SELECT 1 FROM negative_probe_context)
    AND ((NEW.event_type_code='SETTLEMENT' AND NEW.event_sequence=1)
      OR NOT EXISTS (
        SELECT 1 FROM challenge_receipt h
        WHERE h.challenge_id=NEW.challenge_id
          AND h.amount_atomic=NEW.amount_atomic
          AND h.asset_code=NEW.asset_code)
      OR EXISTS (
        SELECT 1 FROM payment_event x
        WHERE x.payment_proof_id=NEW.payment_proof_id)
      OR (NEW.event_sequence>1 AND NOT EXISTS (
        SELECT 1 FROM payment_event p
        WHERE p.payment_event_id=NEW.predecessor_payment_event_id
          AND p.challenge_id=NEW.challenge_id
          AND p.request_id=NEW.request_id
          AND p.machine_access_contract_id=NEW.machine_access_contract_id
          AND p.event_sequence=NEW.event_sequence-1)))
    THEN RAISE(IGNORE) END;
  SELECT RAISE(ABORT,'payment must match challenge amount and asset')
  WHERE NOT EXISTS (
    SELECT 1 FROM challenge_receipt h
    WHERE h.challenge_id=NEW.challenge_id
      AND h.request_id=NEW.request_id
      AND h.machine_access_contract_id=NEW.machine_access_contract_id
      AND h.environment=NEW.environment
      AND h.amount_atomic=NEW.amount_atomic
      AND h.asset_code=NEW.asset_code
      AND datetime(h.issued_at)<=datetime(NEW.occurred_at)
      AND datetime(h.recorded_at)<=datetime(NEW.recorded_at)
  );
  SELECT RAISE(ABORT,'payment proof is single-use and must cover exact request/challenge')
  WHERE (NEW.event_type_code='AUTHORIZATION' AND (
    EXISTS (
      SELECT 1 FROM payment_event x
      WHERE x.payment_proof_id=NEW.payment_proof_id)
    OR NOT EXISTS (
      SELECT 1 FROM payment_proof q
      JOIN challenge_receipt h
        ON h.challenge_id=q.proof_covered_challenge_id
      JOIN payment_offer_version o
        ON o.payment_offer_id=h.payment_offer_id
      WHERE q.payment_proof_id=NEW.payment_proof_id
        AND q.proof_covered_challenge_id=NEW.challenge_id
        AND q.proof_covered_request_id=NEW.request_id
        AND q.payment_offer_id=h.payment_offer_id
        AND q.payment_offer_id=o.payment_offer_id
        AND q.payment_offer_version=o.offer_version
        AND q.amount_atomic=h.amount_atomic
        AND q.asset_code=h.asset_code
        AND q.amount_atomic=o.amount_atomic
        AND q.asset_code=o.asset_code
        AND q.environment=NEW.environment
        AND q.verification_state='VERIFIED'
        AND q.presented_tuple_hash=h.server_expected_tuple_hash
        AND h.challenge_state='ISSUED'
        AND datetime(h.issued_at)<=datetime(q.verified_at)
        AND datetime(q.verified_at)<=datetime(NEW.occurred_at)
        AND datetime(q.recorded_at)<=datetime(NEW.recorded_at)
        AND datetime(NEW.occurred_at)<=datetime(NEW.recorded_at)
        AND datetime(NEW.recorded_at)<datetime(h.expires_at)
    ))) OR (NEW.event_type_code<>'AUTHORIZATION'
             AND NEW.payment_proof_id IS NOT NULL);
  SELECT RAISE(ABORT,'payment after first requires exact predecessor')
  WHERE NEW.event_sequence>1 AND NOT EXISTS (
    SELECT 1 FROM payment_event p
    WHERE p.payment_event_id=NEW.predecessor_payment_event_id
      AND p.challenge_id=NEW.challenge_id
      AND p.request_id=NEW.request_id
      AND p.machine_access_contract_id=NEW.machine_access_contract_id
      AND p.event_sequence=NEW.event_sequence-1
      AND datetime(p.occurred_at)<=datetime(NEW.occurred_at)
  );
  SELECT RAISE(ABORT,'first payment event must be authorization, failure, or expiry')
  WHERE NEW.event_sequence=1
    AND NEW.event_type_code NOT IN ('AUTHORIZATION','FAILURE','EXPIRY');
  SELECT RAISE(ABORT,'authorization cannot follow another payment event')
  WHERE NEW.event_type_code='AUTHORIZATION' AND NEW.event_sequence<>1;
  SELECT RAISE(ABORT,'settlement requires observed verified authorization')
  WHERE NEW.event_type_code='SETTLEMENT' AND NOT EXISTS (
    SELECT 1 FROM payment_event p
    WHERE p.challenge_id=NEW.challenge_id
      AND p.event_type_code='AUTHORIZATION'
      AND p.event_state='OBSERVED'
      AND p.proof_verification_state='VERIFIED'
      AND p.event_sequence<NEW.event_sequence
  );
  SELECT RAISE(ABORT,'reversal or refund requires prior observed settlement')
  WHERE NEW.event_type_code IN ('REVERSAL','REFUND') AND NOT EXISTS (
    SELECT 1 FROM payment_event p
    WHERE p.challenge_id=NEW.challenge_id
      AND p.event_type_code='SETTLEMENT'
      AND p.event_state='OBSERVED'
      AND p.event_sequence<NEW.event_sequence
  );
  SELECT RAISE(ABORT,'authorization requires verified buyer proof; lifecycle events do not')
  WHERE (NEW.event_type_code='AUTHORIZATION'
         AND NEW.proof_verification_state<>'VERIFIED')
     OR (NEW.event_type_code<>'AUTHORIZATION'
         AND (NEW.payment_proof_id IS NOT NULL
           OR NEW.proof_verification_state<>'N/A'));
  SELECT RAISE(ABORT,'payment lifecycle event requires provider evidence')
  WHERE NOT EXISTS (
    SELECT 1 FROM evidence_record e
    WHERE e.evidence_id=NEW.evidence_id
      AND e.evidence_domain='PAYMENT'
      AND e.evidence_rank>=3
      AND e.environment=NEW.environment
  );
END;

CREATE TRIGGER entitlement_semantic_guard
BEFORE INSERT ON entitlement_event
BEGIN
  INSERT INTO negative_probe_result
  SELECT c.probe_id,c.expected_rule_code,'ENTITLEMENT_REQUIRES_SETTLEMENT',
         CASE WHEN c.expected_rule_code='ENTITLEMENT_REQUIRES_SETTLEMENT'
              THEN 'PASS' ELSE 'FAIL' END,
         'entitlement_event',datetime('now')
  FROM negative_probe_context c
  WHERE NEW.entitlement_state='GRANTED'
    AND NEW.source_kind_code='PAYMENT_SETTLEMENT'
    AND NOT EXISTS (
      SELECT 1 FROM payment_event p
      WHERE p.payment_event_id=NEW.source_payment_event_id
        AND p.request_id=NEW.request_id
        AND p.machine_access_contract_id=NEW.machine_access_contract_id
        AND p.event_type_code='SETTLEMENT'
        AND p.event_state='OBSERVED'
        AND EXISTS (
          SELECT 1 FROM payment_event a
          JOIN payment_proof q USING (payment_proof_id)
          WHERE a.challenge_id=p.challenge_id
            AND a.request_id=p.request_id
            AND a.event_type_code='AUTHORIZATION'
            AND a.event_state='OBSERVED'
            AND a.proof_verification_state='VERIFIED'
            AND q.verification_state='VERIFIED'
            AND a.event_sequence<p.event_sequence));
  SELECT CASE WHEN EXISTS (SELECT 1 FROM negative_probe_context)
    AND NEW.entitlement_state='GRANTED'
    AND NEW.source_kind_code='PAYMENT_SETTLEMENT'
    AND NOT EXISTS (
      SELECT 1 FROM payment_event p
      WHERE p.payment_event_id=NEW.source_payment_event_id
        AND p.request_id=NEW.request_id
        AND p.machine_access_contract_id=NEW.machine_access_contract_id
        AND p.event_type_code='SETTLEMENT'
        AND p.event_state='OBSERVED'
        AND EXISTS (
          SELECT 1 FROM payment_event a
          JOIN payment_proof q USING (payment_proof_id)
          WHERE a.challenge_id=p.challenge_id
            AND a.request_id=p.request_id
            AND a.event_type_code='AUTHORIZATION'
            AND a.event_state='OBSERVED'
            AND a.proof_verification_state='VERIFIED'
            AND q.verification_state='VERIFIED'
            AND a.event_sequence<p.event_sequence))
    THEN RAISE(IGNORE) END;
  SELECT RAISE(ABORT,'payment entitlement requires observed verified settlement')
  WHERE NEW.entitlement_state='GRANTED'
    AND NEW.source_kind_code='PAYMENT_SETTLEMENT'
    AND NOT EXISTS (
      SELECT 1 FROM payment_event p
      WHERE p.payment_event_id=NEW.source_payment_event_id
        AND p.request_id=NEW.request_id
        AND p.machine_access_contract_id=NEW.machine_access_contract_id
        AND p.event_type_code='SETTLEMENT'
        AND p.event_state='OBSERVED'
        AND EXISTS (
          SELECT 1 FROM payment_event a
          JOIN payment_proof q USING (payment_proof_id)
          WHERE a.challenge_id=p.challenge_id
            AND a.request_id=p.request_id
            AND a.event_type_code='AUTHORIZATION'
            AND a.event_state='OBSERVED'
            AND a.proof_verification_state='VERIFIED'
            AND q.verification_state='VERIFIED'
            AND a.event_sequence<p.event_sequence)
  );
  SELECT RAISE(ABORT,'contract entitlement source does not match request action')
  WHERE NEW.entitlement_state='GRANTED'
    AND NEW.source_kind_code IN ('CONTRACT_LICENSE','AUTHENTICATED_API')
    AND NOT EXISTS (
      SELECT 1 FROM request_observation r
      WHERE r.request_id=NEW.request_id
        AND r.machine_access_contract_id=NEW.machine_access_contract_id
        AND ((NEW.source_kind_code='CONTRACT_LICENSE'
              AND r.applied_action_mode_code='CONTRACT_LICENSE')
          OR (NEW.source_kind_code='AUTHENTICATED_API'
              AND r.applied_action_mode_code='AUTHENTICATED_API'))
  );
  SELECT RAISE(ABORT,'entitlement after first requires exact predecessor')
  WHERE NEW.event_sequence>1 AND NOT EXISTS (
    SELECT 1 FROM entitlement_event p
    WHERE p.entitlement_event_id=NEW.predecessor_entitlement_event_id
      AND p.entitlement_ref_hash=NEW.entitlement_ref_hash
      AND p.request_id=NEW.request_id
      AND p.event_sequence=NEW.event_sequence-1
      AND datetime(p.occurred_at)<=datetime(NEW.occurred_at)
  );
  SELECT RAISE(ABORT,'entitlement revocation requires prior grant')
  WHERE NEW.entitlement_state='REVOKED' AND NOT EXISTS (
    SELECT 1 FROM entitlement_event p
    WHERE p.entitlement_event_id=NEW.predecessor_entitlement_event_id
      AND p.entitlement_state='GRANTED'
  );
  SELECT RAISE(ABORT,'entitlement environment mismatch')
  WHERE (SELECT environment FROM request_observation
         WHERE request_id=NEW.request_id)<>NEW.environment;
  SELECT RAISE(ABORT,'entitlement cannot precede its settlement lifecycle fact')
  WHERE NEW.source_kind_code='PAYMENT_SETTLEMENT' AND NOT EXISTS (
    SELECT 1 FROM payment_event p
    WHERE p.payment_event_id=NEW.source_payment_event_id
      AND datetime(p.occurred_at)<=datetime(NEW.occurred_at)
      AND datetime(p.recorded_at)<=datetime(NEW.recorded_at)
      AND datetime(p.occurred_at)<=datetime(NEW.valid_from)
  );
  SELECT RAISE(ABORT,'entitlement requires same-environment ENTITLEMENT evidence')
  WHERE NOT EXISTS (
    SELECT 1 FROM evidence_record e
    WHERE e.evidence_id=NEW.evidence_id AND e.environment=NEW.environment
      AND e.evidence_domain='ENTITLEMENT'
      AND e.evidence_rank>=CASE WHEN NEW.entitlement_state IN ('GRANTED','REVOKED')
                                THEN 4 ELSE 2 END);
END;

CREATE TRIGGER delivery_semantic_guard
BEFORE INSERT ON delivery_event
BEGIN
  INSERT INTO negative_probe_result
  SELECT c.probe_id,c.expected_rule_code,
         CASE
           WHEN EXISTS (SELECT 1 FROM delivery_event d
                        WHERE d.idempotency_ref_hash=NEW.idempotency_ref_hash
                           OR (NEW.entitlement_event_id IS NOT NULL
                               AND d.entitlement_event_id=NEW.entitlement_event_id
                               AND d.delivery_state='DELIVERED'))
             THEN 'DELIVERY_EXACTLY_ONCE'
           ELSE 'DELIVERY_REQUIRES_ENTITLEMENT'
         END,
         CASE WHEN c.expected_rule_code=CASE
           WHEN EXISTS (SELECT 1 FROM delivery_event d
                        WHERE d.idempotency_ref_hash=NEW.idempotency_ref_hash
                           OR (NEW.entitlement_event_id IS NOT NULL
                               AND d.entitlement_event_id=NEW.entitlement_event_id
                               AND d.delivery_state='DELIVERED'))
             THEN 'DELIVERY_EXACTLY_ONCE'
           ELSE 'DELIVERY_REQUIRES_ENTITLEMENT' END
         THEN 'PASS' ELSE 'FAIL' END,
         'delivery_event',datetime('now')
  FROM negative_probe_context c
  WHERE EXISTS (
      SELECT 1 FROM delivery_event d
      WHERE d.idempotency_ref_hash=NEW.idempotency_ref_hash
         OR (NEW.entitlement_event_id IS NOT NULL
             AND d.entitlement_event_id=NEW.entitlement_event_id
             AND d.delivery_state='DELIVERED'))
     OR (NEW.delivery_state='DELIVERED' AND EXISTS (
       SELECT 1 FROM request_observation r
       WHERE r.request_id=NEW.request_id
         AND r.applied_action_mode_code IN (
           'HTTP_402','CONTRACT_LICENSE','AUTHENTICATED_API','SERVE_ENTITLED'))
       AND NOT EXISTS (
         SELECT 1 FROM entitlement_event e
         WHERE e.entitlement_event_id=NEW.entitlement_event_id
           AND e.request_id=NEW.request_id
           AND e.machine_access_contract_id=NEW.machine_access_contract_id
           AND e.entitlement_state='GRANTED'
           AND datetime(e.valid_from)<=datetime(NEW.occurred_at)
           AND datetime(NEW.occurred_at)<datetime(e.valid_until)));
  SELECT CASE WHEN EXISTS (SELECT 1 FROM negative_probe_context)
    AND (EXISTS (
      SELECT 1 FROM delivery_event d
      WHERE d.idempotency_ref_hash=NEW.idempotency_ref_hash
         OR (NEW.entitlement_event_id IS NOT NULL
             AND d.entitlement_event_id=NEW.entitlement_event_id
             AND d.delivery_state='DELIVERED'))
      OR (NEW.delivery_state='DELIVERED' AND EXISTS (
        SELECT 1 FROM request_observation r
        WHERE r.request_id=NEW.request_id
          AND r.applied_action_mode_code IN (
            'HTTP_402','CONTRACT_LICENSE','AUTHENTICATED_API','SERVE_ENTITLED'))
        AND NOT EXISTS (
          SELECT 1 FROM entitlement_event e
          WHERE e.entitlement_event_id=NEW.entitlement_event_id
            AND e.request_id=NEW.request_id
            AND e.machine_access_contract_id=NEW.machine_access_contract_id
            AND e.entitlement_state='GRANTED'
            AND datetime(e.valid_from)<=datetime(NEW.occurred_at)
            AND datetime(NEW.occurred_at)<datetime(e.valid_until))))
    THEN RAISE(IGNORE) END;
  SELECT RAISE(ABORT,'delivery idempotency or entitlement already consumed')
  WHERE EXISTS (
    SELECT 1 FROM delivery_event d
    WHERE d.idempotency_ref_hash=NEW.idempotency_ref_hash
       OR (NEW.entitlement_event_id IS NOT NULL
           AND d.entitlement_event_id=NEW.entitlement_event_id
           AND d.delivery_state='DELIVERED')
  );
  SELECT RAISE(ABORT,'chargeable delivery requires current granted entitlement')
  WHERE NEW.delivery_state='DELIVERED' AND EXISTS (
    SELECT 1 FROM request_observation r
    WHERE r.request_id=NEW.request_id
      AND r.applied_action_mode_code IN (
        'HTTP_402','CONTRACT_LICENSE','AUTHENTICATED_API','SERVE_ENTITLED')
  ) AND NOT EXISTS (
    SELECT 1 FROM entitlement_event e
    WHERE e.entitlement_event_id=NEW.entitlement_event_id
      AND e.request_id=NEW.request_id
      AND e.machine_access_contract_id=NEW.machine_access_contract_id
      AND e.entitlement_state='GRANTED'
      AND datetime(e.valid_from)<=datetime(NEW.occurred_at)
      AND datetime(NEW.occurred_at)<datetime(e.valid_until)
      AND datetime(e.recorded_at)<=datetime(NEW.occurred_at)
  );
  SELECT RAISE(ABORT,'free delivery must not claim paid entitlement')
  WHERE NEW.delivery_state='DELIVERED' AND EXISTS (
    SELECT 1 FROM request_observation r
    WHERE r.request_id=NEW.request_id
      AND r.applied_action_mode_code IN ('ALLOW_FREE','MEASURE_ONLY')
  ) AND NEW.entitlement_event_id IS NOT NULL;
  SELECT RAISE(ABORT,'delivery contract or environment mismatch')
  WHERE NOT EXISTS (
    SELECT 1 FROM request_observation r
    WHERE r.request_id=NEW.request_id
      AND r.machine_access_contract_id=NEW.machine_access_contract_id
      AND r.environment=NEW.environment
      AND datetime(r.occurred_at)<=datetime(NEW.occurred_at)
  );
  SELECT RAISE(ABORT,'delivery kind must match resource semantics')
  WHERE NOT EXISTS (
    SELECT 1 FROM request_observation r
    JOIN resource_contract x USING (resource_contract_id)
    WHERE r.request_id=NEW.request_id
      AND ((x.resource_class_code='TOOL_ACTION'
            AND NEW.delivery_kind_code='ACTION_RESULT')
        OR (x.resource_class_code<>'TOOL_ACTION'
            AND NEW.delivery_kind_code='BYTE_RESOURCE'))
  );
  SELECT RAISE(ABORT,'delivery requires same-environment DELIVERY evidence')
  WHERE NOT EXISTS (
    SELECT 1 FROM evidence_record e
    WHERE e.evidence_id=NEW.evidence_id AND e.environment=NEW.environment
      AND e.evidence_domain='DELIVERY'
      AND e.evidence_rank>=CASE WHEN NEW.delivery_state='DELIVERED'
                                THEN 4 ELSE 2 END);
END;

CREATE TRIGGER accepted_outcome_semantic_guard
BEFORE INSERT ON accepted_outcome_event
BEGIN
  INSERT INTO negative_probe_result
  SELECT c.probe_id,c.expected_rule_code,
         CASE WHEN EXISTS (
           SELECT 1 FROM accepted_outcome_event a
           WHERE a.acceptance_ref_hash=NEW.acceptance_ref_hash)
           THEN 'ACCEPTED_OUTCOME_SINGLE_USE'
           ELSE 'ACCEPTED_REQUIRES_EXACT_DELIVERY' END,
         CASE WHEN c.expected_rule_code=CASE WHEN EXISTS (
           SELECT 1 FROM accepted_outcome_event a
           WHERE a.acceptance_ref_hash=NEW.acceptance_ref_hash)
           THEN 'ACCEPTED_OUTCOME_SINGLE_USE'
           ELSE 'ACCEPTED_REQUIRES_EXACT_DELIVERY' END
         THEN 'PASS' ELSE 'FAIL' END,
         'accepted_outcome_event',datetime('now')
  FROM negative_probe_context c
  WHERE EXISTS (
      SELECT 1 FROM accepted_outcome_event a
      WHERE a.acceptance_ref_hash=NEW.acceptance_ref_hash)
     OR NOT EXISTS (
       SELECT 1 FROM delivery_event d
       JOIN request_observation r ON r.request_id=d.request_id
       JOIN evidence_record e ON e.evidence_id=NEW.evidence_id
       WHERE d.delivery_event_id=NEW.delivery_event_id
         AND d.request_id=NEW.request_id
         AND d.machine_access_contract_id=NEW.machine_access_contract_id
         AND d.environment=NEW.environment
         AND d.delivery_state='DELIVERED'
         AND d.response_status BETWEEN 200 AND 299
         AND r.request_id=NEW.request_id
         AND r.maturity_at=NEW.maturity_at
         AND datetime(d.occurred_at)<=datetime(NEW.occurred_at)
         AND datetime(d.recorded_at)<=datetime(NEW.recorded_at)
         AND e.evidence_domain='ACCEPTED_OUTCOME'
         AND e.evidence_rank>=4
         AND e.environment=NEW.environment);
  SELECT CASE WHEN EXISTS (SELECT 1 FROM negative_probe_context)
    AND (EXISTS (
      SELECT 1 FROM accepted_outcome_event a
      WHERE a.acceptance_ref_hash=NEW.acceptance_ref_hash)
      OR NOT EXISTS (
        SELECT 1 FROM delivery_event d
        JOIN request_observation r ON r.request_id=d.request_id
        JOIN evidence_record e ON e.evidence_id=NEW.evidence_id
        WHERE d.delivery_event_id=NEW.delivery_event_id
          AND d.request_id=NEW.request_id
          AND d.machine_access_contract_id=NEW.machine_access_contract_id
          AND d.environment=NEW.environment
          AND d.delivery_state='DELIVERED'
          AND d.response_status BETWEEN 200 AND 299
          AND r.request_id=NEW.request_id
          AND r.maturity_at=NEW.maturity_at
          AND datetime(d.occurred_at)<=datetime(NEW.occurred_at)
          AND datetime(d.recorded_at)<=datetime(NEW.recorded_at)
          AND e.evidence_domain='ACCEPTED_OUTCOME'
          AND e.evidence_rank>=4
          AND e.environment=NEW.environment))
    THEN RAISE(IGNORE) END;
  SELECT RAISE(ABORT,'accepted outcome requires exact first-party request and delivery')
  WHERE NOT EXISTS (
    SELECT 1 FROM delivery_event d
    JOIN request_observation r ON r.request_id=d.request_id
    JOIN evidence_record e ON e.evidence_id=NEW.evidence_id
    WHERE d.delivery_event_id=NEW.delivery_event_id
      AND d.request_id=NEW.request_id
      AND d.machine_access_contract_id=NEW.machine_access_contract_id
      AND d.environment=NEW.environment
      AND d.delivery_state='DELIVERED'
      AND d.response_status BETWEEN 200 AND 299
      AND r.request_id=NEW.request_id
      AND r.maturity_at=NEW.maturity_at
      AND datetime(d.occurred_at)<=datetime(NEW.occurred_at)
      AND datetime(d.recorded_at)<=datetime(NEW.recorded_at)
      AND e.evidence_domain='ACCEPTED_OUTCOME'
      AND e.evidence_rank>=4
      AND e.environment=NEW.environment
  );
  SELECT RAISE(ABORT,'accepted outcome correction requires exact predecessor')
  WHERE NEW.event_sequence>1 AND NOT EXISTS (
    SELECT 1 FROM accepted_outcome_event p
    WHERE p.accepted_outcome_event_id=
            NEW.predecessor_accepted_outcome_event_id
      AND p.delivery_event_id=NEW.delivery_event_id
      AND p.request_id=NEW.request_id
      AND p.machine_access_contract_id=NEW.machine_access_contract_id
      AND p.event_sequence=NEW.event_sequence-1
      AND datetime(p.recorded_at)<datetime(NEW.recorded_at)
  );
END;

CREATE TRIGGER cash_semantic_guard
BEFORE INSERT ON cash_bridge_line
BEGIN
  INSERT INTO negative_probe_result
  SELECT c.probe_id,c.expected_rule_code,
         CASE
           WHEN NEW.line_type_code IN ('REVERSAL','REFUND')
                AND NEW.amount_base_micros>0
             THEN 'REVERSAL_MUST_BE_NEGATIVE'
           WHEN NEW.environment<>(SELECT environment FROM machine_access_contract
                                  WHERE machine_access_contract_id=
                                        NEW.machine_access_contract_id)
             THEN 'TEST_REAL_CASH_SEPARATION'
           ELSE 'CASH_COMPONENT_IDEMPOTENCY_UNIQUE'
         END,
         CASE WHEN c.expected_rule_code=CASE
           WHEN NEW.line_type_code IN ('REVERSAL','REFUND')
                AND NEW.amount_base_micros>0
             THEN 'REVERSAL_MUST_BE_NEGATIVE'
           WHEN NEW.environment<>(SELECT environment FROM machine_access_contract
                                  WHERE machine_access_contract_id=
                                        NEW.machine_access_contract_id)
             THEN 'TEST_REAL_CASH_SEPARATION'
           ELSE 'CASH_COMPONENT_IDEMPOTENCY_UNIQUE' END
         THEN 'PASS' ELSE 'FAIL' END,
         'cash_bridge_line',datetime('now')
  FROM negative_probe_context c
  WHERE (NEW.line_type_code IN ('REVERSAL','REFUND')
         AND NEW.amount_base_micros>0)
     OR NEW.environment<>(SELECT environment FROM machine_access_contract
                         WHERE machine_access_contract_id=
                               NEW.machine_access_contract_id)
     OR EXISTS (
       SELECT 1 FROM cash_bridge_line x
       WHERE x.payment_event_id=NEW.payment_event_id
         AND x.line_type_code=NEW.line_type_code);
  SELECT CASE WHEN EXISTS (SELECT 1 FROM negative_probe_context)
    AND ((NEW.line_type_code IN ('REVERSAL','REFUND')
          AND NEW.amount_base_micros>0)
      OR NEW.environment<>(SELECT environment FROM machine_access_contract
                           WHERE machine_access_contract_id=
                                 NEW.machine_access_contract_id)
      OR EXISTS (
        SELECT 1 FROM cash_bridge_line x
        WHERE x.payment_event_id=NEW.payment_event_id
          AND x.line_type_code=NEW.line_type_code))
    THEN RAISE(IGNORE) END;
  SELECT RAISE(ABORT,'refund and reversal cash lines must be negative')
  WHERE NEW.line_type_code IN ('REVERSAL','REFUND')
    AND NEW.amount_base_micros>0;
  SELECT RAISE(ABORT,'cash component idempotency is owner-independent')
  WHERE EXISTS (
    SELECT 1 FROM cash_bridge_line x
    WHERE x.payment_event_id=NEW.payment_event_id
      AND x.line_type_code=NEW.line_type_code
  );
  SELECT RAISE(ABORT,'cash line contract/request/payment/environment mismatch')
  WHERE NOT EXISTS (
    SELECT 1 FROM payment_event p
    JOIN request_observation r ON r.request_id=p.request_id
    WHERE p.payment_event_id=NEW.payment_event_id
      AND p.machine_access_contract_id=NEW.machine_access_contract_id
      AND r.request_id=NEW.request_id
      AND p.environment=NEW.environment
      AND r.environment=NEW.environment
      AND datetime(p.occurred_at)<=datetime(NEW.occurred_at)
      AND datetime(p.recorded_at)<=datetime(NEW.recorded_at)
  );
  SELECT RAISE(ABORT,'gross settlement requires settlement payment event')
  WHERE NEW.line_type_code IN (
    'GROSS_SETTLED','RAIL_FEE','TAX_WITHHELD','BANK_OR_WALLET_RECEIPT')
    AND NOT EXISTS (
      SELECT 1 FROM payment_event p
      WHERE p.payment_event_id=NEW.payment_event_id
        AND p.event_type_code='SETTLEMENT'
        AND p.event_state='OBSERVED'
  );
  SELECT RAISE(ABORT,'gross base cash must match authoritative offer value')
  WHERE NEW.line_type_code='GROSS_SETTLED' AND NOT EXISTS (
    SELECT 1 FROM payment_event p
    JOIN challenge_receipt h USING (challenge_id)
    JOIN payment_offer_version o USING (payment_offer_id)
    WHERE p.payment_event_id=NEW.payment_event_id
      AND o.base_currency_value_micros=NEW.amount_base_micros
  );
  SELECT RAISE(ABORT,'refund or reversal cash requires matching payment event')
  WHERE NEW.line_type_code IN ('REFUND','REVERSAL')
    AND NOT EXISTS (
      SELECT 1 FROM payment_event p
      WHERE p.payment_event_id=NEW.payment_event_id
        AND ((NEW.line_type_code='REFUND' AND p.event_type_code='REFUND')
          OR (NEW.line_type_code='REVERSAL' AND p.event_type_code='REVERSAL'))
        AND p.event_state='OBSERVED'
  );
  SELECT RAISE(ABORT,'bank or wallet receipt requires E5 authority evidence')
  WHERE NEW.line_type_code='BANK_OR_WALLET_RECEIPT'
    AND ((SELECT evidence_rank FROM evidence_record
          WHERE evidence_id=NEW.evidence_id)<5
      OR NEW.authority_code NOT IN ('CONTROLLED_WALLET','BANK_STATEMENT'));
  SELECT RAISE(ABORT,'cash currency must match contract base currency')
  WHERE NEW.base_currency<>(SELECT base_currency FROM machine_access_contract
                            WHERE machine_access_contract_id=
                                  NEW.machine_access_contract_id);
  SELECT RAISE(ABORT,'cash requires same-environment CASH authority evidence')
  WHERE NOT EXISTS (
    SELECT 1 FROM evidence_record e
    WHERE e.evidence_id=NEW.evidence_id AND e.environment=NEW.environment
      AND e.evidence_domain='CASH'
      AND e.evidence_rank>=CASE WHEN NEW.line_type_code='BANK_OR_WALLET_RECEIPT'
                                THEN 5 ELSE 3 END);
END;

CREATE TRIGGER cost_semantic_guard
BEFORE INSERT ON cost_event
BEGIN
  INSERT INTO negative_probe_result
  SELECT c.probe_id,c.expected_rule_code,
         CASE WHEN (SELECT environment FROM evidence_record
                    WHERE evidence_id=NEW.evidence_id)<>NEW.environment
              THEN 'EVIDENCE_ENVIRONMENT_EXACT'
              ELSE 'EVIDENCE_AUTHORITY_EXACT' END,
         CASE WHEN c.expected_rule_code=CASE
           WHEN (SELECT environment FROM evidence_record
                 WHERE evidence_id=NEW.evidence_id)<>NEW.environment
             THEN 'EVIDENCE_ENVIRONMENT_EXACT'
           ELSE 'EVIDENCE_AUTHORITY_EXACT' END THEN 'PASS' ELSE 'FAIL' END,
         'cost_event',datetime('now')
  FROM negative_probe_context c
  WHERE NOT EXISTS (
    SELECT 1 FROM evidence_record e
    WHERE e.evidence_id=NEW.evidence_id AND e.environment=NEW.environment
      AND e.evidence_domain='COST' AND e.evidence_rank>=3);
  SELECT CASE WHEN EXISTS (SELECT 1 FROM negative_probe_context)
    AND NOT EXISTS (
      SELECT 1 FROM evidence_record e
      WHERE e.evidence_id=NEW.evidence_id AND e.environment=NEW.environment
        AND e.evidence_domain='COST' AND e.evidence_rank>=3)
    THEN RAISE(IGNORE) END;
  SELECT RAISE(ABORT,'cost contract/request/environment mismatch')
  WHERE NOT EXISTS (
    SELECT 1 FROM request_observation r
    WHERE r.request_id=NEW.request_id
      AND r.machine_access_contract_id=NEW.machine_access_contract_id
      AND r.environment=NEW.environment
      AND datetime(r.occurred_at)<=datetime(NEW.occurred_at)
  );
  SELECT RAISE(ABORT,'cost requires same-environment COST E3+ evidence')
  WHERE NOT EXISTS (
    SELECT 1 FROM evidence_record e
    WHERE e.evidence_id=NEW.evidence_id AND e.environment=NEW.environment
      AND e.evidence_domain='COST' AND e.evidence_rank>=3);
END;

CREATE TRIGGER risk_semantic_guard
BEFORE INSERT ON risk_review
BEGIN
  SELECT RAISE(ABORT,'risk review after first requires exact predecessor')
  WHERE NEW.review_sequence>1 AND NOT EXISTS (
    SELECT 1 FROM risk_review p
    WHERE p.risk_review_id=NEW.predecessor_risk_review_id
      AND p.machine_access_contract_id=NEW.machine_access_contract_id
      AND p.review_sequence=NEW.review_sequence-1
      AND datetime(p.recorded_at)<datetime(NEW.recorded_at)
  );
  SELECT RAISE(ABORT,'risk review requires same-environment RISK E4+ evidence')
  WHERE NOT EXISTS (
    SELECT 1 FROM evidence_record e
    JOIN machine_access_contract m
      ON m.machine_access_contract_id=NEW.machine_access_contract_id
    WHERE e.evidence_id=NEW.evidence_id AND e.environment=m.environment
      AND e.evidence_domain='RISK' AND e.evidence_rank>=4);
END;

-- ---------------------------------------------------------------------------
-- Append-only guards. Request UPDATE is probe-aware; every other mutation
-- aborts directly.
-- ---------------------------------------------------------------------------

CREATE TRIGGER immutable_request_update
BEFORE UPDATE ON request_observation
BEGIN
  INSERT INTO negative_probe_result
  SELECT c.probe_id,c.expected_rule_code,'APPEND_ONLY_REQUEST',
         CASE WHEN c.expected_rule_code='APPEND_ONLY_REQUEST'
              THEN 'PASS' ELSE 'FAIL' END,
         'request_observation',datetime('now')
  FROM negative_probe_context c;
  SELECT CASE WHEN EXISTS (SELECT 1 FROM negative_probe_context)
              THEN RAISE(IGNORE) END;
  SELECT RAISE(ABORT,'append-only: request_observation cannot be updated');
END;
CREATE TRIGGER immutable_request_delete BEFORE DELETE ON request_observation
BEGIN SELECT RAISE(ABORT,'append-only: request_observation cannot be deleted'); END;

CREATE TRIGGER immutable_schema_update BEFORE UPDATE ON schema_registry
BEGIN SELECT RAISE(ABORT,'append-only: schema_registry cannot be updated'); END;
CREATE TRIGGER immutable_schema_delete BEFORE DELETE ON schema_registry
BEGIN SELECT RAISE(ABORT,'append-only: schema_registry cannot be deleted'); END;
CREATE TRIGGER immutable_setting_update BEFORE UPDATE ON model_setting
BEGIN SELECT RAISE(ABORT,'append-only: model_setting cannot be updated'); END;
CREATE TRIGGER immutable_setting_delete BEFORE DELETE ON model_setting
BEGIN SELECT RAISE(ABORT,'append-only: model_setting cannot be deleted'); END;
CREATE TRIGGER immutable_evidence_update BEFORE UPDATE ON evidence_record
BEGIN SELECT RAISE(ABORT,'append-only: evidence_record cannot be updated'); END;
CREATE TRIGGER immutable_evidence_delete BEFORE DELETE ON evidence_record
BEGIN SELECT RAISE(ABORT,'append-only: evidence_record cannot be deleted'); END;
CREATE TRIGGER immutable_source_update BEFORE UPDATE ON source_snapshot
BEGIN SELECT RAISE(ABORT,'append-only: source_snapshot cannot be updated'); END;
CREATE TRIGGER immutable_source_delete BEFORE DELETE ON source_snapshot
BEGIN SELECT RAISE(ABORT,'append-only: source_snapshot cannot be deleted'); END;
CREATE TRIGGER immutable_contract_update BEFORE UPDATE ON machine_access_contract
BEGIN SELECT RAISE(ABORT,'append-only: machine_access_contract cannot be updated'); END;
CREATE TRIGGER immutable_contract_delete BEFORE DELETE ON machine_access_contract
BEGIN SELECT RAISE(ABORT,'append-only: machine_access_contract cannot be deleted'); END;
CREATE TRIGGER immutable_resource_update BEFORE UPDATE ON resource_contract
BEGIN SELECT RAISE(ABORT,'append-only: resource_contract cannot be updated'); END;
CREATE TRIGGER immutable_resource_delete BEFORE DELETE ON resource_contract
BEGIN SELECT RAISE(ABORT,'append-only: resource_contract cannot be deleted'); END;
CREATE TRIGGER immutable_policy_update BEFORE UPDATE ON traffic_policy_version
BEGIN SELECT RAISE(ABORT,'append-only: traffic_policy_version cannot be updated'); END;
CREATE TRIGGER immutable_policy_delete BEFORE DELETE ON traffic_policy_version
BEGIN SELECT RAISE(ABORT,'append-only: traffic_policy_version cannot be deleted'); END;
CREATE TRIGGER immutable_identity_update BEFORE UPDATE ON actor_identity_observation
BEGIN SELECT RAISE(ABORT,'append-only: actor_identity_observation cannot be updated'); END;
CREATE TRIGGER immutable_identity_delete BEFORE DELETE ON actor_identity_observation
BEGIN SELECT RAISE(ABORT,'append-only: actor_identity_observation cannot be deleted'); END;
CREATE TRIGGER immutable_offer_update BEFORE UPDATE ON payment_offer_version
BEGIN SELECT RAISE(ABORT,'append-only: payment_offer_version cannot be updated'); END;
CREATE TRIGGER immutable_offer_delete BEFORE DELETE ON payment_offer_version
BEGIN SELECT RAISE(ABORT,'append-only: payment_offer_version cannot be deleted'); END;
CREATE TRIGGER immutable_challenge_update BEFORE UPDATE ON challenge_receipt
BEGIN SELECT RAISE(ABORT,'append-only: challenge_receipt cannot be updated'); END;
CREATE TRIGGER immutable_challenge_delete BEFORE DELETE ON challenge_receipt
BEGIN SELECT RAISE(ABORT,'append-only: challenge_receipt cannot be deleted'); END;
CREATE TRIGGER immutable_payment_proof_update BEFORE UPDATE ON payment_proof
BEGIN SELECT RAISE(ABORT,'append-only: payment_proof cannot be updated'); END;
CREATE TRIGGER immutable_payment_proof_delete BEFORE DELETE ON payment_proof
BEGIN SELECT RAISE(ABORT,'append-only: payment_proof cannot be deleted'); END;
CREATE TRIGGER immutable_payment_update BEFORE UPDATE ON payment_event
BEGIN SELECT RAISE(ABORT,'append-only: payment_event cannot be updated'); END;
CREATE TRIGGER immutable_payment_delete BEFORE DELETE ON payment_event
BEGIN SELECT RAISE(ABORT,'append-only: payment_event cannot be deleted'); END;
CREATE TRIGGER immutable_entitlement_update BEFORE UPDATE ON entitlement_event
BEGIN SELECT RAISE(ABORT,'append-only: entitlement_event cannot be updated'); END;
CREATE TRIGGER immutable_entitlement_delete BEFORE DELETE ON entitlement_event
BEGIN SELECT RAISE(ABORT,'append-only: entitlement_event cannot be deleted'); END;
CREATE TRIGGER immutable_delivery_update BEFORE UPDATE ON delivery_event
BEGIN SELECT RAISE(ABORT,'append-only: delivery_event cannot be updated'); END;
CREATE TRIGGER immutable_delivery_delete BEFORE DELETE ON delivery_event
BEGIN SELECT RAISE(ABORT,'append-only: delivery_event cannot be deleted'); END;
CREATE TRIGGER immutable_accepted_update BEFORE UPDATE ON accepted_outcome_event
BEGIN SELECT RAISE(ABORT,'append-only: accepted_outcome_event cannot be updated'); END;
CREATE TRIGGER immutable_accepted_delete BEFORE DELETE ON accepted_outcome_event
BEGIN SELECT RAISE(ABORT,'append-only: accepted_outcome_event cannot be deleted'); END;
CREATE TRIGGER immutable_cash_update BEFORE UPDATE ON cash_bridge_line
BEGIN SELECT RAISE(ABORT,'append-only: cash_bridge_line cannot be updated'); END;
CREATE TRIGGER immutable_cash_delete BEFORE DELETE ON cash_bridge_line
BEGIN SELECT RAISE(ABORT,'append-only: cash_bridge_line cannot be deleted'); END;
CREATE TRIGGER immutable_cost_update BEFORE UPDATE ON cost_event
BEGIN SELECT RAISE(ABORT,'append-only: cost_event cannot be updated'); END;
CREATE TRIGGER immutable_cost_delete BEFORE DELETE ON cost_event
BEGIN SELECT RAISE(ABORT,'append-only: cost_event cannot be deleted'); END;
CREATE TRIGGER immutable_risk_update BEFORE UPDATE ON risk_review
BEGIN SELECT RAISE(ABORT,'append-only: risk_review cannot be updated'); END;
CREATE TRIGGER immutable_risk_delete BEFORE DELETE ON risk_review
BEGIN SELECT RAISE(ABORT,'append-only: risk_review cannot be deleted'); END;
CREATE TRIGGER immutable_decision_update BEFORE UPDATE ON decision_snapshot
BEGIN SELECT RAISE(ABORT,'append-only: decision_snapshot cannot be updated'); END;
CREATE TRIGGER immutable_decision_delete BEFORE DELETE ON decision_snapshot
BEGIN SELECT RAISE(ABORT,'append-only: decision_snapshot cannot be deleted'); END;

-- ---------------------------------------------------------------------------
-- Five decision-facing views
-- ---------------------------------------------------------------------------

CREATE VIEW v_effective_actor_identity AS
SELECT i.*
FROM actor_identity_observation i
WHERE NOT EXISTS (
  SELECT 1 FROM actor_identity_observation n
  WHERE n.machine_access_contract_id=i.machine_access_contract_id
    AND n.actor_ref_hash=i.actor_ref_hash
    AND (datetime(n.recorded_at)>datetime(i.recorded_at)
      OR (datetime(n.recorded_at)=datetime(i.recorded_at)
          AND n.identity_observation_id>i.identity_observation_id))
);

CREATE VIEW v_request_policy_resolution AS
SELECT r.request_id,r.machine_access_contract_id,r.resource_contract_id,
       r.environment,r.classification_state,r.applied_action_mode_code,
       r.response_status,r.protected_resource_bytes,r.challenge_document_bytes,
       r.occurred_at,r.recorded_at,
       r.outcome_cutoff_at,r.maturity_at,
       p.actor_class_code,p.identity_required,p.chargeable,
       i.verification_state,i.verification_method_code,
       i.verified_actor_class_code,i.valid_until,
       CASE
         WHEN p.identity_required=0 THEN 'N/A'
         WHEN i.verification_state='VERIFIED'
           AND i.verified_actor_class_code=p.actor_class_code
           AND datetime(r.occurred_at)<=datetime(i.valid_until) THEN 'PASS'
         WHEN i.verification_state='FAILED' THEN 'FAILED'
         ELSE 'UNKNOWN'
       END AS identity_gate,
       CASE
         WHEN r.applied_action_mode_code=p.action_mode_code
           AND r.resource_contract_id=p.resource_contract_id
           AND r.machine_access_contract_id=p.machine_access_contract_id
           THEN 'PASS'
         ELSE 'FAILED'
       END AS policy_resolution_gate
FROM request_observation r
JOIN traffic_policy_version p USING (traffic_policy_id)
JOIN actor_identity_observation i USING (identity_observation_id);

CREATE VIEW v_payment_delivery_chain AS
WITH settings AS (
  SELECT default_snapshot_as_of FROM model_setting WHERE singleton_id=1
), payment_facts AS (
  SELECT p.request_id,
         sum(p.event_type_code='AUTHORIZATION' AND p.event_state='OBSERVED')
           AS authorization_n,
         sum(p.event_type_code='SETTLEMENT' AND p.event_state='OBSERVED')
           AS settlement_n,
         sum(p.event_type_code IN ('REVERSAL','REFUND')
             AND p.event_state='OBSERVED') AS reversal_n,
         sum(p.event_type_code='AUTHORIZATION'
             AND p.event_state='OBSERVED'
             AND p.proof_verification_state='VERIFIED'
             AND q.verification_state='VERIFIED'
             AND q.proof_covered_request_id=p.request_id
             AND q.proof_covered_challenge_id=p.challenge_id
             AND q.presented_tuple_hash=h.server_expected_tuple_hash)
           AS verified_payment_proof_n
  FROM payment_event p
  LEFT JOIN payment_proof q USING (payment_proof_id)
  JOIN challenge_receipt h ON h.challenge_id=p.challenge_id
  CROSS JOIN settings s
  WHERE datetime(p.recorded_at)<=datetime(s.default_snapshot_as_of)
  GROUP BY p.request_id
), current_entitlement AS (
  SELECT e.request_id,
         e.entitlement_state AS latest_entitlement_state,
         CASE WHEN e.entitlement_state<>'GRANTED' THEN 'N/A'
              WHEN datetime(e.valid_from)<=datetime(s.default_snapshot_as_of)
               AND datetime(s.default_snapshot_as_of)<datetime(e.valid_until)
                THEN 'UNEXPIRED'
              ELSE 'EXPIRED' END AS entitlement_time_state
  FROM entitlement_event e
  CROSS JOIN settings s
  WHERE datetime(e.recorded_at)<=datetime(s.default_snapshot_as_of)
    AND NOT EXISTS (
      SELECT 1 FROM entitlement_event n
      WHERE n.request_id=e.request_id
        AND datetime(n.recorded_at)<=datetime(s.default_snapshot_as_of)
        AND (n.event_sequence>e.event_sequence
          OR (n.event_sequence=e.event_sequence
              AND n.entitlement_event_id>e.entitlement_event_id))
    )
), current_acceptance AS (
  SELECT a.*
  FROM accepted_outcome_event a CROSS JOIN settings s
  WHERE datetime(a.recorded_at)<=datetime(s.default_snapshot_as_of)
    AND NOT EXISTS (
      SELECT 1 FROM accepted_outcome_event n
      WHERE n.delivery_event_id=a.delivery_event_id
        AND datetime(n.recorded_at)<=datetime(s.default_snapshot_as_of)
        AND (n.event_sequence>a.event_sequence
          OR (n.event_sequence=a.event_sequence
              AND n.accepted_outcome_event_id>a.accepted_outcome_event_id))
    )
), delivery_facts AS (
  SELECT d.request_id,
         sum(d.delivery_state='DELIVERED'
             AND d.response_status BETWEEN 200 AND 299) AS delivered_n,
         sum(d.delivery_state='DELIVERED'
             AND d.response_status BETWEEN 200 AND 299
             AND EXISTS (
               SELECT 1 FROM entitlement_event e
               WHERE e.entitlement_event_id=d.entitlement_event_id
                 AND e.request_id=d.request_id
                 AND e.entitlement_state='GRANTED'
                 AND datetime(e.valid_from)<=datetime(d.occurred_at)
                 AND datetime(d.occurred_at)<datetime(e.valid_until)
                 AND datetime(e.recorded_at)<=datetime(d.occurred_at)))
           AS delivery_entitlement_valid_n,
         sum(d.delivery_state='DELIVERED'
             AND d.response_status BETWEEN 200 AND 299
             AND EXISTS (
               SELECT 1 FROM entitlement_event e
               WHERE e.entitlement_event_id=d.entitlement_event_id
                 AND e.request_id=d.request_id
                 AND e.entitlement_state='GRANTED'
                 AND datetime(e.valid_from)<=datetime(d.occurred_at)
                 AND datetime(d.occurred_at)<datetime(e.valid_until)
                 AND datetime(e.recorded_at)<=datetime(d.occurred_at)
                 AND NOT EXISTS (
                   SELECT 1 FROM entitlement_event n
                   WHERE n.request_id=e.request_id
                     AND n.entitlement_ref_hash=e.entitlement_ref_hash
                     AND n.event_sequence>e.event_sequence
                     AND n.entitlement_state='REVOKED'
                     AND datetime(n.recorded_at)<=
                         datetime(s.default_snapshot_as_of))))
           AS delivery_entitlement_not_revoked_n,
         sum(d.delivery_state='DELIVERED'
             AND d.response_status BETWEEN 200 AND 299
             AND a.outcome_state='ACCEPTED'
             AND a.request_id=d.request_id
             AND datetime(a.recorded_at)<=datetime(s.default_snapshot_as_of)
             AND datetime(a.maturity_at)<=datetime(s.default_snapshot_as_of))
           AS accepted_n
  FROM delivery_event d
  CROSS JOIN settings s
  LEFT JOIN current_acceptance a
    ON a.delivery_event_id=d.delivery_event_id
  WHERE datetime(d.recorded_at)<=datetime(s.default_snapshot_as_of)
  GROUP BY d.request_id
), cash_facts AS (
  SELECT c.request_id,
         sum(CASE WHEN c.line_type_code IN (
                    'GROSS_SETTLED','RAIL_FEE','TAX_WITHHELD','FX_ADJUSTMENT')
                  THEN c.amount_base_micros ELSE 0 END) AS provider_net_micros,
         sum(CASE WHEN c.line_type_code='BANK_OR_WALLET_RECEIPT'
                  THEN c.amount_base_micros ELSE 0 END) AS bank_receipt_micros,
         sum(CASE WHEN c.line_type_code IN ('REFUND','REVERSAL')
                  THEN c.amount_base_micros ELSE 0 END)
           AS negative_cash_adjustment_micros,
         sum(CASE WHEN c.line_type_code IN (
                    'BANK_OR_WALLET_RECEIPT','REFUND','REVERSAL')
                  THEN c.amount_base_micros ELSE 0 END) AS net_cash_receipt_micros
  FROM cash_bridge_line c
  CROSS JOIN settings s
  WHERE datetime(c.recorded_at)<=datetime(s.default_snapshot_as_of)
  GROUP BY c.request_id
), cost_facts AS (
  SELECT c.request_id,sum(c.cash_cost_base_micros) AS cash_cost_micros,
         sum(c.founder_minutes) AS founder_minutes
  FROM cost_event c
  CROSS JOIN settings s
  WHERE datetime(c.recorded_at)<=datetime(s.default_snapshot_as_of)
  GROUP BY c.request_id
)
SELECT r.request_id,r.machine_access_contract_id,r.environment,
       r.applied_action_mode_code,r.maturity_at,
       (SELECT h.challenge_id FROM challenge_receipt h CROSS JOIN settings s
        WHERE h.request_id=r.request_id
          AND datetime(h.recorded_at)<=datetime(s.default_snapshot_as_of)
        ORDER BY h.challenge_id LIMIT 1) AS challenge_id,
       coalesce(p.authorization_n,0) AS authorization_n,
       coalesce(p.settlement_n,0) AS settlement_n,
       coalesce(p.reversal_n,0) AS reversal_n,
       coalesce(p.verified_payment_proof_n,0) AS verified_payment_proof_n,
       coalesce(e.latest_entitlement_state,'N/A') AS latest_entitlement_state,
       coalesce(e.entitlement_time_state,'N/A') AS entitlement_time_state,
       coalesce(d.delivered_n,0) AS delivered_n,
       coalesce(d.delivery_entitlement_valid_n,0)
         AS delivery_entitlement_valid_n,
       coalesce(d.delivery_entitlement_not_revoked_n,0)
         AS delivery_entitlement_not_revoked_n,
       coalesce(d.accepted_n,0) AS accepted_n,
       coalesce(c.provider_net_micros,0) AS provider_net_micros,
       coalesce(c.bank_receipt_micros,0) AS bank_receipt_micros,
       coalesce(c.negative_cash_adjustment_micros,0)
         AS negative_cash_adjustment_micros,
       coalesce(c.net_cash_receipt_micros,0) AS net_cash_receipt_micros,
       CASE
         WHEN coalesce(p.settlement_n,0)=0 THEN 'N/A'
         WHEN coalesce(p.reversal_n,0)>0 THEN 'UNRECONCILED'
         WHEN coalesce(c.bank_receipt_micros,0)>0
           AND c.provider_net_micros=c.bank_receipt_micros THEN 'RECONCILED'
         ELSE 'UNRECONCILED'
       END AS cash_reconciled_state,
       coalesce(k.cash_cost_micros,0) AS cash_cost_micros,
       coalesce(k.founder_minutes,0) AS founder_minutes
FROM request_observation r
LEFT JOIN payment_facts p USING (request_id)
LEFT JOIN current_entitlement e USING (request_id)
LEFT JOIN delivery_facts d USING (request_id)
LEFT JOIN cash_facts c USING (request_id)
LEFT JOIN cost_facts k USING (request_id);

CREATE VIEW v_mature_machine_unit_economics AS
WITH settings AS (
  SELECT default_snapshot_as_of,founder_rate_micros_per_minute
  FROM model_setting WHERE singleton_id=1
), latest_risk AS (
  SELECT r.machine_access_contract_id,r.overall_state
  FROM risk_review r CROSS JOIN settings s
  WHERE datetime(r.recorded_at)<=datetime(s.default_snapshot_as_of)
    AND NOT EXISTS (
      SELECT 1 FROM risk_review n
      WHERE n.machine_access_contract_id=r.machine_access_contract_id
        AND datetime(n.recorded_at)<=datetime(s.default_snapshot_as_of)
        AND n.review_sequence>r.review_sequence)
), request_facts AS (
  SELECT r.request_id,r.machine_access_contract_id,r.environment,
         r.classification_state,r.maturity_at,
         pr.identity_gate,pr.policy_resolution_gate,pr.chargeable,
         rc.rights_state,coalesce(lr.overall_state,'UNKNOWN') AS risk_state,
         CASE WHEN src.program_status='CURRENT'
                    AND src.seller_eligibility_state='OBSERVED'
                    AND datetime(src.stale_after)>=datetime(s.default_snapshot_as_of)
              THEN 'PASS' ELSE 'FAILED' END AS source_eligibility_gate,
         ch.challenge_id,ch.authorization_n,ch.settlement_n,ch.reversal_n,
         ch.verified_payment_proof_n,ch.latest_entitlement_state,
         ch.entitlement_time_state,
         ch.delivery_entitlement_valid_n,
         ch.delivery_entitlement_not_revoked_n,ch.delivered_n,ch.accepted_n,
         ch.cash_reconciled_state,
         ch.bank_receipt_micros,ch.negative_cash_adjustment_micros,
         ch.net_cash_receipt_micros,ch.cash_cost_micros,ch.founder_minutes
  FROM request_observation r
  JOIN v_request_policy_resolution pr USING (request_id)
  JOIN v_payment_delivery_chain ch USING (request_id)
  JOIN resource_contract rc USING (resource_contract_id)
  JOIN machine_access_contract mc USING (machine_access_contract_id)
  JOIN source_snapshot src USING (source_snapshot_id)
  LEFT JOIN latest_risk lr USING (machine_access_contract_id)
  CROSS JOIN settings s
  WHERE datetime(r.recorded_at)<=datetime(s.default_snapshot_as_of)
), qualified AS (
  SELECT f.*,
         (f.environment='REAL'
          AND datetime(f.maturity_at)<=datetime(s.default_snapshot_as_of))
           AS mature_real,
         (f.classification_state='OBSERVED'
          AND f.identity_gate='PASS' AND f.policy_resolution_gate='PASS'
          AND f.chargeable=1 AND f.source_eligibility_gate='PASS')
           AS verified_eligible,
         (f.rights_state='PASS' AND f.risk_state='PASS') AS rights_risk_pass,
         (f.environment='REAL'
          AND datetime(f.maturity_at)<=datetime(s.default_snapshot_as_of)
          AND f.classification_state='OBSERVED'
          AND f.identity_gate='PASS' AND f.policy_resolution_gate='PASS'
          AND f.chargeable=1 AND f.source_eligibility_gate='PASS')
           AS cohort_cost_eligible,
         (f.authorization_n=1 AND f.settlement_n=1
          AND f.verified_payment_proof_n=1) AS payment_proof_verified,
         (f.environment='REAL'
          AND datetime(f.maturity_at)<=datetime(s.default_snapshot_as_of)
          AND f.classification_state='OBSERVED'
          AND f.identity_gate='PASS' AND f.policy_resolution_gate='PASS'
          AND f.chargeable=1 AND f.source_eligibility_gate='PASS'
          AND f.rights_state='PASS' AND f.risk_state='PASS'
          AND f.challenge_id IS NOT NULL
          AND f.authorization_n=1 AND f.settlement_n=1
          AND f.verified_payment_proof_n=1
          AND f.delivery_entitlement_valid_n=1
          AND f.delivery_entitlement_not_revoked_n=1
          AND f.delivered_n=1 AND f.accepted_n=1
          AND f.cash_reconciled_state='RECONCILED'
          AND f.reversal_n=0) AS contribution_eligible
  FROM request_facts f CROSS JOIN settings s
)
SELECT m.machine_access_contract_id,m.environment,
       sum(coalesce(q.mature_real,0)) AS mature_request_n,
       sum(CASE WHEN q.mature_real AND q.identity_gate='PASS' THEN 1 ELSE 0 END)
         AS verified_request_n,
       sum(CASE WHEN q.mature_real AND q.verified_eligible THEN 1 ELSE 0 END)
         AS verified_eligible_request_n,
       sum(CASE WHEN q.mature_real AND q.rights_risk_pass THEN 1 ELSE 0 END)
         AS rights_risk_pass_request_n,
       sum(CASE WHEN q.mature_real AND q.challenge_id IS NOT NULL THEN 1 ELSE 0 END)
         AS challenged_request_n,
       sum(CASE WHEN q.mature_real AND q.authorization_n=1 THEN 1 ELSE 0 END)
         AS authorized_request_n,
       sum(CASE WHEN q.mature_real AND q.payment_proof_verified THEN 1 ELSE 0 END)
         AS payment_proof_verified_request_n,
       sum(CASE WHEN q.mature_real AND q.settlement_n=1 THEN 1 ELSE 0 END)
         AS settled_request_n,
       sum(CASE WHEN q.mature_real AND q.delivery_entitlement_valid_n=1
                THEN 1 ELSE 0 END) AS entitled_request_n,
       sum(CASE WHEN q.mature_real
                  AND q.delivery_entitlement_not_revoked_n=1
                THEN 1 ELSE 0 END) AS not_revoked_entitlement_request_n,
       sum(CASE WHEN q.mature_real AND q.delivered_n=1 THEN 1 ELSE 0 END)
         AS delivered_request_n,
       sum(CASE WHEN q.mature_real AND q.accepted_n=1 THEN 1 ELSE 0 END)
         AS accepted_request_n,
       sum(CASE WHEN q.mature_real AND q.cash_reconciled_state='RECONCILED'
                THEN 1 ELSE 0 END) AS cash_reconciled_request_n,
       sum(CASE WHEN q.contribution_eligible THEN 1 ELSE 0 END)
         AS contribution_eligible_request_n,
       sum(CASE WHEN q.mature_real AND q.reversal_n>0 THEN 1 ELSE 0 END)
         AS reversed_request_n,
       sum(CASE WHEN q.contribution_eligible THEN q.bank_receipt_micros ELSE 0 END)
         +sum(CASE WHEN q.cohort_cost_eligible
                   THEN q.negative_cash_adjustment_micros ELSE 0 END)
         AS bank_or_wallet_cash_micros,
       sum(CASE WHEN q.cohort_cost_eligible THEN q.cash_cost_micros ELSE 0 END)
         AS cash_cost_micros,
       sum(CASE WHEN q.cohort_cost_eligible THEN q.founder_minutes ELSE 0 END)
         AS founder_minutes,
       sum(CASE WHEN q.cohort_cost_eligible THEN q.founder_minutes ELSE 0 END)
         * s.founder_rate_micros_per_minute AS founder_time_cost_micros,
       0 AS license_value_micros,
       0 AS referral_value_micros,
       0 AS cannibalization_value_micros,
       'N/A_REASON_NOT_MODELED' AS non_request_value_support_state,
       'PER_REQUEST_PAID_ACCESS_ONLY' AS kpi_scope_code,
       'UNKNOWN_NOT_COMPUTED' AS inclusive_profit_state,
       sum(CASE WHEN q.contribution_eligible THEN q.bank_receipt_micros ELSE 0 END)
         +sum(CASE WHEN q.cohort_cost_eligible
                   THEN q.negative_cash_adjustment_micros ELSE 0 END)
         -sum(CASE WHEN q.cohort_cost_eligible THEN q.cash_cost_micros ELSE 0 END)
         -sum(CASE WHEN q.cohort_cost_eligible THEN q.founder_minutes ELSE 0 END)
            * s.founder_rate_micros_per_minute
         AS matured_incremental_machine_contribution_micros
FROM machine_access_contract m
CROSS JOIN settings s
LEFT JOIN qualified q
  ON q.machine_access_contract_id=m.machine_access_contract_id
GROUP BY m.machine_access_contract_id,m.environment,
         s.founder_rate_micros_per_minute;

CREATE VIEW v_current_decision_gate AS
SELECT d.decision_snapshot_id,d.machine_access_contract_id,d.decision_state,
       d.action_mode_code,d.snapshot_as_of,d.decided_at,
       r.overall_state AS risk_state,
       e.mature_request_n,e.verified_request_n,e.verified_eligible_request_n,
       e.rights_risk_pass_request_n,e.challenged_request_n,
       e.authorized_request_n,e.payment_proof_verified_request_n,
       e.settled_request_n,e.entitled_request_n,
       e.not_revoked_entitlement_request_n,e.delivered_request_n,
       e.accepted_request_n,e.cash_reconciled_request_n,
       e.contribution_eligible_request_n,e.reversed_request_n,
       e.bank_or_wallet_cash_micros,e.cash_cost_micros,e.founder_minutes,
       e.matured_incremental_machine_contribution_micros,
       CASE
         WHEN r.overall_state='FAILED' THEN 'STOP'
         WHEN r.overall_state='UNKNOWN' THEN 'UNKNOWN'
         WHEN EXISTS (
           SELECT 1 FROM machine_access_contract m
           JOIN source_snapshot s USING (source_snapshot_id)
           WHERE m.machine_access_contract_id=d.machine_access_contract_id
             AND datetime(s.stale_after)<datetime(d.decided_at)) THEN 'UNKNOWN'
         WHEN d.decision_state='EXPAND'
           AND EXISTS (
             SELECT 1 FROM traffic_policy_version p
             WHERE p.machine_access_contract_id=d.machine_access_contract_id
               AND p.action_mode_code=d.action_mode_code
               AND datetime(p.effective_from)<=datetime(d.snapshot_as_of)
               AND (p.effective_until IS NULL
                 OR datetime(d.snapshot_as_of)<datetime(p.effective_until)))
           AND e.mature_request_n>0
           AND e.verified_eligible_request_n=e.mature_request_n
           AND e.rights_risk_pass_request_n=e.mature_request_n
           AND e.challenged_request_n=e.mature_request_n
           AND e.authorized_request_n=e.mature_request_n
           AND e.payment_proof_verified_request_n=e.mature_request_n
           AND e.settled_request_n=e.mature_request_n
           AND e.entitled_request_n=e.mature_request_n
           AND e.not_revoked_entitlement_request_n=e.mature_request_n
           AND e.delivered_request_n=e.mature_request_n
           AND e.accepted_request_n=e.mature_request_n
           AND e.cash_reconciled_request_n=e.mature_request_n
           AND e.contribution_eligible_request_n=e.mature_request_n
           AND e.reversed_request_n=0
           AND e.matured_incremental_machine_contribution_micros>0
           THEN 'READY_BOUNDED_EXPAND'
         WHEN d.decision_state IN ('MAINTAIN','CHANGE','PAUSE','INCONCLUSIVE')
           THEN d.decision_state
         ELSE 'UNKNOWN'
       END AS computed_gate
FROM decision_snapshot d
JOIN risk_review r ON r.risk_review_id=d.risk_review_id
JOIN v_mature_machine_unit_economics e
  ON e.machine_access_contract_id=d.machine_access_contract_id
WHERE NOT EXISTS (
  SELECT 1 FROM decision_snapshot n
  WHERE n.machine_access_contract_id=d.machine_access_contract_id
    AND n.decision_sequence>d.decision_sequence
);

CREATE TRIGGER decision_semantic_guard
BEFORE INSERT ON decision_snapshot
BEGIN
  SELECT RAISE(ABORT,'decision requires same-environment DECISION E4+ evidence')
  WHERE NOT EXISTS (
    SELECT 1 FROM evidence_record e
    JOIN machine_access_contract m
      ON m.machine_access_contract_id=NEW.machine_access_contract_id
    WHERE e.evidence_id=NEW.evidence_id AND e.environment=m.environment
      AND e.evidence_domain='DECISION' AND e.evidence_rank>=4);
  SELECT RAISE(ABORT,'decision clocks and maturity must match immutable cutoff')
  WHERE NOT EXISTS (
    SELECT 1 FROM machine_access_contract m
    JOIN evidence_record e ON e.evidence_id=NEW.evidence_id
    WHERE m.machine_access_contract_id=NEW.machine_access_contract_id
      AND datetime(NEW.evidence_cutoff_at)=datetime(NEW.snapshot_as_of)
      AND datetime(e.recorded_at)<=datetime(NEW.evidence_cutoff_at)
      AND datetime(NEW.maturity_at)=datetime(m.maturity_at)
      AND datetime(NEW.maturity_at)<=datetime(NEW.snapshot_as_of)
      AND datetime(NEW.snapshot_as_of)<=datetime(NEW.decided_at)
      AND datetime(NEW.decided_at)<=datetime(m.decision_due_at));
  INSERT INTO negative_probe_result
  SELECT c.probe_id,c.expected_rule_code,
         CASE
           WHEN NEW.decision_sequence>1 AND NOT EXISTS (
             SELECT 1 FROM decision_snapshot p
             WHERE p.decision_snapshot_id=NEW.predecessor_decision_snapshot_id
               AND p.machine_access_contract_id=NEW.machine_access_contract_id
               AND p.decision_sequence=NEW.decision_sequence-1)
             THEN 'DECISION_PREDECESSOR_EXACT'
           ELSE 'EXPAND_REQUIRES_CURRENT_PASSING_EVIDENCE'
         END,
         CASE WHEN c.expected_rule_code=CASE
           WHEN NEW.decision_sequence>1 AND NOT EXISTS (
             SELECT 1 FROM decision_snapshot p
             WHERE p.decision_snapshot_id=NEW.predecessor_decision_snapshot_id
               AND p.machine_access_contract_id=NEW.machine_access_contract_id
               AND p.decision_sequence=NEW.decision_sequence-1)
             THEN 'DECISION_PREDECESSOR_EXACT'
           ELSE 'EXPAND_REQUIRES_CURRENT_PASSING_EVIDENCE' END
         THEN 'PASS' ELSE 'FAIL' END,
         'decision_snapshot',datetime('now')
  FROM negative_probe_context c
  WHERE (NEW.decision_sequence>1 AND NOT EXISTS (
      SELECT 1 FROM decision_snapshot p
      WHERE p.decision_snapshot_id=NEW.predecessor_decision_snapshot_id
        AND p.machine_access_contract_id=NEW.machine_access_contract_id
        AND p.decision_sequence=NEW.decision_sequence-1))
     OR (NEW.decision_state='EXPAND' AND (
       NOT EXISTS (
         SELECT 1 FROM risk_review r
         WHERE r.risk_review_id=NEW.risk_review_id
           AND r.machine_access_contract_id=NEW.machine_access_contract_id
           AND r.overall_state='PASS')
       OR EXISTS (
         SELECT 1 FROM machine_access_contract m
         JOIN source_snapshot s USING (source_snapshot_id)
         WHERE m.machine_access_contract_id=NEW.machine_access_contract_id
           AND (m.environment<>'REAL' OR s.program_status<>'CURRENT'
             OR s.seller_eligibility_state<>'OBSERVED'
             OR datetime(s.stale_after)<datetime(NEW.decided_at)))
       OR NOT EXISTS (
         SELECT 1 FROM v_mature_machine_unit_economics e
         JOIN machine_access_contract m USING (machine_access_contract_id)
         WHERE e.machine_access_contract_id=NEW.machine_access_contract_id
           AND e.mature_request_n>0
           AND e.verified_eligible_request_n=e.mature_request_n
           AND e.rights_risk_pass_request_n=e.mature_request_n
           AND e.challenged_request_n=e.mature_request_n
           AND e.authorized_request_n=e.mature_request_n
           AND e.payment_proof_verified_request_n=e.mature_request_n
           AND e.settled_request_n=e.mature_request_n
           AND e.entitled_request_n=e.mature_request_n
           AND e.not_revoked_entitlement_request_n=e.mature_request_n
           AND e.delivered_request_n=e.mature_request_n
           AND e.accepted_request_n=e.mature_request_n
           AND e.cash_reconciled_request_n=e.mature_request_n
           AND e.contribution_eligible_request_n=e.mature_request_n
           AND e.reversed_request_n=0
           AND e.matured_incremental_machine_contribution_micros>0
           AND e.cash_cost_micros<=m.maximum_cash_exposure_micros
           AND e.founder_minutes<=m.maximum_founder_minutes)));
  SELECT CASE WHEN EXISTS (SELECT 1 FROM negative_probe_context)
    AND ((NEW.decision_sequence>1 AND NOT EXISTS (
      SELECT 1 FROM decision_snapshot p
      WHERE p.decision_snapshot_id=NEW.predecessor_decision_snapshot_id
        AND p.machine_access_contract_id=NEW.machine_access_contract_id
        AND p.decision_sequence=NEW.decision_sequence-1))
      OR (NEW.decision_state='EXPAND' AND (
        NOT EXISTS (
          SELECT 1 FROM risk_review r
          WHERE r.risk_review_id=NEW.risk_review_id
            AND r.machine_access_contract_id=NEW.machine_access_contract_id
            AND r.overall_state='PASS')
        OR EXISTS (
          SELECT 1 FROM machine_access_contract m
          JOIN source_snapshot s USING (source_snapshot_id)
          WHERE m.machine_access_contract_id=NEW.machine_access_contract_id
            AND (m.environment<>'REAL' OR s.program_status<>'CURRENT'
              OR s.seller_eligibility_state<>'OBSERVED'
              OR datetime(s.stale_after)<datetime(NEW.decided_at)))
        OR NOT EXISTS (
          SELECT 1 FROM v_mature_machine_unit_economics e
          JOIN machine_access_contract m USING (machine_access_contract_id)
          WHERE e.machine_access_contract_id=NEW.machine_access_contract_id
            AND e.mature_request_n>0
            AND e.verified_eligible_request_n=e.mature_request_n
            AND e.rights_risk_pass_request_n=e.mature_request_n
            AND e.challenged_request_n=e.mature_request_n
            AND e.authorized_request_n=e.mature_request_n
            AND e.payment_proof_verified_request_n=e.mature_request_n
            AND e.settled_request_n=e.mature_request_n
            AND e.entitled_request_n=e.mature_request_n
            AND e.not_revoked_entitlement_request_n=e.mature_request_n
            AND e.delivered_request_n=e.mature_request_n
            AND e.accepted_request_n=e.mature_request_n
            AND e.cash_reconciled_request_n=e.mature_request_n
            AND e.contribution_eligible_request_n=e.mature_request_n
            AND e.reversed_request_n=0
            AND e.matured_incremental_machine_contribution_micros>0
            AND e.cash_cost_micros<=m.maximum_cash_exposure_micros
            AND e.founder_minutes<=m.maximum_founder_minutes))))
    THEN RAISE(IGNORE) END;
  SELECT RAISE(ABORT,'decision after first requires exact predecessor')
  WHERE NEW.decision_sequence>1 AND NOT EXISTS (
    SELECT 1 FROM decision_snapshot p
    WHERE p.decision_snapshot_id=NEW.predecessor_decision_snapshot_id
      AND p.machine_access_contract_id=NEW.machine_access_contract_id
      AND p.decision_sequence=NEW.decision_sequence-1
      AND datetime(p.decided_at)<datetime(NEW.decided_at)
  );
  SELECT RAISE(ABORT,'decision must use latest risk review available')
  WHERE NOT EXISTS (
    SELECT 1 FROM risk_review r
    WHERE r.risk_review_id=NEW.risk_review_id
      AND r.machine_access_contract_id=NEW.machine_access_contract_id
      AND datetime(r.recorded_at)<=datetime(NEW.evidence_cutoff_at)
      AND NOT EXISTS (
        SELECT 1 FROM risk_review n
        WHERE n.machine_access_contract_id=r.machine_access_contract_id
          AND n.review_sequence>r.review_sequence
          AND datetime(n.recorded_at)<=datetime(NEW.evidence_cutoff_at))
  );
  SELECT RAISE(ABORT,'decision snapshot must equal model reference snapshot')
  WHERE datetime(NEW.snapshot_as_of)<>datetime(
    (SELECT default_snapshot_as_of FROM model_setting WHERE singleton_id=1));
  SELECT RAISE(ABORT,'raw decision state must agree with risk authority')
  WHERE EXISTS (
    SELECT 1 FROM risk_review r
    WHERE r.risk_review_id=NEW.risk_review_id
      AND ((r.overall_state='FAILED' AND NEW.decision_state<>'STOP')
        OR (r.overall_state='UNKNOWN' AND NEW.decision_state NOT IN (
              'STOP','PAUSE','UNKNOWN','INCONCLUSIVE')))
  );
  SELECT RAISE(ABORT,'decision action must be a current policy at snapshot')
  WHERE NOT EXISTS (
    SELECT 1 FROM traffic_policy_version p
    WHERE p.machine_access_contract_id=NEW.machine_access_contract_id
      AND p.action_mode_code=NEW.action_mode_code
      AND datetime(p.effective_from)<=datetime(NEW.snapshot_as_of)
      AND (p.effective_until IS NULL
        OR datetime(NEW.snapshot_as_of)<datetime(p.effective_until))
  );
  SELECT RAISE(ABORT,'decision metrics must reconcile to immutable source facts')
  WHERE NOT EXISTS (
    SELECT 1 FROM v_mature_machine_unit_economics e
    WHERE e.machine_access_contract_id=NEW.machine_access_contract_id
      AND e.mature_request_n=NEW.mature_request_n
      AND e.verified_request_n=NEW.verified_request_n
      AND e.verified_eligible_request_n=NEW.verified_eligible_request_n
      AND e.rights_risk_pass_request_n=NEW.rights_risk_pass_request_n
      AND e.challenged_request_n=NEW.challenged_request_n
      AND e.authorized_request_n=NEW.authorized_request_n
      AND e.payment_proof_verified_request_n=
          NEW.payment_proof_verified_request_n
      AND e.settled_request_n=NEW.settled_request_n
      AND e.entitled_request_n=NEW.entitled_request_n
      AND e.not_revoked_entitlement_request_n=NEW.not_revoked_entitlement_request_n
      AND e.delivered_request_n=NEW.delivered_request_n
      AND e.accepted_request_n=NEW.accepted_request_n
      AND e.cash_reconciled_request_n=NEW.cash_reconciled_request_n
      AND e.contribution_eligible_request_n=
          NEW.contribution_eligible_request_n
      AND e.reversed_request_n=NEW.reversed_request_n
      AND e.bank_or_wallet_cash_micros=NEW.bank_or_wallet_cash_micros
      AND e.cash_cost_micros=NEW.cash_cost_micros
      AND e.founder_minutes=NEW.founder_minutes
      AND e.founder_time_cost_micros=NEW.founder_time_cost_micros
      AND e.matured_incremental_machine_contribution_micros=
          NEW.matured_incremental_machine_contribution_micros
  );
  SELECT RAISE(ABORT,'EXPAND requires current passing evidence and positive mature economics')
  WHERE NEW.decision_state='EXPAND' AND (
    NOT EXISTS (
      SELECT 1 FROM risk_review r
      WHERE r.risk_review_id=NEW.risk_review_id
        AND r.machine_access_contract_id=NEW.machine_access_contract_id
        AND r.overall_state='PASS')
    OR EXISTS (
      SELECT 1 FROM machine_access_contract m
      JOIN source_snapshot s USING (source_snapshot_id)
      WHERE m.machine_access_contract_id=NEW.machine_access_contract_id
        AND (m.environment<>'REAL' OR s.program_status<>'CURRENT'
          OR s.seller_eligibility_state<>'OBSERVED'
          OR datetime(s.stale_after)<datetime(NEW.decided_at)))
    OR NOT EXISTS (
      SELECT 1 FROM v_mature_machine_unit_economics e
      JOIN machine_access_contract m USING (machine_access_contract_id)
      WHERE e.machine_access_contract_id=NEW.machine_access_contract_id
        AND e.mature_request_n>0
        AND e.verified_eligible_request_n=e.mature_request_n
        AND e.rights_risk_pass_request_n=e.mature_request_n
        AND e.challenged_request_n=e.mature_request_n
        AND e.authorized_request_n=e.mature_request_n
        AND e.payment_proof_verified_request_n=e.mature_request_n
        AND e.settled_request_n=e.mature_request_n
        AND e.entitled_request_n=e.mature_request_n
        AND e.not_revoked_entitlement_request_n=e.mature_request_n
        AND e.delivered_request_n=e.mature_request_n
        AND e.accepted_request_n=e.mature_request_n
        AND e.cash_reconciled_request_n=e.mature_request_n
        AND e.contribution_eligible_request_n=e.mature_request_n
        AND e.reversed_request_n=0
        AND e.matured_incremental_machine_contribution_micros>0
        AND e.cash_cost_micros<=m.maximum_cash_exposure_micros
        AND e.founder_minutes<=m.maximum_founder_minutes)
  );
  SELECT RAISE(ABORT,'decision action must exist in contract policy')
  WHERE NOT EXISTS (
    SELECT 1 FROM traffic_policy_version p
    WHERE p.machine_access_contract_id=NEW.machine_access_contract_id
      AND p.action_mode_code=NEW.action_mode_code
  );
END;

-- ---------------------------------------------------------------------------
-- Fully synthetic fixtures
-- ---------------------------------------------------------------------------

INSERT INTO schema_registry VALUES (
  1,'machine_traffic_monetization','1.1.0','SQLite 3.37+',
  '2026-08-02T00:00:00Z','SYNTHETIC_ONLY_NO_RAW_PII_OR_SECRETS'
);
INSERT INTO model_setting VALUES (
  1,'2026-08-02T13:00:00Z','2026-08-02T12:00:00Z','JPY',1000,168,200
);

WITH fixture(evidence_id,evidence_rank,evidence_domain,environment,hash_seed,
             occurred_at,recorded_at) AS (VALUES
  ('EV_SRC_P',2,'SOURCE','REAL',1001,'2026-07-01T00:00:00Z','2026-07-01T00:01:00Z'),
  ('EV_SRC_F',2,'SOURCE','REAL',1002,'2026-07-01T00:00:00Z','2026-07-01T00:01:00Z'),
  ('EV_SRC_U',2,'SOURCE','REAL',1003,'2026-07-01T00:00:00Z','2026-07-01T00:01:00Z'),
  ('EV_SRC_T',2,'SOURCE','TEST',1004,'2026-07-01T00:00:00Z','2026-07-01T00:01:00Z'),
  ('EV_MAC_P',2,'CONTRACT','REAL',1011,'2026-07-01T00:02:00Z','2026-07-01T00:03:00Z'),
  ('EV_MAC_F',2,'CONTRACT','REAL',1012,'2026-07-01T00:02:00Z','2026-07-01T00:03:00Z'),
  ('EV_MAC_U',2,'CONTRACT','REAL',1013,'2026-07-01T00:02:00Z','2026-07-01T00:03:00Z'),
  ('EV_MAC_T',2,'CONTRACT','TEST',1014,'2026-07-01T00:02:00Z','2026-07-01T00:03:00Z'),
  ('EV_RES_P',4,'RESOURCE','REAL',1021,'2026-07-01T00:04:00Z','2026-07-01T00:05:00Z'),
  ('EV_RES_F',4,'RESOURCE','REAL',1022,'2026-07-01T00:04:00Z','2026-07-01T00:05:00Z'),
  ('EV_RES_U',4,'RESOURCE','REAL',1023,'2026-07-01T00:04:00Z','2026-07-01T00:05:00Z'),
  ('EV_RES_T',4,'RESOURCE','TEST',1024,'2026-07-01T00:04:00Z','2026-07-01T00:05:00Z'),
  ('EV_POL_P',2,'POLICY','REAL',1031,'2026-07-01T00:06:00Z','2026-07-01T00:07:00Z'),
  ('EV_POL_F',2,'POLICY','REAL',1032,'2026-07-01T00:06:00Z','2026-07-01T00:07:00Z'),
  ('EV_POL_U',2,'POLICY','REAL',1033,'2026-07-01T00:06:00Z','2026-07-01T00:07:00Z'),
  ('EV_POL_T',2,'POLICY','TEST',1034,'2026-07-01T00:06:00Z','2026-07-01T00:07:00Z'),
  ('EV_ID_P',3,'IDENTITY','REAL',1041,'2026-07-02T09:00:00Z','2026-07-02T09:00:05Z'),
  ('EV_ID_F',3,'IDENTITY','REAL',1042,'2026-07-02T09:00:00Z','2026-07-02T09:00:05Z'),
  ('EV_ID_U',1,'IDENTITY','REAL',1043,'2026-07-02T09:00:00Z','2026-07-02T09:00:05Z'),
  ('EV_ID_T',3,'IDENTITY','TEST',1044,'2026-07-02T09:00:00Z','2026-07-02T09:00:05Z'),
  ('EV_REQ_P',4,'REQUEST','REAL',1051,'2026-07-02T09:01:00Z','2026-07-02T09:01:02Z'),
  ('EV_REQ_F',4,'REQUEST','REAL',1052,'2026-07-02T09:02:00Z','2026-07-02T09:02:02Z'),
  ('EV_REQ_U',3,'REQUEST','REAL',1053,'2026-07-02T09:03:00Z','2026-07-02T09:03:02Z'),
  ('EV_REQ_T',4,'REQUEST','TEST',1054,'2026-07-02T09:04:00Z','2026-07-02T09:04:02Z'),
  ('EV_OFFER_P',2,'OFFER','REAL',1061,'2026-07-01T01:00:00Z','2026-07-01T01:01:00Z'),
  ('EV_OFFER_T',2,'OFFER','TEST',1062,'2026-07-01T01:00:00Z','2026-07-01T01:01:00Z'),
  ('EV_CH_P',4,'CHALLENGE','REAL',1071,'2026-07-02T09:01:00Z','2026-07-02T09:01:03Z'),
  ('EV_CH_T',4,'CHALLENGE','TEST',1072,'2026-07-02T09:04:00Z','2026-07-02T09:04:03Z'),
  ('EV_PAY_PA',3,'PAYMENT','REAL',1081,'2026-07-02T09:01:10Z','2026-07-02T09:01:11Z'),
  ('EV_PAY_PS',3,'PAYMENT','REAL',1082,'2026-07-02T09:01:12Z','2026-07-02T09:01:13Z'),
  ('EV_PAY_TA',3,'PAYMENT','TEST',1083,'2026-07-02T09:04:10Z','2026-07-02T09:04:11Z'),
  ('EV_PAY_TS',3,'PAYMENT','TEST',1084,'2026-07-02T09:04:12Z','2026-07-02T09:04:13Z'),
  ('EV_PAY_TR',3,'PAYMENT','TEST',1085,'2026-07-08T09:04:12Z','2026-07-08T09:04:13Z'),
  ('EV_ENT_PG',4,'ENTITLEMENT','REAL',1091,'2026-07-02T09:01:14Z','2026-07-02T09:01:15Z'),
  ('EV_ENT_TG',4,'ENTITLEMENT','TEST',1092,'2026-07-02T09:04:14Z','2026-07-02T09:04:15Z'),
  ('EV_ENT_TR',4,'ENTITLEMENT','TEST',1093,'2026-07-08T09:04:14Z','2026-07-08T09:04:15Z'),
  ('EV_DEL_P',4,'DELIVERY','REAL',1101,'2026-07-02T09:01:16Z','2026-07-02T09:01:17Z'),
  ('EV_DEL_F',4,'DELIVERY','REAL',1102,'2026-07-02T09:02:00Z','2026-07-02T09:02:03Z'),
  ('EV_DEL_T',4,'DELIVERY','TEST',1103,'2026-07-02T09:04:16Z','2026-07-02T09:04:17Z'),
  ('EV_CASH_PG',3,'CASH','REAL',1111,'2026-07-02T09:01:12Z','2026-07-02T09:01:20Z'),
  ('EV_CASH_PF',3,'CASH','REAL',1112,'2026-07-02T09:01:12Z','2026-07-02T09:01:20Z'),
  ('EV_CASH_PB',5,'CASH','REAL',1113,'2026-07-03T09:00:00Z','2026-07-03T09:01:00Z'),
  ('EV_CASH_PX',3,'CASH','REAL',1118,'2026-07-02T09:01:12Z','2026-07-02T09:01:20Z'),
  ('EV_CASH_TG',3,'CASH','TEST',1114,'2026-07-02T09:04:12Z','2026-07-02T09:04:20Z'),
  ('EV_CASH_TF',3,'CASH','TEST',1115,'2026-07-02T09:04:12Z','2026-07-02T09:04:20Z'),
  ('EV_CASH_TB',5,'CASH','TEST',1116,'2026-07-03T09:04:00Z','2026-07-03T09:05:00Z'),
  ('EV_CASH_TR',5,'CASH','TEST',1117,'2026-07-08T09:04:12Z','2026-07-08T09:05:00Z'),
  ('EV_COST_PO',4,'COST','REAL',1121,'2026-07-02T09:01:16Z','2026-07-02T09:01:18Z'),
  ('EV_COST_PF',4,'COST','REAL',1122,'2026-07-02T09:10:00Z','2026-07-02T09:10:01Z'),
  ('EV_COST_FO',4,'COST','REAL',1123,'2026-07-02T09:02:00Z','2026-07-02T09:02:04Z'),
  ('EV_COST_TO',4,'COST','TEST',1124,'2026-07-02T09:04:16Z','2026-07-02T09:04:18Z'),
  ('EV_RISK_P',4,'RISK','REAL',1131,'2026-08-01T00:00:00Z','2026-08-01T00:01:00Z'),
  ('EV_RISK_F',4,'RISK','REAL',1132,'2026-08-01T00:00:00Z','2026-08-01T00:01:00Z'),
  ('EV_RISK_U',4,'RISK','REAL',1133,'2026-08-01T00:00:00Z','2026-08-01T00:01:00Z'),
  ('EV_RISK_T',4,'RISK','TEST',1134,'2026-08-01T00:00:00Z','2026-08-01T00:01:00Z'),
  ('EV_DEC_P',4,'DECISION','REAL',1141,'2026-08-02T11:58:00Z','2026-08-02T11:59:00Z'),
  ('EV_DEC_F',4,'DECISION','REAL',1142,'2026-08-02T11:58:00Z','2026-08-02T11:59:00Z'),
  ('EV_DEC_U',4,'DECISION','REAL',1143,'2026-08-02T11:58:00Z','2026-08-02T11:59:00Z'),
  ('EV_DEC_T',4,'DECISION','TEST',1144,'2026-08-02T11:58:00Z','2026-08-02T11:59:00Z'),
  ('EV_MAC_N',2,'CONTRACT','REAL',1201,'2026-07-01T00:02:00Z','2026-07-01T00:03:00Z'),
  ('EV_RES_N',4,'RESOURCE','REAL',1202,'2026-07-01T00:04:00Z','2026-07-01T00:05:00Z'),
  ('EV_POL_N',2,'POLICY','REAL',1203,'2026-07-01T00:06:00Z','2026-07-01T00:07:00Z'),
  ('EV_ID_N',3,'IDENTITY','REAL',1204,'2026-07-02T08:59:00Z','2026-07-02T08:59:05Z'),
  ('EV_REQ_NS',4,'REQUEST','REAL',1205,'2026-07-02T10:01:00Z','2026-07-02T10:01:02Z'),
  ('EV_REQ_ND',4,'REQUEST','REAL',1206,'2026-07-02T10:02:00Z','2026-07-02T10:02:02Z'),
  ('EV_REQ_NC',4,'REQUEST','REAL',1207,'2026-07-02T10:03:00Z','2026-07-02T10:03:02Z'),
  ('EV_OFFER_N',2,'OFFER','REAL',1208,'2026-07-01T01:00:00Z','2026-07-01T01:01:00Z'),
  ('EV_CH_NS',4,'CHALLENGE','REAL',1211,'2026-07-02T10:01:00Z','2026-07-02T10:01:03Z'),
  ('EV_CH_ND',4,'CHALLENGE','REAL',1212,'2026-07-02T10:02:00Z','2026-07-02T10:02:03Z'),
  ('EV_CH_NC',4,'CHALLENGE','REAL',1213,'2026-07-02T10:03:00Z','2026-07-02T10:03:03Z'),
  ('EV_PROOF_PA',3,'PAYMENT','REAL',1214,'2026-07-02T09:01:09Z','2026-07-02T09:01:10Z'),
  ('EV_PROOF_TA',3,'PAYMENT','TEST',1216,'2026-07-02T09:04:09Z','2026-07-02T09:04:10Z'),
  ('EV_PROOF_NSA',3,'PAYMENT','REAL',1221,'2026-07-02T10:01:09Z','2026-07-02T10:01:10Z'),
  ('EV_PROOF_NDA',3,'PAYMENT','REAL',1223,'2026-07-02T10:02:09Z','2026-07-02T10:02:10Z'),
  ('EV_PROOF_NCA',3,'PAYMENT','REAL',1225,'2026-07-02T10:03:09Z','2026-07-02T10:03:10Z'),
  ('EV_PAY_NSA',3,'PAYMENT','REAL',1231,'2026-07-02T10:01:10Z','2026-07-02T10:01:11Z'),
  ('EV_PAY_NSS',3,'PAYMENT','REAL',1232,'2026-07-02T10:01:12Z','2026-07-02T10:01:13Z'),
  ('EV_PAY_NDA',3,'PAYMENT','REAL',1233,'2026-07-02T10:02:10Z','2026-07-02T10:02:11Z'),
  ('EV_PAY_NDS',3,'PAYMENT','REAL',1234,'2026-07-02T10:02:12Z','2026-07-02T10:02:13Z'),
  ('EV_PAY_NCA',3,'PAYMENT','REAL',1235,'2026-07-02T10:03:10Z','2026-07-02T10:03:11Z'),
  ('EV_PAY_NCS',3,'PAYMENT','REAL',1236,'2026-07-02T10:03:12Z','2026-07-02T10:03:13Z'),
  ('EV_ENT_ND',4,'ENTITLEMENT','REAL',1241,'2026-07-02T10:02:14Z','2026-07-02T10:02:15Z'),
  ('EV_ENT_NC',4,'ENTITLEMENT','REAL',1242,'2026-07-02T10:03:14Z','2026-07-02T10:03:15Z'),
  ('EV_DEL_ND',4,'DELIVERY','REAL',1251,'2026-07-02T10:02:16Z','2026-07-02T10:02:17Z'),
  ('EV_DEL_NC',4,'DELIVERY','REAL',1252,'2026-07-02T10:03:16Z','2026-07-02T10:03:17Z'),
  ('EV_ACC_P',4,'ACCEPTED_OUTCOME','REAL',1261,'2026-07-02T09:01:18Z','2026-07-02T09:01:19Z'),
  ('EV_ACC_T',4,'ACCEPTED_OUTCOME','TEST',1262,'2026-07-02T09:04:18Z','2026-07-11T09:04:19Z'),
  ('EV_ACC_NC',4,'ACCEPTED_OUTCOME','REAL',1263,'2026-07-02T10:03:18Z','2026-07-02T10:03:19Z'),
  ('EV_CASH_NDG',3,'CASH','REAL',1271,'2026-07-02T10:02:12Z','2026-07-02T10:02:20Z'),
  ('EV_CASH_NDF',3,'CASH','REAL',1272,'2026-07-02T10:02:12Z','2026-07-02T10:02:20Z'),
  ('EV_CASH_NDB',5,'CASH','REAL',1273,'2026-07-03T10:02:00Z','2026-07-03T10:03:00Z'),
  ('EV_CASH_NCG',3,'CASH','REAL',1274,'2026-07-02T10:03:12Z','2026-07-02T10:03:20Z'),
  ('EV_CASH_NCF',3,'CASH','REAL',1275,'2026-07-02T10:03:12Z','2026-07-02T10:03:20Z'),
  ('EV_COST_NS',4,'COST','REAL',1282,'2026-07-02T10:05:00Z','2026-07-02T10:05:01Z'),
  ('EV_COST_NF',4,'COST','REAL',1283,'2026-07-02T10:06:00Z','2026-07-02T10:06:01Z'),
  ('EV_RISK_N',4,'RISK','REAL',1281,'2026-08-01T00:00:00Z','2026-08-01T00:01:00Z')
)
INSERT INTO evidence_record
SELECT evidence_id,
       CASE evidence_rank WHEN 0 THEN 'E0_INFERENCE'
         WHEN 1 THEN 'E1_MANUAL_OBSERVATION'
         WHEN 2 THEN 'E2_VERSIONED_CONFIG'
         WHEN 3 THEN 'E3_VERIFIED_PROVIDER_EVENT'
         WHEN 4 THEN 'E4_FIRST_PARTY_AUTHORITATIVE'
         WHEN 5 THEN 'E5_BANK_WALLET_OR_CUSTOMER_AUTHORITATIVE' END,
       evidence_rank,evidence_domain,environment,'synthetic_fixture',
       printf('%064x',hash_seed),printf('%064x',hash_seed+10000),
       occurred_at,recorded_at,NULL,'SYNTHETIC_OPAQUE_REFERENCE_ONLY'
FROM fixture;

INSERT INTO source_snapshot VALUES
 ('SRC_PAID','SYN_EDGE','SYN_PAY_PER_REQUEST','CURRENT','OBSERVED','OBSERVED',
  'syn-v1','2026-07-01T00:00:00Z','2026-07-01T00:01:00Z',
  '2026-08-10T00:00:00Z',printf('%064x',2001),'EV_SRC_P'),
 ('SRC_FREE','SYN_SEARCH','SYN_FREE_DISCOVERY','CURRENT','OBSERVED','N/A',
  'syn-v1','2026-07-01T00:00:00Z','2026-07-01T00:01:00Z',
  '2026-08-10T00:00:00Z',printf('%064x',2002),'EV_SRC_F'),
 ('SRC_UNKNOWN','SYN_EDGE','SYN_UNKNOWN_AUTOMATION','CURRENT','OBSERVED','UNKNOWN',
  'syn-v1','2026-07-01T00:00:00Z','2026-07-01T00:01:00Z',
  '2026-08-10T00:00:00Z',printf('%064x',2003),'EV_SRC_U'),
 ('SRC_TEST','SYN_EDGE','SYN_SANDBOX_RAIL','CURRENT','OBSERVED','FAILED',
  'syn-v1','2026-07-01T00:00:00Z','2026-07-01T00:01:00Z',
  '2026-08-10T00:00:00Z',printf('%064x',2004),'EV_SRC_T');

INSERT INTO machine_access_contract VALUES
 ('MAC_PAID_V1','MAC_PAID',1,NULL,'REAL','SRC_PAID','ACTIVE','OBSERVED',
  'SYN_FOUNDER','USER_TRIGGERED_AGENT','PREMIUM_CONTENT',
  'MATURED_INCREMENTAL_MACHINE_CONTRIBUTION','JPY',100000,30,
  '2026-07-01T00:00:00Z','2026-07-05T00:00:00Z',
  '2026-07-10T00:00:00Z','2026-08-02T13:00:00Z','EV_MAC_P'),
 ('MAC_FREE_V1','MAC_FREE',1,NULL,'REAL','SRC_FREE','ACTIVE','N/A',
  'SYN_FOUNDER','SEARCH_INDEXER','PUBLIC_MARKETING',
  'MATURED_INCREMENTAL_MACHINE_CONTRIBUTION','JPY',10000,10,
  '2026-07-01T00:00:00Z','2026-07-05T00:00:00Z',
  '2026-07-10T00:00:00Z','2026-08-02T13:00:00Z','EV_MAC_F'),
 ('MAC_UNKNOWN_V1','MAC_UNKNOWN',1,NULL,'REAL','SRC_UNKNOWN','PAUSED','UNKNOWN',
  'SYN_FOUNDER','UNKNOWN_AUTOMATION','PREMIUM_CONTENT',
  'MATURED_INCREMENTAL_MACHINE_CONTRIBUTION','JPY',10000,10,
  '2026-07-01T00:00:00Z','2026-07-05T00:00:00Z',
  '2026-07-10T00:00:00Z','2026-08-02T13:00:00Z','EV_MAC_U'),
 ('MAC_NEG_V1','MAC_NEG',1,NULL,'REAL','SRC_PAID','ACTIVE','OBSERVED',
  'SYN_FOUNDER','USER_TRIGGERED_AGENT','PREMIUM_CONTENT',
  'MATURED_INCREMENTAL_MACHINE_CONTRIBUTION','JPY',100000,30,
  '2026-07-01T00:00:00Z','2026-07-05T00:00:00Z',
  '2026-07-10T00:00:00Z','2026-08-02T13:00:00Z','EV_MAC_N'),
 ('MAC_TEST_V1','MAC_TEST',1,NULL,'TEST','SRC_TEST','PAUSED','FAILED',
  'SYN_FOUNDER','USER_TRIGGERED_AGENT','TOOL_ACTION',
  'MATURED_INCREMENTAL_MACHINE_CONTRIBUTION','JPY',100000,30,
  '2026-07-01T00:00:00Z','2026-07-09T00:00:00Z',
  '2026-07-10T00:00:00Z','2026-08-02T13:00:00Z','EV_MAC_T');

INSERT INTO resource_contract VALUES
 ('RES_PAID','MAC_PAID_V1','PREMIUM_CONTENT','sha256:syn-paid-v1','PASS',0,0,
  printf('%064x',3001),'EV_RES_P'),
 ('RES_FREE','MAC_FREE_V1','PUBLIC_MARKETING','sha256:syn-free-v1','PASS',1,1,
  printf('%064x',3002),'EV_RES_F'),
 ('RES_UNKNOWN','MAC_UNKNOWN_V1','PREMIUM_CONTENT','sha256:syn-unknown-v1','PASS',0,0,
  printf('%064x',3003),'EV_RES_U'),
 ('RES_NEG','MAC_NEG_V1','PREMIUM_CONTENT','sha256:syn-neg-v1','PASS',0,0,
  printf('%064x',3005),'EV_RES_N'),
 ('RES_TEST','MAC_TEST_V1','TOOL_ACTION','sha256:syn-test-v1','PASS',0,0,
  printf('%064x',3004),'EV_RES_T');

INSERT INTO traffic_policy_version VALUES
 ('POL_PAID','MAC_PAID_V1','RES_PAID','USER_TRIGGERED_AGENT',1,NULL,
  'HTTP_402',1,1,'2026-07-01T00:10:00Z',NULL,'EV_POL_P'),
 ('POL_FREE','MAC_FREE_V1','RES_FREE','SEARCH_INDEXER',1,NULL,
  'ALLOW_FREE',1,0,'2026-07-01T00:10:00Z',NULL,'EV_POL_F'),
 ('POL_UNKNOWN','MAC_UNKNOWN_V1','RES_UNKNOWN','UNKNOWN_AUTOMATION',1,NULL,
  'RATE_LIMIT',0,0,'2026-07-01T00:10:00Z',NULL,'EV_POL_U'),
 ('POL_NEG','MAC_NEG_V1','RES_NEG','USER_TRIGGERED_AGENT',1,NULL,
  'HTTP_402',1,1,'2026-07-01T00:10:00Z',NULL,'EV_POL_N'),
 ('POL_TEST','MAC_TEST_V1','RES_TEST','USER_TRIGGERED_AGENT',1,NULL,
  'HTTP_402',1,1,'2026-07-01T00:10:00Z',NULL,'EV_POL_T');

INSERT INTO actor_identity_observation VALUES
 ('ID_PAID','MAC_PAID_V1',printf('%064x',4001),'USER_TRIGGERED_AGENT',
  'USER_TRIGGERED_AGENT','VERIFIED','SIGNED_REQUEST',980,
  '2026-07-02T09:00:00Z','2026-07-02T09:00:05Z','2026-08-05T00:00:00Z','EV_ID_P'),
 ('ID_FREE','MAC_FREE_V1',printf('%064x',4002),'SEARCH_INDEXER',
  'SEARCH_INDEXER','VERIFIED','PROVIDER_VERIFIED_BOT',950,
  '2026-07-02T09:00:00Z','2026-07-02T09:00:05Z','2026-08-05T00:00:00Z','EV_ID_F'),
 ('ID_UNKNOWN','MAC_UNKNOWN_V1',printf('%064x',4003),'UNKNOWN_AUTOMATION',
  NULL,'UNKNOWN','USER_AGENT_ONLY',0,
  '2026-07-02T09:00:00Z','2026-07-02T09:00:05Z','2026-08-05T00:00:00Z','EV_ID_U'),
 ('ID_NEG','MAC_NEG_V1',printf('%064x',4005),'USER_TRIGGERED_AGENT',
  'USER_TRIGGERED_AGENT','VERIFIED','SIGNED_REQUEST',975,
  '2026-07-02T08:59:00Z','2026-07-02T08:59:05Z','2026-08-05T00:00:00Z','EV_ID_N'),
 ('ID_TEST','MAC_TEST_V1',printf('%064x',4004),'USER_TRIGGERED_AGENT',
  'USER_TRIGGERED_AGENT','VERIFIED','SIGNED_REQUEST',990,
  '2026-07-02T09:00:00Z','2026-07-02T09:00:05Z','2026-08-05T00:00:00Z','EV_ID_T');

INSERT INTO request_observation VALUES
 ('REQ_PAID','MAC_PAID_V1','RES_PAID','POL_PAID','ID_PAID','REAL',
  printf('%064x',5001),'SYN_NET_A',printf('%064x',5101),'GET',
  printf('%064x',5201),printf('%064x',5301),'OBSERVED','HTTP_402',402,0,512,
  '2026-07-02T09:01:00Z','2026-07-02T09:01:02Z',
  '2026-07-05T00:00:00Z','2026-07-10T00:00:00Z','EV_REQ_P'),
 ('REQ_FREE','MAC_FREE_V1','RES_FREE','POL_FREE','ID_FREE','REAL',
  printf('%064x',5002),'SYN_NET_PUBLIC',printf('%064x',5102),'GET',
  printf('%064x',5202),printf('%064x',5302),'OBSERVED','ALLOW_FREE',200,4096,0,
  '2026-07-02T09:02:00Z','2026-07-02T09:02:02Z',
  '2026-07-05T00:00:00Z','2026-07-10T00:00:00Z','EV_REQ_F'),
 ('REQ_UNKNOWN','MAC_UNKNOWN_V1','RES_UNKNOWN','POL_UNKNOWN','ID_UNKNOWN','REAL',
  printf('%064x',5003),'SYN_NET_A',printf('%064x',5103),'POST',
  printf('%064x',5203),printf('%064x',5303),'UNKNOWN','RATE_LIMIT',429,0,0,
  '2026-07-02T09:03:00Z','2026-07-02T09:03:02Z',
  '2026-07-05T00:00:00Z','2026-07-10T00:00:00Z','EV_REQ_U'),
 ('REQ_NEG_SETTLEMENT_ONLY','MAC_NEG_V1','RES_NEG','POL_NEG','ID_NEG','REAL',
  printf('%064x',5011),'SYN_NET_A',printf('%064x',5110),'GET',
  printf('%064x',5211),printf('%064x',5311),'OBSERVED','HTTP_402',402,0,512,
  '2026-07-02T10:01:00Z','2026-07-02T10:01:02Z',
  '2026-07-05T00:00:00Z','2026-07-10T00:00:00Z','EV_REQ_NS'),
 ('REQ_NEG_DELIVERED','MAC_NEG_V1','RES_NEG','POL_NEG','ID_NEG','REAL',
  printf('%064x',5012),'SYN_NET_A',printf('%064x',5110),'GET',
  printf('%064x',5212),printf('%064x',5312),'OBSERVED','HTTP_402',402,0,512,
  '2026-07-02T10:02:00Z','2026-07-02T10:02:02Z',
  '2026-07-05T00:00:00Z','2026-07-10T00:00:00Z','EV_REQ_ND'),
 ('REQ_NEG_CASH','MAC_NEG_V1','RES_NEG','POL_NEG','ID_NEG','REAL',
  printf('%064x',5013),'SYN_NET_A',printf('%064x',5110),'GET',
  printf('%064x',5213),printf('%064x',5313),'OBSERVED','HTTP_402',402,0,512,
  '2026-07-02T10:03:00Z','2026-07-02T10:03:02Z',
  '2026-07-05T00:00:00Z','2026-07-10T00:00:00Z','EV_REQ_NC'),
 ('REQ_TEST','MAC_TEST_V1','RES_TEST','POL_TEST','ID_TEST','TEST',
  printf('%064x',5004),'SYN_NET_TEST',printf('%064x',5104),'GET',
  printf('%064x',5204),printf('%064x',5304),'OBSERVED','HTTP_402',402,0,512,
  '2026-07-02T09:04:00Z','2026-07-02T09:04:02Z',
  '2026-07-09T00:00:00Z','2026-07-10T00:00:00Z','EV_REQ_T');

INSERT INTO payment_offer_version VALUES
 ('OFFER_PAID','OFFER_FAMILY_PAID',1,NULL,'MAC_PAID_V1','RES_PAID','CURRENT',
  'SYN_MACHINE_RAIL','SYNUSD',50000,50000,'AUTHORITATIVE_SETTLEMENT',
  'SYN_NET_A',printf('%064x',5101),printf('%064x',5401),
  '2026-07-01T01:00:00Z','2026-08-05T00:00:00Z','EV_OFFER_P'),
 ('OFFER_NEG','OFFER_FAMILY_NEG',1,NULL,'MAC_NEG_V1','RES_NEG','CURRENT',
  'SYN_MACHINE_RAIL','SYNUSD',50000,50000,'AUTHORITATIVE_SETTLEMENT',
  'SYN_NET_A',printf('%064x',5110),printf('%064x',5405),
  '2026-07-01T01:00:00Z','2026-08-05T00:00:00Z','EV_OFFER_N'),
 ('OFFER_TEST','OFFER_FAMILY_TEST',1,NULL,'MAC_TEST_V1','RES_TEST','CURRENT',
  'SYN_MACHINE_RAIL','SYNUSD',50000,50000,'AUTHORITATIVE_SETTLEMENT',
  'SYN_NET_TEST',printf('%064x',5104),printf('%064x',5404),
  '2026-07-01T01:00:00Z','2026-08-05T00:00:00Z','EV_OFFER_T');

INSERT INTO challenge_receipt VALUES
 ('CH_PAID','REQ_PAID','MAC_PAID_V1','OFFER_PAID','REAL','ISSUED',402,
  printf('%064x',6001),printf('%064x',6101),'SYN_NET_A',printf('%064x',5101),
  printf('%064x',4001),'RESOURCE_ACCESS',printf('%064x',3001),printf('%064x',5401),
  'GET',printf('%064x',5201),printf('%064x',5301),printf('%064x',6201),
  printf('%064x',6301),50000,'SYNUSD',
  '2026-07-02T09:01:00Z','2026-07-02T09:06:00Z',
  '2026-07-02T09:01:03Z','EV_CH_P'),
 ('CH_NEG_SETTLEMENT_ONLY','REQ_NEG_SETTLEMENT_ONLY','MAC_NEG_V1','OFFER_NEG',
  'REAL','ISSUED',402,printf('%064x',6011),printf('%064x',6111),'SYN_NET_A',
  printf('%064x',5110),printf('%064x',4005),'RESOURCE_ACCESS',
  printf('%064x',3005),printf('%064x',5405),'GET',printf('%064x',5211),
  printf('%064x',5311),printf('%064x',6211),printf('%064x',6311),50000,'SYNUSD',
  '2026-07-02T10:01:00Z','2026-07-02T10:06:00Z',
  '2026-07-02T10:01:03Z','EV_CH_NS'),
 ('CH_NEG_DELIVERED','REQ_NEG_DELIVERED','MAC_NEG_V1','OFFER_NEG',
  'REAL','ISSUED',402,printf('%064x',6012),printf('%064x',6112),'SYN_NET_A',
  printf('%064x',5110),printf('%064x',4005),'RESOURCE_ACCESS',
  printf('%064x',3005),printf('%064x',5405),'GET',printf('%064x',5212),
  printf('%064x',5312),printf('%064x',6212),printf('%064x',6312),50000,'SYNUSD',
  '2026-07-02T10:02:00Z','2026-07-02T10:07:00Z',
  '2026-07-02T10:02:03Z','EV_CH_ND'),
 ('CH_NEG_CASH','REQ_NEG_CASH','MAC_NEG_V1','OFFER_NEG','REAL','ISSUED',402,
  printf('%064x',6013),printf('%064x',6113),'SYN_NET_A',printf('%064x',5110),
  printf('%064x',4005),'RESOURCE_ACCESS',printf('%064x',3005),printf('%064x',5405),
  'GET',printf('%064x',5213),printf('%064x',5313),printf('%064x',6213),
  printf('%064x',6313),50000,'SYNUSD',
  '2026-07-02T10:03:00Z','2026-07-02T10:08:00Z',
  '2026-07-02T10:03:03Z','EV_CH_NC'),
 ('CH_TEST','REQ_TEST','MAC_TEST_V1','OFFER_TEST','TEST','ISSUED',402,
  printf('%064x',6002),printf('%064x',6102),'SYN_NET_TEST',printf('%064x',5104),
  printf('%064x',4004),'RESOURCE_ACCESS',printf('%064x',3004),printf('%064x',5404),
  'GET',printf('%064x',5204),printf('%064x',5304),printf('%064x',6204),
  printf('%064x',6304),50000,'SYNUSD',
  '2026-07-02T09:04:00Z','2026-07-02T09:09:00Z',
  '2026-07-02T09:04:03Z','EV_CH_T');

INSERT INTO payment_proof VALUES
 ('PROOF_PA','REQ_PAID','CH_PAID','OFFER_PAID',1,50000,'SYNUSD','REAL','SYN_NET_A',printf('%064x',5101),
  printf('%064x',4001),'RESOURCE_ACCESS',printf('%064x',3001),printf('%064x',5401),
  'GET',printf('%064x',5201),printf('%064x',5301),printf('%064x',6201),
  printf('%064x',6401),'VERIFIED','2026-07-02T09:01:09Z',
  '2026-07-02T09:01:10Z','EV_PROOF_PA'),
 ('PROOF_NSA','REQ_NEG_SETTLEMENT_ONLY','CH_NEG_SETTLEMENT_ONLY','OFFER_NEG',1,50000,'SYNUSD','REAL',
  'SYN_NET_A',printf('%064x',5110),printf('%064x',4005),'RESOURCE_ACCESS',
  printf('%064x',3005),printf('%064x',5405),'GET',printf('%064x',5211),
  printf('%064x',5311),printf('%064x',6211),printf('%064x',6411),'VERIFIED',
  '2026-07-02T10:01:09Z','2026-07-02T10:01:10Z','EV_PROOF_NSA'),
 ('PROOF_NDA','REQ_NEG_DELIVERED','CH_NEG_DELIVERED','OFFER_NEG',1,50000,'SYNUSD','REAL','SYN_NET_A',
  printf('%064x',5110),printf('%064x',4005),'RESOURCE_ACCESS',printf('%064x',3005),
  printf('%064x',5405),'GET',printf('%064x',5212),printf('%064x',5312),
  printf('%064x',6212),printf('%064x',6413),'VERIFIED','2026-07-02T10:02:09Z',
  '2026-07-02T10:02:10Z','EV_PROOF_NDA'),
 ('PROOF_NCA','REQ_NEG_CASH','CH_NEG_CASH','OFFER_NEG',1,50000,'SYNUSD','REAL','SYN_NET_A',
  printf('%064x',5110),printf('%064x',4005),'RESOURCE_ACCESS',printf('%064x',3005),
  printf('%064x',5405),'GET',printf('%064x',5213),printf('%064x',5313),
  printf('%064x',6213),printf('%064x',6415),'VERIFIED','2026-07-02T10:03:09Z',
  '2026-07-02T10:03:10Z','EV_PROOF_NCA'),
 ('PROOF_TA','REQ_TEST','CH_TEST','OFFER_TEST',1,50000,'SYNUSD','TEST','SYN_NET_TEST',printf('%064x',5104),
  printf('%064x',4004),'RESOURCE_ACCESS',printf('%064x',3004),printf('%064x',5404),
  'GET',printf('%064x',5204),printf('%064x',5304),printf('%064x',6204),
  printf('%064x',6403),'VERIFIED','2026-07-02T09:04:09Z',
  '2026-07-02T09:04:10Z','EV_PROOF_TA');

INSERT INTO payment_event VALUES
 ('PAY_PA','CH_PAID','REQ_PAID','MAC_PAID_V1','PROOF_PA',1,NULL,'AUTHORIZATION','OBSERVED',
  'REAL',printf('%064x',7001),50000,'SYNUSD','VERIFIED',
  '2026-07-02T09:01:10Z','2026-07-02T09:01:11Z','EV_PAY_PA'),
 ('PAY_PS','CH_PAID','REQ_PAID','MAC_PAID_V1',NULL,2,'PAY_PA','SETTLEMENT','OBSERVED',
  'REAL',printf('%064x',7002),50000,'SYNUSD','N/A',
  '2026-07-02T09:01:12Z','2026-07-02T09:01:13Z','EV_PAY_PS'),
 ('PAY_NSA','CH_NEG_SETTLEMENT_ONLY','REQ_NEG_SETTLEMENT_ONLY','MAC_NEG_V1',
  'PROOF_NSA',1,NULL,'AUTHORIZATION','OBSERVED','REAL',printf('%064x',7011),
  50000,'SYNUSD','VERIFIED','2026-07-02T10:01:10Z',
  '2026-07-02T10:01:11Z','EV_PAY_NSA'),
 ('PAY_NSS','CH_NEG_SETTLEMENT_ONLY','REQ_NEG_SETTLEMENT_ONLY','MAC_NEG_V1',
  NULL,2,'PAY_NSA','SETTLEMENT','OBSERVED','REAL',printf('%064x',7012),
  50000,'SYNUSD','N/A','2026-07-02T10:01:12Z',
  '2026-07-02T10:01:13Z','EV_PAY_NSS'),
 ('PAY_NDA','CH_NEG_DELIVERED','REQ_NEG_DELIVERED','MAC_NEG_V1','PROOF_NDA',1,
  NULL,'AUTHORIZATION','OBSERVED','REAL',printf('%064x',7013),50000,'SYNUSD',
  'VERIFIED','2026-07-02T10:02:10Z','2026-07-02T10:02:11Z','EV_PAY_NDA'),
 ('PAY_NDS','CH_NEG_DELIVERED','REQ_NEG_DELIVERED','MAC_NEG_V1',NULL,2,
  'PAY_NDA','SETTLEMENT','OBSERVED','REAL',printf('%064x',7014),50000,'SYNUSD',
  'N/A','2026-07-02T10:02:12Z','2026-07-02T10:02:13Z','EV_PAY_NDS'),
 ('PAY_NCA','CH_NEG_CASH','REQ_NEG_CASH','MAC_NEG_V1','PROOF_NCA',1,NULL,
  'AUTHORIZATION','OBSERVED','REAL',printf('%064x',7015),50000,'SYNUSD',
  'VERIFIED','2026-07-02T10:03:10Z','2026-07-02T10:03:11Z','EV_PAY_NCA'),
 ('PAY_NCS','CH_NEG_CASH','REQ_NEG_CASH','MAC_NEG_V1',NULL,2,'PAY_NCA',
  'SETTLEMENT','OBSERVED','REAL',printf('%064x',7016),50000,'SYNUSD','N/A',
  '2026-07-02T10:03:12Z','2026-07-02T10:03:13Z','EV_PAY_NCS'),
 ('PAY_TA','CH_TEST','REQ_TEST','MAC_TEST_V1','PROOF_TA',1,NULL,'AUTHORIZATION','OBSERVED',
  'TEST',printf('%064x',7003),50000,'SYNUSD','VERIFIED',
  '2026-07-02T09:04:10Z','2026-07-02T09:04:11Z','EV_PAY_TA'),
 ('PAY_TS','CH_TEST','REQ_TEST','MAC_TEST_V1',NULL,2,'PAY_TA','SETTLEMENT','OBSERVED',
  'TEST',printf('%064x',7004),50000,'SYNUSD','N/A',
  '2026-07-02T09:04:12Z','2026-07-02T09:04:13Z','EV_PAY_TS'),
 ('PAY_TR','CH_TEST','REQ_TEST','MAC_TEST_V1',NULL,3,'PAY_TS','REVERSAL','OBSERVED',
  'TEST',printf('%064x',7005),50000,'SYNUSD','N/A',
  '2026-07-08T09:04:12Z','2026-07-08T09:04:13Z','EV_PAY_TR');

INSERT INTO entitlement_event VALUES
 ('ENT_PG','REQ_PAID','MAC_PAID_V1',printf('%064x',8001),1,NULL,'GRANTED',
  'PAYMENT_SETTLEMENT','PAY_PS','REAL','2026-07-02T09:01:14Z',
  '2026-07-03T09:01:14Z','2026-07-02T09:01:14Z',
  '2026-07-02T09:01:15Z','EV_ENT_PG'),
 ('ENT_ND','REQ_NEG_DELIVERED','MAC_NEG_V1',printf('%064x',8012),1,NULL,'GRANTED',
  'PAYMENT_SETTLEMENT','PAY_NDS','REAL','2026-07-02T10:02:14Z',
  '2026-08-05T10:02:14Z','2026-07-02T10:02:14Z',
  '2026-07-02T10:02:15Z','EV_ENT_ND'),
 ('ENT_NC','REQ_NEG_CASH','MAC_NEG_V1',printf('%064x',8013),1,NULL,'GRANTED',
  'PAYMENT_SETTLEMENT','PAY_NCS','REAL','2026-07-02T10:03:14Z',
  '2026-08-05T10:03:14Z','2026-07-02T10:03:14Z',
  '2026-07-02T10:03:15Z','EV_ENT_NC'),
 ('ENT_TG','REQ_TEST','MAC_TEST_V1',printf('%064x',8002),1,NULL,'GRANTED',
  'PAYMENT_SETTLEMENT','PAY_TS','TEST','2026-07-02T09:04:14Z',
  '2026-07-09T09:04:14Z','2026-07-02T09:04:14Z',
  '2026-07-02T09:04:15Z','EV_ENT_TG'),
 ('ENT_TR','REQ_TEST','MAC_TEST_V1',printf('%064x',8002),2,'ENT_TG','REVOKED',
  'PAYMENT_SETTLEMENT','PAY_TR','TEST','2026-07-08T09:04:14Z',
  '2026-07-09T09:04:14Z','2026-07-08T09:04:14Z',
  '2026-07-08T09:04:15Z','EV_ENT_TR');

INSERT INTO delivery_event VALUES
 ('DEL_P','REQ_PAID','MAC_PAID_V1','ENT_PG','BYTE_RESOURCE','DELIVERED','REAL',200,8192,
  printf('%064x',9001),printf('%064x',9101),'2026-07-02T09:01:16Z',
  '2026-07-02T09:01:17Z','EV_DEL_P'),
 ('DEL_F','REQ_FREE','MAC_FREE_V1',NULL,'BYTE_RESOURCE','DELIVERED','REAL',200,4096,
  printf('%064x',9002),printf('%064x',9102),'2026-07-02T09:02:00Z',
  '2026-07-02T09:02:03Z','EV_DEL_F'),
 ('DEL_ND','REQ_NEG_DELIVERED','MAC_NEG_V1','ENT_ND','BYTE_RESOURCE','DELIVERED','REAL',200,8192,
  printf('%064x',9012),printf('%064x',9112),'2026-07-02T10:02:16Z',
  '2026-07-02T10:02:17Z','EV_DEL_ND'),
 ('DEL_NC','REQ_NEG_CASH','MAC_NEG_V1','ENT_NC','BYTE_RESOURCE','DELIVERED','REAL',200,8192,
  printf('%064x',9013),printf('%064x',9113),'2026-07-02T10:03:16Z',
  '2026-07-02T10:03:17Z','EV_DEL_NC'),
 ('DEL_T','REQ_TEST','MAC_TEST_V1','ENT_TG','ACTION_RESULT','DELIVERED','TEST',204,0,
  printf('%064x',9003),printf('%064x',9103),'2026-07-02T09:04:16Z',
  '2026-07-02T09:04:17Z','EV_DEL_T');

INSERT INTO accepted_outcome_event VALUES
 ('ACC_P','REQ_PAID','DEL_P','MAC_PAID_V1',1,NULL,'REAL','ACCEPTED',printf('%064x',9201),
  '2026-07-02T09:01:18Z','2026-07-02T09:01:19Z',
  '2026-07-10T00:00:00Z','EV_ACC_P'),
 ('ACC_NC','REQ_NEG_CASH','DEL_NC','MAC_NEG_V1',1,NULL,'REAL','ACCEPTED',
  printf('%064x',9213),'2026-07-02T10:03:18Z','2026-07-02T10:03:19Z',
  '2026-07-10T00:00:00Z','EV_ACC_NC'),
 ('ACC_T','REQ_TEST','DEL_T','MAC_TEST_V1',1,NULL,'TEST','ACCEPTED',printf('%064x',9204),
  '2026-07-02T09:04:18Z','2026-07-11T09:04:19Z',
  '2026-07-10T00:00:00Z','EV_ACC_T');

INSERT INTO cash_bridge_line VALUES
 ('CASH_PG','MAC_PAID_V1','REQ_PAID','PAY_PS','OWNER_PAID','GROSS_SETTLED',
  50000,'JPY','BASE_CURRENCY_NO_FX',NULL,'REAL','PROVIDER_LEDGER','2026-07-02T09:01:12Z',
  '2026-07-02T09:01:20Z','EV_CASH_PG'),
 ('CASH_PF','MAC_PAID_V1','REQ_PAID','PAY_PS','OWNER_PAID','RAIL_FEE',
  -6000,'JPY','BASE_CURRENCY_NO_FX',NULL,'REAL','PROVIDER_LEDGER','2026-07-02T09:01:12Z',
  '2026-07-02T09:01:20Z','EV_CASH_PF'),
 ('CASH_PX','MAC_PAID_V1','REQ_PAID','PAY_PS','OWNER_PAID','FX_ADJUSTMENT',
  1000,'JPY','FX_ADJUSTMENT_TO_BASE',printf('%064x',9401),'REAL',
  'ACCOUNTING_BRIDGE','2026-07-02T09:01:12Z',
  '2026-07-02T09:01:20Z','EV_CASH_PX'),
 ('CASH_PB','MAC_PAID_V1','REQ_PAID','PAY_PS','OWNER_PAID',
  'BANK_OR_WALLET_RECEIPT',45000,'JPY','BASE_CURRENCY_NO_FX',NULL,'REAL','BANK_STATEMENT',
  '2026-07-03T09:00:00Z','2026-07-03T09:01:00Z','EV_CASH_PB'),
 ('CASH_NDG','MAC_NEG_V1','REQ_NEG_DELIVERED','PAY_NDS','OWNER_NEG_D',
  'GROSS_SETTLED',50000,'JPY','BASE_CURRENCY_NO_FX',NULL,'REAL','PROVIDER_LEDGER',
  '2026-07-02T10:02:12Z','2026-07-02T10:02:20Z','EV_CASH_NDG'),
 ('CASH_NDF','MAC_NEG_V1','REQ_NEG_DELIVERED','PAY_NDS','OWNER_NEG_D',
  'RAIL_FEE',-5000,'JPY','BASE_CURRENCY_NO_FX',NULL,'REAL','PROVIDER_LEDGER',
  '2026-07-02T10:02:12Z','2026-07-02T10:02:20Z','EV_CASH_NDF'),
 ('CASH_NDB','MAC_NEG_V1','REQ_NEG_DELIVERED','PAY_NDS','OWNER_NEG_D',
  'BANK_OR_WALLET_RECEIPT',45000,'JPY','BASE_CURRENCY_NO_FX',NULL,'REAL','BANK_STATEMENT',
  '2026-07-03T10:02:00Z','2026-07-03T10:03:00Z','EV_CASH_NDB'),
 ('CASH_NCG','MAC_NEG_V1','REQ_NEG_CASH','PAY_NCS','OWNER_NEG_C',
  'GROSS_SETTLED',50000,'JPY','BASE_CURRENCY_NO_FX',NULL,'REAL','PROVIDER_LEDGER',
  '2026-07-02T10:03:12Z','2026-07-02T10:03:20Z','EV_CASH_NCG'),
 ('CASH_NCF','MAC_NEG_V1','REQ_NEG_CASH','PAY_NCS','OWNER_NEG_C',
  'RAIL_FEE',-5000,'JPY','BASE_CURRENCY_NO_FX',NULL,'REAL','PROVIDER_LEDGER',
  '2026-07-02T10:03:12Z','2026-07-02T10:03:20Z','EV_CASH_NCF'),
 ('CASH_TG','MAC_TEST_V1','REQ_TEST','PAY_TS','OWNER_TEST','GROSS_SETTLED',
  50000,'JPY','BASE_CURRENCY_NO_FX',NULL,'TEST','PROVIDER_LEDGER','2026-07-02T09:04:12Z',
  '2026-07-02T09:04:20Z','EV_CASH_TG'),
 ('CASH_TF','MAC_TEST_V1','REQ_TEST','PAY_TS','OWNER_TEST','RAIL_FEE',
  -5000,'JPY','BASE_CURRENCY_NO_FX',NULL,'TEST','PROVIDER_LEDGER','2026-07-02T09:04:12Z',
  '2026-07-02T09:04:20Z','EV_CASH_TF'),
 ('CASH_TB','MAC_TEST_V1','REQ_TEST','PAY_TS','OWNER_TEST',
  'BANK_OR_WALLET_RECEIPT',45000,'JPY','BASE_CURRENCY_NO_FX',NULL,'TEST','CONTROLLED_WALLET',
  '2026-07-03T09:04:00Z','2026-07-03T09:05:00Z','EV_CASH_TB'),
 ('CASH_TR','MAC_TEST_V1','REQ_TEST','PAY_TR','OWNER_TEST','REVERSAL',
  -45000,'JPY','BASE_CURRENCY_NO_FX',NULL,'TEST','CONTROLLED_WALLET','2026-07-08T09:04:12Z',
  '2026-07-08T09:05:00Z','EV_CASH_TR');

INSERT INTO cost_event VALUES
 ('COST_PO','MAC_PAID_V1','REQ_PAID','ORIGIN',10000,0,'REAL',
  '2026-07-02T09:01:16Z','2026-07-02T09:01:18Z','EV_COST_PO'),
 ('COST_PF','MAC_PAID_V1','REQ_PAID','FOUNDER_TIME',0,10,'REAL',
  '2026-07-02T09:10:00Z','2026-07-02T09:10:01Z','EV_COST_PF'),
 ('COST_FO','MAC_FREE_V1','REQ_FREE','ORIGIN',1000,0,'REAL',
  '2026-07-02T09:02:00Z','2026-07-02T09:02:04Z','EV_COST_FO'),
 ('COST_NS','MAC_NEG_V1','REQ_NEG_SETTLEMENT_ONLY','ORIGIN',2000,0,'REAL',
  '2026-07-02T10:05:00Z','2026-07-02T10:05:01Z','EV_COST_NS'),
 ('COST_NF','MAC_NEG_V1','REQ_NEG_SETTLEMENT_ONLY','FOUNDER_TIME',0,1,'REAL',
  '2026-07-02T10:06:00Z','2026-07-02T10:06:01Z','EV_COST_NF'),
 ('COST_TO','MAC_TEST_V1','REQ_TEST','ORIGIN',10000,0,'TEST',
  '2026-07-02T09:04:16Z','2026-07-02T09:04:18Z','EV_COST_TO');

INSERT INTO risk_review VALUES
 ('RISK_P','MAC_PAID_V1',1,NULL,'PASS','PASS','PASS','PASS','PASS','PASS',
  '2026-08-01T00:00:00Z','2026-08-01T00:01:00Z','EV_RISK_P'),
 ('RISK_F','MAC_FREE_V1',1,NULL,'PASS','PASS','PASS','PASS','PASS','PASS',
  '2026-08-01T00:00:00Z','2026-08-01T00:01:00Z','EV_RISK_F'),
 ('RISK_U','MAC_UNKNOWN_V1',1,NULL,'PASS','PASS','UNKNOWN','PASS','PASS','UNKNOWN',
  '2026-08-01T00:00:00Z','2026-08-01T00:01:00Z','EV_RISK_U'),
 ('RISK_N','MAC_NEG_V1',1,NULL,'PASS','PASS','PASS','PASS','PASS','PASS',
  '2026-08-01T00:00:00Z','2026-08-01T00:01:00Z','EV_RISK_N'),
 ('RISK_T','MAC_TEST_V1',1,NULL,'PASS','FAILED','PASS','PASS','PASS','FAILED',
  '2026-08-01T00:00:00Z','2026-08-01T00:01:00Z','EV_RISK_T');

INSERT INTO decision_snapshot VALUES
 ('DEC_P','MAC_PAID_V1',1,NULL,'EXPAND','HTTP_402','RISK_P',
  '2026-08-02T12:00:00Z','2026-08-02T12:00:00Z','2026-07-10T00:00:00Z',
  1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,45000,10000,10,10000,25000,
  '2026-08-02T12:30:00Z','EV_DEC_P'),
 ('DEC_F','MAC_FREE_V1',1,NULL,'MAINTAIN','ALLOW_FREE','RISK_F',
  '2026-08-02T12:00:00Z','2026-08-02T12:00:00Z','2026-07-10T00:00:00Z',
  1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,
  '2026-08-02T12:30:00Z','EV_DEC_F'),
 ('DEC_U','MAC_UNKNOWN_V1',1,NULL,'PAUSE','RATE_LIMIT','RISK_U',
  '2026-08-02T12:00:00Z','2026-08-02T12:00:00Z','2026-07-10T00:00:00Z',
  1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  '2026-08-02T12:30:00Z','EV_DEC_U'),
 ('DEC_T','MAC_TEST_V1',1,NULL,'STOP','HTTP_402','RISK_T',
  '2026-08-02T12:00:00Z','2026-08-02T12:00:00Z','2026-07-10T00:00:00Z',
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  '2026-08-02T12:30:00Z','EV_DEC_T');

-- ---------------------------------------------------------------------------
-- Twenty-five independent negative probes. Each mutation traverses the same guard
-- as a normal statement. RAISE(IGNORE) preserves the probe receipt and prevents
-- invalid domain data from being written. SAVEPOINT boundaries make each probe
-- independently auditable.
-- ---------------------------------------------------------------------------

SAVEPOINT negative_probe_01;
INSERT INTO negative_probe_context VALUES (1,'NP01','APPEND_ONLY_REQUEST');
UPDATE request_observation SET response_status=200 WHERE request_id='REQ_PAID';
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_01;

SAVEPOINT negative_probe_02;
INSERT INTO negative_probe_context VALUES (1,'NP02','USER_AGENT_NOT_IDENTITY');
INSERT INTO actor_identity_observation VALUES
 ('ID_BAD_UA','MAC_PAID_V1',printf('%064x',9902),'USER_TRIGGERED_AGENT',
  'USER_TRIGGERED_AGENT','VERIFIED','USER_AGENT_ONLY',900,
  '2026-07-02T09:00:00Z','2026-07-02T09:00:05Z',
  '2026-08-05T00:00:00Z','EV_ID_P');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_02;

SAVEPOINT negative_probe_03;
INSERT INTO negative_probe_context VALUES (1,'NP03','POLICY_ACTION_EXACT');
INSERT INTO request_observation VALUES
 ('REQ_BAD_POLICY','MAC_FREE_V1','RES_FREE','POL_FREE','ID_FREE','REAL',
  printf('%064x',9903),'SYN_NET_PUBLIC',printf('%064x',5102),'GET',
  printf('%064x',5202),printf('%064x',5302),'OBSERVED','HTTP_402',402,0,512,
  '2026-07-02T09:02:30Z','2026-07-02T09:02:31Z',
  '2026-07-05T00:00:00Z','2026-07-10T00:00:00Z','EV_REQ_F');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_03;

SAVEPOINT negative_probe_04;
INSERT INTO negative_probe_context VALUES
 (1,'NP04','SETTLEMENT_REQUIRES_AUTHORIZATION');
INSERT INTO payment_event VALUES
 ('PAY_BAD_FIRST_SETTLE','CH_PAID','REQ_PAID','MAC_PAID_V1','PROOF_MISSING_NP04',1,NULL,
  'SETTLEMENT','OBSERVED','REAL',printf('%064x',9904),50000,'SYNUSD',
  'VERIFIED','2026-07-02T09:01:09Z','2026-07-02T09:01:10Z','EV_PAY_PS');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_04;

SAVEPOINT negative_probe_05;
INSERT INTO negative_probe_context VALUES
 (1,'NP05','NONCE_AND_IDEMPOTENCY_UNIQUE');
INSERT INTO challenge_receipt VALUES
 ('CH_BAD_REPLAY','REQ_PAID','MAC_PAID_V1','OFFER_PAID','REAL','ISSUED',402,
  printf('%064x',6001),printf('%064x',9995),'SYN_NET_A',printf('%064x',5101),
  printf('%064x',4001),'RESOURCE_ACCESS',printf('%064x',3001),printf('%064x',5401),
  'GET',printf('%064x',5201),printf('%064x',5301),printf('%064x',6995),
  printf('%064x',6996),50000,'SYNUSD',
  '2026-07-02T09:01:01Z','2026-07-02T09:06:00Z',
  '2026-07-02T09:01:03Z','EV_CH_P');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_05;

SAVEPOINT negative_probe_06;
INSERT INTO negative_probe_context VALUES (1,'NP06','PAYMENT_MUST_MATCH_OFFER');
INSERT INTO payment_event VALUES
 ('PAY_BAD_AMOUNT','CH_PAID','REQ_PAID','MAC_PAID_V1','PROOF_PS',3,'PAY_PS','REFUND',
  'OBSERVED','REAL',printf('%064x',9906),40000,'SYNUSD','VERIFIED',
  '2026-07-03T09:01:12Z','2026-07-03T09:01:13Z','EV_PAY_PS');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_06;

SAVEPOINT negative_probe_07;
INSERT INTO negative_probe_context VALUES (1,'NP07','TEST_REAL_CASH_SEPARATION');
INSERT INTO cash_bridge_line VALUES
 ('CASH_BAD_ENV','MAC_TEST_V1','REQ_TEST','PAY_TS','OWNER_BAD',
  'GROSS_SETTLED',50000,'JPY','BASE_CURRENCY_NO_FX',NULL,'REAL','PROVIDER_LEDGER',
  '2026-07-02T09:04:12Z','2026-07-02T09:04:20Z','EV_CASH_TG');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_07;

SAVEPOINT negative_probe_08;
INSERT INTO negative_probe_context VALUES
 (1,'NP08','ENTITLEMENT_REQUIRES_SETTLEMENT');
INSERT INTO entitlement_event VALUES
 ('ENT_BAD_AUTH','REQ_PAID','MAC_PAID_V1',printf('%064x',9908),1,NULL,
  'GRANTED','PAYMENT_SETTLEMENT','PAY_PA','REAL','2026-07-02T09:01:11Z',
  '2026-07-03T09:01:11Z','2026-07-02T09:01:11Z',
  '2026-07-02T09:01:12Z','EV_ENT_PG');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_08;

SAVEPOINT negative_probe_09;
INSERT INTO negative_probe_context VALUES (1,'NP09','DELIVERY_REQUIRES_ENTITLEMENT');
INSERT INTO delivery_event VALUES
 ('DEL_BAD_NO_ENT','REQ_PAID','MAC_PAID_V1',NULL,'BYTE_RESOURCE','DELIVERED','REAL',200,1024,
  printf('%064x',9909),printf('%064x',9919),'2026-07-02T09:01:16Z',
  '2026-07-02T09:01:17Z','EV_DEL_P');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_09;

SAVEPOINT negative_probe_10;
INSERT INTO negative_probe_context VALUES (1,'NP10','DELIVERY_EXACTLY_ONCE');
INSERT INTO delivery_event VALUES
 ('DEL_BAD_REPLAY','REQ_PAID','MAC_PAID_V1','ENT_PG','BYTE_RESOURCE','DELIVERED','REAL',200,1024,
  printf('%064x',9910),printf('%064x',9101),'2026-07-02T09:01:18Z',
  '2026-07-02T09:01:19Z','EV_DEL_P');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_10;

SAVEPOINT negative_probe_11;
INSERT INTO negative_probe_context VALUES
 (1,'NP11','REAL_CHARGEABLE_RIGHTS_REQUIRED');
INSERT INTO resource_contract VALUES
 ('RES_BAD_RIGHTS','MAC_PAID_V1','PREMIUM_CONTENT','sha256:syn-bad-rights',
  'UNKNOWN',0,0,printf('%064x',9911),'EV_RES_P');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_11;

SAVEPOINT negative_probe_12;
INSERT INTO negative_probe_context VALUES
 (1,'NP12','CASH_COMPONENT_IDEMPOTENCY_UNIQUE');
INSERT INTO cash_bridge_line VALUES
 ('CASH_BAD_DUP','MAC_PAID_V1','REQ_PAID','PAY_PS','OWNER_PAID',
  'GROSS_SETTLED',50000,'JPY','BASE_CURRENCY_NO_FX',NULL,'REAL','PROVIDER_LEDGER',
  '2026-07-02T09:01:12Z','2026-07-02T09:01:21Z','EV_CASH_PG');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_12;

SAVEPOINT negative_probe_13;
INSERT INTO negative_probe_context VALUES (1,'NP13','REVERSAL_MUST_BE_NEGATIVE');
INSERT INTO cash_bridge_line VALUES
 ('CASH_BAD_REV','MAC_TEST_V1','REQ_TEST','PAY_TR','OWNER_BAD','REVERSAL',
  45000,'JPY','BASE_CURRENCY_NO_FX',NULL,'TEST','CONTROLLED_WALLET','2026-07-08T09:04:12Z',
  '2026-07-08T09:05:01Z','EV_CASH_TR');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_13;

SAVEPOINT negative_probe_14;
INSERT INTO negative_probe_context VALUES
 (1,'NP14','EXPAND_REQUIRES_CURRENT_PASSING_EVIDENCE');
INSERT INTO decision_snapshot VALUES
 ('DEC_BAD_EXPAND','MAC_UNKNOWN_V1',2,'DEC_U','EXPAND','RATE_LIMIT','RISK_U',
  '2026-08-02T12:00:00Z','2026-08-02T12:00:00Z','2026-07-10T00:00:00Z',
  1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  '2026-08-02T12:40:00Z','EV_DEC_U');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_14;

SAVEPOINT negative_probe_15;
INSERT INTO negative_probe_context VALUES (1,'NP15','DECISION_PREDECESSOR_EXACT');
INSERT INTO decision_snapshot VALUES
 ('DEC_BAD_PREDECESSOR','MAC_PAID_V1',2,'DEC_F','MAINTAIN','HTTP_402','RISK_P',
  '2026-08-02T12:00:00Z','2026-08-02T12:00:00Z','2026-07-10T00:00:00Z',
  1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,45000,10000,10,10000,25000,
  '2026-08-02T12:40:00Z','EV_DEC_P');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_15;

SAVEPOINT negative_probe_16;
INSERT INTO negative_probe_context VALUES (1,'NP16','PROOF_NETWORK_BINDING');
INSERT INTO payment_proof VALUES
 ('PROOF_BAD_NETWORK','REQ_PAID','CH_PAID','OFFER_PAID',1,50000,'SYNUSD','REAL','SYN_NET_B',printf('%064x',5101),
  printf('%064x',4001),'RESOURCE_ACCESS',printf('%064x',3001),printf('%064x',5401),
  'GET',printf('%064x',5201),printf('%064x',5301),printf('%064x',6201),
  printf('%064x',9916),'VERIFIED','2026-07-02T09:01:09Z',
  '2026-07-02T09:01:10Z','EV_PROOF_PA');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_16;

SAVEPOINT negative_probe_17;
INSERT INTO negative_probe_context VALUES (1,'NP17','PROOF_RECIPIENT_BINDING');
INSERT INTO payment_proof VALUES
 ('PROOF_BAD_RECIPIENT','REQ_PAID','CH_PAID','OFFER_PAID',1,50000,'SYNUSD','REAL','SYN_NET_A',printf('%064x',9917),
  printf('%064x',4001),'RESOURCE_ACCESS',printf('%064x',3001),printf('%064x',5401),
  'GET',printf('%064x',5201),printf('%064x',5301),printf('%064x',6201),
  printf('%064x',9927),'VERIFIED','2026-07-02T09:01:09Z',
  '2026-07-02T09:01:10Z','EV_PROOF_PA');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_17;

SAVEPOINT negative_probe_18;
INSERT INTO negative_probe_context VALUES (1,'NP18','PROOF_RESOURCE_BINDING');
INSERT INTO payment_proof VALUES
 ('PROOF_BAD_RESOURCE','REQ_PAID','CH_PAID','OFFER_PAID',1,50000,'SYNUSD','REAL','SYN_NET_A',printf('%064x',5101),
  printf('%064x',4001),'RESOURCE_ACCESS',printf('%064x',3001),printf('%064x',5401),
  'GET',printf('%064x',9918),printf('%064x',5301),printf('%064x',6201),
  printf('%064x',9928),'VERIFIED','2026-07-02T09:01:09Z',
  '2026-07-02T09:01:10Z','EV_PROOF_PA');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_18;

SAVEPOINT negative_probe_19;
INSERT INTO negative_probe_context VALUES (1,'NP19','PROOF_BODY_BINDING');
INSERT INTO payment_proof VALUES
 ('PROOF_BAD_BODY','REQ_PAID','CH_PAID','OFFER_PAID',1,50000,'SYNUSD','REAL','SYN_NET_A',printf('%064x',5101),
  printf('%064x',4001),'RESOURCE_ACCESS',printf('%064x',3001),printf('%064x',5401),
  'GET',printf('%064x',5201),printf('%064x',9919),printf('%064x',6201),
  printf('%064x',9929),'VERIFIED','2026-07-02T09:01:09Z',
  '2026-07-02T09:01:10Z','EV_PROOF_PA');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_19;

SAVEPOINT negative_probe_20;
INSERT INTO negative_probe_context VALUES
 (1,'NP20','EXPECTED_PRESENTED_TUPLE_EQUALITY');
INSERT INTO payment_proof VALUES
 ('PROOF_BAD_TUPLE','REQ_PAID','CH_PAID','OFFER_PAID',1,50000,'SYNUSD','REAL','SYN_NET_A',printf('%064x',5101),
  printf('%064x',4001),'RESOURCE_ACCESS',printf('%064x',3001),printf('%064x',5401),
  'GET',printf('%064x',5201),printf('%064x',5301),printf('%064x',9920),
  printf('%064x',9930),'VERIFIED','2026-07-02T09:01:09Z',
  '2026-07-02T09:01:10Z','EV_PROOF_PA');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_20;

SAVEPOINT negative_probe_21;
INSERT INTO negative_probe_context VALUES (1,'NP21','PROOF_SINGLE_USE');
INSERT INTO payment_event VALUES
 ('PAY_BAD_PROOF_REPLAY','CH_PAID','REQ_PAID','MAC_PAID_V1','PROOF_PA',3,'PAY_PS',
  'REFUND','OBSERVED','REAL',printf('%064x',9921),50000,'SYNUSD','VERIFIED',
  '2026-07-03T09:01:12Z','2026-07-03T09:01:13Z','EV_PAY_PS');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_21;

SAVEPOINT negative_probe_22;
INSERT INTO negative_probe_context VALUES
 (1,'NP22','ACCEPTED_REQUIRES_EXACT_DELIVERY');
INSERT INTO accepted_outcome_event VALUES
 ('ACC_BAD_EXACT','REQ_PAID','DEL_F','MAC_PAID_V1',1,NULL,'REAL','ACCEPTED',
  printf('%064x',9922),'2026-07-02T09:02:04Z','2026-07-02T09:02:05Z',
  '2026-07-10T00:00:00Z','EV_ACC_P');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_22;

SAVEPOINT negative_probe_23;
INSERT INTO negative_probe_context VALUES
 (1,'NP23','EVIDENCE_ENVIRONMENT_EXACT');
INSERT INTO cost_event VALUES
 ('COST_BAD_ENV','MAC_PAID_V1','REQ_PAID','ORIGIN',1,0,'REAL',
  '2026-07-02T09:20:00Z','2026-07-02T09:20:01Z','EV_COST_TO');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_23;

SAVEPOINT negative_probe_24;
INSERT INTO negative_probe_context VALUES
 (1,'NP24','EVIDENCE_AUTHORITY_EXACT');
INSERT INTO cost_event VALUES
 ('COST_BAD_AUTHORITY','MAC_PAID_V1','REQ_PAID','ORIGIN',1,0,'REAL',
  '2026-07-02T09:21:00Z','2026-07-02T09:21:01Z','EV_ID_P');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_24;

SAVEPOINT negative_probe_25;
INSERT INTO negative_probe_context VALUES
 (1,'NP25','CASH_COMPONENT_IDEMPOTENCY_UNIQUE');
INSERT INTO cash_bridge_line VALUES
 ('CASH_BAD_OWNER_BYPASS','MAC_TEST_V1','REQ_TEST','PAY_TR','OWNER_OTHER',
  'REVERSAL',-50000,'JPY','BASE_CURRENCY_NO_FX',NULL,'TEST','CONTROLLED_WALLET',
  '2026-07-08T09:04:12Z','2026-07-08T09:05:02Z','EV_CASH_TR');
DELETE FROM negative_probe_context WHERE singleton_id=1;
RELEASE negative_probe_25;

-- ---------------------------------------------------------------------------
-- Named data-quality contract (DQ01-DQ80)
-- ---------------------------------------------------------------------------

CREATE TEMP VIEW v_evidence_chain_violations AS
SELECT 'SOURCE' AS stage_code,m.machine_access_contract_id AS row_id
FROM machine_access_contract m JOIN source_snapshot s USING (source_snapshot_id)
JOIN evidence_record e ON e.evidence_id=s.evidence_id
WHERE e.environment<>m.environment OR e.evidence_domain<>'SOURCE' OR e.evidence_rank<2
UNION ALL SELECT 'CONTRACT',m.machine_access_contract_id
FROM machine_access_contract m JOIN evidence_record e USING (evidence_id)
WHERE e.environment<>m.environment OR e.evidence_domain<>'CONTRACT' OR e.evidence_rank<2
UNION ALL SELECT 'RESOURCE',r.resource_contract_id
FROM resource_contract r JOIN machine_access_contract m USING (machine_access_contract_id)
JOIN evidence_record e ON e.evidence_id=r.evidence_id
WHERE e.environment<>m.environment OR e.evidence_domain<>'RESOURCE'
   OR e.evidence_rank<CASE WHEN r.rights_state='PASS' THEN 4 ELSE 2 END
UNION ALL SELECT 'POLICY',p.traffic_policy_id
FROM traffic_policy_version p JOIN machine_access_contract m USING (machine_access_contract_id)
JOIN evidence_record e ON e.evidence_id=p.evidence_id
WHERE e.environment<>m.environment OR e.evidence_domain<>'POLICY' OR e.evidence_rank<2
UNION ALL SELECT 'IDENTITY',i.identity_observation_id
FROM actor_identity_observation i JOIN machine_access_contract m USING (machine_access_contract_id)
JOIN evidence_record e ON e.evidence_id=i.evidence_id
WHERE e.environment<>m.environment OR e.evidence_domain<>'IDENTITY'
   OR e.evidence_rank<CASE WHEN i.verification_state='VERIFIED' THEN 3 ELSE 1 END
UNION ALL SELECT 'REQUEST',r.request_id
FROM request_observation r JOIN evidence_record e USING (evidence_id)
WHERE e.environment<>r.environment OR e.evidence_domain<>'REQUEST'
   OR e.evidence_rank<CASE WHEN r.classification_state='OBSERVED' THEN 3 ELSE 1 END
UNION ALL SELECT 'OFFER',o.payment_offer_id
FROM payment_offer_version o JOIN machine_access_contract m USING (machine_access_contract_id)
JOIN evidence_record e ON e.evidence_id=o.evidence_id
WHERE e.environment<>m.environment OR e.evidence_domain<>'OFFER' OR e.evidence_rank<2
UNION ALL SELECT 'CHALLENGE',h.challenge_id
FROM challenge_receipt h JOIN evidence_record e USING (evidence_id)
WHERE e.environment<>h.environment OR e.evidence_domain<>'CHALLENGE' OR e.evidence_rank<4
UNION ALL SELECT 'PROOF',q.payment_proof_id
FROM payment_proof q JOIN evidence_record e USING (evidence_id)
WHERE e.environment<>q.environment OR e.evidence_domain<>'PAYMENT' OR e.evidence_rank<3
UNION ALL SELECT 'PAYMENT',p.payment_event_id
FROM payment_event p JOIN evidence_record e USING (evidence_id)
WHERE e.environment<>p.environment OR e.evidence_domain<>'PAYMENT' OR e.evidence_rank<3
UNION ALL SELECT 'ENTITLEMENT',x.entitlement_event_id
FROM entitlement_event x JOIN evidence_record e USING (evidence_id)
WHERE e.environment<>x.environment OR e.evidence_domain<>'ENTITLEMENT'
   OR e.evidence_rank<CASE WHEN x.entitlement_state IN ('GRANTED','REVOKED') THEN 4 ELSE 2 END
UNION ALL SELECT 'DELIVERY',d.delivery_event_id
FROM delivery_event d JOIN evidence_record e USING (evidence_id)
WHERE e.environment<>d.environment OR e.evidence_domain<>'DELIVERY'
   OR e.evidence_rank<CASE WHEN d.delivery_state='DELIVERED' THEN 4 ELSE 2 END
UNION ALL SELECT 'ACCEPTED',a.accepted_outcome_event_id
FROM accepted_outcome_event a JOIN evidence_record e USING (evidence_id)
WHERE e.environment<>a.environment OR e.evidence_domain<>'ACCEPTED_OUTCOME'
   OR e.evidence_rank<CASE WHEN a.outcome_state='ACCEPTED' THEN 4 ELSE 2 END
UNION ALL SELECT 'CASH',c.cash_line_id
FROM cash_bridge_line c JOIN evidence_record e USING (evidence_id)
WHERE e.environment<>c.environment OR e.evidence_domain<>'CASH'
   OR e.evidence_rank<CASE WHEN c.line_type_code='BANK_OR_WALLET_RECEIPT' THEN 5 ELSE 3 END
UNION ALL SELECT 'COST',c.cost_event_id
FROM cost_event c JOIN evidence_record e USING (evidence_id)
WHERE e.environment<>c.environment OR e.evidence_domain<>'COST' OR e.evidence_rank<3
UNION ALL SELECT 'RISK',r.risk_review_id
FROM risk_review r JOIN machine_access_contract m USING (machine_access_contract_id)
JOIN evidence_record e ON e.evidence_id=r.evidence_id
WHERE e.environment<>m.environment OR e.evidence_domain<>'RISK' OR e.evidence_rank<4
UNION ALL SELECT 'DECISION',d.decision_snapshot_id
FROM decision_snapshot d JOIN machine_access_contract m USING (machine_access_contract_id)
JOIN evidence_record e ON e.evidence_id=d.evidence_id
WHERE e.environment<>m.environment OR e.evidence_domain<>'DECISION' OR e.evidence_rank<4;

CREATE TEMP VIEW v_causal_clock_violations AS
SELECT 'IDENTITY_TO_REQUEST' AS stage_code,r.request_id AS row_id
FROM request_observation r
JOIN actor_identity_observation i USING (identity_observation_id)
WHERE datetime(i.occurred_at)>datetime(r.occurred_at)
   OR datetime(i.recorded_at)>datetime(r.occurred_at)
UNION ALL SELECT 'REQUEST_TO_CHALLENGE',h.challenge_id
FROM challenge_receipt h JOIN request_observation r USING (request_id)
WHERE datetime(r.occurred_at)>datetime(h.issued_at)
   OR datetime(r.recorded_at)>datetime(h.recorded_at)
UNION ALL SELECT 'CHALLENGE_TO_PROOF',q.payment_proof_id
FROM payment_proof q
JOIN challenge_receipt h
  ON h.challenge_id=q.proof_covered_challenge_id
WHERE datetime(h.issued_at)>datetime(q.verified_at)
   OR datetime(h.recorded_at)>datetime(q.verified_at)
   OR datetime(q.verified_at)>datetime(q.recorded_at)
   OR datetime(q.verified_at)>=datetime(h.expires_at)
UNION ALL SELECT 'CHALLENGE_TO_PAYMENT',p.payment_event_id
FROM payment_event p JOIN challenge_receipt h USING (challenge_id)
LEFT JOIN payment_proof q USING (payment_proof_id)
WHERE datetime(h.issued_at)>datetime(p.occurred_at)
   OR datetime(h.recorded_at)>datetime(p.recorded_at)
   OR (p.event_type_code='AUTHORIZATION' AND (
        datetime(q.verified_at)>datetime(p.occurred_at)
        OR datetime(q.recorded_at)>datetime(p.recorded_at)))
UNION ALL SELECT 'PAYMENT_PREDECESSOR',p.payment_event_id
FROM payment_event p
JOIN payment_event q ON q.payment_event_id=p.predecessor_payment_event_id
WHERE datetime(q.occurred_at)>datetime(p.occurred_at)
   OR datetime(q.recorded_at)>datetime(p.recorded_at)
UNION ALL SELECT 'PAYMENT_TO_ENTITLEMENT',x.entitlement_event_id
FROM entitlement_event x
JOIN payment_event p ON p.payment_event_id=x.source_payment_event_id
WHERE datetime(p.occurred_at)>datetime(x.occurred_at)
   OR datetime(p.recorded_at)>datetime(x.recorded_at)
   OR datetime(p.occurred_at)>datetime(x.valid_from)
UNION ALL SELECT 'ENTITLEMENT_TO_DELIVERY',d.delivery_event_id
FROM delivery_event d JOIN request_observation r USING (request_id)
LEFT JOIN entitlement_event x USING (entitlement_event_id)
WHERE datetime(r.occurred_at)>datetime(d.occurred_at)
   OR (d.entitlement_event_id IS NOT NULL AND (
        datetime(x.recorded_at)>datetime(d.occurred_at)
        OR datetime(x.valid_from)>datetime(d.occurred_at)))
UNION ALL SELECT 'DELIVERY_TO_ACCEPTANCE',a.accepted_outcome_event_id
FROM accepted_outcome_event a JOIN delivery_event d USING (delivery_event_id)
WHERE datetime(d.occurred_at)>datetime(a.occurred_at)
   OR datetime(d.recorded_at)>datetime(a.recorded_at)
UNION ALL SELECT 'PAYMENT_TO_CASH',c.cash_line_id
FROM cash_bridge_line c JOIN payment_event p USING (payment_event_id)
WHERE datetime(p.occurred_at)>datetime(c.occurred_at)
   OR datetime(p.recorded_at)>datetime(c.recorded_at)
UNION ALL SELECT 'REQUEST_TO_COST',c.cost_event_id
FROM cost_event c JOIN request_observation r USING (request_id)
WHERE datetime(r.occurred_at)>datetime(c.occurred_at);

CREATE TEMP VIEW v_dq_results AS
SELECT 'DQ01' AS dq_id,'FOREIGN_KEYS_ENABLED' AS check_name,
       CASE WHEN (SELECT foreign_keys FROM pragma_foreign_keys)=1
            THEN 'PASS' ELSE 'FAIL' END AS status,
       CASE WHEN (SELECT foreign_keys FROM pragma_foreign_keys)=1
            THEN 0 ELSE 1 END AS failing_row_count
UNION ALL
SELECT 'DQ02','ALL_22_TABLES_ARE_STRICT',
       CASE WHEN (SELECT count(*) FROM sqlite_schema
                  WHERE type='table' AND name NOT LIKE 'sqlite_%'
                    AND sql LIKE '% STRICT')=22 THEN 'PASS' ELSE 'FAIL' END,
       abs(22-(SELECT count(*) FROM sqlite_schema
               WHERE type='table' AND name NOT LIKE 'sqlite_%'
                 AND sql LIKE '% STRICT'))
UNION ALL
SELECT 'DQ03','SCHEMA_IDENTITY_AND_SYNTHETIC_POLICY',
       CASE WHEN EXISTS (
         SELECT 1 FROM schema_registry
         WHERE schema_name='machine_traffic_monetization'
           AND schema_version='1.1.0'
           AND data_policy_code='SYNTHETIC_ONLY_NO_RAW_PII_OR_SECRETS')
       THEN 'PASS' ELSE 'FAIL' END,
       CASE WHEN EXISTS (
         SELECT 1 FROM schema_registry
         WHERE schema_name='machine_traffic_monetization'
           AND schema_version='1.1.0'
           AND data_policy_code='SYNTHETIC_ONLY_NO_RAW_PII_OR_SECRETS')
       THEN 0 ELSE 1 END
UNION ALL
SELECT 'DQ04','CATEGORICAL_UNKNOWN_NA_FAILED_WITHOUT_ZERO',
       CASE WHEN (SELECT count(DISTINCT state_code) FROM (
         SELECT seller_eligibility_state AS state_code FROM source_snapshot
         UNION ALL SELECT buyer_support_state FROM source_snapshot
         UNION ALL SELECT observation_state FROM machine_access_contract
         UNION ALL SELECT classification_state FROM request_observation)
         WHERE state_code IN ('UNKNOWN','N/A','FAILED'))=3
         AND NOT EXISTS (SELECT 1 FROM (
           SELECT seller_eligibility_state AS state_code FROM source_snapshot
           UNION ALL SELECT buyer_support_state FROM source_snapshot
           UNION ALL SELECT observation_state FROM machine_access_contract
           UNION ALL SELECT classification_state FROM request_observation)
           WHERE state_code='0')
       THEN 'PASS' ELSE 'FAIL' END,
       3-(SELECT count(DISTINCT state_code) FROM (
         SELECT seller_eligibility_state AS state_code FROM source_snapshot
         UNION ALL SELECT buyer_support_state FROM source_snapshot
         UNION ALL SELECT observation_state FROM machine_access_contract
         UNION ALL SELECT classification_state FROM request_observation)
         WHERE state_code IN ('UNKNOWN','N/A','FAILED'))
         +(SELECT count(*) FROM (
           SELECT seller_eligibility_state AS state_code FROM source_snapshot
           UNION ALL SELECT buyer_support_state FROM source_snapshot
           UNION ALL SELECT observation_state FROM machine_access_contract
           UNION ALL SELECT classification_state FROM request_observation)
           WHERE state_code='0')
UNION ALL
SELECT 'DQ05','EVIDENCE_HASH_AND_DATA_CLASS_SHAPE',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM evidence_record
         WHERE length(source_object_ref_hash)<>64
            OR source_object_ref_hash GLOB '*[^0-9a-f]*'
            OR length(payload_ref_hash)<>64
            OR payload_ref_hash GLOB '*[^0-9a-f]*'
            OR data_class_code<>'SYNTHETIC_OPAQUE_REFERENCE_ONLY')
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM evidence_record
        WHERE length(source_object_ref_hash)<>64
           OR source_object_ref_hash GLOB '*[^0-9a-f]*'
           OR length(payload_ref_hash)<>64
           OR payload_ref_hash GLOB '*[^0-9a-f]*'
           OR data_class_code<>'SYNTHETIC_OPAQUE_REFERENCE_ONLY')
UNION ALL
SELECT 'DQ06','EVIDENCE_CLASS_RANK_EXACT',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM evidence_record WHERE NOT (
           (evidence_class='E0_INFERENCE' AND evidence_rank=0)
           OR (evidence_class='E1_MANUAL_OBSERVATION' AND evidence_rank=1)
           OR (evidence_class='E2_VERSIONED_CONFIG' AND evidence_rank=2)
           OR (evidence_class='E3_VERIFIED_PROVIDER_EVENT' AND evidence_rank=3)
           OR (evidence_class='E4_FIRST_PARTY_AUTHORITATIVE' AND evidence_rank=4)
           OR (evidence_class='E5_BANK_WALLET_OR_CUSTOMER_AUTHORITATIVE'
               AND evidence_rank=5)))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM evidence_record WHERE NOT (
         (evidence_class='E0_INFERENCE' AND evidence_rank=0)
         OR (evidence_class='E1_MANUAL_OBSERVATION' AND evidence_rank=1)
         OR (evidence_class='E2_VERSIONED_CONFIG' AND evidence_rank=2)
         OR (evidence_class='E3_VERIFIED_PROVIDER_EVENT' AND evidence_rank=3)
         OR (evidence_class='E4_FIRST_PARTY_AUTHORITATIVE' AND evidence_rank=4)
         OR (evidence_class='E5_BANK_WALLET_OR_CUSTOMER_AUTHORITATIVE'
             AND evidence_rank=5)))
UNION ALL
SELECT 'DQ07','EVIDENCE_CLOCK_ORDER',
       CASE WHEN NOT EXISTS (SELECT 1 FROM evidence_record
                             WHERE datetime(occurred_at)>datetime(recorded_at))
            THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM evidence_record
        WHERE datetime(occurred_at)>datetime(recorded_at))
UNION ALL
SELECT 'DQ08','EVIDENCE_PREDECESSOR_DOMAIN_AND_TIME',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM evidence_record e
         LEFT JOIN evidence_record p ON p.evidence_id=e.supersedes_evidence_id
         WHERE e.supersedes_evidence_id IS NOT NULL
           AND (p.evidence_id IS NULL OR p.evidence_domain<>e.evidence_domain
             OR datetime(p.recorded_at)>=datetime(e.recorded_at)))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM evidence_record e
        LEFT JOIN evidence_record p ON p.evidence_id=e.supersedes_evidence_id
        WHERE e.supersedes_evidence_id IS NOT NULL
          AND (p.evidence_id IS NULL OR p.evidence_domain<>e.evidence_domain
            OR datetime(p.recorded_at)>=datetime(e.recorded_at)))
UNION ALL
SELECT 'DQ09','APPEND_ONLY_TRIGGER_PAIRS_PRESENT',
       CASE WHEN (SELECT count(*) FROM sqlite_schema
                  WHERE type='trigger' AND name LIKE 'immutable_%')=40
            THEN 'PASS' ELSE 'FAIL' END,
       abs(40-(SELECT count(*) FROM sqlite_schema
               WHERE type='trigger' AND name LIKE 'immutable_%'))
UNION ALL
SELECT 'DQ10','FIVE_DECISION_VIEWS_PRESENT',
       CASE WHEN (SELECT count(*) FROM sqlite_schema
                  WHERE type='view' AND name IN (
                    'v_effective_actor_identity','v_request_policy_resolution',
                    'v_payment_delivery_chain','v_mature_machine_unit_economics',
                    'v_current_decision_gate'))=5 THEN 'PASS' ELSE 'FAIL' END,
       abs(5-(SELECT count(*) FROM sqlite_schema
              WHERE type='view' AND name IN (
                'v_effective_actor_identity','v_request_policy_resolution',
                'v_payment_delivery_chain','v_mature_machine_unit_economics',
                'v_current_decision_gate')))
UNION ALL
SELECT 'DQ11','CONTRACT_EVIDENCE_ENVIRONMENT_MATCHES',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM machine_access_contract m
         JOIN evidence_record e USING (evidence_id)
         WHERE m.environment<>e.environment) THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM machine_access_contract m
        JOIN evidence_record e USING (evidence_id)
        WHERE m.environment<>e.environment)
UNION ALL
SELECT 'DQ12','REAL_CONTRACT_SOURCE_CURRENT_AND_ELIGIBLE',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM machine_access_contract m
         JOIN source_snapshot s USING (source_snapshot_id)
         WHERE m.environment='REAL'
           AND (s.program_status<>'CURRENT'
             OR s.seller_eligibility_state<>'OBSERVED'))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM machine_access_contract m
        JOIN source_snapshot s USING (source_snapshot_id)
        WHERE m.environment='REAL'
          AND (s.program_status<>'CURRENT'
            OR s.seller_eligibility_state<>'OBSERVED'))
UNION ALL
SELECT 'DQ13','SOURCE_FRESH_THROUGH_DECISION_DUE',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM machine_access_contract m
         JOIN source_snapshot s USING (source_snapshot_id)
         WHERE m.environment='REAL'
           AND datetime(s.stale_after)<datetime(m.decision_due_at))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM machine_access_contract m
        JOIN source_snapshot s USING (source_snapshot_id)
        WHERE m.environment='REAL'
          AND datetime(s.stale_after)<datetime(m.decision_due_at))
UNION ALL
SELECT 'DQ14','CONTRACT_CLOCKS_ORDERED',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM machine_access_contract
         WHERE datetime(enrollment_starts_at)>=datetime(outcome_cutoff_at)
            OR datetime(outcome_cutoff_at)>datetime(maturity_at)
            OR datetime(maturity_at)>datetime(decision_due_at))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM machine_access_contract
        WHERE datetime(enrollment_starts_at)>=datetime(outcome_cutoff_at)
           OR datetime(outcome_cutoff_at)>datetime(maturity_at)
           OR datetime(maturity_at)>datetime(decision_due_at))
UNION ALL
SELECT 'DQ15','CONTRACT_VERSION_CHAIN_EXACT',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM machine_access_contract m
         LEFT JOIN machine_access_contract p
           ON p.machine_access_contract_id=m.supersedes_contract_id
         WHERE (m.contract_version=1 AND m.supersedes_contract_id IS NOT NULL)
            OR (m.contract_version>1 AND (p.contract_family_id<>m.contract_family_id
              OR p.contract_version<>m.contract_version-1)))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM machine_access_contract m
        LEFT JOIN machine_access_contract p
          ON p.machine_access_contract_id=m.supersedes_contract_id
        WHERE (m.contract_version=1 AND m.supersedes_contract_id IS NOT NULL)
           OR (m.contract_version>1 AND (p.contract_family_id<>m.contract_family_id
             OR p.contract_version<>m.contract_version-1)))
UNION ALL
SELECT 'DQ16','RESOURCE_CONTRACT_SCOPE_RESOLVES',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM resource_contract r
         LEFT JOIN machine_access_contract m USING (machine_access_contract_id)
         WHERE m.machine_access_contract_id IS NULL) THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM resource_contract r
        LEFT JOIN machine_access_contract m USING (machine_access_contract_id)
        WHERE m.machine_access_contract_id IS NULL)
UNION ALL
SELECT 'DQ17','REAL_CHARGEABLE_RESOURCES_HAVE_RIGHTS_PASS',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM resource_contract r
         JOIN machine_access_contract m USING (machine_access_contract_id)
         WHERE m.environment='REAL'
           AND r.resource_class_code IN (
             'PREMIUM_CONTENT','API_COMPUTE','TOOL_ACTION','CUSTOMER_DATA')
           AND r.rights_state<>'PASS') THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM resource_contract r
        JOIN machine_access_contract m USING (machine_access_contract_id)
        WHERE m.environment='REAL'
          AND r.resource_class_code IN (
            'PREMIUM_CONTENT','API_COMPUTE','TOOL_ACTION','CUSTOMER_DATA')
          AND r.rights_state<>'PASS')
UNION ALL
SELECT 'DQ18','HUMAN_AND_SEARCH_POLICIES_NOT_CHARGEABLE',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM traffic_policy_version
         WHERE actor_class_code IN ('HUMAN_BROWSER','SEARCH_INDEXER')
           AND (chargeable=1 OR action_mode_code IN (
             'CONTRACT_LICENSE','AUTHENTICATED_API','HTTP_402',
             'SERVE_ENTITLED')))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM traffic_policy_version
        WHERE actor_class_code IN ('HUMAN_BROWSER','SEARCH_INDEXER')
          AND (chargeable=1 OR action_mode_code IN (
            'CONTRACT_LICENSE','AUTHENTICATED_API','HTTP_402',
            'SERVE_ENTITLED')))
UNION ALL
SELECT 'DQ19','CHARGEABLE_POLICY_REQUIRES_IDENTITY',
       CASE WHEN NOT EXISTS (SELECT 1 FROM traffic_policy_version
                             WHERE chargeable=1 AND identity_required<>1)
            THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM traffic_policy_version
        WHERE chargeable=1 AND identity_required<>1)
UNION ALL
SELECT 'DQ20','POLICY_ACTION_CHARGEABLE_SHAPE',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM traffic_policy_version WHERE NOT (
           (chargeable=1 AND action_mode_code IN (
             'CONTRACT_LICENSE','AUTHENTICATED_API','HTTP_402',
             'SERVE_ENTITLED'))
           OR (chargeable=0 AND action_mode_code IN (
             'MEASURE_ONLY','ALLOW_FREE','RATE_LIMIT','SECURITY_CHALLENGE',
             'BLOCK','PAUSE'))))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM traffic_policy_version WHERE NOT (
         (chargeable=1 AND action_mode_code IN (
           'CONTRACT_LICENSE','AUTHENTICATED_API','HTTP_402',
           'SERVE_ENTITLED'))
         OR (chargeable=0 AND action_mode_code IN (
           'MEASURE_ONLY','ALLOW_FREE','RATE_LIMIT','SECURITY_CHALLENGE',
           'BLOCK','PAUSE'))))
UNION ALL
SELECT 'DQ21','POLICY_CLOCK_INSIDE_CONTRACT',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM traffic_policy_version p
         JOIN machine_access_contract m USING (machine_access_contract_id)
         WHERE datetime(p.effective_from)<datetime(m.enrollment_starts_at)
            OR datetime(p.effective_from)>datetime(m.outcome_cutoff_at))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM traffic_policy_version p
        JOIN machine_access_contract m USING (machine_access_contract_id)
        WHERE datetime(p.effective_from)<datetime(m.enrollment_starts_at)
           OR datetime(p.effective_from)>datetime(m.outcome_cutoff_at))
UNION ALL
SELECT 'DQ22','POLICY_SCOPE_AND_VERSION_EXACT',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM traffic_policy_version p
         JOIN resource_contract r USING (resource_contract_id)
         WHERE p.machine_access_contract_id<>r.machine_access_contract_id)
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM traffic_policy_version p
        JOIN resource_contract r USING (resource_contract_id)
        WHERE p.machine_access_contract_id<>r.machine_access_contract_id)
UNION ALL
SELECT 'DQ23','USER_AGENT_ALONE_NEVER_VERIFIED',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM actor_identity_observation
         WHERE verification_state='VERIFIED'
           AND verification_method_code IN ('NONE','USER_AGENT_ONLY'))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM actor_identity_observation
        WHERE verification_state='VERIFIED'
          AND verification_method_code IN ('NONE','USER_AGENT_ONLY'))
UNION ALL
SELECT 'DQ24','VERIFIED_ACTOR_CLASS_MATCHES_CLAIM',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM actor_identity_observation
         WHERE verification_state='VERIFIED'
           AND verified_actor_class_code<>claimed_actor_class_code)
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM actor_identity_observation
        WHERE verification_state='VERIFIED'
          AND verified_actor_class_code<>claimed_actor_class_code)
UNION ALL
SELECT 'DQ25','IDENTITY_EVIDENCE_ENVIRONMENT_MATCHES',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM actor_identity_observation i
         JOIN machine_access_contract m USING (machine_access_contract_id)
         JOIN evidence_record e USING (evidence_id)
         WHERE m.environment<>e.environment) THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM actor_identity_observation i
        JOIN machine_access_contract m USING (machine_access_contract_id)
        JOIN evidence_record e USING (evidence_id)
        WHERE m.environment<>e.environment)
UNION ALL
SELECT 'DQ26','EFFECTIVE_IDENTITY_ONE_PER_ACTOR',
       CASE WHEN NOT EXISTS (
         SELECT machine_access_contract_id,actor_ref_hash,count(*) AS n
         FROM v_effective_actor_identity
         GROUP BY machine_access_contract_id,actor_ref_hash HAVING n<>1)
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM (
         SELECT machine_access_contract_id,actor_ref_hash,count(*) AS n
         FROM v_effective_actor_identity
         GROUP BY machine_access_contract_id,actor_ref_hash HAVING n<>1))
UNION ALL
SELECT 'DQ27','REQUEST_SCOPE_RESOLVES',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM request_observation r
         JOIN resource_contract x USING (resource_contract_id)
         JOIN traffic_policy_version p USING (traffic_policy_id)
         JOIN actor_identity_observation i USING (identity_observation_id)
         WHERE r.machine_access_contract_id<>x.machine_access_contract_id
            OR r.machine_access_contract_id<>p.machine_access_contract_id
            OR r.machine_access_contract_id<>i.machine_access_contract_id)
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM request_observation r
        JOIN resource_contract x USING (resource_contract_id)
        JOIN traffic_policy_version p USING (traffic_policy_id)
        JOIN actor_identity_observation i USING (identity_observation_id)
        WHERE r.machine_access_contract_id<>x.machine_access_contract_id
           OR r.machine_access_contract_id<>p.machine_access_contract_id
           OR r.machine_access_contract_id<>i.machine_access_contract_id)
UNION ALL
SELECT 'DQ28','REQUEST_ACTION_MATCHES_POLICY',
       CASE WHEN NOT EXISTS (SELECT 1 FROM v_request_policy_resolution
                             WHERE policy_resolution_gate<>'PASS')
            THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM v_request_policy_resolution
        WHERE policy_resolution_gate<>'PASS')
UNION ALL
SELECT 'DQ29','IDENTITY_REQUIRED_REQUESTS_PASS',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM v_request_policy_resolution
         WHERE identity_required=1 AND identity_gate<>'PASS')
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM v_request_policy_resolution
        WHERE identity_required=1 AND identity_gate<>'PASS')
UNION ALL
SELECT 'DQ30','REQUEST_CLOCKS_ORDERED_AND_BOUNDED',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM request_observation r
         JOIN machine_access_contract m USING (machine_access_contract_id)
         WHERE datetime(r.occurred_at)>datetime(r.recorded_at)
            OR datetime(r.occurred_at)>datetime(r.outcome_cutoff_at)
            OR datetime(r.outcome_cutoff_at)>datetime(r.maturity_at)
            OR datetime(r.outcome_cutoff_at)>datetime(m.outcome_cutoff_at)
            OR datetime(r.maturity_at)>datetime(m.maturity_at))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM request_observation r
        JOIN machine_access_contract m USING (machine_access_contract_id)
        WHERE datetime(r.occurred_at)>datetime(r.recorded_at)
           OR datetime(r.occurred_at)>datetime(r.outcome_cutoff_at)
           OR datetime(r.outcome_cutoff_at)>datetime(r.maturity_at)
           OR datetime(r.outcome_cutoff_at)>datetime(m.outcome_cutoff_at)
           OR datetime(r.maturity_at)>datetime(m.maturity_at))
UNION ALL
SELECT 'DQ31','HTTP_402_RESPONSE_SHAPE',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM request_observation
         WHERE (applied_action_mode_code='HTTP_402'
           AND (response_status<>402 OR protected_resource_bytes<>0
             OR challenge_document_bytes<=0))
            OR (applied_action_mode_code<>'HTTP_402'
              AND challenge_document_bytes<>0))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM request_observation
        WHERE (applied_action_mode_code='HTTP_402'
          AND (response_status<>402 OR protected_resource_bytes<>0
            OR challenge_document_bytes<=0))
           OR (applied_action_mode_code<>'HTTP_402'
             AND challenge_document_bytes<>0))
UNION ALL
SELECT 'DQ32','RATE_LIMIT_AND_BLOCK_RESPONSE_SHAPE',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM request_observation
         WHERE (applied_action_mode_code='RATE_LIMIT' AND response_status<>429)
            OR (applied_action_mode_code='BLOCK' AND response_status<>403))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM request_observation
        WHERE (applied_action_mode_code='RATE_LIMIT' AND response_status<>429)
           OR (applied_action_mode_code='BLOCK' AND response_status<>403))
UNION ALL
SELECT 'DQ33','OFFER_SCOPE_AND_RIGHTS_PASS',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM payment_offer_version o
         JOIN resource_contract r USING (resource_contract_id)
         WHERE o.machine_access_contract_id<>r.machine_access_contract_id
            OR r.rights_state<>'PASS') THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM payment_offer_version o
        JOIN resource_contract r USING (resource_contract_id)
        WHERE o.machine_access_contract_id<>r.machine_access_contract_id
           OR r.rights_state<>'PASS')
UNION ALL
SELECT 'DQ34','OFFER_VERSION_CHAIN_EXACT',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM payment_offer_version o
         LEFT JOIN payment_offer_version p
           ON p.payment_offer_id=o.supersedes_offer_id
         WHERE o.offer_version>1
           AND (p.offer_family_id<>o.offer_family_id
             OR p.offer_version<>o.offer_version-1))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM payment_offer_version o
        LEFT JOIN payment_offer_version p
          ON p.payment_offer_id=o.supersedes_offer_id
        WHERE o.offer_version>1
          AND (p.offer_family_id<>o.offer_family_id
            OR p.offer_version<>o.offer_version-1))
UNION ALL
SELECT 'DQ35','CHALLENGE_MATCHES_REQUEST_AND_OFFER',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM challenge_receipt h
         JOIN request_observation r USING (request_id)
         JOIN payment_offer_version o USING (payment_offer_id)
         WHERE r.applied_action_mode_code<>'HTTP_402'
            OR h.response_status<>402 OR o.offer_state<>'CURRENT'
            OR h.machine_access_contract_id<>r.machine_access_contract_id
            OR h.machine_access_contract_id<>o.machine_access_contract_id
            OR r.resource_contract_id<>o.resource_contract_id
            OR h.amount_atomic<>o.amount_atomic OR h.asset_code<>o.asset_code
            OR h.network_scope_code<>r.network_scope_code
            OR h.network_scope_code<>o.network_scope_code
            OR h.recipient_ref_hash<>r.recipient_ref_hash
            OR h.recipient_ref_hash<>o.recipient_ref_hash
            OR datetime(h.issued_at)<datetime(o.effective_from)
            OR datetime(h.expires_at)>datetime(o.expires_at))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM challenge_receipt h
        JOIN request_observation r USING (request_id)
        JOIN payment_offer_version o USING (payment_offer_id)
        WHERE r.applied_action_mode_code<>'HTTP_402'
           OR h.response_status<>402 OR o.offer_state<>'CURRENT'
           OR h.machine_access_contract_id<>r.machine_access_contract_id
           OR h.machine_access_contract_id<>o.machine_access_contract_id
           OR r.resource_contract_id<>o.resource_contract_id
           OR h.amount_atomic<>o.amount_atomic OR h.asset_code<>o.asset_code
           OR h.network_scope_code<>r.network_scope_code
           OR h.network_scope_code<>o.network_scope_code
           OR h.recipient_ref_hash<>r.recipient_ref_hash
           OR h.recipient_ref_hash<>o.recipient_ref_hash
           OR datetime(h.issued_at)<datetime(o.effective_from)
           OR datetime(h.expires_at)>datetime(o.expires_at))
UNION ALL
SELECT 'DQ36','CHALLENGE_NONCE_AND_IDEMPOTENCY_UNIQUE',
       CASE WHEN NOT EXISTS (
         SELECT nonce_ref_hash FROM challenge_receipt GROUP BY nonce_ref_hash
         HAVING count(*)<>1) AND NOT EXISTS (
         SELECT idempotency_ref_hash FROM challenge_receipt
         GROUP BY idempotency_ref_hash HAVING count(*)<>1)
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM (
         SELECT nonce_ref_hash FROM challenge_receipt GROUP BY nonce_ref_hash
         HAVING count(*)<>1))+(SELECT count(*) FROM (
         SELECT idempotency_ref_hash FROM challenge_receipt
         GROUP BY idempotency_ref_hash HAVING count(*)<>1))
UNION ALL
SELECT 'DQ37','PAYMENT_CHAIN_PREDECESSOR_EXACT',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM payment_event p
         LEFT JOIN payment_event q
           ON q.payment_event_id=p.predecessor_payment_event_id
         WHERE (p.event_sequence=1 AND p.predecessor_payment_event_id IS NOT NULL)
            OR (p.event_sequence>1 AND (q.challenge_id<>p.challenge_id
              OR q.request_id<>p.request_id
              OR q.event_sequence<>p.event_sequence-1)))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM payment_event p
        LEFT JOIN payment_event q
          ON q.payment_event_id=p.predecessor_payment_event_id
        WHERE (p.event_sequence=1 AND p.predecessor_payment_event_id IS NOT NULL)
           OR (p.event_sequence>1 AND (q.challenge_id<>p.challenge_id
             OR q.request_id<>p.request_id
             OR q.event_sequence<>p.event_sequence-1)))
UNION ALL
SELECT 'DQ38','PAYMENT_AMOUNT_AND_ASSET_MATCH_CHALLENGE',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM payment_event p JOIN challenge_receipt h USING (challenge_id)
         WHERE p.amount_atomic<>h.amount_atomic OR p.asset_code<>h.asset_code)
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM payment_event p JOIN challenge_receipt h USING (challenge_id)
        WHERE p.amount_atomic<>h.amount_atomic OR p.asset_code<>h.asset_code)
UNION ALL
SELECT 'DQ39','FIRST_PAYMENT_EVENT_AUTH_FAILURE_OR_EXPIRY',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM payment_event
         WHERE (event_sequence=1 AND event_type_code NOT IN (
                  'AUTHORIZATION','FAILURE','EXPIRY'))
            OR (event_type_code='AUTHORIZATION' AND event_sequence<>1))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM payment_event
        WHERE (event_sequence=1 AND event_type_code NOT IN (
                 'AUTHORIZATION','FAILURE','EXPIRY'))
           OR (event_type_code='AUTHORIZATION' AND event_sequence<>1))
UNION ALL
SELECT 'DQ40','SETTLEMENT_HAS_PRIOR_AUTHORIZATION',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM payment_event s WHERE s.event_type_code='SETTLEMENT'
           AND NOT EXISTS (SELECT 1 FROM payment_event a
                           WHERE a.challenge_id=s.challenge_id
                             AND a.event_type_code='AUTHORIZATION'
                             AND a.event_state='OBSERVED'
                             AND a.event_sequence<s.event_sequence))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM payment_event s WHERE s.event_type_code='SETTLEMENT'
          AND NOT EXISTS (SELECT 1 FROM payment_event a
                          WHERE a.challenge_id=s.challenge_id
                            AND a.event_type_code='AUTHORIZATION'
                            AND a.event_state='OBSERVED'
                            AND a.event_sequence<s.event_sequence))
UNION ALL
SELECT 'DQ41','REVERSAL_HAS_PRIOR_SETTLEMENT',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM payment_event x
         WHERE x.event_type_code IN ('REVERSAL','REFUND')
           AND NOT EXISTS (SELECT 1 FROM payment_event s
                           WHERE s.challenge_id=x.challenge_id
                             AND s.event_type_code='SETTLEMENT'
                             AND s.event_state='OBSERVED'
                             AND s.event_sequence<x.event_sequence))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM payment_event x
        WHERE x.event_type_code IN ('REVERSAL','REFUND')
          AND NOT EXISTS (SELECT 1 FROM payment_event s
                          WHERE s.challenge_id=x.challenge_id
                            AND s.event_type_code='SETTLEMENT'
                            AND s.event_state='OBSERVED'
                            AND s.event_sequence<x.event_sequence))
UNION ALL
SELECT 'DQ42','AUTH_BUYER_PROOF_AND_PROVIDER_LIFECYCLE_SEPARATED',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM payment_event p
         LEFT JOIN payment_proof q USING (payment_proof_id)
         WHERE (p.event_type_code='AUTHORIZATION'
                AND (p.payment_proof_id IS NULL
                  OR p.proof_verification_state<>'VERIFIED'
                  OR q.verification_state<>'VERIFIED'))
            OR (p.event_type_code<>'AUTHORIZATION'
                AND (p.payment_proof_id IS NOT NULL
                  OR p.proof_verification_state<>'N/A')))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM payment_event p
        LEFT JOIN payment_proof q USING (payment_proof_id)
        WHERE (p.event_type_code='AUTHORIZATION'
               AND (p.payment_proof_id IS NULL
                 OR p.proof_verification_state<>'VERIFIED'
                 OR q.verification_state<>'VERIFIED'))
           OR (p.event_type_code<>'AUTHORIZATION'
               AND (p.payment_proof_id IS NOT NULL
                 OR p.proof_verification_state<>'N/A')))
UNION ALL
SELECT 'DQ43','PAYMENT_ENTITLEMENT_TRACES_SETTLEMENT_TO_AUTH_PROOF',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM entitlement_event e
         LEFT JOIN payment_event p ON p.payment_event_id=e.source_payment_event_id
         WHERE e.entitlement_state='GRANTED'
           AND e.source_kind_code='PAYMENT_SETTLEMENT'
           AND (p.event_type_code<>'SETTLEMENT' OR p.event_state<>'OBSERVED'
             OR NOT EXISTS (
               SELECT 1 FROM payment_event a
               JOIN payment_proof q USING (payment_proof_id)
               WHERE a.challenge_id=p.challenge_id
                 AND a.request_id=p.request_id
                 AND a.event_type_code='AUTHORIZATION'
                 AND a.event_state='OBSERVED'
                 AND a.proof_verification_state='VERIFIED'
                 AND q.verification_state='VERIFIED'
                 AND a.event_sequence<p.event_sequence)))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM entitlement_event e
        LEFT JOIN payment_event p ON p.payment_event_id=e.source_payment_event_id
        WHERE e.entitlement_state='GRANTED'
          AND e.source_kind_code='PAYMENT_SETTLEMENT'
          AND (p.event_type_code<>'SETTLEMENT' OR p.event_state<>'OBSERVED'
            OR NOT EXISTS (
              SELECT 1 FROM payment_event a
              JOIN payment_proof q USING (payment_proof_id)
              WHERE a.challenge_id=p.challenge_id
                AND a.request_id=p.request_id
                AND a.event_type_code='AUTHORIZATION'
                AND a.event_state='OBSERVED'
                AND a.proof_verification_state='VERIFIED'
                AND q.verification_state='VERIFIED'
                AND a.event_sequence<p.event_sequence)))
UNION ALL
SELECT 'DQ44','ENTITLEMENT_CHAIN_PREDECESSOR_EXACT',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM entitlement_event e
         LEFT JOIN entitlement_event p
           ON p.entitlement_event_id=e.predecessor_entitlement_event_id
         WHERE e.event_sequence>1
           AND (p.entitlement_ref_hash<>e.entitlement_ref_hash
             OR p.request_id<>e.request_id
             OR p.event_sequence<>e.event_sequence-1))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM entitlement_event e
        LEFT JOIN entitlement_event p
          ON p.entitlement_event_id=e.predecessor_entitlement_event_id
        WHERE e.event_sequence>1
          AND (p.entitlement_ref_hash<>e.entitlement_ref_hash
            OR p.request_id<>e.request_id
            OR p.event_sequence<>e.event_sequence-1))
UNION ALL
SELECT 'DQ45','ENTITLEMENT_REVOKE_FOLLOWS_GRANT',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM entitlement_event e
         LEFT JOIN entitlement_event p
           ON p.entitlement_event_id=e.predecessor_entitlement_event_id
         WHERE e.entitlement_state='REVOKED' AND p.entitlement_state<>'GRANTED')
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM entitlement_event e
        LEFT JOIN entitlement_event p
          ON p.entitlement_event_id=e.predecessor_entitlement_event_id
        WHERE e.entitlement_state='REVOKED' AND p.entitlement_state<>'GRANTED')
UNION ALL
SELECT 'DQ46','CHARGEABLE_DELIVERY_HAS_GRANTED_ENTITLEMENT',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM delivery_event d
         JOIN request_observation r USING (request_id)
         LEFT JOIN entitlement_event e
           ON e.entitlement_event_id=d.entitlement_event_id
         WHERE d.delivery_state='DELIVERED'
           AND r.applied_action_mode_code IN (
             'HTTP_402','CONTRACT_LICENSE','AUTHENTICATED_API','SERVE_ENTITLED')
           AND (e.entitlement_event_id IS NULL OR e.entitlement_state<>'GRANTED'))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM delivery_event d
        JOIN request_observation r USING (request_id)
        LEFT JOIN entitlement_event e
          ON e.entitlement_event_id=d.entitlement_event_id
        WHERE d.delivery_state='DELIVERED'
          AND r.applied_action_mode_code IN (
            'HTTP_402','CONTRACT_LICENSE','AUTHENTICATED_API','SERVE_ENTITLED')
          AND (e.entitlement_event_id IS NULL OR e.entitlement_state<>'GRANTED'))
UNION ALL
SELECT 'DQ47','DELIVERY_IDEMPOTENCY_AND_ENTITLEMENT_EXACTLY_ONCE',
       CASE WHEN NOT EXISTS (
         SELECT idempotency_ref_hash FROM delivery_event
         GROUP BY idempotency_ref_hash HAVING count(*)<>1)
         AND NOT EXISTS (
           SELECT entitlement_event_id FROM delivery_event
           WHERE delivery_state='DELIVERED' AND entitlement_event_id IS NOT NULL
           GROUP BY entitlement_event_id HAVING count(*)<>1)
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM (
         SELECT idempotency_ref_hash FROM delivery_event
         GROUP BY idempotency_ref_hash HAVING count(*)<>1))+
       (SELECT count(*) FROM (
         SELECT entitlement_event_id FROM delivery_event
         WHERE delivery_state='DELIVERED' AND entitlement_event_id IS NOT NULL
         GROUP BY entitlement_event_id HAVING count(*)<>1))
UNION ALL
SELECT 'DQ48','FREE_DELIVERY_HAS_NO_PAID_ENTITLEMENT',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM delivery_event d JOIN request_observation r USING (request_id)
         WHERE d.delivery_state='DELIVERED'
           AND r.applied_action_mode_code IN ('ALLOW_FREE','MEASURE_ONLY')
           AND d.entitlement_event_id IS NOT NULL) THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM delivery_event d JOIN request_observation r USING (request_id)
        WHERE d.delivery_state='DELIVERED'
          AND r.applied_action_mode_code IN ('ALLOW_FREE','MEASURE_ONLY')
          AND d.entitlement_event_id IS NOT NULL)
UNION ALL
SELECT 'DQ49','CASH_SCOPE_AND_ENVIRONMENT_MATCH',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM cash_bridge_line c
         JOIN payment_event p USING (payment_event_id)
         JOIN request_observation r USING (request_id)
         WHERE c.machine_access_contract_id<>p.machine_access_contract_id
            OR c.machine_access_contract_id<>r.machine_access_contract_id
            OR c.environment<>p.environment OR c.environment<>r.environment)
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM cash_bridge_line c
        JOIN payment_event p USING (payment_event_id)
        JOIN request_observation r USING (request_id)
        WHERE c.machine_access_contract_id<>p.machine_access_contract_id
           OR c.machine_access_contract_id<>r.machine_access_contract_id
           OR c.environment<>p.environment OR c.environment<>r.environment)
UNION ALL
SELECT 'DQ50','BANK_OR_WALLET_RECEIPT_HAS_E5_AUTHORITY',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM cash_bridge_line c JOIN evidence_record e USING (evidence_id)
         WHERE c.line_type_code='BANK_OR_WALLET_RECEIPT'
           AND (e.evidence_rank<5 OR c.authority_code NOT IN (
             'CONTROLLED_WALLET','BANK_STATEMENT')))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM cash_bridge_line c JOIN evidence_record e USING (evidence_id)
        WHERE c.line_type_code='BANK_OR_WALLET_RECEIPT'
          AND (e.evidence_rank<5 OR c.authority_code NOT IN (
            'CONTROLLED_WALLET','BANK_STATEMENT')))
UNION ALL
SELECT 'DQ51','CASH_LINE_SIGN_BY_TYPE',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM cash_bridge_line WHERE
           (line_type_code IN ('GROSS_SETTLED','BANK_OR_WALLET_RECEIPT')
             AND amount_base_micros<=0)
           OR (line_type_code IN ('RAIL_FEE','TAX_WITHHELD','REFUND','REVERSAL')
             AND amount_base_micros>=0)) THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM cash_bridge_line WHERE
         (line_type_code IN ('GROSS_SETTLED','BANK_OR_WALLET_RECEIPT')
           AND amount_base_micros<=0)
         OR (line_type_code IN ('RAIL_FEE','TAX_WITHHELD','REFUND','REVERSAL')
           AND amount_base_micros>=0))
UNION ALL
SELECT 'DQ52','CASH_RECONCILIATION_STATE_EXACT_AND_FAIL_CLOSED',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM v_payment_delivery_chain
         WHERE (cash_reconciled_state='RECONCILED'
                AND (settlement_n<>1 OR reversal_n<>0
                  OR provider_net_micros<=0 OR bank_receipt_micros<=0
                  OR provider_net_micros<>bank_receipt_micros))
            OR (cash_reconciled_state<>'RECONCILED'
                AND settlement_n=1 AND reversal_n=0
                AND provider_net_micros>0
                AND provider_net_micros=bank_receipt_micros))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM v_payment_delivery_chain
        WHERE (cash_reconciled_state='RECONCILED'
               AND (settlement_n<>1 OR reversal_n<>0
                 OR provider_net_micros<=0 OR bank_receipt_micros<=0
                 OR provider_net_micros<>bank_receipt_micros))
           OR (cash_reconciled_state<>'RECONCILED'
               AND settlement_n=1 AND reversal_n=0
               AND provider_net_micros>0
               AND provider_net_micros=bank_receipt_micros))
UNION ALL
SELECT 'DQ53','COST_SCOPE_AND_ENVIRONMENT_MATCH',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM cost_event c JOIN request_observation r USING (request_id)
         WHERE c.machine_access_contract_id<>r.machine_access_contract_id
            OR c.environment<>r.environment) THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM cost_event c JOIN request_observation r USING (request_id)
        WHERE c.machine_access_contract_id<>r.machine_access_contract_id
           OR c.environment<>r.environment)
UNION ALL
SELECT 'DQ54','FOUNDER_TIME_COST_SHAPE',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM cost_event WHERE
           (cost_type_code='FOUNDER_TIME'
             AND (founder_minutes<=0 OR cash_cost_base_micros<>0))
           OR (cost_type_code<>'FOUNDER_TIME' AND founder_minutes<>0))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM cost_event WHERE
         (cost_type_code='FOUNDER_TIME'
           AND (founder_minutes<=0 OR cash_cost_base_micros<>0))
         OR (cost_type_code<>'FOUNDER_TIME' AND founder_minutes<>0))
UNION ALL
SELECT 'DQ55','RISK_OVERALL_RECONCILES_COMPONENTS',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM risk_review WHERE NOT (
           (overall_state='PASS' AND rights_state='PASS' AND security_state='PASS'
             AND privacy_state='PASS' AND tax_payment_state='PASS'
             AND human_search_guardrail_state='PASS')
           OR (overall_state='FAILED' AND 'FAILED' IN (
             rights_state,security_state,privacy_state,tax_payment_state,
             human_search_guardrail_state))
           OR (overall_state='UNKNOWN' AND 'FAILED' NOT IN (
             rights_state,security_state,privacy_state,tax_payment_state,
             human_search_guardrail_state)
             AND 'UNKNOWN' IN (rights_state,security_state,privacy_state,
                               tax_payment_state,human_search_guardrail_state))
           OR (overall_state='N/A' AND rights_state='N/A' AND security_state='N/A'
             AND privacy_state='N/A' AND tax_payment_state='N/A'
             AND human_search_guardrail_state='N/A')))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM risk_review WHERE NOT (
         (overall_state='PASS' AND rights_state='PASS' AND security_state='PASS'
           AND privacy_state='PASS' AND tax_payment_state='PASS'
           AND human_search_guardrail_state='PASS')
         OR (overall_state='FAILED' AND 'FAILED' IN (
           rights_state,security_state,privacy_state,tax_payment_state,
           human_search_guardrail_state))
         OR (overall_state='UNKNOWN' AND 'FAILED' NOT IN (
           rights_state,security_state,privacy_state,tax_payment_state,
           human_search_guardrail_state)
           AND 'UNKNOWN' IN (rights_state,security_state,privacy_state,
                             tax_payment_state,human_search_guardrail_state))
         OR (overall_state='N/A' AND rights_state='N/A' AND security_state='N/A'
           AND privacy_state='N/A' AND tax_payment_state='N/A'
           AND human_search_guardrail_state='N/A')))
UNION ALL
SELECT 'DQ56','DECISION_USES_LATEST_RISK_REVIEW',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM decision_snapshot d JOIN risk_review r USING (risk_review_id)
         WHERE EXISTS (SELECT 1 FROM risk_review n
                       WHERE n.machine_access_contract_id=d.machine_access_contract_id
                         AND n.review_sequence>r.review_sequence
                         AND datetime(n.recorded_at)<=datetime(d.evidence_cutoff_at)))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM decision_snapshot d JOIN risk_review r USING (risk_review_id)
        WHERE EXISTS (SELECT 1 FROM risk_review n
                      WHERE n.machine_access_contract_id=d.machine_access_contract_id
                        AND n.review_sequence>r.review_sequence
                        AND datetime(n.recorded_at)<=datetime(d.evidence_cutoff_at)))
UNION ALL
SELECT 'DQ57','DECISION_METRICS_RECONCILE_TO_SOURCE_FACTS',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM decision_snapshot d
         JOIN v_mature_machine_unit_economics e USING (machine_access_contract_id)
         WHERE d.mature_request_n<>e.mature_request_n
            OR d.verified_request_n<>e.verified_request_n
            OR d.verified_eligible_request_n<>e.verified_eligible_request_n
            OR d.rights_risk_pass_request_n<>e.rights_risk_pass_request_n
            OR d.challenged_request_n<>e.challenged_request_n
            OR d.authorized_request_n<>e.authorized_request_n
            OR d.payment_proof_verified_request_n<>
               e.payment_proof_verified_request_n
            OR d.settled_request_n<>e.settled_request_n
            OR d.entitled_request_n<>e.entitled_request_n
            OR d.not_revoked_entitlement_request_n<>
               e.not_revoked_entitlement_request_n
            OR d.delivered_request_n<>e.delivered_request_n
            OR d.accepted_request_n<>e.accepted_request_n
            OR d.cash_reconciled_request_n<>e.cash_reconciled_request_n
            OR d.contribution_eligible_request_n<>
               e.contribution_eligible_request_n
            OR d.reversed_request_n<>e.reversed_request_n
            OR d.bank_or_wallet_cash_micros<>e.bank_or_wallet_cash_micros
            OR d.cash_cost_micros<>e.cash_cost_micros
            OR d.founder_minutes<>e.founder_minutes
            OR d.founder_time_cost_micros<>e.founder_time_cost_micros
            OR d.matured_incremental_machine_contribution_micros<>
               e.matured_incremental_machine_contribution_micros)
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM decision_snapshot d
        JOIN v_mature_machine_unit_economics e USING (machine_access_contract_id)
        WHERE d.mature_request_n<>e.mature_request_n
           OR d.verified_request_n<>e.verified_request_n
           OR d.verified_eligible_request_n<>e.verified_eligible_request_n
           OR d.rights_risk_pass_request_n<>e.rights_risk_pass_request_n
           OR d.challenged_request_n<>e.challenged_request_n
           OR d.authorized_request_n<>e.authorized_request_n
           OR d.payment_proof_verified_request_n<>
              e.payment_proof_verified_request_n
           OR d.settled_request_n<>e.settled_request_n
           OR d.entitled_request_n<>e.entitled_request_n
           OR d.not_revoked_entitlement_request_n<>
              e.not_revoked_entitlement_request_n
           OR d.delivered_request_n<>e.delivered_request_n
           OR d.accepted_request_n<>e.accepted_request_n
           OR d.cash_reconciled_request_n<>e.cash_reconciled_request_n
           OR d.contribution_eligible_request_n<>
              e.contribution_eligible_request_n
           OR d.reversed_request_n<>e.reversed_request_n
           OR d.bank_or_wallet_cash_micros<>e.bank_or_wallet_cash_micros
           OR d.cash_cost_micros<>e.cash_cost_micros
           OR d.founder_minutes<>e.founder_minutes
           OR d.founder_time_cost_micros<>e.founder_time_cost_micros
           OR d.matured_incremental_machine_contribution_micros<>
              e.matured_incremental_machine_contribution_micros)
UNION ALL
SELECT 'DQ58','EXPAND_IS_BOUNDED_CURRENT_CLEAN_AND_PROFITABLE',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM v_current_decision_gate
         WHERE decision_state='EXPAND' AND computed_gate<>'READY_BOUNDED_EXPAND')
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM v_current_decision_gate
        WHERE decision_state='EXPAND' AND computed_gate<>'READY_BOUNDED_EXPAND')
UNION ALL
SELECT 'DQ59','TEST_NEVER_ENTERS_REAL_ECONOMICS',
       CASE WHEN EXISTS (
         SELECT 1 FROM v_mature_machine_unit_economics
         WHERE machine_access_contract_id='MAC_TEST_V1'
           AND mature_request_n=0 AND verified_request_n=0
           AND challenged_request_n=0 AND settled_request_n=0
           AND bank_or_wallet_cash_micros=0
           AND matured_incremental_machine_contribution_micros=0)
       THEN 'PASS' ELSE 'FAIL' END,
       CASE WHEN EXISTS (
         SELECT 1 FROM v_mature_machine_unit_economics
         WHERE machine_access_contract_id='MAC_TEST_V1'
           AND mature_request_n=0 AND verified_request_n=0
           AND challenged_request_n=0 AND settled_request_n=0
           AND bank_or_wallet_cash_micros=0
           AND matured_incremental_machine_contribution_micros=0)
       THEN 0 ELSE 1 END
UNION ALL
SELECT 'DQ60','TWENTY_FIVE_NEGATIVE_PROBES_REJECTED_AND_CONTEXT_CLOSED',
       CASE WHEN (SELECT count(*) FROM negative_probe_result)=25
                  AND (SELECT count(*) FROM negative_probe_result
                       WHERE status='PASS')=25
                  AND (SELECT count(*) FROM negative_probe_context)=0
            THEN 'PASS' ELSE 'FAIL' END,
       abs(25-(SELECT count(*) FROM negative_probe_result))
         +(SELECT count(*) FROM negative_probe_result WHERE status<>'PASS')
         +(SELECT count(*) FROM negative_probe_context)
UNION ALL
SELECT 'DQ61','SETTLEMENT_ONLY_MATURE_UNIT_EXCLUDED',
       CASE WHEN EXISTS (
         SELECT 1 FROM v_payment_delivery_chain
         WHERE request_id='REQ_NEG_SETTLEMENT_ONLY'
           AND authorization_n=1 AND settlement_n=1
           AND verified_payment_proof_n=1 AND delivered_n=0 AND accepted_n=0
           AND cash_reconciled_state='UNRECONCILED')
       THEN 'PASS' ELSE 'FAIL' END,
       CASE WHEN EXISTS (
         SELECT 1 FROM v_payment_delivery_chain
         WHERE request_id='REQ_NEG_SETTLEMENT_ONLY'
           AND authorization_n=1 AND settlement_n=1
           AND verified_payment_proof_n=1 AND delivered_n=0 AND accepted_n=0
           AND cash_reconciled_state='UNRECONCILED') THEN 0 ELSE 1 END
UNION ALL
SELECT 'DQ62','DELIVERED_NOT_ACCEPTED_MATURE_UNIT_EXCLUDED',
       CASE WHEN EXISTS (
         SELECT 1 FROM v_payment_delivery_chain
         WHERE request_id='REQ_NEG_DELIVERED' AND delivery_entitlement_valid_n=1
           AND delivered_n=1 AND accepted_n=0
           AND cash_reconciled_state='RECONCILED')
       THEN 'PASS' ELSE 'FAIL' END,
       CASE WHEN EXISTS (
         SELECT 1 FROM v_payment_delivery_chain
         WHERE request_id='REQ_NEG_DELIVERED' AND delivery_entitlement_valid_n=1
           AND delivered_n=1 AND accepted_n=0
           AND cash_reconciled_state='RECONCILED') THEN 0 ELSE 1 END
UNION ALL
SELECT 'DQ63','CASH_UNRECONCILED_ACCEPTED_UNIT_EXCLUDED',
       CASE WHEN EXISTS (
         SELECT 1 FROM v_payment_delivery_chain
         WHERE request_id='REQ_NEG_CASH' AND delivered_n=1 AND accepted_n=1
           AND provider_net_micros=45000 AND bank_receipt_micros=0
           AND cash_reconciled_state='UNRECONCILED')
       THEN 'PASS' ELSE 'FAIL' END,
       CASE WHEN EXISTS (
         SELECT 1 FROM v_payment_delivery_chain
         WHERE request_id='REQ_NEG_CASH' AND delivered_n=1 AND accepted_n=1
           AND provider_net_micros=45000 AND bank_receipt_micros=0
           AND cash_reconciled_state='UNRECONCILED') THEN 0 ELSE 1 END
UNION ALL
SELECT 'DQ64','TEST_FULL_CHAIN_CANNOT_CONTAMINATE_REAL_KPI',
       CASE WHEN EXISTS (SELECT 1 FROM payment_event
                         WHERE request_id='REQ_TEST' AND event_type_code='SETTLEMENT')
                  AND EXISTS (SELECT 1 FROM accepted_outcome_event
                              WHERE request_id='REQ_TEST' AND outcome_state='ACCEPTED')
                  AND EXISTS (
                    SELECT 1 FROM v_mature_machine_unit_economics
                    WHERE machine_access_contract_id='MAC_TEST_V1'
                      AND mature_request_n=0
                      AND contribution_eligible_request_n=0
                      AND matured_incremental_machine_contribution_micros=0)
       THEN 'PASS' ELSE 'FAIL' END,
       CASE WHEN EXISTS (SELECT 1 FROM payment_event
                         WHERE request_id='REQ_TEST' AND event_type_code='SETTLEMENT')
                  AND EXISTS (SELECT 1 FROM accepted_outcome_event
                              WHERE request_id='REQ_TEST' AND outcome_state='ACCEPTED')
                  AND EXISTS (
                    SELECT 1 FROM v_mature_machine_unit_economics
                    WHERE machine_access_contract_id='MAC_TEST_V1'
                      AND mature_request_n=0
                      AND contribution_eligible_request_n=0
                      AND matured_incremental_machine_contribution_micros=0)
            THEN 0 ELSE 1 END
UNION ALL
SELECT 'DQ65','PROOF_EXACT_TUPLE_CURRENT_AND_CONSUMED_ONCE_BY_AUTH',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM payment_proof q JOIN challenge_receipt h
           ON h.challenge_id=q.proof_covered_challenge_id
         JOIN payment_offer_version o ON o.payment_offer_id=h.payment_offer_id
         WHERE h.request_id<>q.proof_covered_request_id
            OR h.environment<>q.environment
            OR q.payment_offer_id<>o.payment_offer_id
            OR q.payment_offer_version<>o.offer_version
            OR q.amount_atomic<>h.amount_atomic
            OR q.amount_atomic<>o.amount_atomic
            OR q.asset_code<>h.asset_code OR q.asset_code<>o.asset_code
            OR o.network_scope_code<>q.network_scope_code
            OR o.recipient_ref_hash<>q.recipient_ref_hash
            OR h.network_scope_code<>q.network_scope_code
            OR h.recipient_ref_hash<>q.recipient_ref_hash
            OR h.principal_ref_hash<>q.principal_ref_hash
            OR h.purpose_scope_code<>q.purpose_scope_code
            OR h.rights_scope_ref_hash<>q.rights_scope_ref_hash
            OR h.entitlement_scope_ref_hash<>q.entitlement_scope_ref_hash
            OR h.request_method_code<>q.request_method_code
            OR h.canonical_target_ref_hash<>q.canonical_target_ref_hash
            OR h.request_body_digest_hash<>q.request_body_digest_hash
            OR h.server_expected_tuple_hash<>q.presented_tuple_hash
            OR h.challenge_state<>'ISSUED'
            OR datetime(q.verified_at)<datetime(h.issued_at)
            OR datetime(q.verified_at)<datetime(h.recorded_at)
            OR datetime(q.verified_at)>=datetime(h.expires_at))
         AND NOT EXISTS (
           SELECT q.payment_proof_id FROM payment_proof q
           LEFT JOIN payment_event p USING (payment_proof_id)
           GROUP BY q.payment_proof_id
           HAVING count(p.payment_event_id)<>1
              OR max(p.event_type_code)<>'AUTHORIZATION')
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM payment_proof q JOIN challenge_receipt h
          ON h.challenge_id=q.proof_covered_challenge_id
        JOIN payment_offer_version o ON o.payment_offer_id=h.payment_offer_id
        WHERE h.request_id<>q.proof_covered_request_id
           OR h.environment<>q.environment
           OR q.payment_offer_id<>o.payment_offer_id
           OR q.payment_offer_version<>o.offer_version
           OR q.amount_atomic<>h.amount_atomic
           OR q.amount_atomic<>o.amount_atomic
           OR q.asset_code<>h.asset_code OR q.asset_code<>o.asset_code
           OR o.network_scope_code<>q.network_scope_code
           OR o.recipient_ref_hash<>q.recipient_ref_hash
           OR h.network_scope_code<>q.network_scope_code
           OR h.recipient_ref_hash<>q.recipient_ref_hash
           OR h.principal_ref_hash<>q.principal_ref_hash
           OR h.purpose_scope_code<>q.purpose_scope_code
           OR h.rights_scope_ref_hash<>q.rights_scope_ref_hash
           OR h.entitlement_scope_ref_hash<>q.entitlement_scope_ref_hash
           OR h.request_method_code<>q.request_method_code
           OR h.canonical_target_ref_hash<>q.canonical_target_ref_hash
           OR h.request_body_digest_hash<>q.request_body_digest_hash
           OR h.server_expected_tuple_hash<>q.presented_tuple_hash
           OR h.challenge_state<>'ISSUED'
           OR datetime(q.verified_at)<datetime(h.issued_at)
           OR datetime(q.verified_at)<datetime(h.recorded_at)
           OR datetime(q.verified_at)>=datetime(h.expires_at))
       +(SELECT count(*) FROM (
          SELECT q.payment_proof_id FROM payment_proof q
          LEFT JOIN payment_event p USING (payment_proof_id)
          GROUP BY q.payment_proof_id
          HAVING count(p.payment_event_id)<>1
             OR max(p.event_type_code)<>'AUTHORIZATION'))
UNION ALL
SELECT 'DQ66','ACCEPTED_OUTCOME_EXACT_APPEND_ONLY_CORRECTION_CHAIN',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM accepted_outcome_event a
         JOIN delivery_event d USING (delivery_event_id)
         JOIN evidence_record e ON e.evidence_id=a.evidence_id
         LEFT JOIN accepted_outcome_event p
           ON p.accepted_outcome_event_id=a.predecessor_accepted_outcome_event_id
         WHERE a.request_id<>d.request_id
            OR a.machine_access_contract_id<>d.machine_access_contract_id
            OR a.environment<>d.environment OR d.delivery_state<>'DELIVERED'
            OR e.evidence_domain<>'ACCEPTED_OUTCOME' OR e.evidence_rank<4
            OR (a.event_sequence>1 AND (p.delivery_event_id<>a.delivery_event_id
              OR p.request_id<>a.request_id
              OR p.event_sequence<>a.event_sequence-1)))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM accepted_outcome_event a
        JOIN delivery_event d USING (delivery_event_id)
        JOIN evidence_record e ON e.evidence_id=a.evidence_id
        LEFT JOIN accepted_outcome_event p
          ON p.accepted_outcome_event_id=a.predecessor_accepted_outcome_event_id
        WHERE a.request_id<>d.request_id
           OR a.machine_access_contract_id<>d.machine_access_contract_id
           OR a.environment<>d.environment OR d.delivery_state<>'DELIVERED'
           OR e.evidence_domain<>'ACCEPTED_OUTCOME' OR e.evidence_rank<4
           OR (a.event_sequence>1 AND (p.delivery_event_id<>a.delivery_event_id
             OR p.request_id<>a.request_id
             OR p.event_sequence<>a.event_sequence-1)))
UNION ALL
SELECT 'DQ67','ALL_CHAIN_EVIDENCE_ENVIRONMENT_DOMAIN_AND_RANK_EXACT',
       CASE WHEN NOT EXISTS (SELECT 1 FROM v_evidence_chain_violations)
            THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM v_evidence_chain_violations)
UNION ALL
SELECT 'DQ68','CATEGORICAL_RESULT_ENUMS_NEVER_USE_NUMERIC_ZERO',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM sqlite_schema
         WHERE type='table' AND name IN (
           'actor_identity_observation','request_observation','challenge_receipt',
           'payment_proof','payment_event','entitlement_event','delivery_event',
           'accepted_outcome_event') AND sql GLOB "*'0'*")
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM sqlite_schema
        WHERE type='table' AND name IN (
          'actor_identity_observation','request_observation','challenge_receipt',
          'payment_proof','payment_event','entitlement_event','delivery_event',
          'accepted_outcome_event') AND sql GLOB "*'0'*")
UNION ALL
SELECT 'DQ69','NON_REQUEST_VALUES_REASONED_NA_ZERO_AND_INCLUSIVE_UNKNOWN',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM v_mature_machine_unit_economics
         WHERE license_value_micros<>0 OR referral_value_micros<>0
            OR cannibalization_value_micros<>0
            OR non_request_value_support_state<>'N/A_REASON_NOT_MODELED'
            OR kpi_scope_code<>'PER_REQUEST_PAID_ACCESS_ONLY'
            OR inclusive_profit_state<>'UNKNOWN_NOT_COMPUTED')
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM v_mature_machine_unit_economics
        WHERE license_value_micros<>0 OR referral_value_micros<>0
           OR cannibalization_value_micros<>0
           OR non_request_value_support_state<>'N/A_REASON_NOT_MODELED'
           OR kpi_scope_code<>'PER_REQUEST_PAID_ACCESS_ONLY'
           OR inclusive_profit_state<>'UNKNOWN_NOT_COMPUTED')
UNION ALL
SELECT 'DQ70','COHORT_COSTS_DEDUCTED_AND_PAID_FIXTURE_RECOMPUTES',
       CASE WHEN EXISTS (
         SELECT 1 FROM v_mature_machine_unit_economics
         WHERE machine_access_contract_id='MAC_NEG_V1'
           AND contribution_eligible_request_n=0 AND cash_cost_micros=2000
           AND founder_minutes=1 AND founder_time_cost_micros=1000
           AND matured_incremental_machine_contribution_micros=-3000)
         AND EXISTS (
           SELECT 1 FROM v_mature_machine_unit_economics
           WHERE machine_access_contract_id='MAC_PAID_V1'
             AND bank_or_wallet_cash_micros=45000 AND cash_cost_micros=10000
             AND founder_time_cost_micros=10000
             AND matured_incremental_machine_contribution_micros=25000)
       THEN 'PASS' ELSE 'FAIL' END,
       CASE WHEN EXISTS (
         SELECT 1 FROM v_mature_machine_unit_economics
         WHERE machine_access_contract_id='MAC_NEG_V1'
           AND contribution_eligible_request_n=0 AND cash_cost_micros=2000
           AND founder_minutes=1 AND founder_time_cost_micros=1000
           AND matured_incremental_machine_contribution_micros=-3000)
         AND EXISTS (
           SELECT 1 FROM v_mature_machine_unit_economics
           WHERE machine_access_contract_id='MAC_PAID_V1'
             AND bank_or_wallet_cash_micros=45000 AND cash_cost_micros=10000
             AND founder_time_cost_micros=10000
             AND matured_incremental_machine_contribution_micros=25000)
       THEN 0 ELSE 1 END
UNION ALL
SELECT 'DQ71','SETTLEMENT_AND_REVERSAL_SURVIVE_NULL_PROOF_LIFECYCLE_JOIN',
       CASE WHEN EXISTS (
         SELECT 1 FROM v_payment_delivery_chain
         WHERE request_id='REQ_PAID' AND settlement_n=1
           AND verified_payment_proof_n=1)
         AND EXISTS (
           SELECT 1 FROM v_payment_delivery_chain
           WHERE request_id='REQ_TEST' AND settlement_n=1 AND reversal_n=1)
       THEN 'PASS' ELSE 'FAIL' END,
       CASE WHEN EXISTS (
         SELECT 1 FROM v_payment_delivery_chain
         WHERE request_id='REQ_PAID' AND settlement_n=1
           AND verified_payment_proof_n=1)
         AND EXISTS (
           SELECT 1 FROM v_payment_delivery_chain
           WHERE request_id='REQ_TEST' AND settlement_n=1 AND reversal_n=1)
       THEN 0 ELSE 1 END
UNION ALL
SELECT 'DQ72','EXPAND_REQUIRES_FULL_MATURE_AND_CURRENT_GATE_SET',
       CASE WHEN EXISTS (
         SELECT 1 FROM v_current_decision_gate
         WHERE machine_access_contract_id='MAC_PAID_V1'
           AND mature_request_n=1 AND verified_eligible_request_n=1
           AND rights_risk_pass_request_n=1 AND challenged_request_n=1
           AND authorized_request_n=1 AND payment_proof_verified_request_n=1
           AND settled_request_n=1 AND entitled_request_n=1
           AND not_revoked_entitlement_request_n=1 AND delivered_request_n=1
           AND accepted_request_n=1 AND cash_reconciled_request_n=1
           AND contribution_eligible_request_n=1 AND reversed_request_n=0
           AND computed_gate='READY_BOUNDED_EXPAND')
       THEN 'PASS' ELSE 'FAIL' END,
       CASE WHEN EXISTS (
         SELECT 1 FROM v_current_decision_gate
         WHERE machine_access_contract_id='MAC_PAID_V1'
           AND mature_request_n=1 AND verified_eligible_request_n=1
           AND rights_risk_pass_request_n=1 AND challenged_request_n=1
           AND authorized_request_n=1 AND payment_proof_verified_request_n=1
           AND settled_request_n=1 AND entitled_request_n=1
           AND not_revoked_entitlement_request_n=1 AND delivered_request_n=1
           AND accepted_request_n=1 AND cash_reconciled_request_n=1
           AND contribution_eligible_request_n=1 AND reversed_request_n=0
           AND computed_gate='READY_BOUNDED_EXPAND') THEN 0 ELSE 1 END
UNION ALL
SELECT 'DQ73','AUTHORITATIVE_OFFER_AND_STRUCTURED_PROOF_BINDING',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM payment_proof q
         JOIN challenge_receipt h
           ON h.challenge_id=q.proof_covered_challenge_id
         JOIN request_observation r ON r.request_id=h.request_id
         JOIN payment_offer_version o ON o.payment_offer_id=h.payment_offer_id
         WHERE q.proof_covered_request_id<>r.request_id
            OR q.payment_offer_id<>o.payment_offer_id
            OR q.payment_offer_version<>o.offer_version
            OR q.amount_atomic<>h.amount_atomic
            OR q.amount_atomic<>o.amount_atomic
            OR q.asset_code<>h.asset_code OR q.asset_code<>o.asset_code
            OR q.network_scope_code<>h.network_scope_code
            OR q.network_scope_code<>o.network_scope_code
            OR q.network_scope_code<>r.network_scope_code
            OR q.recipient_ref_hash<>h.recipient_ref_hash
            OR q.recipient_ref_hash<>o.recipient_ref_hash
            OR q.recipient_ref_hash<>r.recipient_ref_hash)
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM payment_proof q
        JOIN challenge_receipt h
          ON h.challenge_id=q.proof_covered_challenge_id
        JOIN request_observation r ON r.request_id=h.request_id
        JOIN payment_offer_version o ON o.payment_offer_id=h.payment_offer_id
        WHERE q.proof_covered_request_id<>r.request_id
           OR q.payment_offer_id<>o.payment_offer_id
           OR q.payment_offer_version<>o.offer_version
           OR q.amount_atomic<>h.amount_atomic
           OR q.amount_atomic<>o.amount_atomic
           OR q.asset_code<>h.asset_code OR q.asset_code<>o.asset_code
           OR q.network_scope_code<>h.network_scope_code
           OR q.network_scope_code<>o.network_scope_code
           OR q.network_scope_code<>r.network_scope_code
           OR q.recipient_ref_hash<>h.recipient_ref_hash
           OR q.recipient_ref_hash<>o.recipient_ref_hash
           OR q.recipient_ref_hash<>r.recipient_ref_hash)
UNION ALL
SELECT 'DQ74','CAUSAL_CLOCKS_AND_LATE_ACCEPTANCE_SNAPSHOT',
       CASE WHEN NOT EXISTS (SELECT 1 FROM v_causal_clock_violations)
         AND EXISTS (
           SELECT 1 FROM accepted_outcome_event a
           JOIN v_payment_delivery_chain c USING (request_id)
           WHERE a.accepted_outcome_event_id='ACC_T'
             AND datetime(a.recorded_at)>datetime(a.maturity_at)
             AND c.accepted_n=1)
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM v_causal_clock_violations)
       +CASE WHEN EXISTS (
          SELECT 1 FROM accepted_outcome_event a
          JOIN v_payment_delivery_chain c USING (request_id)
          WHERE a.accepted_outcome_event_id='ACC_T'
            AND datetime(a.recorded_at)>datetime(a.maturity_at)
            AND c.accepted_n=1) THEN 0 ELSE 1 END
UNION ALL
SELECT 'DQ75','CASH_GROSS_FX_AND_OWNER_INDEPENDENT_COMPONENT_IDEMPOTENCY',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM cash_bridge_line c
         JOIN payment_event p USING (payment_event_id)
         JOIN challenge_receipt h USING (challenge_id)
         JOIN payment_offer_version o USING (payment_offer_id)
         WHERE c.line_type_code='GROSS_SETTLED'
           AND c.amount_base_micros<>o.base_currency_value_micros)
         AND NOT EXISTS (
           SELECT 1 FROM cash_bridge_line
           WHERE (line_type_code='FX_ADJUSTMENT' AND (
                    fx_policy_code<>'FX_ADJUSTMENT_TO_BASE'
                    OR fx_basis_ref_hash IS NULL))
              OR (line_type_code<>'FX_ADJUSTMENT' AND (
                    fx_policy_code<>'BASE_CURRENCY_NO_FX'
                    OR fx_basis_ref_hash IS NOT NULL)))
         AND NOT EXISTS (
           SELECT payment_event_id,line_type_code
           FROM cash_bridge_line
           GROUP BY payment_event_id,line_type_code
           HAVING count(*)<>1)
         AND EXISTS (
           SELECT 1 FROM sqlite_schema
           WHERE type='index' AND name='one_cash_component_per_payment'
             AND sql LIKE 'CREATE UNIQUE INDEX%')
         AND (SELECT count(*) FROM pragma_index_info(
                'one_cash_component_per_payment'))=2
         AND EXISTS (
           SELECT 1 FROM pragma_index_info('one_cash_component_per_payment')
           WHERE name='payment_event_id')
         AND EXISTS (
           SELECT 1 FROM pragma_index_info('one_cash_component_per_payment')
           WHERE name='line_type_code')
         AND NOT EXISTS (
           SELECT 1 FROM pragma_index_info('one_cash_component_per_payment')
           WHERE name='commercial_owner_key')
         AND EXISTS (
           SELECT 1 FROM cash_bridge_line
           WHERE cash_line_id='CASH_PX' AND line_type_code='FX_ADJUSTMENT'
             AND amount_base_micros=1000
             AND fx_policy_code='FX_ADJUSTMENT_TO_BASE'
             AND length(fx_basis_ref_hash)=64)
         AND EXISTS (
           SELECT 1 FROM v_payment_delivery_chain
           WHERE request_id='REQ_PAID' AND provider_net_micros=45000
             AND bank_receipt_micros=45000
             AND cash_reconciled_state='RECONCILED')
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM cash_bridge_line c
        JOIN payment_event p USING (payment_event_id)
        JOIN challenge_receipt h USING (challenge_id)
        JOIN payment_offer_version o USING (payment_offer_id)
        WHERE c.line_type_code='GROSS_SETTLED'
          AND c.amount_base_micros<>o.base_currency_value_micros)
       +(SELECT count(*) FROM cash_bridge_line
         WHERE (line_type_code='FX_ADJUSTMENT' AND (
                  fx_policy_code<>'FX_ADJUSTMENT_TO_BASE'
                  OR fx_basis_ref_hash IS NULL))
            OR (line_type_code<>'FX_ADJUSTMENT' AND (
                  fx_policy_code<>'BASE_CURRENCY_NO_FX'
                  OR fx_basis_ref_hash IS NOT NULL)))
       +(SELECT count(*) FROM (
         SELECT payment_event_id,line_type_code
         FROM cash_bridge_line
         GROUP BY payment_event_id,line_type_code
         HAVING count(*)<>1))
       +CASE WHEN EXISTS (
          SELECT 1 FROM sqlite_schema
          WHERE type='index' AND name='one_cash_component_per_payment'
            AND sql LIKE 'CREATE UNIQUE INDEX%')
         AND (SELECT count(*) FROM pragma_index_info(
                'one_cash_component_per_payment'))=2
         AND EXISTS (
          SELECT 1 FROM pragma_index_info('one_cash_component_per_payment')
          WHERE name='payment_event_id')
         AND EXISTS (
          SELECT 1 FROM pragma_index_info('one_cash_component_per_payment')
          WHERE name='line_type_code')
         AND NOT EXISTS (
          SELECT 1 FROM pragma_index_info('one_cash_component_per_payment')
          WHERE name='commercial_owner_key') THEN 0 ELSE 1 END
       +CASE WHEN EXISTS (
          SELECT 1 FROM cash_bridge_line
          WHERE cash_line_id='CASH_PX' AND line_type_code='FX_ADJUSTMENT'
            AND amount_base_micros=1000
            AND fx_policy_code='FX_ADJUSTMENT_TO_BASE'
            AND length(fx_basis_ref_hash)=64) THEN 0 ELSE 1 END
       +CASE WHEN EXISTS (
          SELECT 1 FROM v_payment_delivery_chain
          WHERE request_id='REQ_PAID' AND provider_net_micros=45000
            AND bank_receipt_micros=45000
            AND cash_reconciled_state='RECONCILED') THEN 0 ELSE 1 END
UNION ALL
SELECT 'DQ76','DECISION_CLOCKS_RAW_RISK_AND_CURRENT_POLICY',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM decision_snapshot d
         JOIN machine_access_contract m USING (machine_access_contract_id)
         JOIN risk_review r USING (risk_review_id)
         JOIN evidence_record e ON e.evidence_id=d.evidence_id
         WHERE datetime(d.evidence_cutoff_at)<>datetime(d.snapshot_as_of)
            OR datetime(d.maturity_at)<>datetime(m.maturity_at)
            OR datetime(d.maturity_at)>datetime(d.snapshot_as_of)
            OR datetime(d.snapshot_as_of)>datetime(d.decided_at)
            OR datetime(d.decided_at)>datetime(m.decision_due_at)
            OR datetime(e.recorded_at)>datetime(d.evidence_cutoff_at)
            OR datetime(r.recorded_at)>datetime(d.evidence_cutoff_at)
            OR (r.overall_state='FAILED' AND d.decision_state<>'STOP')
            OR (r.overall_state='UNKNOWN' AND d.decision_state NOT IN (
                  'STOP','PAUSE','UNKNOWN','INCONCLUSIVE'))
            OR NOT EXISTS (
              SELECT 1 FROM traffic_policy_version p
              WHERE p.machine_access_contract_id=d.machine_access_contract_id
                AND p.action_mode_code=d.action_mode_code
                AND datetime(p.effective_from)<=datetime(d.snapshot_as_of)
                AND (p.effective_until IS NULL OR datetime(d.snapshot_as_of)<
                     datetime(p.effective_until))))
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM decision_snapshot d
        JOIN machine_access_contract m USING (machine_access_contract_id)
        JOIN risk_review r USING (risk_review_id)
        JOIN evidence_record e ON e.evidence_id=d.evidence_id
        WHERE datetime(d.evidence_cutoff_at)<>datetime(d.snapshot_as_of)
           OR datetime(d.maturity_at)<>datetime(m.maturity_at)
           OR datetime(d.maturity_at)>datetime(d.snapshot_as_of)
           OR datetime(d.snapshot_as_of)>datetime(d.decided_at)
           OR datetime(d.decided_at)>datetime(m.decision_due_at)
           OR datetime(e.recorded_at)>datetime(d.evidence_cutoff_at)
           OR datetime(r.recorded_at)>datetime(d.evidence_cutoff_at)
           OR (r.overall_state='FAILED' AND d.decision_state<>'STOP')
           OR (r.overall_state='UNKNOWN' AND d.decision_state NOT IN (
                 'STOP','PAUSE','UNKNOWN','INCONCLUSIVE'))
           OR NOT EXISTS (
             SELECT 1 FROM traffic_policy_version p
             WHERE p.machine_access_contract_id=d.machine_access_contract_id
               AND p.action_mode_code=d.action_mode_code
               AND datetime(p.effective_from)<=datetime(d.snapshot_as_of)
               AND (p.effective_until IS NULL OR datetime(d.snapshot_as_of)<
                    datetime(p.effective_until))))
UNION ALL
SELECT 'DQ77','ONE_SHOT_VALID_AT_DELIVERY_NO_LATER_TERMINAL_EVENT',
       CASE WHEN EXISTS (
         SELECT 1 FROM v_payment_delivery_chain
         WHERE request_id='REQ_PAID' AND delivery_entitlement_valid_n=1
           AND delivery_entitlement_not_revoked_n=1
           AND latest_entitlement_state='GRANTED'
           AND entitlement_time_state='EXPIRED' AND reversal_n=0
           AND accepted_n=1 AND cash_reconciled_state='RECONCILED')
         AND EXISTS (
           SELECT 1 FROM v_mature_machine_unit_economics
           WHERE machine_access_contract_id='MAC_PAID_V1'
             AND contribution_eligible_request_n=1)
         AND EXISTS (
           SELECT 1 FROM v_payment_delivery_chain
           WHERE request_id='REQ_TEST' AND delivery_entitlement_valid_n=1
             AND delivery_entitlement_not_revoked_n=0
             AND latest_entitlement_state='REVOKED' AND reversal_n=1)
         AND NOT EXISTS (
           SELECT 1 FROM v_payment_delivery_chain c
           JOIN delivery_event d USING (request_id)
           JOIN entitlement_event g
             ON g.entitlement_event_id=d.entitlement_event_id
           WHERE c.delivery_entitlement_not_revoked_n<>0
             AND EXISTS (
               SELECT 1 FROM entitlement_event n
               WHERE n.request_id=g.request_id
                 AND n.entitlement_ref_hash=g.entitlement_ref_hash
                 AND n.event_sequence>g.event_sequence
                 AND n.entitlement_state='REVOKED'))
       THEN 'PASS' ELSE 'FAIL' END,
       CASE WHEN EXISTS (
          SELECT 1 FROM v_payment_delivery_chain
          WHERE request_id='REQ_PAID' AND delivery_entitlement_valid_n=1
            AND delivery_entitlement_not_revoked_n=1
            AND latest_entitlement_state='GRANTED'
            AND entitlement_time_state='EXPIRED' AND reversal_n=0
            AND accepted_n=1 AND cash_reconciled_state='RECONCILED')
         AND EXISTS (
          SELECT 1 FROM v_mature_machine_unit_economics
          WHERE machine_access_contract_id='MAC_PAID_V1'
            AND contribution_eligible_request_n=1)
         AND EXISTS (
          SELECT 1 FROM v_payment_delivery_chain
          WHERE request_id='REQ_TEST' AND delivery_entitlement_valid_n=1
            AND delivery_entitlement_not_revoked_n=0
            AND latest_entitlement_state='REVOKED' AND reversal_n=1)
         AND NOT EXISTS (
          SELECT 1 FROM v_payment_delivery_chain c
          JOIN delivery_event d USING (request_id)
          JOIN entitlement_event g
            ON g.entitlement_event_id=d.entitlement_event_id
          WHERE c.delivery_entitlement_not_revoked_n<>0
            AND EXISTS (
              SELECT 1 FROM entitlement_event n
              WHERE n.request_id=g.request_id
                AND n.entitlement_ref_hash=g.entitlement_ref_hash
                AND n.event_sequence>g.event_sequence
                AND n.entitlement_state='REVOKED'))
       THEN 0 ELSE 1 END
UNION ALL
SELECT 'DQ78','NO_DEAD_CHALLENGE_OR_PROOF_STATES',
       CASE WHEN instr((SELECT sql FROM sqlite_schema
                         WHERE type='table' AND name='challenge_receipt'),
                       '''EXPIRED''')=0
         AND instr((SELECT sql FROM sqlite_schema
                     WHERE type='table' AND name='payment_proof'),
                   'verification_state=''VERIFIED''')>0
         AND instr((SELECT sql FROM sqlite_schema
                     WHERE type='table' AND name='payment_event'),
                   '''EXPIRY''')>0
         AND NOT EXISTS (SELECT 1 FROM payment_proof
                         WHERE verification_state<>'VERIFIED')
       THEN 'PASS' ELSE 'FAIL' END,
       CASE WHEN instr((SELECT sql FROM sqlite_schema
                         WHERE type='table' AND name='challenge_receipt'),
                       '''EXPIRED''')=0
         AND instr((SELECT sql FROM sqlite_schema
                     WHERE type='table' AND name='payment_proof'),
                   'verification_state=''VERIFIED''')>0
         AND instr((SELECT sql FROM sqlite_schema
                     WHERE type='table' AND name='payment_event'),
                   '''EXPIRY''')>0
         AND NOT EXISTS (SELECT 1 FROM payment_proof
                         WHERE verification_state<>'VERIFIED')
       THEN 0 ELSE 1 END
UNION ALL
SELECT 'DQ79','TOOL_ACTION_2XX_ZERO_BYTE_DELIVERY',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM delivery_event d
         JOIN request_observation r USING (request_id)
         JOIN resource_contract x USING (resource_contract_id)
         WHERE (x.resource_class_code='TOOL_ACTION'
                  AND d.delivery_kind_code<>'ACTION_RESULT')
            OR (x.resource_class_code<>'TOOL_ACTION'
                  AND d.delivery_kind_code<>'BYTE_RESOURCE')
            OR (d.delivery_state='DELIVERED'
                  AND d.delivery_kind_code='BYTE_RESOURCE'
                  AND d.delivered_bytes<=0))
         AND EXISTS (
           SELECT 1 FROM delivery_event d
           JOIN request_observation r USING (request_id)
           JOIN resource_contract x USING (resource_contract_id)
           WHERE d.delivery_event_id='DEL_T'
             AND x.resource_class_code='TOOL_ACTION'
             AND d.delivery_kind_code='ACTION_RESULT'
             AND d.response_status=204 AND d.delivered_bytes=0)
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM delivery_event d
        JOIN request_observation r USING (request_id)
        JOIN resource_contract x USING (resource_contract_id)
        WHERE (x.resource_class_code='TOOL_ACTION'
                 AND d.delivery_kind_code<>'ACTION_RESULT')
           OR (x.resource_class_code<>'TOOL_ACTION'
                 AND d.delivery_kind_code<>'BYTE_RESOURCE')
           OR (d.delivery_state='DELIVERED'
                 AND d.delivery_kind_code='BYTE_RESOURCE'
                 AND d.delivered_bytes<=0))
       +CASE WHEN EXISTS (
          SELECT 1 FROM delivery_event d
          JOIN request_observation r USING (request_id)
          JOIN resource_contract x USING (resource_contract_id)
          WHERE d.delivery_event_id='DEL_T'
            AND x.resource_class_code='TOOL_ACTION'
            AND d.delivery_kind_code='ACTION_RESULT'
            AND d.response_status=204 AND d.delivered_bytes=0)
        THEN 0 ELSE 1 END
UNION ALL
SELECT 'DQ80','HTTP_402_CHALLENGE_DOCUMENT_NOT_PROTECTED_RESOURCE',
       CASE WHEN NOT EXISTS (
         SELECT 1 FROM request_observation
         WHERE (applied_action_mode_code='HTTP_402' AND (
                  response_status<>402 OR protected_resource_bytes<>0
                  OR challenge_document_bytes<=0))
            OR (applied_action_mode_code<>'HTTP_402'
                  AND challenge_document_bytes<>0))
         AND EXISTS (
           SELECT 1 FROM request_observation
           WHERE request_id='REQ_PAID' AND response_status=402
             AND protected_resource_bytes=0 AND challenge_document_bytes=512)
       THEN 'PASS' ELSE 'FAIL' END,
       (SELECT count(*) FROM request_observation
        WHERE (applied_action_mode_code='HTTP_402' AND (
                 response_status<>402 OR protected_resource_bytes<>0
                 OR challenge_document_bytes<=0))
           OR (applied_action_mode_code<>'HTTP_402'
                 AND challenge_document_bytes<>0))
       +CASE WHEN EXISTS (
          SELECT 1 FROM request_observation
          WHERE request_id='REQ_PAID' AND response_status=402
            AND protected_resource_bytes=0 AND challenge_document_bytes=512)
        THEN 0 ELSE 1 END;

CREATE TEMP VIEW v_assertion_report AS
SELECT count(*) AS check_count,count(DISTINCT dq_id) AS distinct_check_count,
       sum(status='PASS') AS pass_count,sum(status='FAIL') AS failure_count,
       coalesce(sum(failing_row_count),0) AS failing_row_count
FROM v_dq_results;

CREATE TEMP TABLE assertion_guard (
  run_label TEXT PRIMARY KEY,
  check_count INTEGER NOT NULL CHECK (check_count=80),
  distinct_check_count INTEGER NOT NULL CHECK (distinct_check_count=80),
  failure_count INTEGER NOT NULL CHECK (failure_count=0),
  failing_row_count INTEGER NOT NULL CHECK (failing_row_count=0),
  negative_probe_count INTEGER NOT NULL CHECK (negative_probe_count>=25),
  negative_probe_pass_count INTEGER NOT NULL
    CHECK (negative_probe_pass_count=negative_probe_count)
) STRICT;

INSERT INTO assertion_guard
SELECT 'DQ01_DQ80',check_count,distinct_check_count,failure_count,
       failing_row_count,
       (SELECT count(*) FROM negative_probe_result),
       (SELECT count(*) FROM negative_probe_result WHERE status='PASS')
FROM v_assertion_report;

COMMIT;

-- ---------------------------------------------------------------------------
-- Bounded final receipts
-- ---------------------------------------------------------------------------

PRAGMA foreign_key_check;
PRAGMA integrity_check;

SELECT check_count,distinct_check_count,pass_count,failure_count,
       failing_row_count
FROM v_assertion_report;

SELECT probe_id,expected_rule_code,observed_rule_code,status,target_table
FROM negative_probe_result
ORDER BY probe_id
LIMIT (SELECT bounded_output_limit FROM model_setting WHERE singleton_id=1);

SELECT machine_access_contract_id,environment,mature_request_n,
       verified_request_n,verified_eligible_request_n,
       rights_risk_pass_request_n,challenged_request_n,authorized_request_n,
       payment_proof_verified_request_n,settled_request_n,entitled_request_n,
       not_revoked_entitlement_request_n,delivered_request_n,accepted_request_n,
       cash_reconciled_request_n,contribution_eligible_request_n,
       reversed_request_n,bank_or_wallet_cash_micros,cash_cost_micros,
       founder_minutes,founder_time_cost_micros,
       license_value_micros,referral_value_micros,cannibalization_value_micros,
       non_request_value_support_state,kpi_scope_code,inclusive_profit_state,
       matured_incremental_machine_contribution_micros
FROM v_mature_machine_unit_economics
ORDER BY machine_access_contract_id
LIMIT (SELECT bounded_output_limit FROM model_setting WHERE singleton_id=1);

SELECT machine_access_contract_id,decision_state,action_mode_code,risk_state,
       computed_gate,matured_incremental_machine_contribution_micros
FROM v_current_decision_gate
ORDER BY machine_access_contract_id
LIMIT (SELECT bounded_output_limit FROM model_setting WHERE singleton_id=1);

SELECT dq_id,check_name,status,failing_row_count
FROM v_dq_results
WHERE status='FAIL'
ORDER BY dq_id
LIMIT (SELECT bounded_output_limit FROM model_setting WHERE singleton_id=1);
