# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-its-own-anomaly-score-score-inversion-under-provenance-graph-densification-on-the-memory-write-path.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-its-own-anomaly-score-score-inversion-under-provenance-graph-densification-on-the-memory-write-path.warrant.json
# Markdown SHA-256:   f0fad6e76f305f40a0d32508f12e7841b591cbc7ad1a9748129d6848dfedceee
# Code AST SHA-256:   beea8f6889f52afc5bae4c0436d5fdac164cdf0a4c136ec3a247a45d77a99e28
# Verified Classes:   ProvenanceScoreInvalidError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ProvenanceScoreInvalidError(RuntimeError):
    """Raised when an anomaly score is computed under graph density
    outside its calibration band, making the score-to-trust mapping
    undefined (score inversion risk)."""
    pass


def gate_memory_write(
    write_id: str,
    anomaly_score: float,
    ancestor_degree_p95: float,
    calibration_degree_band: tuple[float, float],
    separation_margin: float,
    variance_floor: float,
) -> str:
    low, high = calibration_degree_band

    density_drifted = not (low <= ancestor_degree_p95 <= high)
    separation_collapsed = separation_margin < variance_floor

    if density_drifted or separation_collapsed:
        # Do NOT re-tune the threshold here. The score carries no
        # decision information under these conditions; escalate to a
        # density-independent fallback path instead.
        raise ProvenanceScoreInvalidError(
            f"write {write_id!r}: score {anomaly_score:.3f} is not "
            f"trustworthy (ancestor_degree_p95={ancestor_degree_p95:.2f}, "
            f"calibrated_band={calibration_degree_band}, "
            f"separation_margin={separation_margin:.3f}, "
            f"variance_floor={variance_floor:.3f}); "
            f"route to taint-reachability fallback or human review"
        )

    return "accept" if anomaly_score < 0.5 else "quarantine"
