# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-degrades-a-tool-result-to-satisfy-a-context-budget-governor-and-the-truncated-artifact-becomes-the-ground-truth-for-the.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-degrades-a-tool-result-to-satisfy-a-context-budget-governor-and-the-truncated-artifact-becomes-the-ground-truth-for-the.warrant.json
# Markdown SHA-256:   6c16d393b907617523282f98158e588595e2c3d6e5b0bb1c6aa4fb893306ebd9
# Code AST SHA-256:   912c87cc4497164bb0c95b6f283858ac9829320f09369854dc18dbd455f67776
# Verified Classes:   ContextBudgetIntegrityError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ContextBudgetIntegrityError(RuntimeError):
    """Raised when a degradation step would strip verifiability from a
    load-bearing artifact without leaving a coverage certificate."""


SAFE_DEGRADATIONS = {"slice_with_sentinel", "handle_substitution"}
UNSAFE_DEGRADATIONS = {"summarize", "drop_oldest"}


def degrade_artifact(artifact, projected_tokens, ceiling, ladder):
    """
    Apply the first ladder step that brings projected_tokens under ceiling,
    but refuse any step that destroys referential integrity without a
    coverage certificate. artifact: {id, tokens, byte_len, load_bearing}
    """
    if projected_tokens <= ceiling:
        return artifact

    for step in ladder:
        if step in UNSAFE_DEGRADATIONS and artifact["load_bearing"]:
            # Do not silently project a load-bearing artifact.
            raise ContextBudgetIntegrityError(
                f"refusing '{step}' on load-bearing artifact "
                f"{artifact['id']!r} ({artifact['tokens']} tokens): "
                f"no coverage certificate would remain; "
                f"agent cannot distinguish 'unseen' from 'absent'"
            )
        if step == "slice_with_sentinel":
            return _slice_with_coverage(artifact)
        if step == "handle_substitution":
            return _substitute_handle(artifact)
        if step in UNSAFE_DEGRADATIONS:
            # Non-load-bearing: safe to project, but still tombstone it.
            return _project_with_tombstone(artifact, step)

    # Ladder exhausted without a safe step: fail loudly, do not degrade.
    raise ContextBudgetIntegrityError(
        f"no safe degradation for {artifact['id']!r} at ceiling {ceiling}; "
        f"surface ContextBudgetExceeded to the planner"
    )


def _slice_with_coverage(artifact):
    return {**artifact, "mode": "slice",
            "sentinel": f"[TRUNCATED: {artifact['byte_len']}B total]"}


def _substitute_handle(artifact):
    return {**artifact, "mode": "handle",
            "handle": f"artifact://{artifact['id']}", "tokens": 40}


def _project_with_tombstone(artifact, step):
    return {**artifact, "mode": step,
            "tombstone": f"[{step} applied; original retrievable via handle]"}
