# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-scores-an-mcp-server-s-trust-from-the-server-s-own-self-reported-attestation-payload.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-scores-an-mcp-server-s-trust-from-the-server-s-own-self-reported-attestation-payload.warrant.json
# Markdown SHA-256:   a0dab4f5ea0a432e6d5a9a54a45c5ab5d72c9627bc5ee783d1b95d45c4d59e51
# Code AST SHA-256:   1e6bcaef5c5b1be0c17b87c191e553adc42b44763ea1c1c825652818df31888a
# Verified Classes:   TrustAmplificationError, AnchoredManifest
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class TrustAmplificationError(RuntimeError):
    """Raised when a re-score would let attacker-controlled fields raise trust."""
    pass


@dataclass(frozen=True)
class AnchoredManifest:
    manifest_hash: str
    version: str
    evidence_trust: float


def canonical_hash(tools_list: dict) -> str:
    blob = json.dumps(tools_list, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(blob.encode("utf-8")).hexdigest()


def rescore(
    tools_list: dict,
    self_reported: dict,
    anchored: dict[str, AnchoredManifest],
    last_verified_evidence_trust: float,
    auto_invoke_threshold: float = 0.90,
) -> float:
    h = canonical_hash(tools_list)

    # Only anchored hashes may contribute positive evidence.
    if h in anchored:
        evidence_trust = anchored[h].evidence_trust
    else:
        # Unknown manifest: floor at last verified, never promote.
        evidence_trust = last_verified_evidence_trust

    # Self-reported fields can only subtract.
    penalty = 0.0
    if not self_reported.get("attestation", {}).get("signature"):
        penalty += 0.10
    if not self_reported.get("description"):
        penalty += 0.05
    declared_version = self_reported.get("version", "")
    if declared_version and declared_version not in {a.version for a in anchored.values()}:
        penalty += 0.15

    score = min(evidence_trust, last_verified_evidence_trust) - penalty

    # Invariant: an unanchored manifest must never cross the promotion gate.
    if h not in anchored and score >= auto_invoke_threshold:
        raise TrustAmplificationError(
            f"unanchored manifest {h[:12]} scored {score:.2f} >= "
            f"auto-invoke threshold {auto_invoke_threshold}; "
            "self-reported fields cannot promote trust"
        )
    return max(0.0, score)
