# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-dynamically-re-fetched-tool-manifest-as-an-untrusted-capability-grant-rather-than-a-schema-refresh.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-dynamically-re-fetched-tool-manifest-as-an-untrusted-capability-grant-rather-than-a-schema-refresh.warrant.json
# Markdown SHA-256:   c8ab7363e861fe791da68515f7df15595e16d71eaca3b2fbb3e159cbc4dee4d1
# Code AST SHA-256:   99903ef7395f273f84fb05f712ecbda331900c048c6b342539a5b6e01e0e276b
# Verified Classes:   ManifestTrustViolation, TrustRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any

CAPABILITY_FIELDS = frozenset({
    "readOnlyHint", "destructiveHint", "idempotentHint", "openWorldHint",
    "additionalProperties", "$ref", "required", "sideEffects",
})

SAFE_FIELDS = frozenset({"description", "title", "examples", "documentation"})


class ManifestTrustViolation(RuntimeError):
    """Raised when a re-fetched manifest mutates capability surface under a stale warrant."""
    pass


@dataclass
class TrustRecord:
    tool_name: str
    version: str
    manifest_hash: str
    trust_epoch: int
    authorized_manifest: dict[str, Any] = field(repr=False)


def canonical_hash(manifest: dict[str, Any]) -> str:
    blob = json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


def diff_keys(old: dict[str, Any], new: dict[str, Any], prefix: str = "") -> set[str]:
    keys: set[str] = set()
    for k in set(old) | set(new):
        path = f"{prefix}{k}"
        if k not in old or k not in new:
            keys.add(path)
            continue
        ov, nv = old[k], new[k]
        if isinstance(ov, dict) and isinstance(nv, dict):
            keys |= diff_keys(ov, nv, prefix=f"{path}.")
        elif ov != nv:
            keys.add(path)
    return keys


def refresh_manifest(record: TrustRecord, fresh: dict[str, Any]) -> TrustRecord:
    fresh_hash = canonical_hash(fresh)
    if fresh_hash == record.manifest_hash:
        return record  # no-op refresh

    changed = diff_keys(record.authorized_manifest, fresh)
    leaf_keys = {p.rsplit(".", 1)[-1] for p in changed}

    if leaf_keys <= SAFE_FIELDS:
        # Schema refresh only: keep warrant, update cached hash.
        return TrustRecord(
            tool_name=record.tool_name,
            version=record.version,
            manifest_hash=fresh_hash,
            trust_epoch=record.trust_epoch,
            authorized_manifest=fresh,
        )

    if leaf_keys & CAPABILITY_FIELDS or not (leaf_keys <= SAFE_FIELDS):
        # Capability mutation OR unknown field: fail-closed, invalidate warrant.
        raise ManifestTrustViolation(
            f"tool {record.tool_name!r} v{record.version} capability surface mutated "
            f"under unchanged version; changed={sorted(changed)}; "
            f"old_hash={record.manifest_hash[:12]} new_hash={fresh_hash[:12]}; "
            f"trust_epoch={record.trust_epoch} MUST be re-authorized"
        )

    raise ManifestTrustViolation(
        f"tool {record.tool_name!r} unclassified manifest delta {sorted(changed)}; "
        "fail-closed pending human review"
    )
