# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-lossy-auto-compaction-has-silently-severed-a-recovery-anchor-from-its-live-reasoning-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-lossy-auto-compaction-has-silently-severed-a-recovery-anchor-from-its-live-reasoning-trace.warrant.json
# Markdown SHA-256:   4820d55c9529793651cd6786a5d3b88161b6207a2b37643c728e5a91c70dc65a
# Code AST SHA-256:   b85fd60633a9af6c2f4d8328851688a41a4921deae2bc7ff5de22b2a129aa4a1
# Verified Classes:   AnchorProvenanceError, ActionPayload
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass


class AnchorProvenanceError(RuntimeError):
    """Raised when an action payload contains a literal that is reconstructed,
    not recalled verbatim from the live context or an external anchor store."""
    pass


@dataclass
class ActionPayload:
    tool: str
    args: dict


def _literals_in(payload: ActionPayload) -> list[str]:
    # Extract the byte-exact literals that will cross an irreversible boundary.
    # Identifiers, ordered lists, and quoted contract clauses are the usual anchors.
    found = []
    for value in payload.args.values():
        if isinstance(value, str) and len(value) >= 6:
            found.append(value)
        elif isinstance(value, (list, tuple)):
            found.extend(str(v) for v in value if len(str(v)) >= 4)
    return found


def verify_anchor_provenance(
    payload: ActionPayload,
    live_context: str,
    anchor_store: dict[str, str] | None = None,
) -> None:
    """Invariant: every action literal must appear verbatim in live_context
    or be resolvable by key in anchor_store. Reconstruction is forbidden."""
    anchor_store = anchor_store or {}
    for literal in _literals_in(payload):
        in_context = literal in live_context
        in_store = literal in anchor_store.values()
        if not (in_context or in_store):
            raise AnchorProvenanceError(
                f"literal {literal!r} in {payload.tool}.args is reconstructed, "
                f"not recalled verbatim; compaction likely severed its anchor. "
                f"Re-fetch from anchor_store or halt and re-derive."
            )


def guarded_emit(
    payload: ActionPayload,
    live_context: str,
    anchor_store: dict[str, str] | None = None,
) -> ActionPayload:
    verify_anchor_provenance(payload, live_context, anchor_store)
    return payload
