# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-attenuation-guarantees-when-a-delegated-capability-is-re-derived-from-observed-behavior-instead-of-the-signed-warrant-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-attenuation-guarantees-when-a-delegated-capability-is-re-derived-from-observed-behavior-instead-of-the-signed-warrant-chain.warrant.json
# Markdown SHA-256:   4b4d124c1221a2cb61fb001b79b0db2f2bb0944ba7e4860c3c468ebfa721a40d
# Code AST SHA-256:   578a0dea5f877c3d97ae6f3fd6a2e1de89056e8585ef851a360e87323b0daca9
# Verified Classes:   AttenuationViolation, Warrant, Executor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class AttenuationViolation(RuntimeError):
    """Raised when an admitted action is not a member of the signed warrant scope."""


@dataclass(frozen=True)
class Warrant:
    caveats: FrozenSet[str]          # e.g. {"fs:write:/work/j/drafts/*.md"}
    max_calls: int
    expires_at: float


def parse_scope(warrant: Warrant) -> FrozenSet[str]:
    # Structural parse of the signed caveat set. No model in the loop.
    return frozenset(c for c in warrant.caveats if c.startswith("fs:write:"))


def action_in_scope(action: str, scope: FrozenSet[str]) -> bool:
    # Path-algebra check: exact prefix + extension match, not semantic similarity.
    for caveat in scope:
        prefix = caveat[len("fs:write:"):]
        if prefix.endswith("/*.md"):
            base = prefix[:-len("*.md")]
            if action.startswith(base) and action.endswith(".md"):
                return True
    return False


@dataclass
class Executor:
    warrant: Warrant
    calls_made: int = 0
    peer_activity: list = field(default_factory=list)  # observed behavior — planning only

    def admit(self, action: str, now: float) -> None:
        if now > self.warrant.expires_at:
            raise AttenuationViolation(f"warrant expired at {self.warrant.expires_at}")
        if self.calls_made >= self.warrant.max_calls:
            raise AttenuationViolation(f"max_calls={self.warrant.max_calls} exhausted")

        scope = parse_scope(self.warrant)
        if not action_in_scope(action, scope):
            # Deliberately do NOT consult peer_activity here.
            raise AttenuationViolation(
                f"action {action!r} not in signed scope {sorted(scope)}; "
                f"observed peer activity {self.peer_activity!r} is not authorization"
            )
        self.calls_made += 1


def run_hop(executor: Executor, planned_action: str, now: float) -> None:
    # Planning may use peer_activity; admission may not.
    executor.admit(planned_action, now)


if __name__ == "__main__":
    w = Warrant(
        caveats=frozenset({"fs:write:/work/j/drafts/*.md"}),
        max_calls=20,
        expires_at=1_000_000.0,
    )
    ex = Executor(warrant=w)
    ex.peer_activity.append("write /work/j/drafts/_scratch/plan.json")
    # Sibling probe: plausible, adjacent, and NOT in the signed chain.
    run_hop(ex, "/work/j/drafts/_scratch/render.bin", now=999_999.0)  # raises
