# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-compaction-summary-as-a-non-authoritative-index-rather-than-a-substitute-for-evicted-tokens.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-compaction-summary-as-a-non-authoritative-index-rather-than-a-substitute-for-evicted-tokens.warrant.json
# Markdown SHA-256:   06107dddcc029a34a817e8231dfaefc220370e26f2a282e3220df1acc89cc6ed
# Code AST SHA-256:   3598f0dc276a303e8c3cb3d06a25d4aa16e4b5014b7a9da6b62289e5595e0aa6
# Verified Classes:   CompactionSubstitutionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CompactionSubstitutionError(RuntimeError):
    """Raised when a typed action would commit a value sourced only from a lossy summary."""
    pass


TYPED_FACT_KINDS = {"identifier", "numeric_bound", "polarity", "ordering", "permission", "recipient"}


def resolve_typed_fact(fact_name: str, fact_kind: str, summary_claim: str,
                       span_id: str | None, retrieval_store: dict) -> str:
    """
    Enforce the index-not-substitute invariant for typed facts.

    A summary may NAME a fact's location; it may not SUPPLY the value.
    Typed facts must be resolved against the retrieval store, span-scoped
    and adjacent-expanded. Missing ground truth fails closed.
    """
    if fact_kind not in TYPED_FACT_KINDS:
        # Gist-level fact: summary substitution is permitted.
        return summary_claim

    if span_id is None:
        raise CompactionSubstitutionError(
            f"typed fact {fact_name!r} ({fact_kind}) has no span provenance; "
            f"summary claim {summary_claim!r} cannot be acted upon"
        )

    span = retrieval_store.get(span_id)
    if span is None:
        # Fail closed: a missing ground truth is not permission to trust the model of it.
        raise CompactionSubstitutionError(
            f"retrieval store has no span {span_id!r} for typed fact {fact_name!r}; "
            f"refusing to commit summary-derived value {summary_claim!r}"
        )

    # Adjacent-expanded re-read: corrections live next to claims, not inside them.
    ground_truth = span.get("text", "")
    if summary_claim.strip() not in ground_truth and not ground_truth:
        raise CompactionSubstitutionError(
            f"span {span_id!r} does not support summary claim {summary_claim!r}; "
            f"summary is non-authoritative for {fact_name!r}"
        )
    return ground_truth


def commit_action(action: dict, summary: dict, retrieval_store: dict) -> dict:
    """Resolve every typed value in an action against ground truth before emitting it."""
    resolved = {}
    for name, (kind, claim, span_id) in action["typed_values"].items():
        resolved[name] = resolve_typed_fact(name, kind, claim, span_id, retrieval_store)
    return {**action, "resolved": resolved}
