# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-provenance-threshold-boundary-when-a-poisoned-memory-write-arrives-with-a-valid-but-laundered-derivation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-provenance-threshold-boundary-when-a-poisoned-memory-write-arrives-with-a-valid-but-laundered-derivation-chain.warrant.json
# Markdown SHA-256:   5a69752e42d71fdc1df83c0b5d1360bc969d63325f16378df4099cfd6977f6f5
# Code AST SHA-256:   45a52d0f5360e9b1300eae52cf80b5af35978301a00716588cdbab1a243166e5
# Verified Classes:   UngroundedChainError, SeveredLeafError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UngroundedChainError(RuntimeError):
    pass


class SeveredLeafError(RuntimeError):
    pass


ANCHOR_KINDS = {"re_executable_tool", "content_hash", "signed_user_assertion"}
THRESHOLD = 0.72


def admit_write(chain, score):
    has_anchor = any(hop["kind"] in ANCHOR_KINDS for hop in chain)
    leaf_present = bool(chain) and chain[-1].get("source_id") is not None

    if not leaf_present:
        raise SeveredLeafError(
            f"chain of length {len(chain)} has no leaf source_id; "
            "cannot propagate downstream poisoning alerts"
        )

    if score < THRESHOLD:
        return {"decision": "reject", "reason": "below_threshold"}

    if has_anchor:
        return {"decision": "admit", "grounded": True}

    if not has_anchor:
        # ungrounded but plausible: quarantine, do not silently admit
        if score >= THRESHOLD and not has_anchor and leaf_present:
            return {"decision": "admit_with_quarantine", "grounded": False}
        raise UngroundedChainError(
            "ungrounded chain reached admission path without quarantine routing"
        )
