# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-semantic-drift-from-poisoning-a-persistent-agent-knowledge-store-when-attestation-is-scoped-per-write-rather-than-per.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-semantic-drift-from-poisoning-a-persistent-agent-knowledge-store-when-attestation-is-scoped-per-write-rather-than-per.warrant.json
# Markdown SHA-256:   42505c744147df4f960ffd273e33764f653bddf4d67c6521501c65ead3d01f12
# Code AST SHA-256:   7daeb5873babb6d9f620b13cd29349bec90919c4d0d8b4d500914081e23b0f81
# Verified Classes:   SemanticDriftError, Fact
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class SemanticDriftError(RuntimeError):
    """Raised when a consolidated record is attested at the byte level but its
    semantic claim is not entailed by its attested inputs."""
    pass


@dataclass
class Fact:
    fact_id: str
    content: str
    claim_type: str            # "contact" | "routing_directive" | ...
    source_ids: list
    content_hash: str = ""
    signature: str = ""

    def __post_init__(self):
        if not self.content_hash:
            self.content_hash = hashlib.sha256(self.content.encode()).hexdigest()


def verify_bytes(fact: Fact, expected_sig: str) -> bool:
    # Per-write attestation: proves bytes unchanged, says nothing about meaning.
    return fact.signature == expected_sig and \
        fact.content_hash == hashlib.sha256(fact.content.encode()).hexdigest()


def consolidate(inputs: list, merged: Fact, entailment_verifier) -> Fact:
    """Enforce the per-consolidation invariant. Per-write attestation alone is
    insufficient because merged.content is a fresh, validly-signed blob."""
    for f in inputs:
        if not verify_bytes(f, f.signature):
            raise SemanticDriftError(f"input {f.fact_id} failed byte attestation")

    # Invariant 1: any multi-input or meaning-changing write needs a derivation
    # record, not just a fresh signature on the output.
    if len(inputs) != 1:
        for src in inputs:
            if not entailment_verifier(src, merged):
                raise SemanticDriftError(
                    f"merge {merged.fact_id} not entailed by input {src.fact_id}: "
                    f"claim_type {src.claim_type}->{merged.claim_type} "
                    f"or modality dropped"
                )

    # Invariant 2: a directive may not be silently re-typed as a datum.
    input_types = {f.claim_type for f in inputs}
    if "routing_directive" in input_types and merged.claim_type == "contact":
        raise SemanticDriftError(
            f"consolidation {merged.fact_id} re-typed routing_directive as contact; "
            "per-write signature would have passed this"
        )

    merged.signature = hashlib.sha256(
        (merged.content_hash + "|" + ",".join(sorted(f.fact_id for f in inputs))).encode()
    ).hexdigest()
    return merged


def read(fact: Fact, needed_type: str) -> str:
    if fact.claim_type != needed_type:
        raise SemanticDriftError(
            f"consumer needs {needed_type} but {fact.fact_id} attested as {fact.claim_type}"
        )
    return fact.content
