# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-s-declared-capability-set-instead-of-attesting-it-at-invocation-time.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-s-declared-capability-set-instead-of-attesting-it-at-invocation-time.warrant.json
# Markdown SHA-256:   ffe441664e68aaffd6a122ebceedd05a4b3a11aa1770e7b11ea9a28afd3cf7a1
# Code AST SHA-256:   6b22c303e269b6bbd2bf4456cb02f53755ef9ba9785b5e8ec9eb3a288659570e
# Verified Classes:   UnattestedCapabilityError, ToolCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnattestedCapabilityError(RuntimeError):
    """Raised when a plan edge relies on a declared-but-unattested tool effect class."""
    pass


class ToolCall:
    def __init__(self, tool: str, declared_effect: str, observed_effect: str | None,
                 attested: bool, output: str = ""):
        self.tool = tool
        self.declared_effect = declared_effect      # from manifest, attacker-controlled
        self.observed_effect = observed_effect      # from runtime sandbox observation
        self.attested = attested                    # manifest<->handler binding verified?
        self.output = output


EFFECT_RANK = {"read": 0, "write": 1, "network": 2, "exec": 3}


def attest_edge(reader: ToolCall, writer_effect: str) -> None:
    """Enforce: observed_effect(reader) <= declared_effect(writer) AND reader attested.

    Called at plan-compile time for every dataflow edge reader -> writer.
    """
    if not reader.attested:
        raise UnattestedCapabilityError(
            f"tool {reader.tool!r} is unattested; its output cannot feed a "
            f"{writer_effect!r} step without quarantine"
        )
    if reader.observed_effect is None:
        raise UnattestedCapabilityError(
            f"tool {reader.tool!r} has no observed effect; declaration "
            f"{reader.declared_effect!r} is unverified"
        )
    if EFFECT_RANK[reader.observed_effect] > EFFECT_RANK[writer_effect]:
        raise UnattestedCapabilityError(
            f"tool {reader.tool!r} observed effect {reader.observed_effect!r} "
            f"exceeds writer effect {writer_effect!r}; plan edge refused"
        )


def compile_plan(edges: list[tuple[ToolCall, str]]) -> None:
    for reader, writer_effect in edges:
        attest_edge(reader, writer_effect)


if __name__ == "__main__":
    malicious_read = ToolCall(
        tool="repo.peek",
        declared_effect="read",
        observed_effect="network",   # handler actually exfiltrated via socket
        attested=False,
    )
    try:
        compile_plan([(malicious_read, "write")])
    except UnattestedCapabilityError as e:
        print(f"plan refused: {e}")
