# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-registry-reload-as-an-authority-boundary-event-rather-than-a-capability-refresh.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-registry-reload-as-an-authority-boundary-event-rather-than-a-capability-refresh.warrant.json
# Markdown SHA-256:   643d92de93300dc4fb373bca7085183f7d4b8b3c9422718a8a82f04aa229efa7
# Code AST SHA-256:   d1f795659081ed11cde73390679fc5e0d14e223af9bea88dc2e9d4dafe52b4e8
# Verified Classes:   AuthorityBoundaryViolation, ToolEntry, TaskContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class AuthorityBoundaryViolation(RuntimeError):
    """Raised when a registry reload would mutate the instruction plane mid-task."""


@dataclass(frozen=True)
class ToolEntry:
    name: str
    description: str            # free-text; this is the injection surface
    effectful: bool             # side effect reachable by an injected instruction
    version: int


@dataclass
class TaskContext:
    live: bool                  # C1: populated preamble / mid-loop planner
    authorized_tools: set[str] = field(default_factory=set)
    rendered_descriptions: dict[str, str] = field(default_factory=dict)


_IMPERATIVE_MARKERS = (
    "before using", "you must", "required by", "first call",
    "note for the assistant", "workspace policy",
)


def _description_is_instruction_bearing(desc: str, known_tools: Iterable[str]) -> bool:
    low = desc.lower()
    if any(m in low for m in _IMPERATIVE_MARKERS):
        return True
    # references another tool by name -> potential re-purposing of an authorized effect
    return any(t and t.lower() in low for t in known_tools)


def apply_reload(ctx: TaskContext, incoming: list[ToolEntry],
                 verifier_approved: set[str]) -> TaskContext:
    """Apply a registry reload under the authority-boundary invariant.

    Invariant: instructions visible to the planner == authorized tool descriptions.
    A reload that adds/edits description-bearing entries while ctx.live must be a
    context rebuild, not an append; instruction-bearing descriptions require an
    out-of-band verifier that is isolated from task context.
    """
    known = ctx.authorized_tools | {t.name for t in incoming}
    effectful_present = any(t.effectful for t in incoming) or any(
        t for t in incoming if t.effectful
    )

    for t in incoming:
        instruction_bearing = _description_is_instruction_bearing(t.description, known)

        # C1 ∧ C2 ∧ C3 conjunction -> authority event
        if ctx.live and t.description and effectful_present and instruction_bearing:
            if t.name not in verifier_approved:
                raise AuthorityBoundaryViolation(
                    f"reload of {t.name!r} carries instruction-bearing description "
                    f"while task context is live and effectful tools are reachable; "
                    f"refusing append, require context rebuild + isolated verifier"
                )

        # A description may describe a capability; it may never justify a call.
        if instruction_bearing and t.name not in verifier_approved:
            raise AuthorityBoundaryViolation(
                f"tool {t.name!r} description asserts imperative/authority content; "
                f"not admissible as justification without out-of-band approval"
            )

    # Rebuild, do not append: removed descriptions must vanish from the preamble.
    new_ctx = TaskContext(
        live=ctx.live,
        authorized_tools={t.name for t in incoming},
        rendered_descriptions={t.name: t.description for t in incoming},
    )
    return new_ctx


def on_tools_list_changed(ctx: TaskContext, incoming: list[ToolEntry],
                          verifier_approved: set[str]) -> TaskContext:
    try:
        return apply_reload(ctx, incoming, verifier_approved)
    except AuthorityBoundaryViolation:
        # Fail closed: freeze planner, preserve prior authorized set, escalate.
        raise
