"""
Sweetbrier Eleven-Entry Bookkeeping — Production Engine v2 (`ledger_v2.py`).

Attestation: probabilistic_structural (Box Verified under Sweetbrier Master DAG)

Upgrades the v1 proof-of-concept (`ledger.py`) with production hardening:
  1. Code-Canonical Axis 11 = `forgiveness` (closing the book), with explicit
     `LEGACY_PROSE_AXIS_ALIASES` that fail loudly unless migration is opted in.
  2. One-Time Obligation Discharge & Provenance Conservation Ledger (`obligations`),
     blocking repeatable forgiveness replays and post-settlement forgiveness.
  3. Party-held asymmetric Ed25519 signatures (`cryptography`) + offline WebCrypto
     public JWK export — `BookV2` holds ZERO private keys.
  4. Offline Encrypted Keyfile Backup & Recovery Ritual (`Scrypt` + `AES-256-GCM`),
     enforcing the operational doctrine: "A lost keyfile is a lost identity."
  5. Freeze-at-posting immutable `EntryV2` (`@dataclass(frozen=True, slots=True)`),
     positive integer minor units (`amount_minor`, `unit`), UTC ISO-8601 `posted_at`,
     acyclic provenance terminating at `GENESIS`, symmetric version-drift diffs,
     and SQLite WAL append-only storage with `BEFORE UPDATE`/`BEFORE DELETE`
     abort triggers and SHA-256 hash chaining (`prev_chain_hash` -> `chain_hash`).
"""

from __future__ import annotations

import base64
import hashlib
import json
import math
import os
import sqlite3
import threading
import warnings
from dataclasses import dataclass, field, replace
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple, Union

from cryptography.exceptions import InvalidSignature, InvalidTag
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
    Ed25519PrivateKey,
    Ed25519PublicKey,
)
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt


SCHEMA_VERSION = "sweetbrier.11d.v2"
BACKUP_SCHEMA_VERSION = "sweetbrier.keybackup.v2"
SIGNING_DOMAIN = b"SWEETBRIER_11D_V2|"
GENESIS_CHAIN_HASH = "0" * 64
KEY_LOSS_DOCTRINE = (
    "A lost keyfile is a lost identity. Export and store your encrypted backup "
    "ritual file offline immediately; Sweetbrier / One Big Backend holds zero "
    "private keys and cannot recover a lost keyfile."
)

# Code-canonical 1-11 axis numbering (matches Entry dataclass layout in the wild;
# Forgiveness closes the book on Axis 11).
CANONICAL_AXES: Dict[int, str] = {
    1: "debit_account",
    2: "credit_account",
    3: "amount",
    4: "posted_at",
    5: "provenance",
    6: "author",
    7: "reason",
    8: "consent",
    9: "definition_version",
    10: "momentum",
    11: "forgiveness",
}

ENVELOPE_FIELDS: Tuple[str, ...] = (
    "entry_id",
    "unit",
    "discharges",
    "prev_chain_hash",
    "receipt_sha256",
    "chain_hash",
    "signatures",
)

# Explicit alias table documenting Oct 24 / Oct 30 prose ordering vs code-canonical Axis 11.
LEGACY_PROSE_AXIS_ALIASES: Dict[str, Dict[str, str]] = {
    "3. forgiveness": {
        "canonical_axis": "11. forgiveness",
        "canonical_field": "forgiveness",
        "status": "DEPRECATED_PROSE_ALIAS",
        "note": "Legacy Oct 24/30 whitepaper prose placed forgiveness at Axis 3; canonical v2 places forgiveness at Axis 11 (closing the book).",
    },
    "4. amount": {
        "canonical_axis": "3. amount",
        "canonical_field": "amount_minor",
        "status": "DEPRECATED_PROSE_ALIAS",
        "note": "Legacy prose numbered amount as Axis 4 after Axis 3 forgiveness.",
    },
    "index. posted_at": {
        "canonical_axis": "4. posted_at",
        "canonical_field": "posted_at",
        "status": "DEPRECATED_PROSE_ALIAS",
        "note": "Legacy prose treated posted_at as book index; canonical v2 numbers posted_at at Axis 4.",
    },
    "11. receipt": {
        "canonical_axis": "envelope.receipt_sha256",
        "canonical_field": "receipt_sha256",
        "status": "DEPRECATED_PROSE_ALIAS",
        "note": "In canonical v2, the countersigned receipt SHA-256 + Ed25519 signatures seal the entire 11-axis entry envelope.",
    },
}

VALID_FORGIVENESS_STATES = ("owed", "settled", "forgiven")


class Rejected(Exception):
    """Raised when an entry violates any deterministic Eleven-Entry invariant."""


class LegacyAxisAliasError(Rejected):
    """Raised when a legacy Axis-3 forgiveness document is presented without explicit migration."""


class LegacyAxisAliasWarning(UserWarning):
    """Emitted when a legacy Axis-3 forgiveness document is explicitly migrated to Axis 11."""


# --------------------------------------------------------------------------- helpers


def _b64u_encode(raw: bytes) -> str:
    return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")


def _canonical_json_dumps(obj: Any) -> str:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)


def _sha256_hex(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def _require_non_empty_str(val: Any, field_name: str) -> str:
    if not isinstance(val, str) or not val.strip():
        raise Rejected(f"{field_name} must be a non-empty string")
    return val.strip()


def _require_pos_int_minor(val: Any, field_name: str) -> int:
    if isinstance(val, bool) or not isinstance(val, int) or val <= 0:
        raise Rejected(
            f"{field_name} must be a strictly positive integer in minor units (got {val!r})"
        )
    return val


def _validate_iso8601_aware(val: Any, field_name: str = "posted_at") -> str:
    s = _require_non_empty_str(val, field_name)
    norm = s[:-1] + "+00:00" if s.endswith("Z") else s
    try:
        dt = datetime.fromisoformat(norm)
    except ValueError as exc:
        raise Rejected(f"Axis 4 ({field_name}) is not valid ISO-8601: {val!r}") from exc
    if dt.tzinfo is None or dt.utcoffset() is None:
        raise Rejected(
            f"Axis 4 ({field_name}) must include explicit UTC/timezone offset (got naive {val!r})"
        )
    return s


def _now_utc_iso() -> str:
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def resolve_entry_document(
    doc: Mapping[str, Any], *, allow_legacy_axis3_migration: bool = False
) -> Tuple[Dict[str, Any], List[str]]:
    """
    Detect legacy Axis-3 prose documents and resolve loudly to canonical Axis 11.

    By default (`allow_legacy_axis3_migration=False`), any document declaring or shaped
    with legacy `Axis 3 = forgiveness` / `Axis 11 = receipt` raises
    `LegacyAxisAliasError` so mismatches never slide silently. When migration is
    explicitly enabled, emits `LegacyAxisAliasWarning` and returns `(canonical_doc, notices)`.
    """
    if not isinstance(doc, Mapping):
        raise Rejected("Entry document must be a mapping")

    reasons: List[str] = []
    if doc.get("axis_map") in ("legacy_prose_axis3", "v1_prose"):
        reasons.append(f"axis_map={doc.get('axis_map')!r}")
    for legacy_key in LEGACY_PROSE_AXIS_ALIASES:
        if legacy_key in doc:
            alias_info = LEGACY_PROSE_AXIS_ALIASES[legacy_key]
            reasons.append(f"{legacy_key!r} -> {alias_info['canonical_axis']}")
    axes_block = doc.get("axes")
    if isinstance(axes_block, Mapping):
        ax3 = axes_block.get("3", axes_block.get(3))
        if ax3 in ("owed", "settled", "forgiven", "forgiveness") or (
            isinstance(ax3, str) and ax3.lower() == "forgiveness"
        ):
            reasons.append("axes['3'] encodes legacy Axis 3 forgiveness (now Axis 11)")

    if reasons and not allow_legacy_axis3_migration:
        raise LegacyAxisAliasError(
            "Legacy Axis-3 prose schema detected ("
            + "; ".join(reasons)
            + "). Canonical v2 standardizes on Axis 11 = forgiveness. "
            "Pass allow_legacy_axis3_migration=True to migrate loudly."
        )

    out: Dict[str, Any] = dict(doc)
    notices: List[str] = []

    if reasons:
        if "3. forgiveness" in out:
            out["forgiveness"] = out.pop("3. forgiveness")
        if "4. amount" in out:
            raw_amt = out.pop("4. amount")
            out.setdefault("amount_minor", raw_amt)
        if "index. posted_at" in out:
            out["posted_at"] = out.pop("index. posted_at")
        if "11. receipt" in out:
            out["legacy_receipt_sha256"] = out.pop("11. receipt")
        if isinstance(axes_block, Mapping):
            ax3_val = axes_block.get("3", axes_block.get(3))
            if ax3_val in VALID_FORGIVENESS_STATES and "forgiveness" not in out:
                out["forgiveness"] = ax3_val
            ax4_val = axes_block.get("4", axes_block.get(4))
            if ax4_val is not None and "amount_minor" not in out and "amount" not in out:
                out["amount_minor"] = ax4_val
        out.pop("axis_map", None)
        out.pop("axes", None)
        out["canonical_axis_map"] = "Axis 11 = forgiveness"
        msg = (
            "Migrated legacy Axis-3 prose document loudly to canonical Axis 11 = forgiveness: "
            + "; ".join(reasons)
        )
        notices.append(msg)
        warnings.warn(msg, LegacyAxisAliasWarning, stacklevel=2)

    # Support `amount` integer alias on canonical dict inputs
    if "amount_minor" not in out and "amount" in out:
        amt = out.pop("amount")
        if isinstance(amt, float) and math.isfinite(amt) and amt.is_integer():
            raise Rejected(
                f"Legacy float amount {amt!r} cannot convert silently; provide integer amount_minor"
            )
        out["amount_minor"] = amt
    if "momentum_minor" not in out and "momentum" in out:
        out["momentum_minor"] = out.pop("momentum")

    return out, notices


# ----------------------------------------------------------- cryptography & backup


def verify_ed25519_receipt_signature(
    public_key_hex: str, receipt_sha256: str, signature_hex: str
) -> bool:
    """Verify a party's detached Ed25519 signature over `SIGNING_DOMAIN + receipt_sha256`."""
    try:
        pub_bytes = bytes.fromhex(public_key_hex)
        sig_bytes = bytes.fromhex(signature_hex)
        if len(pub_bytes) != 32 or len(sig_bytes) != 64:
            return False
        if not isinstance(receipt_sha256, str) or len(receipt_sha256) != 64:
            return False
        pub = Ed25519PublicKey.from_public_bytes(pub_bytes)
        pub.verify(sig_bytes, SIGNING_DOMAIN + receipt_sha256.encode("ascii"))
        return True
    except (ValueError, InvalidSignature):
        return False


@dataclass(frozen=True, slots=True)
class PartyKeypair:
    """
    Party-held local Ed25519 keypair. Never passed into or stored inside `BookV2`.

    Doctrine: A lost keyfile is a lost identity.
    """

    party_id: str
    _seed_bytes: bytes = field(repr=False)
    public_key_hex: str

    def __post_init__(self) -> None:
        pid = _require_non_empty_str(self.party_id, "party_id")
        object.__setattr__(self, "party_id", pid)
        if not isinstance(self._seed_bytes, (bytes, bytearray)) or len(self._seed_bytes) != 32:
            raise ValueError("Ed25519 seed must be exactly 32 bytes")
        raw_seed = bytes(self._seed_bytes)
        object.__setattr__(self, "_seed_bytes", raw_seed)
        priv = Ed25519PrivateKey.from_private_bytes(raw_seed)
        derived_pub = priv.public_key().public_bytes(
            serialization.Encoding.Raw, serialization.PublicFormat.Raw
        ).hex()
        if derived_pub != self.public_key_hex:
            raise ValueError("public_key_hex does not match Ed25519 private seed")

    @classmethod
    def generate(cls, party_id: str) -> "PartyKeypair":
        priv = Ed25519PrivateKey.generate()
        seed = priv.private_bytes(
            serialization.Encoding.Raw,
            serialization.PrivateFormat.Raw,
            serialization.NoEncryption(),
        )
        pub_hex = priv.public_key().public_bytes(
            serialization.Encoding.Raw, serialization.PublicFormat.Raw
        ).hex()
        return cls(party_id=party_id, _seed_bytes=seed, public_key_hex=pub_hex)

    def sign_receipt_hex(self, receipt_sha256: str) -> str:
        if not isinstance(receipt_sha256, str) or len(receipt_sha256) != 64:
            raise ValueError("receipt_sha256 must be a 64-char SHA-256 hex digest")
        bytes.fromhex(receipt_sha256)
        priv = Ed25519PrivateKey.from_private_bytes(self._seed_bytes)
        return priv.sign(SIGNING_DOMAIN + receipt_sha256.encode("ascii")).hex()

    def public_jwk(self) -> Dict[str, Any]:
        pub_bytes = bytes.fromhex(self.public_key_hex)
        return {
            "kty": "OKP",
            "crv": "Ed25519",
            "x": _b64u_encode(pub_bytes),
            "ext": True,
            "key_ops": ["verify"],
            "kid": self.party_id,
        }

    def public_record(self) -> Dict[str, Any]:
        return {
            "party_id": self.party_id,
            "public_key_hex": self.public_key_hex,
            "jwk": self.public_jwk(),
            "key_loss_doctrine": KEY_LOSS_DOCTRINE,
        }

    def export_encrypted_backup(
        self, passphrase: str, out_path: Optional[Union[str, Path]] = None
    ) -> Dict[str, Any]:
        """
        Encrypt the party's 32-byte Ed25519 seed with Scrypt + AES-256-GCM.

        Performs an immediate trial round-trip verification before returning or writing
        so a corrupt backup ritual file is never emitted.
        """
        if not isinstance(passphrase, str) or len(passphrase.strip()) < 12:
            raise ValueError("Backup passphrase must be at least 12 non-whitespace characters")
        salt = os.urandom(16)
        nonce = os.urandom(12)
        n_cost, r_cost, p_cost = 2**14, 8, 1
        kdf = Scrypt(salt=salt, length=32, n=n_cost, r=r_cost, p=p_cost)
        kek = kdf.derive(passphrase.encode("utf-8"))

        aad_obj = {
            "schema": BACKUP_SCHEMA_VERSION,
            "party_id": self.party_id,
            "public_key_hex": self.public_key_hex,
            "doctrine": KEY_LOSS_DOCTRINE,
        }
        aad_json = _canonical_json_dumps(aad_obj)
        ciphertext = AESGCM(kek).encrypt(nonce, self._seed_bytes, aad_json.encode("utf-8"))

        bundle: Dict[str, Any] = {
            "schema": BACKUP_SCHEMA_VERSION,
            "algorithm": "Scrypt-AES256-GCM",
            "kdf_params": {"n": n_cost, "r": r_cost, "p": p_cost, "length": 32},
            "party_id": self.party_id,
            "public_key_hex": self.public_key_hex,
            "jwk": self.public_jwk(),
            "salt_b64": base64.b64encode(salt).decode("ascii"),
            "nonce_b64": base64.b64encode(nonce).decode("ascii"),
            "ciphertext_b64": base64.b64encode(ciphertext).decode("ascii"),
            "aad_json": aad_json,
            "doctrine": KEY_LOSS_DOCTRINE,
            "created_at": _now_utc_iso(),
        }

        # Self-verification gate before persisting
        restored = self.restore_encrypted_backup(bundle, passphrase)
        challenge = hashlib.sha256(b"keybackup-selfcheck").hexdigest()
        sig = restored.sign_receipt_hex(challenge)
        if not verify_ed25519_receipt_signature(self.public_key_hex, challenge, sig):
            raise RuntimeError("Backup self-verification failed")

        if out_path is not None:
            p = Path(out_path)
            p.parent.mkdir(parents=True, exist_ok=True)
            p.write_text(json.dumps(bundle, indent=2), encoding="utf-8")
            try:
                os.chmod(p, 0o600)
            except OSError:
                pass
        return bundle

    @classmethod
    def restore_encrypted_backup(
        cls, bundle_or_path: Union[Mapping[str, Any], str, Path], passphrase: str
    ) -> "PartyKeypair":
        if not isinstance(passphrase, str) or not passphrase:
            raise ValueError("Passphrase is required to restore an encrypted key backup")
        if isinstance(bundle_or_path, Path) or (
            isinstance(bundle_or_path, str) and not bundle_or_path.lstrip().startswith("{")
        ):
            bundle = json.loads(Path(bundle_or_path).read_text(encoding="utf-8"))
        elif isinstance(bundle_or_path, str):
            bundle = json.loads(bundle_or_path)
        else:
            bundle = dict(bundle_or_path)

        if bundle.get("schema") != BACKUP_SCHEMA_VERSION:
            raise ValueError(f"Unsupported backup schema: {bundle.get('schema')!r}")

        expected_aad = _canonical_json_dumps(
            {
                "schema": BACKUP_SCHEMA_VERSION,
                "party_id": bundle["party_id"],
                "public_key_hex": bundle["public_key_hex"],
                "doctrine": bundle["doctrine"],
            }
        )
        if bundle.get("aad_json") != expected_aad:
            raise ValueError("Encrypted key backup metadata does not match signed AAD")

        params = bundle["kdf_params"]
        kdf = Scrypt(
            salt=base64.b64decode(bundle["salt_b64"]),
            length=int(params["length"]),
            n=int(params["n"]),
            r=int(params["r"]),
            p=int(params["p"]),
        )
        kek = kdf.derive(passphrase.encode("utf-8"))
        try:
            seed = AESGCM(kek).decrypt(
                base64.b64decode(bundle["nonce_b64"]),
                base64.b64decode(bundle["ciphertext_b64"]),
                bundle["aad_json"].encode("utf-8"),
            )
        except InvalidTag as exc:
            raise ValueError(
                "Encrypted key backup decryption failed (wrong passphrase or tampered bundle). "
                + KEY_LOSS_DOCTRINE
            ) from exc

        return cls(
            party_id=bundle["party_id"],
            _seed_bytes=seed,
            public_key_hex=bundle["public_key_hex"],
        )


# ----------------------------------------------------------------- immutable entry


@dataclass(frozen=True, slots=True)
class EntryV2:
    """
    Freeze-at-posting immutable Eleven-Entry v2 record (`Axis 11 = forgiveness`).
    """

    entry_id: str
    debit_account: str          # Axis 1
    credit_account: str         # Axis 2
    amount_minor: int           # Axis 3 (strict positive integer minor units)
    posted_at: str              # Axis 4 (UTC/offset-aware ISO-8601)
    provenance: str             # Axis 5 (parent entry_id or "GENESIS")
    author: str                 # Axis 6 (registered party_id)
    reason: str                 # Axis 7 (non-empty stated purpose)
    consent: Tuple[str, ...]    # Axis 8 (immutable tuple of consenting party_ids)
    definition_version: str     # Axis 9 (pinned dictionary version)
    momentum_minor: Optional[int] = None   # Axis 10 (optional projected next amount_minor)
    forgiveness: str = "settled"           # Axis 11 ("owed" | "settled" | "forgiven")
    unit: str = "meals"                    # Explicit asset/count unit (e.g. "meals", "crates")
    discharges: Optional[str] = None       # Target obligation entry_id when discharging owed balance
    signatures: Tuple[Tuple[str, str], ...] = ()  # Detached Ed25519 (party_id, sig_hex) pairs

    def __post_init__(self) -> None:
        eid = _require_non_empty_str(self.entry_id, "entry_id")
        if eid == "GENESIS":
            raise Rejected("'GENESIS' is reserved as provenance sentinel and cannot be an entry_id")
        debit = _require_non_empty_str(self.debit_account, "Axis 1 (debit_account)")
        credit = _require_non_empty_str(self.credit_account, "Axis 2 (credit_account)")
        if debit == credit:
            raise Rejected(
                f"Axes 1 & 2 wash entry forbidden: debit_account and credit_account cannot both be '{debit}'"
            )
        amt = _require_pos_int_minor(self.amount_minor, "Axis 3 (amount_minor)")
        ts = _validate_iso8601_aware(self.posted_at, "posted_at")
        prov = _require_non_empty_str(self.provenance, "Axis 5 (provenance)")
        auth = _require_non_empty_str(self.author, "Axis 6 (author)")
        reas = _require_non_empty_str(self.reason, "Axis 7 (reason)")

        if isinstance(self.consent, str) or not isinstance(self.consent, Iterable):
            raise Rejected("Axis 8 (consent) must be a tuple/list of party_ids")
        cleaned_consent = tuple(
            sorted({_require_non_empty_str(p, "consent[]") for p in self.consent})
        )
        def_ver = _require_non_empty_str(self.definition_version, "Axis 9 (definition_version)")

        mom: Optional[int] = self.momentum_minor
        if mom is not None:
            mom = _require_pos_int_minor(mom, "Axis 10 (momentum_minor)")

        if self.forgiveness not in VALID_FORGIVENESS_STATES:
            raise Rejected(
                f"Axis 11 (forgiveness) standing {self.forgiveness!r} is invalid; "
                f"expected one of {VALID_FORGIVENESS_STATES}"
            )

        unit_clean = _require_non_empty_str(self.unit, "unit")
        disch = self.discharges
        if disch is not None:
            disch = _require_non_empty_str(disch, "discharges")
        if self.forgiveness == "forgiven":
            if disch is not None and disch != prov:
                raise Rejected(
                    "When Axis 11 forgiveness=='forgiven', discharges must match Axis 5 provenance"
                )
            disch = prov

        if isinstance(self.signatures, Mapping):
            sig_items = self.signatures.items()
        else:
            sig_items = self.signatures
        cleaned_sigs: Dict[str, str] = {}
        for k, v in sig_items:
            pk = _require_non_empty_str(k, "signatures key")
            sv = _require_non_empty_str(v, f"signatures[{pk}]").lower()
            cleaned_sigs[pk] = sv
        sigs_tuple = tuple(sorted(cleaned_sigs.items()))

        object.__setattr__(self, "entry_id", eid)
        object.__setattr__(self, "debit_account", debit)
        object.__setattr__(self, "credit_account", credit)
        object.__setattr__(self, "amount_minor", amt)
        object.__setattr__(self, "posted_at", ts)
        object.__setattr__(self, "provenance", prov)
        object.__setattr__(self, "author", auth)
        object.__setattr__(self, "reason", reas)
        object.__setattr__(self, "consent", cleaned_consent)
        object.__setattr__(self, "definition_version", def_ver)
        object.__setattr__(self, "momentum_minor", mom)
        object.__setattr__(self, "discharges", disch)
        object.__setattr__(self, "unit", unit_clean)
        object.__setattr__(self, "signatures", sigs_tuple)

    def payload_dict(self) -> Dict[str, Any]:
        return {
            "schema_version": SCHEMA_VERSION,
            "entry_id": self.entry_id,
            "debit_account": self.debit_account,
            "credit_account": self.credit_account,
            "amount_minor": self.amount_minor,
            "unit": self.unit,
            "posted_at": self.posted_at,
            "provenance": self.provenance,
            "author": self.author,
            "reason": self.reason,
            "consent": list(self.consent),
            "definition_version": self.definition_version,
            "momentum_minor": self.momentum_minor,
            "forgiveness": self.forgiveness,
            "discharges": self.discharges,
        }

    def canonical_json(self) -> str:
        return _canonical_json_dumps(self.payload_dict())

    def receipt(self) -> str:
        """SHA-256 common record computed over canonical envelope + Axes 1..11."""
        return _sha256_hex(self.canonical_json())

    def signatures_dict(self) -> Dict[str, str]:
        return dict(self.signatures)

    def with_signature(self, keypair: PartyKeypair) -> "EntryV2":
        sig = keypair.sign_receipt_hex(self.receipt())
        return self.with_detached_signature(keypair.party_id, sig)

    def with_detached_signature(self, party_id: str, signature_hex: str) -> "EntryV2":
        sigs = self.signatures_dict()
        sigs[_require_non_empty_str(party_id, "party_id")] = _require_non_empty_str(
            signature_hex, "signature_hex"
        ).lower()
        return replace(self, signatures=tuple(sorted(sigs.items())))

    @classmethod
    def from_document(
        cls, doc: Mapping[str, Any], *, allow_legacy_axis3_migration: bool = False
    ) -> Tuple["EntryV2", List[str]]:
        norm, notices = resolve_entry_document(
            doc, allow_legacy_axis3_migration=allow_legacy_axis3_migration
        )
        sigs = norm.get("signatures", {})
        entry = cls(
            entry_id=norm["entry_id"],
            debit_account=norm["debit_account"],
            credit_account=norm["credit_account"],
            amount_minor=norm["amount_minor"],
            posted_at=norm["posted_at"],
            provenance=norm["provenance"],
            author=norm["author"],
            reason=norm["reason"],
            consent=tuple(norm["consent"]),
            definition_version=norm["definition_version"],
            momentum_minor=norm.get("momentum_minor"),
            forgiveness=norm.get("forgiveness", "settled"),
            unit=norm.get("unit", "meals"),
            discharges=norm.get("discharges"),
            signatures=sigs,
        )
        return entry, notices


@dataclass(frozen=True, slots=True)
class VerificationReport:
    ok: bool
    tenant_id: str
    entry_count: int
    head_chain_hash: str
    obligations: Dict[str, Dict[str, Any]]
    errors: Tuple[str, ...] = ()


# ------------------------------------------------------------------ durable book


class BookV2:
    """
    Append-only SQLite WAL + Hash-Chained Eleven-Entry Book (`Axis 11 = forgiveness`).

    Holds ZERO private keys. All signatures verified via Ed25519 public keys registered
    per party. All obligations track principal vs. discharged minor units atomically.
    """

    def __init__(
        self,
        db_path: Union[str, Path] = ":memory:",
        tenant_id: str = "default",
    ) -> None:
        self.db_path = str(db_path)
        self.tenant_id = _require_non_empty_str(tenant_id, "tenant_id")
        self._lock = threading.RLock()
        if self.db_path != ":memory:":
            Path(self.db_path).parent.mkdir(parents=True, exist_ok=True)
        self._conn = sqlite3.connect(
            self.db_path, check_same_thread=False, isolation_level=None, timeout=10.0
        )
        self._conn.row_factory = sqlite3.Row
        self._init_db()

    def close(self) -> None:
        with self._lock:
            self._conn.close()

    def _init_db(self) -> None:
        with self._lock:
            cur = self._conn.cursor()
            if self.db_path != ":memory:":
                cur.execute("PRAGMA journal_mode=WAL;")
            cur.execute("PRAGMA synchronous=FULL;")
            cur.execute("PRAGMA foreign_keys=ON;")
            cur.execute("PRAGMA busy_timeout=5000;")
            cur.executescript(
                """
                CREATE TABLE IF NOT EXISTS parties (
                    tenant_id TEXT NOT NULL,
                    party_id TEXT NOT NULL,
                    public_key_hex TEXT NOT NULL,
                    jwk_json TEXT NOT NULL,
                    registered_at TEXT NOT NULL,
                    PRIMARY KEY (tenant_id, party_id)
                );

                CREATE TABLE IF NOT EXISTS accounts (
                    tenant_id TEXT NOT NULL,
                    account_id TEXT NOT NULL,
                    owner_party_id TEXT NOT NULL,
                    registered_at TEXT NOT NULL,
                    PRIMARY KEY (tenant_id, account_id),
                    FOREIGN KEY (tenant_id, owner_party_id)
                        REFERENCES parties(tenant_id, party_id)
                );

                CREATE TABLE IF NOT EXISTS definitions (
                    tenant_id TEXT NOT NULL,
                    version_id TEXT NOT NULL,
                    terms_json TEXT NOT NULL,
                    terms_sha256 TEXT NOT NULL,
                    registered_at TEXT NOT NULL,
                    PRIMARY KEY (tenant_id, version_id)
                );

                CREATE TABLE IF NOT EXISTS entries (
                    tenant_id TEXT NOT NULL,
                    seq_no INTEGER NOT NULL,
                    entry_id TEXT NOT NULL,
                    canonical_json TEXT NOT NULL,
                    receipt_sha256 TEXT NOT NULL,
                    signatures_json TEXT NOT NULL,
                    prev_chain_hash TEXT NOT NULL,
                    chain_hash TEXT NOT NULL,
                    posted_utc TEXT NOT NULL,
                    PRIMARY KEY (tenant_id, seq_no),
                    UNIQUE (tenant_id, entry_id)
                );

                CREATE TABLE IF NOT EXISTS obligations (
                    tenant_id TEXT NOT NULL,
                    obligation_entry_id TEXT NOT NULL,
                    creditor_account TEXT NOT NULL,
                    debtor_account TEXT NOT NULL,
                    unit TEXT NOT NULL,
                    principal_minor INTEGER NOT NULL,
                    discharged_minor INTEGER NOT NULL,
                    status TEXT NOT NULL CHECK (status IN ('OPEN', 'PARTIAL', 'SETTLED', 'FORGIVEN')),
                    discharge_history_json TEXT NOT NULL,
                    PRIMARY KEY (tenant_id, obligation_entry_id)
                );

                CREATE TRIGGER IF NOT EXISTS entries_no_update
                BEFORE UPDATE ON entries
                BEGIN
                    SELECT RAISE(ABORT, 'append-only ledger: UPDATE forbidden');
                END;

                CREATE TRIGGER IF NOT EXISTS entries_no_delete
                BEFORE DELETE ON entries
                BEGIN
                    SELECT RAISE(ABORT, 'append-only ledger: DELETE forbidden');
                END;
                """
            )

    def _begin_immediate(self) -> None:
        self._conn.execute("BEGIN IMMEDIATE;")

    def _rollback_quietly(self) -> None:
        try:
            self._conn.execute("ROLLBACK;")
        except sqlite3.Error:
            pass

    # ------------------------------------------------------------ registries

    def register_party(
        self, party_id: str, public_key_hex: str, jwk: Optional[Mapping[str, Any]] = None
    ) -> Dict[str, Any]:
        """Register ONLY a party's public Ed25519 key (zero private keys stored in BookV2)."""
        pid = _require_non_empty_str(party_id, "party_id")
        pub_hex = _require_non_empty_str(public_key_hex, "public_key_hex").lower()
        try:
            pub_bytes = bytes.fromhex(pub_hex)
            Ed25519PublicKey.from_public_bytes(pub_bytes)
        except Exception as exc:
            raise Rejected(f"Invalid Ed25519 public key for party '{pid}'") from exc
        if len(pub_bytes) != 32:
            raise Rejected(f"Ed25519 public key for party '{pid}' must be 32 bytes")

        jwk_obj = (
            dict(jwk)
            if jwk is not None
            else {
                "kty": "OKP",
                "crv": "Ed25519",
                "x": _b64u_encode(pub_bytes),
                "ext": True,
                "key_ops": ["verify"],
                "kid": pid,
            }
        )
        jwk_str = _canonical_json_dumps(jwk_obj)
        with self._lock:
            self._begin_immediate()
            try:
                row = self._conn.execute(
                    "SELECT public_key_hex FROM parties WHERE tenant_id=? AND party_id=?",
                    (self.tenant_id, pid),
                ).fetchone()
                if row is not None:
                    if row["public_key_hex"] != pub_hex:
                        raise Rejected(
                            f"Party '{pid}' is already registered with a different public key; rotation forbidden in place"
                        )
                    self._conn.execute("COMMIT;")
                    return jwk_obj
                self._conn.execute(
                    "INSERT INTO parties(tenant_id, party_id, public_key_hex, jwk_json, registered_at) VALUES (?, ?, ?, ?, ?)",
                    (self.tenant_id, pid, pub_hex, jwk_str, _now_utc_iso()),
                )
                self._conn.execute("COMMIT;")
                return jwk_obj
            except Exception:
                self._rollback_quietly()
                raise

    def register_party_public(self, keypair: PartyKeypair) -> Dict[str, Any]:
        """Convenience wrapper that extracts ONLY public key material from a local `PartyKeypair`."""
        return self.register_party(
            keypair.party_id, keypair.public_key_hex, keypair.public_jwk()
        )

    def register_account(self, account_id: str, owner_party_id: str) -> None:
        aid = _require_non_empty_str(account_id, "account_id")
        pid = _require_non_empty_str(owner_party_id, "owner_party_id")
        with self._lock:
            self._begin_immediate()
            try:
                p_row = self._conn.execute(
                    "SELECT 1 FROM parties WHERE tenant_id=? AND party_id=?",
                    (self.tenant_id, pid),
                ).fetchone()
                if p_row is None:
                    raise Rejected(f"Cannot register account '{aid}': unknown owner party '{pid}'")
                a_row = self._conn.execute(
                    "SELECT owner_party_id FROM accounts WHERE tenant_id=? AND account_id=?",
                    (self.tenant_id, aid),
                ).fetchone()
                if a_row is not None:
                    if a_row["owner_party_id"] != pid:
                        raise Rejected(
                            f"Account '{aid}' owner is already pinned to '{a_row['owner_party_id']}'"
                        )
                    self._conn.execute("COMMIT;")
                    return
                self._conn.execute(
                    "INSERT INTO accounts(tenant_id, account_id, owner_party_id, registered_at) VALUES (?, ?, ?, ?)",
                    (self.tenant_id, aid, pid, _now_utc_iso()),
                )
                self._conn.execute("COMMIT;")
            except Exception:
                self._rollback_quietly()
                raise

    def register_definition(self, version_id: str, terms: Mapping[str, str]) -> str:
        vid = _require_non_empty_str(version_id, "version_id")
        if not isinstance(terms, Mapping) or not terms:
            raise Rejected("Definition terms must be a non-empty mapping")
        clean_terms = {
            _require_non_empty_str(k, "definition term key"): _require_non_empty_str(
                v, f"definition[{k}]"
            )
            for k, v in sorted(terms.items())
        }
        terms_json = _canonical_json_dumps(clean_terms)
        terms_sha = _sha256_hex(terms_json)
        with self._lock:
            self._begin_immediate()
            try:
                row = self._conn.execute(
                    "SELECT terms_sha256 FROM definitions WHERE tenant_id=? AND version_id=?",
                    (self.tenant_id, vid),
                ).fetchone()
                if row is not None:
                    if row["terms_sha256"] != terms_sha:
                        raise Rejected(
                            f"Axis 9 immutability violation: definition_version '{vid}' is already pinned with hash {row['terms_sha256']}"
                        )
                    self._conn.execute("COMMIT;")
                    return terms_sha
                self._conn.execute(
                    "INSERT INTO definitions(tenant_id, version_id, terms_json, terms_sha256, registered_at) VALUES (?, ?, ?, ?, ?)",
                    (self.tenant_id, vid, terms_json, terms_sha, _now_utc_iso()),
                )
                self._conn.execute("COMMIT;")
                return terms_sha
            except Exception:
                self._rollback_quietly()
                raise

    # ----------------------------------------------------- checking & posting

    @staticmethod
    def _compute_chain_hash(
        prev_chain_hash: str, seq_no: int, receipt_sha256: str, sigs_json: str
    ) -> str:
        preimage = f"{prev_chain_hash}|{seq_no}|{receipt_sha256}|{sigs_json}"
        return _sha256_hex(preimage)

    def _validate_in_tx(self, cur: sqlite3.Cursor, e: EntryV2) -> Optional[Dict[str, Any]]:
        """Run all 11+ deterministic rules against current SQLite snapshot inside TX."""
        dup = cur.execute(
            "SELECT 1 FROM entries WHERE tenant_id=? AND entry_id=?",
            (self.tenant_id, e.entry_id),
        ).fetchone()
        if dup is not None:
            raise Rejected(
                f"id '{e.entry_id}' already posted; the book is append-only (corrections are new entries, never edits)"
            )

        deb_row = cur.execute(
            "SELECT owner_party_id FROM accounts WHERE tenant_id=? AND account_id=?",
            (self.tenant_id, e.debit_account),
        ).fetchone()
        cred_row = cur.execute(
            "SELECT owner_party_id FROM accounts WHERE tenant_id=? AND account_id=?",
            (self.tenant_id, e.credit_account),
        ).fetchone()
        if deb_row is None or cred_row is None:
            raise Rejected(
                f"Axes 1 & 2 unknown account: debit={e.debit_account!r}, credit={e.credit_account!r}"
            )

        auth_row = cur.execute(
            "SELECT public_key_hex FROM parties WHERE tenant_id=? AND party_id=?",
            (self.tenant_id, e.author),
        ).fetchone()
        if auth_row is None:
            raise Rejected(f"Axis 6 unregistered author party '{e.author}'")

        def_row = cur.execute(
            "SELECT 1 FROM definitions WHERE tenant_id=? AND version_id=?",
            (self.tenant_id, e.definition_version),
        ).fetchone()
        if def_row is None:
            raise Rejected(
                f"Axis 9 definition_version '{e.definition_version}' is not registered; unpinned meanings refused"
            )

        # Axis 5: Acyclic provenance walk to GENESIS
        if e.provenance == e.entry_id:
            raise Rejected("Axis 5 provenance is the entry itself (circular self-definition)")
        seen = set()
        cursor_id = e.provenance
        parent_payload: Optional[Dict[str, Any]] = None
        while cursor_id != "GENESIS":
            if cursor_id in seen:
                raise Rejected("Axis 5 provenance chain is cyclic")
            p_row = cur.execute(
                "SELECT canonical_json FROM entries WHERE tenant_id=? AND entry_id=?",
                (self.tenant_id, cursor_id),
            ).fetchone()
            if p_row is None:
                raise Rejected(f"Axis 5 provenance '{cursor_id}' is not in the book; chain dangles")
            p_obj = json.loads(p_row["canonical_json"])
            if cursor_id == e.provenance:
                parent_payload = p_obj
            seen.add(cursor_id)
            cursor_id = p_obj["provenance"]

        # Axis 10: Momentum check (Axis 11 'forgiven' is sole lawful exception)
        if e.provenance != "GENESIS" and e.forgiveness != "forgiven" and parent_payload is not None:
            proj = parent_payload.get("momentum_minor")
            if proj is not None and proj != e.amount_minor:
                raise Rejected(
                    f"Axis 10 trajectory broken: parent '{e.provenance}' projected {proj}, got {e.amount_minor}"
                )

        # Axis 11: One-Time Obligation Discharge & Provenance Conservation Rule
        obligation_update: Optional[Dict[str, Any]] = None
        if e.forgiveness == "forgiven":
            if e.provenance == "GENESIS":
                raise Rejected("Axis 11 forgiveness must rest on the owed obligation it releases")
            ob_row = cur.execute(
                "SELECT * FROM obligations WHERE tenant_id=? AND obligation_entry_id=?",
                (self.tenant_id, e.provenance),
            ).fetchone()
            if ob_row is None:
                raise Rejected(
                    "Axis 11 violation: parent entry never stood as an 'owed' obligation (counterfeit grace)"
                )
            remaining = int(ob_row["principal_minor"]) - int(ob_row["discharged_minor"])
            if remaining <= 0 or ob_row["status"] in ("SETTLED", "FORGIVEN"):
                raise Rejected(
                    f"Axis 11 discharge violation: obligation '{e.provenance}' already {ob_row['status']}; "
                    "forgiveness cannot be double-spent"
                )
            if (e.debit_account, e.credit_account, e.unit) != (
                ob_row["debtor_account"],
                ob_row["creditor_account"],
                ob_row["unit"],
            ):
                raise Rejected(
                    "Axis 11 forgiveness must reverse creditor/debtor accounts and unit identically"
                )
            if e.amount_minor != remaining:
                raise Rejected(
                    f"Axis 11 forgiveness must match exact remaining balance ({remaining} {ob_row['unit']}), got {e.amount_minor}"
                )
            history = json.loads(ob_row["discharge_history_json"])
            history.append({"entry_id": e.entry_id, "type": "forgiven", "amount_minor": e.amount_minor})
            obligation_update = {
                "mode": "UPDATE",
                "obligation_entry_id": e.provenance,
                "discharged_minor": int(ob_row["principal_minor"]),
                "status": "FORGIVEN",
                "history": history,
            }
        elif e.discharges is not None:
            if e.forgiveness != "settled":
                raise Rejected("Only 'settled' entries may cite `discharges` for repayment")
            if e.discharges == e.entry_id:
                raise Rejected("Entry cannot discharge itself")
            ob_row = cur.execute(
                "SELECT * FROM obligations WHERE tenant_id=? AND obligation_entry_id=?",
                (self.tenant_id, e.discharges),
            ).fetchone()
            if ob_row is None:
                raise Rejected(f"Discharge target '{e.discharges}' is not an open obligation")
            remaining = int(ob_row["principal_minor"]) - int(ob_row["discharged_minor"])
            if remaining <= 0 or ob_row["status"] in ("SETTLED", "FORGIVEN"):
                raise Rejected(
                    f"Axis 11 discharge violation: obligation '{e.discharges}' is already {ob_row['status']}"
                )
            if (e.debit_account, e.credit_account, e.unit) != (
                ob_row["debtor_account"],
                ob_row["creditor_account"],
                ob_row["unit"],
            ):
                raise Rejected(
                    "Repayment must reverse creditor/debtor accounts and match unit identically"
                )
            if e.amount_minor > remaining:
                raise Rejected(
                    f"Repayment amount {e.amount_minor} exceeds remaining balance {remaining}"
                )
            new_discharged = int(ob_row["discharged_minor"]) + e.amount_minor
            new_status = "SETTLED" if new_discharged == int(ob_row["principal_minor"]) else "PARTIAL"
            history = json.loads(ob_row["discharge_history_json"])
            history.append({"entry_id": e.entry_id, "type": "settled", "amount_minor": e.amount_minor})
            obligation_update = {
                "mode": "UPDATE",
                "obligation_entry_id": e.discharges,
                "discharged_minor": new_discharged,
                "status": new_status,
                "history": history,
            }
        elif e.forgiveness == "owed":
            obligation_update = {
                "mode": "INSERT",
                "obligation_entry_id": e.entry_id,
                "creditor_account": e.debit_account,
                "debtor_account": e.credit_account,
                "unit": e.unit,
                "principal_minor": e.amount_minor,
            }

        # Axis 8 + Envelope Seal: Bilateral Consent & Ed25519 Signature Verification
        needed = {deb_row["owner_party_id"], cred_row["owner_party_id"]}
        consent_set = set(e.consent)
        if not needed.issubset(consent_set):
            raise Rejected(f"Axis 8 consent missing parties: {sorted(needed - consent_set)}")

        sigs = e.signatures_dict()
        required_signers = needed | consent_set | {e.author}
        receipt_hex = e.receipt()
        for party_id in sorted(required_signers):
            p_row = cur.execute(
                "SELECT public_key_hex FROM parties WHERE tenant_id=? AND party_id=?",
                (self.tenant_id, party_id),
            ).fetchone()
            if p_row is None:
                raise Rejected(f"Axis 8 unknown party '{party_id}' in consent/author")
            sig_hex = sigs.get(party_id)
            if not sig_hex:
                raise Rejected(f"Missing Ed25519 signature for required party '{party_id}'")
            if not verify_ed25519_receipt_signature(p_row["public_key_hex"], receipt_hex, sig_hex):
                raise Rejected(
                    f"Ed25519 signature failed for '{party_id}'; key mismatch or payload altered after signing"
                )
        for extra_party, sig_hex in sigs.items():
            if extra_party not in required_signers:
                p_row = cur.execute(
                    "SELECT public_key_hex FROM parties WHERE tenant_id=? AND party_id=?",
                    (self.tenant_id, extra_party),
                ).fetchone()
                if p_row is None or not verify_ed25519_receipt_signature(
                    p_row["public_key_hex"], receipt_hex, sig_hex
                ):
                    raise Rejected(f"Invalid detached signature from '{extra_party}'")

        return obligation_update

    def post(self, e: EntryV2) -> Dict[str, Any]:
        """Validate and atomically append an immutable `EntryV2` into SQLite WAL."""
        if not isinstance(e, EntryV2):
            raise Rejected("Expected an immutable EntryV2 instance")
        with self._lock:
            self._begin_immediate()
            try:
                cur = self._conn.cursor()
                ob_update = self._validate_in_tx(cur, e)

                tail = cur.execute(
                    "SELECT seq_no, chain_hash FROM entries WHERE tenant_id=? ORDER BY seq_no DESC LIMIT 1",
                    (self.tenant_id,),
                ).fetchone()
                seq_no = 1 if tail is None else int(tail["seq_no"]) + 1
                prev_chain = GENESIS_CHAIN_HASH if tail is None else tail["chain_hash"]

                can_json = e.canonical_json()
                receipt_hex = e.receipt()
                sigs_json = _canonical_json_dumps(e.signatures_dict())
                chain_hash = self._compute_chain_hash(prev_chain, seq_no, receipt_hex, sigs_json)

                cur.execute(
                    """
                    INSERT INTO entries(
                        tenant_id, seq_no, entry_id, canonical_json,
                        receipt_sha256, signatures_json, prev_chain_hash,
                        chain_hash, posted_utc
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                    """,
                    (
                        self.tenant_id,
                        seq_no,
                        e.entry_id,
                        can_json,
                        receipt_hex,
                        sigs_json,
                        prev_chain,
                        chain_hash,
                        _now_utc_iso(),
                    ),
                )

                if ob_update is not None:
                    if ob_update["mode"] == "INSERT":
                        cur.execute(
                            """
                            INSERT INTO obligations(
                                tenant_id, obligation_entry_id, creditor_account,
                                debtor_account, unit, principal_minor,
                                discharged_minor, status, discharge_history_json
                            ) VALUES (?, ?, ?, ?, ?, ?, 0, 'OPEN', '[]')
                            """,
                            (
                                self.tenant_id,
                                ob_update["obligation_entry_id"],
                                ob_update["creditor_account"],
                                ob_update["debtor_account"],
                                ob_update["unit"],
                                ob_update["principal_minor"],
                            ),
                        )
                    else:
                        cur.execute(
                            """
                            UPDATE obligations
                            SET discharged_minor=?, status=?, discharge_history_json=?
                            WHERE tenant_id=? AND obligation_entry_id=?
                            """,
                            (
                                ob_update["discharged_minor"],
                                ob_update["status"],
                                _canonical_json_dumps(ob_update["history"]),
                                self.tenant_id,
                                ob_update["obligation_entry_id"],
                            ),
                        )

                self._conn.execute("COMMIT;")
                return {
                    "seq_no": seq_no,
                    "entry_id": e.entry_id,
                    "receipt_sha256": receipt_hex,
                    "prev_chain_hash": prev_chain,
                    "chain_hash": chain_hash,
                }
            except Exception:
                self._rollback_quietly()
                raise

    # -------------------------------------------------- queries & workflows

    def get_entry(self, entry_id: str) -> EntryV2:
        with self._lock:
            row = self._conn.execute(
                "SELECT canonical_json, signatures_json FROM entries WHERE tenant_id=? AND entry_id=?",
                (self.tenant_id, entry_id),
            ).fetchone()
            if row is None:
                raise KeyError(f"Entry '{entry_id}' not found")
            doc = json.loads(row["canonical_json"])
            doc["signatures"] = json.loads(row["signatures_json"])
            entry, _ = EntryV2.from_document(doc)
            return entry

    def get_obligation(self, obligation_entry_id: str) -> Dict[str, Any]:
        with self._lock:
            row = self._conn.execute(
                "SELECT * FROM obligations WHERE tenant_id=? AND obligation_entry_id=?",
                (self.tenant_id, obligation_entry_id),
            ).fetchone()
            if row is None:
                raise KeyError(f"Obligation '{obligation_entry_id}' not found")
            return {
                "obligation_entry_id": row["obligation_entry_id"],
                "creditor_account": row["creditor_account"],
                "debtor_account": row["debtor_account"],
                "unit": row["unit"],
                "principal_minor": int(row["principal_minor"]),
                "discharged_minor": int(row["discharged_minor"]),
                "remaining_minor": int(row["principal_minor"]) - int(row["discharged_minor"]),
                "status": row["status"],
                "discharge_history": json.loads(row["discharge_history_json"]),
            }

    def prepare_forgiveness_draft(
        self,
        obligation_id: str,
        author: str,
        reason: str,
        posted_at: str,
        definition_version: str,
        *,
        entry_id: Optional[str] = None,
    ) -> EntryV2:
        """
        Build an UNSIGNED `Axis 11 = forgiven` reversal draft against an open obligation.

        Both creditor and debtor (plus author) MUST sign this draft with their own
        `PartyKeypair`s before `post()` will accept it; `BookV2` never self-signs.
        """
        with self._lock:
            ob = self.get_obligation(obligation_id)
            if ob["remaining_minor"] <= 0 or ob["status"] in ("SETTLED", "FORGIVEN"):
                raise Rejected(
                    f"Cannot prepare forgiveness: obligation '{obligation_id}' is already {ob['status']}"
                )
            cred_owner = self._conn.execute(
                "SELECT owner_party_id FROM accounts WHERE tenant_id=? AND account_id=?",
                (self.tenant_id, ob["creditor_account"]),
            ).fetchone()["owner_party_id"]
            debt_owner = self._conn.execute(
                "SELECT owner_party_id FROM accounts WHERE tenant_id=? AND account_id=?",
                (self.tenant_id, ob["debtor_account"]),
            ).fetchone()["owner_party_id"]
            return EntryV2(
                entry_id=entry_id or f"{obligation_id}-forgiven",
                debit_account=ob["debtor_account"],
                credit_account=ob["creditor_account"],
                amount_minor=ob["remaining_minor"],
                unit=ob["unit"],
                posted_at=posted_at,
                provenance=obligation_id,
                author=author,
                reason=reason,
                consent=tuple(sorted({cred_owner, debt_owner})),
                definition_version=definition_version,
                momentum_minor=None,
                forgiveness="forgiven",
                discharges=obligation_id,
                signatures=(),
            )

    def read(self, entry_id: str, reader_version: str) -> Dict[str, Any]:
        """Symmetric Axis 9 definition audit detecting added, removed, and redefined terms."""
        with self._lock:
            e = self.get_entry(entry_id)
            old_row = self._conn.execute(
                "SELECT terms_json, terms_sha256 FROM definitions WHERE tenant_id=? AND version_id=?",
                (self.tenant_id, e.definition_version),
            ).fetchone()
            new_row = self._conn.execute(
                "SELECT terms_json, terms_sha256 FROM definitions WHERE tenant_id=? AND version_id=?",
                (self.tenant_id, reader_version),
            ).fetchone()
            if new_row is None:
                raise Rejected(f"Unknown reader definition_version '{reader_version}'")

            if reader_version == e.definition_version:
                return {
                    "entry_id": entry_id,
                    "posted_version": e.definition_version,
                    "reader_version": reader_version,
                    "clean": True,
                    "added_terms": [],
                    "removed_terms": [],
                    "redefined_terms": [],
                    "summary": f"{entry_id}: read under {reader_version}, the meanings it was posted under. Clean.",
                }

            old_terms = json.loads(old_row["terms_json"])
            new_terms = json.loads(new_row["terms_json"])
            all_keys = sorted(set(old_terms) | set(new_terms))
            added = [k for k in all_keys if k not in old_terms]
            removed = [k for k in all_keys if k not in new_terms]
            redefined = [
                k for k in all_keys if k in old_terms and k in new_terms and old_terms[k] != new_terms[k]
            ]
            clean = not (added or removed or redefined)
            return {
                "entry_id": entry_id,
                "posted_version": e.definition_version,
                "reader_version": reader_version,
                "clean": clean,
                "added_terms": added,
                "removed_terms": removed,
                "redefined_terms": redefined,
                "summary": (
                    f"{entry_id}: WARNING, posted under {e.definition_version}, read under "
                    f"{reader_version}. Added={added}, Removed={removed}, Redefined={redefined}."
                    if not clean
                    else f"{entry_id}: read under {reader_version}; symmetric term set unchanged."
                ),
            }

    def verify_book(self) -> VerificationReport:
        """
        Deterministically replay the entire book from seq_no=1 / GENESIS and verify
        all hashes, chain links, Ed25519 signatures, and obligation conservation.
        """
        with self._lock:
            parties_rows = self._conn.execute(
                "SELECT party_id, public_key_hex FROM parties WHERE tenant_id=?",
                (self.tenant_id,),
            ).fetchall()
            parties = {r["party_id"]: r["public_key_hex"] for r in parties_rows}

            acct_rows = self._conn.execute(
                "SELECT account_id, owner_party_id FROM accounts WHERE tenant_id=?",
                (self.tenant_id,),
            ).fetchall()
            accounts = {r["account_id"]: r["owner_party_id"] for r in acct_rows}

            def_rows = self._conn.execute(
                "SELECT version_id, terms_json, terms_sha256 FROM definitions WHERE tenant_id=?",
                (self.tenant_id,),
            ).fetchall()
            defs: Dict[str, str] = {}
            errors: List[str] = []
            for r in def_rows:
                recomputed = _sha256_hex(
                    _canonical_json_dumps(json.loads(r["terms_json"]))
                )
                if recomputed != r["terms_sha256"]:
                    errors.append(f"Definition '{r['version_id']}' hash tampered")
                defs[r["version_id"]] = r["terms_sha256"]

            entry_rows = self._conn.execute(
                "SELECT * FROM entries WHERE tenant_id=? ORDER BY seq_no ASC",
                (self.tenant_id,),
            ).fetchall()

            expected_seq = 1
            expected_prev = GENESIS_CHAIN_HASH
            seen_entries: Dict[str, EntryV2] = {}
            replayed_obs: Dict[str, Dict[str, Any]] = {}

            for r in entry_rows:
                seq_no = int(r["seq_no"])
                if seq_no != expected_seq:
                    errors.append(f"Sequence gap: expected {expected_seq}, got {seq_no}")
                if r["prev_chain_hash"] != expected_prev:
                    errors.append(
                        f"Chain break at seq_no={seq_no} ({r['entry_id']}): prev_chain_hash mismatch"
                    )

                try:
                    doc = json.loads(r["canonical_json"])
                    doc["signatures"] = json.loads(r["signatures_json"])
                    e, _ = EntryV2.from_document(doc)
                except Exception as exc:
                    errors.append(f"Entry seq_no={seq_no} invalid structure: {exc}")
                    expected_seq = seq_no + 1
                    expected_prev = r["chain_hash"]
                    continue

                if e.entry_id != r["entry_id"]:
                    errors.append(f"Entry id mismatch at seq_no={seq_no}")
                if e.canonical_json() != r["canonical_json"]:
                    errors.append(f"Canonical JSON drift at '{e.entry_id}'")
                if e.receipt() != r["receipt_sha256"]:
                    errors.append(f"Receipt SHA-256 tamper at '{e.entry_id}'")

                re_chain = self._compute_chain_hash(
                    r["prev_chain_hash"],
                    seq_no,
                    r["receipt_sha256"],
                    r["signatures_json"],
                )
                if re_chain != r["chain_hash"]:
                    errors.append(f"Chain hash tamper at '{e.entry_id}'")

                # Provenance, accounts, defs, consent, Ed25519
                if e.debit_account not in accounts or e.credit_account not in accounts:
                    errors.append(f"Unknown account in '{e.entry_id}'")
                else:
                    needed = {accounts[e.debit_account], accounts[e.credit_account]}
                    if not needed.issubset(set(e.consent)):
                        errors.append(f"Missing consent in '{e.entry_id}'")
                    req = needed | set(e.consent) | {e.author}
                    sigs = e.signatures_dict()
                    for p in req:
                        pub = parties.get(p)
                        if not pub or not verify_ed25519_receipt_signature(
                            pub, r["receipt_sha256"], sigs.get(p, "")
                        ):
                            errors.append(
                                f"Invalid/missing Ed25519 signature for '{p}' on '{e.entry_id}'"
                            )

                if e.definition_version not in defs:
                    errors.append(f"Unregistered definition_version in '{e.entry_id}'")

                if e.provenance != "GENESIS":
                    if e.provenance not in seen_entries:
                        errors.append(f"Dangling or out-of-order provenance in '{e.entry_id}'")
                    else:
                        parent = seen_entries[e.provenance]
                        if (
                            e.forgiveness != "forgiven"
                            and parent.momentum_minor is not None
                            and parent.momentum_minor != e.amount_minor
                        ):
                            errors.append(f"Momentum mismatch at '{e.entry_id}'")

                # Obligation replay & conservation
                if e.forgiveness == "owed":
                    replayed_obs[e.entry_id] = {
                        "creditor_account": e.debit_account,
                        "debtor_account": e.credit_account,
                        "unit": e.unit,
                        "principal_minor": e.amount_minor,
                        "discharged_minor": 0,
                        "status": "OPEN",
                    }
                elif e.forgiveness == "forgiven":
                    ob = replayed_obs.get(e.provenance)
                    if ob is None or (ob["principal_minor"] - ob["discharged_minor"]) != e.amount_minor:
                        errors.append(f"Invalid forgiveness discharge at '{e.entry_id}'")
                    elif (e.debit_account, e.credit_account, e.unit) != (
                        ob["debtor_account"],
                        ob["creditor_account"],
                        ob["unit"],
                    ):
                        errors.append(f"Forgiveness account/unit mismatch at '{e.entry_id}'")
                    else:
                        ob["discharged_minor"] = ob["principal_minor"]
                        ob["status"] = "FORGIVEN"
                elif e.discharges is not None:
                    ob = replayed_obs.get(e.discharges)
                    rem = (ob["principal_minor"] - ob["discharged_minor"]) if ob else -1
                    if ob is None or e.amount_minor > rem:
                        errors.append(f"Over-settlement or missing obligation at '{e.entry_id}'")
                    else:
                        ob["discharged_minor"] += e.amount_minor
                        ob["status"] = (
                            "SETTLED"
                            if ob["discharged_minor"] == ob["principal_minor"]
                            else "PARTIAL"
                        )

                seen_entries[e.entry_id] = e
                expected_seq = seq_no + 1
                expected_prev = r["chain_hash"]

            # Cross-check stored obligations table matches deterministic replay
            db_obs = {
                row["obligation_entry_id"]: {
                    "creditor_account": row["creditor_account"],
                    "debtor_account": row["debtor_account"],
                    "unit": row["unit"],
                    "principal_minor": int(row["principal_minor"]),
                    "discharged_minor": int(row["discharged_minor"]),
                    "status": row["status"],
                }
                for row in self._conn.execute(
                    "SELECT * FROM obligations WHERE tenant_id=?", (self.tenant_id,)
                ).fetchall()
            }
            if db_obs != replayed_obs:
                errors.append("Stored obligations table diverges from deterministic entry replay")

            return VerificationReport(
                ok=len(errors) == 0,
                tenant_id=self.tenant_id,
                entry_count=len(entry_rows),
                head_chain_hash=expected_prev,
                obligations=replayed_obs,
                errors=tuple(errors),
            )

    def all_entries(self) -> List[Dict[str, Any]]:
        with self._lock:
            rows = self._conn.execute(
                "SELECT * FROM entries WHERE tenant_id=? ORDER BY seq_no ASC",
                (self.tenant_id,),
            ).fetchall()
            out: List[Dict[str, Any]] = []
            for r in rows:
                payload = json.loads(r["canonical_json"])
                out.append(
                    {
                        "seq_no": int(r["seq_no"]),
                        "entry_id": r["entry_id"],
                        "payload": payload,
                        "receipt_sha256": r["receipt_sha256"],
                        "prev_chain_hash": r["prev_chain_hash"],
                        "chain_hash": r["chain_hash"],
                        "signatures": json.loads(r["signatures_json"]),
                        "posted_utc": r["posted_utc"],
                    }
                )
            return out

    def export_audit_bundle(self) -> Dict[str, Any]:
        """Export zero-private-key JSON bundle verifyable in Python or browser WebCrypto."""
        report = self.verify_book()
        with self._lock:
            parties = {
                r["party_id"]: {
                    "public_key_hex": r["public_key_hex"],
                    "jwk": json.loads(r["jwk_json"]),
                    "registered_at": r["registered_at"],
                }
                for r in self._conn.execute(
                    "SELECT * FROM parties WHERE tenant_id=? ORDER BY party_id ASC",
                    (self.tenant_id,),
                ).fetchall()
            }
            accounts = {
                r["account_id"]: r["owner_party_id"]
                for r in self._conn.execute(
                    "SELECT account_id, owner_party_id FROM accounts WHERE tenant_id=? ORDER BY account_id ASC",
                    (self.tenant_id,),
                ).fetchall()
            }
            definitions = {
                r["version_id"]: {
                    "terms": json.loads(r["terms_json"]),
                    "terms_sha256": r["terms_sha256"],
                }
                for r in self._conn.execute(
                    "SELECT version_id, terms_json, terms_sha256 FROM definitions WHERE tenant_id=? ORDER BY version_id ASC",
                    (self.tenant_id,),
                ).fetchall()
            }
            return {
                "schema_version": SCHEMA_VERSION,
                "tenant_id": self.tenant_id,
                "signing_domain": SIGNING_DOMAIN.decode("ascii"),
                "genesis_chain_hash": GENESIS_CHAIN_HASH,
                "key_loss_doctrine": KEY_LOSS_DOCTRINE,
                "canonical_axes": {str(k): v for k, v in CANONICAL_AXES.items()},
                "envelope_fields": list(ENVELOPE_FIELDS),
                "legacy_axis_aliases": LEGACY_PROSE_AXIS_ALIASES,
                "verification": {
                    "ok": report.ok,
                    "entry_count": report.entry_count,
                    "head_chain_hash": report.head_chain_hash,
                    "errors": list(report.errors),
                },
                "parties": parties,
                "accounts": accounts,
                "definitions": definitions,
                "obligations": report.obligations,
                "entries": self.all_entries(),
            }
