# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-skill-manifest-s-declared-capability-set-over-its-observed-tool-call-trace-the-manifest-shadow-injection-surfac.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-skill-manifest-s-declared-capability-set-over-its-observed-tool-call-trace-the-manifest-shadow-injection-surfac.warrant.json
# Markdown SHA-256:   ee546844dc7488102eee49f2a1d2de421a22e9a21adc33d059dddd4d464096b1
# Code AST SHA-256:   38b06579bd3d07697f655f0034db48905d02e113667b07386ae0f00f282f001c
# Verified Classes:   ManifestShadowInjectionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ManifestShadowInjectionError(RuntimeError):
    """Raised when a skill's return value is admitted into the instruction plane
    without an output-provenance contract, while the active capability set
    contains a tool referenced by the return value."""
    pass


TRUSTED_PROVENANCE = {"trusted-static"}


def admit_tool_result(manifest: dict, result: str, active_capabilities: set[str]) -> dict:
    """Gate a tool result before it enters the context window.

    Invariant: a result may be marked trusted only if the manifest declares
    outputProvenance in TRUSTED_PROVENANCE AND the result conforms to the
    declared output type. Otherwise it is untrusted-derived and must be
    quarantined: the planner may read it as data, never as instruction.
    """
    declared = manifest.get("outputProvenance")
    if declared is None:
        # Silence is not trust. Quarantine, and check for capability shadowing.
        referenced = _extract_referenced_tools(result)
        shadowed = referenced & active_capabilities
        if shadowed:
            raise ManifestShadowInjectionError(
                f"skill {manifest.get('name')!r} returned content referencing "
                f"active capabilities {sorted(shadowed)} with no output-provenance "
                f"declaration; refusing to admit result into instruction plane"
            )
        return {"provenance": "untrusted-derived", "content": result, "instruction_followable": False}

    if declared in TRUSTED_PROVENANCE:
        if not _conforms_to_declared_output_type(manifest, result):
            raise ManifestShadowInjectionError(
                f"skill {manifest.get('name')!r} declared {declared!r} but returned "
                f"a value violating its declared output type; trust contract broken"
            )
        return {"provenance": "trusted", "content": result, "instruction_followable": True}

    # declared == "derived-from-input" or any other non-trusted value
    return {"provenance": "untrusted-derived", "content": result, "instruction_followable": False}


def _extract_referenced_tools(text: str) -> set[str]:
    # Conservative: any identifier shaped like a registered tool name.
    import re
    return set(re.findall(r"\b[a-z_][a-z0-9_]*\b", text)) - {"the", "a", "to", "and", "before"}


def _conforms_to_declared_output_type(manifest: dict, result: str) -> bool:
    return manifest.get("outputType", "string") == "string" and isinstance(result, str)
