# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-taint-label-survive-an-mcp-tool-call-but-not-the-syscall-mediation-that-follows-it-the-label-laundering-boundary-at-the-mediati.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-taint-label-survive-an-mcp-tool-call-but-not-the-syscall-mediation-that-follows-it-the-label-laundering-boundary-at-the-mediati.warrant.json
# Markdown SHA-256:   bc313c9a5b71282a0808be6e205e3a13af250fb207bd2ee1c77103c9967a26a4
# Code AST SHA-256:   e5883ef6a29dbcdfd6c15e0a7b2dffe1189061d16680691d789a3170e7307add
# Verified Classes:   TaintLabelUnjoinable, TaintLabelConflict
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class TaintLabelUnjoinable(RuntimeError):
    """Raised when a mediation-visible buffer has no provenance token that
    joins to a tracker record. This is the laundering boundary: the label was
    dropped or substituted somewhere in the MCP serialization path. It must
    never be silently resolved to 'trusted' or 'tainted'."""
    pass


class TaintLabelConflict(RuntimeError):
    """Raised when the token at mediation joins to a tracker record whose
    label disagrees with the label carried in the MCP argument metadata
    (manifest-over-value substitution)."""
    pass


def mediate_syscall(syscall, tracker, argument_meta):
    """
    syscall:        the pending write, with buffer.provenance_token (may be None)
    tracker:        records provenance_token -> label assigned at ingestion
    argument_meta:  the MCP argument metadata the tool server received
    """
    token = syscall.buffer.provenance_token

    # C1/C4: no joinable token means the label did not survive transport.
    if token is None:
        raise TaintLabelUnjoinable(
            f"buffer for {syscall.path!r} carries no provenance token; "
            f"cannot determine taint. Refusing (fail-closed, C3)."
        )

    record = tracker.lookup(token)
    if record is None:
        raise TaintLabelUnjoinable(
            f"provenance token {token!r} has no tracker record; "
            f"label was minted outside the tracker. Refusing."
        )

    # C2: the authority is the tracker record, not the manifest or the meta.
    value_label = record.label
    carried_label = argument_meta.get("taint_label")

    if carried_label is not None and carried_label != value_label:
        raise TaintLabelConflict(
            f"argument metadata claims {carried_label!r} but tracker says "
            f"{value_label!r} for token {token!r}; manifest-over-value substitution."
        )

    capability = syscall.process.capability("fs:write")
    if not capability.scoped_to(value_label):
        raise PermissionError(
            f"fs:write scoped to {capability.label!r} cannot write "
            f"{value_label!r} buffer to {syscall.path!r}"
        )
    return syscall.execute()
