# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-capability-manifest-replay-window-that-silently-widens-tool-grants-at-load-time.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-capability-manifest-replay-window-that-silently-widens-tool-grants-at-load-time.warrant.json
# Markdown SHA-256:   0ad399290394add595eaa045270d6ef6def8ff8f0cf167e196c16a7925b2f158
# Code AST SHA-256:   b7202897c32561522f4c199a575ec60d6a7de31cf5b8c2cc8d4a60c167d7a2ce
# Verified Classes:   CapabilityDiffError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CapabilityDiffError(RuntimeError):
    """Raised when a load-time manifest diff cannot be soundly auto-approved."""


OPEN_EFFECT_TOOLS = {"shell.exec", "python.eval", "js.dynamic_import", "make.run"}


def evaluate_manifest_diff(
    prev_manifest: dict,
    next_manifest: dict,
    revocation_ledger: dict,
    replay_window: int,
) -> str:
    """
    Classify a manifest delta at agent load time.
    Returns 'APPROVED' or raises CapabilityDiffError with a typed verdict.
    replay_window is advisory only; revocations are checked with full lookback.
    """
    prev_grants = set(prev_manifest.get("grants", []))
    next_grants = set(next_manifest.get("grants", []))
    added = next_grants - prev_grants

    for grant in added:
        tool, _, scope = grant.partition(":")

        # (1) Open-effect tools: set membership is not a sound safety proxy.
        if tool in OPEN_EFFECT_TOOLS:
            raise CapabilityDiffError(
                f"OPEN_EFFECT widening on {grant!r}: tool admits an open "
                f"effect set; additive-set heuristic is unsound. "
                f"Requires out-of-band approval bound to composite hash."
            )

        # (2) Revocation amnesia: full lineage lookback, not replay_window.
        if grant in revocation_ledger:
            revoked_at = revocation_ledger[grant]
            raise CapabilityDiffError(
                f"REVOKED_GRANT_REINTRODUCTION: {grant!r} was revoked at "
                f"manifest v{revoked_at}. Replay window ({replay_window}) "
                f"does not license forgetting a revocation."
            )

        # (3) Cross-domain widening within an identical grant class.
        prev_scopes = {g.partition(":")[2] for g in prev_grants if g.startswith(tool + ":")}
        if prev_scopes and scope not in prev_scopes:
            prev_domains = {s.split("/")[1] for s in prev_scopes if s.count("/") >= 2}
            next_domain = scope.split("/")[1] if scope.count("/") >= 2 else scope
            if prev_domains and next_domain not in prev_domains:
                raise CapabilityDiffError(
                    f"CROSS_DOMAIN_WIDENING: {grant!r} extends {tool} from "
                    f"domain(s) {sorted(prev_domains)} into {next_domain!r}; "
                    f"set-diff cannot see trust boundaries."
                )

    return "APPROVED"
