# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-survives-a-tool-boundary-when-provenance-labels-are-stripped-by-schema-coercion.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-survives-a-tool-boundary-when-provenance-labels-are-stripped-by-schema-coercion.warrant.json
# Markdown SHA-256:   64469e69adb6738bbd23df305f0456776233a3cff4d88bc402e38176b45d4c20
# Code AST SHA-256:   9ed83e300aa5ba978ea3de598ab6b3a764127665d13cb3118457cb73200a3f82
# Verified Classes:   TaintProjectionError, ProvenanceNullError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintProjectionError(RuntimeError):
    """Raised when a tainted object is projected into a schema that cannot carry its provenance."""
    pass


class ProvenanceNullError(RuntimeError):
    """Raised when a provenance field is present but null — treated as untrusted, not defaulted."""
    pass


TRUSTED = "trusted"
UNTRUSTED = "untrusted"


def project_arguments(annotated_obj: dict, target_schema: dict) -> dict:
    """
    Project an annotated argument object onto a tool's declared schema.
    Refuses to drop a taint label. Fails closed on null provenance.
    """
    provenance = annotated_obj.get("provenance")
    is_tainted = bool(provenance) and provenance.get("trust") == UNTRUSTED

    schema_fields = target_schema.get("properties", {})
    carries_provenance = any(
        f in schema_fields for f in ("provenance", "origin", "taint_id", "trust")
    )

    if is_tainted and not carries_provenance:
        raise TaintProjectionError(
            f"taint_id={provenance.get('taint_id')} cannot be projected into schema "
            f"lacking a provenance field; refusing to strip label across tool boundary"
        )

    projected = {k: v for k, v in annotated_obj.items() if k in schema_fields}

    # Fail-closed: a declared-but-null provenance field is untrusted, not trusted.
    for pf in ("provenance", "origin", "trust", "taint_id"):
        if pf in schema_fields:
            if projected.get(pf) is None:
                raise ProvenanceNullError(
                    f"provenance field '{pf}' present in schema but null after projection; "
                    f"treating as untrusted and halting"
                )

    return projected


def guard_side_effect(arguments: dict, side_effecting: bool) -> None:
    """Gate in front of any tool with external side effects."""
    if not side_effecting:
        return
    prov = arguments.get("provenance") or {}
    if prov.get("trust") != TRUSTED:
        raise TaintProjectionError(
            f"side-effecting call blocked: trust={prov.get('trust')!r} "
            f"(absent or non-trusted provenance fails closed)"
        )
