# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-hallucinate-continuity-across-a-compaction-boundary-it-cannot-audit.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-hallucinate-continuity-across-a-compaction-boundary-it-cannot-audit.warrant.json
# Markdown SHA-256:   aa8eaf3e69b89539347e1927bcba16481031a5eabeba5ef8f3e78fafd470e4a5
# Code AST SHA-256:   e04d592e2d052cca621127e706cdbd812683141bb6611f254b4ab6a3c790d6b1
# Verified Classes:   CompactionFidelityError, Claim, CompactionLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionFidelityError(RuntimeError):
    """Raised when a compaction step launders epistemic status:
    raises assertion strength on an unverified claim as provenance
    distance grows, or emits an unresolvable definite reference."""


@dataclass
class Claim:
    claim_id: str
    text: str
    hedge_score: float          # 0.0 bare fact .. 1.0 fully hedged
    provenance_distance: int    # compaction hops from originating span
    verified_in_environment: bool = False


@dataclass
class CompactionLedger:
    claims: dict[str, Claim] = field(default_factory=dict)

    def carry_forward(self, prior: "CompactionLedger", assertion_strengths: dict[str, float]) -> None:
        # Increment provenance distance for every carried claim, then audit.
        for cid, claim in prior.claims.items():
            carried = Claim(
                claim_id=cid,
                text=claim.text,
                hedge_score=claim.hedge_score,
                provenance_distance=claim.provenance_distance + 1,
                verified_in_environment=claim.verified_in_environment,
            )
            self.claims[cid] = carried
        self._audit_laundering(assertion_strengths)

    def _audit_laundering(self, assertion_strengths: dict[str, float]) -> None:
        for cid, claim in self.claims.items():
            a = assertion_strengths.get(cid, claim.hedge_score)
            # Invariant: assertion strength may not exceed origin hedge
            # unless the claim was verified against the live environment.
            if a > claim.hedge_score and not claim.verified_in_environment:
                raise CompactionFidelityError(
                    f"claim {cid!r} laundered: assertion={a:.2f} > "
                    f"origin_hedge={claim.hedge_score:.2f} at "
                    f"provenance_distance={claim.provenance_distance} "
                    f"(unverified). Refusing to emit summary; re-verify or "
                    f"carry hedge forward."
                )
            # Second guard: deep claims must not be treated as bare fact.
            if claim.provenance_distance >= 2 and a >= 0.9 and not claim.verified_in_environment:
                raise CompactionFidelityError(
                    f"claim {cid!r} promoted to fact at hop "
                    f"{claim.provenance_distance} without environment "
                    f"verification; successor would build on a hypothesis."
                )


def compact(prior: CompactionLedger, assertion_strengths: dict[str, float]) -> CompactionLedger:
    ledger = CompactionLedger()
    ledger.carry_forward(prior, assertion_strengths)
    return ledger


# Trace of the staging-creds incident:
origin = CompactionLedger(claims={
    "staging_creds_path": Claim(
        claim_id="staging_creds_path",
        text="creds maybe in secrets/staging.env",
        hedge_score=0.8,
        provenance_distance=0,
    )
})
hop1 = compact(origin, {"staging_creds_path": 0.8})   # hedge carried: OK
hop2 = compact(hop1, {"staging_creds_path": 0.95})    # compactor flattens -> raises
