# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-summary-drift-when-hierarchical-context-compaction-silently-diverges-from-the-lossless-retrieval-sidecar-it-wa.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-summary-drift-when-hierarchical-context-compaction-silently-diverges-from-the-lossless-retrieval-sidecar-it-wa.warrant.json
# Markdown SHA-256:   985dca259cc2100f7e5370e7488d1243940969f276e814692fcdb29b2eef219f
# Code AST SHA-256:   1d60404d7fc014514377e0818903af62a621552a8f3db09ba988f1f87f7f6368
# Verified Classes:   SummaryDriftError, Claim
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class SummaryDriftError(RuntimeError):
    """Raised when a compacted summary strengthens or broadens a source claim,
    indicating summary-sidecar dissociation that would misroute retrieval."""
    pass


@dataclass
class Claim:
    text: str
    scope: str          # e.g. "migration_report" or "global"
    source_span_id: str


def specificity_leq(summary_scope: str, source_scopes: list[str]) -> bool:
    # A summary claim is valid only if its scope is no broader than at least
    # one source span it derives from. "global" is broader than any named scope.
    if summary_scope == "global":
        return all(s == "global" for s in source_scopes)
    return summary_scope in source_scopes


def round_trip_gate(
    new_summary_claims: list[Claim],
    source_only_index,
    entail_fn,
) -> None:
    """Verify each summary claim against SOURCE-ONLY spans (never the summary
    namespace). Reject on specificity gain or failed source->summary entailment."""
    for claim in new_summary_claims:
        spans = source_only_index.retrieve(claim.text, k=5, namespace="source")
        if not spans:
            raise SummaryDriftError(
                f"claim {claim.text!r} has no source support in sidecar"
            )
        source_scopes = [s.scope for s in spans]
        if not specificity_leq(claim.scope, source_scopes):
            raise SummaryDriftError(
                f"specificity gain: summary scope {claim.scope!r} broader than "
                f"source scopes {source_scopes}; claim {claim.text!r} is drifted"
            )
        if not any(entail_fn(s.text, claim.text) for s in spans):
            raise SummaryDriftError(
                f"no source span entails summary claim {claim.text!r}; "
                f"re-derive from source, do not re-summarize the summary"
            )


def compact_cycle(previous_summary, source_only_index, summarizer, entail_fn):
    candidate = summarizer(previous_summary)  # may be drifted
    round_trip_gate(candidate.claims, source_only_index, entail_fn)
    return candidate  # only reached if gate passes
