# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-planner-intent-and-tool-returned-content-when-a-retrieved-document-can-rewrite-its-own-goal.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-planner-intent-and-tool-returned-content-when-a-retrieved-document-can-rewrite-its-own-goal.warrant.json
# Markdown SHA-256:   364ec0bc8d142907cd52b61594374e808ffb5dd65870a5914cf58162c8830216
# Code AST SHA-256:   2901e775ae7e16f8a81bfc6e4104cf296bd4e54230ea6878bbd8bdbb32c4feaf
# Verified Classes:   GoalAuthorityViolation, PlannerStep
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class GoalAuthorityViolation(RuntimeError):
    """Raised when a plan step's authority traces to tool output, not the goal channel."""
    pass


class PlannerStep:
    def __init__(self, tool: str, args: dict, justification: str, provenance: str):
        self.tool = tool
        self.args = args
        self.justification = justification
        self.provenance = provenance  # "goal" | "tool_output" | "model_prior"


SIDE_EFFECTING = {"read_file", "create_issue", "http_post", "exec"}
SENSITIVE_PATHS = ("~/.ssh", "/etc/shadow", ".aws/credentials")


def gate_plan_step(step: PlannerStep, goal_token_ids: set, context_saturation: float) -> None:
    # 1. Subgoal provenance: a new capability justified by tool output is a hijack.
    if step.tool in SIDE_EFFECTING and step.provenance != "goal":
        raise GoalAuthorityViolation(
            f"step '{step.tool}' authorized by {step.provenance}, not goal channel"
        )

    # 2. Sensitive-path read requires goal-channel justification, never retrieved text.
    target = str(step.args.get("path", ""))
    if any(s in target for s in SENSITIVE_PATHS):
        if step.provenance != "goal":
            raise GoalAuthorityViolation(
                f"sensitive read '{target}' lacks goal-derived warrant"
            )

    # 3. Flooding-aware re-anchor: high saturation + new capability = force re-check.
    if context_saturation > 0.5 and step.tool in SIDE_EFFECTING:
        if step.provenance != "goal":
            raise GoalAuthorityViolation(
                "context saturation high and step not goal-anchored; refusing"
            )


def run_planner_step(step: PlannerStep, goal_token_ids: set, saturation: float) -> None:
    try:
        gate_plan_step(step, goal_token_ids, saturation)
    except GoalAuthorityViolation:
        # Re-anchor goal at tail of prompt and replan without the poisoned step.
        raise
    # ... execute tool only after gate passes ...
