Metadata-Version: 2.4
Name: sovereign-sdk-ledger
Version: 2.0.0
Summary: Immutable, local-first, hash-chained SQLite provenance engine for ForensicReceipt Write-Side Custody
License: MIT
Project-URL: Homepage, https://github.com/kenwalger/sovereign-sdk
Project-URL: Repository, https://github.com/kenwalger/sovereign-sdk
Project-URL: Changelog, https://github.com/kenwalger/sovereign-sdk/blob/main/CHANGELOG.md
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.12
Classifier: Intended Audience :: Developers
Classifier: Topic :: Security
Classifier: Topic :: Database
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.12
Description-Content-Type: text/markdown

# sovereign-ledger

**Immutable, local-first, hash-chained SQLite provenance engine for ForensicReceipt Write-Side Custody.**

`sovereign-ledger` is a zero-external-dependency Python package that stores every
`ForensicReceipt` produced by `sovereign-core` in a tamper-evident, append-only SQLite
database. It enforces Write-Side Custody through two complementary mechanisms: engine-level
SQL triggers that abort any `UPDATE` or `DELETE` at the SQLite layer, and a SHA-256 hash
chain that makes out-of-band filesystem tampering mathematically detectable.

The ledger records evidence; it does not judge it. It reports whether an entry is signed,
but it never verifies signatures; that remains `sovereign-core`'s `verify_receipt`.

---

## Installation

The distribution is **`sovereign-sdk-ledger`**; the import is **`sovereign_ledger`**.

```bash
pip install sovereign-sdk-ledger
```

```bash
uv add sovereign-sdk-ledger
```

Requires Python 3.12 or later. Zero runtime dependencies beyond the Python standard library.

---

## Quick start

Runs as written; the in-memory store makes it repeatable.

```python
import hashlib

from sovereign_ledger import IdempotencyKeyConflictError, SovereignLedger

content = "page unchanged"
receipt = {
    "payload_hash": hashlib.sha256(content.encode("utf-8")).hexdigest(),
    "timestamp": "2026-11-04T12:00:00+00:00",
    "signature": "c2lnbmF0dXJl",
}

with SovereignLedger(db_path=":memory:") as ledger:
    # Identical content is recorded once per append; the idempotency key makes a retry safe.
    monday = ledger.append_entry(receipt, content, idempotency_key="check-monday")
    ledger.append_entry(receipt, content, idempotency_key="check-friday")
    try:
        ledger.append_entry(receipt, content, idempotency_key="check-friday")
    except IdempotencyKeyConflictError as exc:
        print("retry rejected:", exc.idempotency_key)  # → retry rejected: check-friday

    # No signature recorded: an explicit, hashed UNSIGNED entry.
    ledger.append_entry({"payload_hash": receipt["payload_hash"], "timestamp": receipt["timestamp"]}, content)

    # Read back, verified from the Point of Genesis.
    for entry in ledger.iter_entries():
        print(entry.sequence, entry.signature_status.value, entry.idempotency_key)
    # → 1 SIGNED check-monday
    # → 2 SIGNED check-friday
    # → 3 UNSIGNED None

    tip = ledger.get_tip()
    print(tip.sequence)  # → 3

    # Structured verification, anchored to an externally persisted tip.
    report = ledger.verify_ledger(expected_tip=monday)
    print(report.verified, report.entries_checked, report.tip == tip)  # → True 3 True
```

---

## API reference

All names are importable from `sovereign_ledger`. The full reference, including the entry
format and the migration procedure, is in
[`docs/sovereign-ledger.md`](https://github.com/kenwalger/sovereign-sdk/blob/main/docs/sovereign-ledger.md).

### `SovereignLedger(db_path=".keys/sovereign_audit.db")`

Opens the SQLite database at `db_path`, applies WAL journal mode, `NORMAL` synchronous
enforcement, strict foreign-key constraints and a 5-second `busy_timeout`, then creates the
`forensic_ledger` schema and Write-Side Custody triggers, or migrates a 1.3.0 file once (see
below). Pass `":memory:"` for an ephemeral in-process store.

Supports the Python context manager protocol; use a `with` block to guarantee all
thread-local connection handles are released on exit.

### `append_entry(receipt, sieved_content, *, idempotency_key=None, signer_key_id=None) -> LedgerTip`

Appends a format version 2 entry inside a `BEGIN IMMEDIATE` transaction and returns its
`LedgerTip` (sequence number and entry hash). A missing or `None` `receipt["signature"]`
records an explicitly `UNSIGNED` entry; an empty-string signature raises `ValueError`.
Identical content is recorded once per append. A repeated `idempotency_key` raises
`IdempotencyKeyConflictError` (an `sqlite3.IntegrityError`) and leaves the ledger unchanged.

### `append_receipt(receipt: dict, sieved_content: str) -> str`

The 1.3.0 append. Writes the same format version 2 entry as `append_entry` and returns
`receipt["payload_hash"]`. Identical content is no longer rejected, so the returned
`payload_hash` does not identify an entry uniquely; use `append_entry` for a `LedgerTip`.

### `iter_entries(start_sequence=1, *, verify=True) -> Iterator[LedgerEntry]`

Yields entries in sequence order. With `verify=True` every link is re-derived from the
genesis constant, including links before `start_sequence`, and `LedgerIntegrityError`
(carrying `.sequence` and `.reason`) is raised at the first failure; an entry that failed
is never yielded. `verify=False` returns whatever is stored, tampered or not.

### `get_tip() -> LedgerTip | None`

The last entry's sequence number and entry hash, as stored (unverified), or `None`.

### `verify_ledger(expected_tip=None) -> LedgerIntegrityReport`

Full chain sweep returning `verified`, `entries_checked`, `failure_sequence`,
`failure_reason` (an `IntegrityFailureReason`: `BROKEN_LINK`, `SEQUENCE_GAP`,
`UNSUPPORTED_FORMAT_VERSION`, `MALFORMED_ENTRY`, `TIP_MISMATCH`) and the current `tip`.
With `expected_tip`, a ledger cut short fails with `TIP_MISMATCH`.

### `verify_ledger_integrity(expected_tip_hash=None) -> bool`

The 1.3.0 verification, unchanged: `True` when the chain verifies and, if supplied, the
final entry's `payload_hash` equals `expected_tip_hash`. That anchor is ambiguous once
identical content exists; prefer `verify_ledger(expected_tip=...)`.

### `close()`

Releases all thread-local SQLite connection handles tracked by this instance.

### Exceptions and types

| Name | Purpose |
|---|---|
| `LedgerTip`, `LedgerEntry`, `LedgerIntegrityReport` | Frozen dataclasses returned by the API |
| `SignatureStatus` | `SIGNED` or `UNSIGNED` |
| `IntegrityFailureReason` | Verification reason codes |
| `LedgerIntegrityError` | First failure met by `iter_entries` |
| `IdempotencyKeyConflictError` | Repeated idempotency key |
| `LedgerMigrationError` | A 1.3.0 file failed verification and was not migrated |
| `SovereignStorageError` | Closed instance or unrecognized schema |

---

## Upgrading from 1.3.0

The first open of a 1.3.0 file rebuilds its table once, in one transaction, to drop the
`UNIQUE` constraint on `payload_hash` and add the version 2 columns. The existing chain is
verified first; a file that fails verification is left untouched and
`LedgerMigrationError` is raised. Every existing row keeps its `id`, values and entry hash.

Before migrating, the ledger writes and verifies a backup of the 1.3.0 file beside it,
named `<name>.v1-backup` (or `<name>.v1-backup.1`, `.2`, ... if that name is taken; a
backup is never overwritten). If the backup cannot be written or verified, the file is
not migrated.

The migration is one-way, and the backup is the only route back to 1.3.0. Version 1.3.0
can still open a migrated file, but its `verify_ledger_integrity()` returns `False` once
any entry follows a version 2 entry, and its appends are refused by a database trigger.
Delete the backup once you are satisfied with the migrated file.

If you run `sovereign-edge`, drain its off-grid buffer before the first open on the new
release. Edge now deduplicates replays by the receipt's signature, and receipts committed
before migration carry no idempotency key, so an already-committed buffered receipt would
be recorded twice.

---

## Integration pattern

`sovereign-ledger` slots into the end of the Sovereign pipeline:

```
[Inbound Payload]
    → sovereign-sieve  (Prose Tax reduction)
    → sovereign-core   (Ed25519 sign → ForensicReceipt)
    → sovereign-ledger (append_entry → immutable audit record)
```

```python
from sovereign_core import SovereignGateway
from sovereign_ledger import SovereignLedger

gateway = SovereignGateway(signing_key=".keys/sovereign_identity.pem")

with SovereignLedger(db_path=".keys/sovereign_audit.db") as ledger:
    response = await gateway.sieve_and_sign(raw_payload)
    tip = ledger.append_entry(response.receipt, response.content)
    assert ledger.verify_ledger(expected_tip=tip).verified
```
