# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-capability-token-attenuation-with-egress-taint-gates-when-a-tool-s-declared-output-schema-is-coarser-than-its-actual.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-capability-token-attenuation-with-egress-taint-gates-when-a-tool-s-declared-output-schema-is-coarser-than-its-actual.warrant.json
# Markdown SHA-256:   1a7c1ac265c8f0fa05643f589161285a4ad4eba26ee6a0ee666e73a531c4e0bb
# Code AST SHA-256:   50e9e1551c55c1a0ef30b6046470bcc0dea4e9c2717b4d6f51e8581e31adeade
# Verified Classes:   SchemaTaintDivergence
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SchemaTaintDivergence(RuntimeError):
    """Raised when a tool result's actual payload is not closed under the
    schema the capability token was minted against, or when the declared
    encoding diverges from the byte-level sniffed type in a way that would
    let the taint classifier miss provenance-bearing material."""
    pass


def ingest_tool_result(token, result_bytes, sniffed_type, declared_schema, classifier):
    # 1. Token must assert schema closure; otherwise the gate cannot be sound.
    if not token.attenuation.get("schema_closed", False):
        raise SchemaTaintDivergence(
            f"token {token.id} lacks schema_closed; result cannot be classified soundly"
        )

    # 2. Actual keys must be a subset of declared keys.
    actual_keys = set(result_bytes.keys())
    declared_keys = set(declared_schema.get("properties", {}).keys())
    undeclared = actual_keys - declared_keys
    if undeclared:
        raise SchemaTaintDivergence(
            f"tool {token.tool} returned undeclared keys {sorted(undeclared)}; "
            f"classifier field enumeration is not closed"
        )

    # 3. Declared content type must match sniffed type, or transforms are forbidden.
    declared_type = result_bytes.get("content_type")
    if declared_type != sniffed_type and not token.attenuation.get("no_transform", False):
        raise SchemaTaintDivergence(
            f"declared content_type {declared_type!r} != sniffed {sniffed_type!r} "
            f"and no_transform not set; classifier would miss provenance"
        )

    # 4. Classify the *actual* bytes, not the declared view.
    label = classifier.classify(result_bytes, sniffed_type)
    return {"payload": result_bytes, "taint_label": label, "token_id": token.id}
