# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-tombstone-provenance-when-a-scoped-forget-deletes-a-parent-memory-that-derived-facts-still-cite.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-tombstone-provenance-when-a-scoped-forget-deletes-a-parent-memory-that-derived-facts-still-cite.warrant.json
# Markdown SHA-256:   b76ddc6cdc970172079eb2f2f2aa46af812244fc20fb99f1f381af2c42daa596
# Code AST SHA-256:   90af6f7b1c5e332058e63770365436f373664222000e5757255a191a6b523972
# Verified Classes:   ProvenanceAuditError, Tombstone
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Literal

Verdict = Literal["VALID", "UNVERIFIABLE", "INVALIDATED", "DANGLING"]


class ProvenanceAuditError(RuntimeError):
    """Raised when a derived record's provenance chain cannot be resolved safely."""


@dataclass(frozen=True)
class Tombstone:
    record_id: str
    deleted_by_scope: str


def scope_covers(tombstone_scope: str, child_scope: str) -> bool:
    # Containment, not equality: a tenant tombstone covers its sessions;
    # a session tombstone does NOT cover a sibling tenant.
    return child_scope == tombstone_scope or child_scope.startswith(tombstone_scope + ":")


def resolve_derived(
    child_id: str,
    child_scope: str,
    parents: list[str],
    live_store: dict[str, str],       # id -> owner_scope
    tombstones: dict[str, Tombstone],
) -> Verdict:
    saw_unverifiable = False
    for pid in parents:
        if pid in live_store:
            if not scope_covers(child_scope, live_store[pid]):
                # parent exists but this reader cannot see it
                saw_unverifiable = True
            continue
        ts = tombstones.get(pid)
        if ts is None:
            # absent from live store AND no tombstone: corruption
            raise ProvenanceAuditError(
                f"derived {child_id}: parent {pid} dangling (no live record, no tombstone)"
            )
        if scope_covers(ts.deleted_by_scope, child_scope):
            return "INVALIDATED"
        # deleted under a scope that does not cover this child
        saw_unverifiable = True

    return "UNVERIFIABLE" if saw_unverifiable else "VALID"


def read_memory(
    child_id: str,
    child_scope: str,
    parents: list[str],
    live_store: dict[str, str],
    tombstones: dict[str, Tombstone],
) -> dict:
    verdict = resolve_derived(child_id, child_scope, parents, live_store, tombstones)
    if verdict == "INVALIDATED":
        raise ProvenanceAuditError(
            f"derived {child_id}: ancestor deleted under covering scope; refusing to surface"
        )
    if verdict == "UNVERIFIABLE":
        raise ProvenanceAuditError(
            f"derived {child_id}: ancestor unverifiable in scope {child_scope}; "
            f"refusing to surface as fact"
        )
    return {"id": child_id, "verdict": verdict, "confidence": "as-recorded"}
