# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-delegated-task-s-audit-trail-diverges-from-the-federated-policy-epoch-it-was-authorized-under.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-delegated-task-s-audit-trail-diverges-from-the-federated-policy-epoch-it-was-authorized-under.warrant.json
# Markdown SHA-256:   f5073ddcdb866c798a9628b66a9186e3331f08aaa6394c8f0fef3143b56a9717
# Code AST SHA-256:   ddfa286070c9e1b869ca5341ec3b8064408326cd5e73daf1cacd16e534aaff2d
# Verified Classes:   EpochDivergenceError, DeltaKind, CompletionRecord, OriginReconciler
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class EpochDivergenceError(RuntimeError):
    """Raised when a completion record's applied policy epoch cannot be
    reconciled with the warrant epoch under which the task was authorized."""
    pass


class DeltaKind(Enum):
    ADDITIVE = "additive"      # new obligation (redaction, retention, gate)
    SUBTRACTIVE = "subtractive"  # removed capability; audit union still sound


@dataclass(frozen=True)
class CompletionRecord:
    task_id: str
    warrant_epoch: str
    applied_epoch: str
    delta_manifest: dict  # obligation_name -> DeltaKind
    payload_hash: str
    signature: str


@dataclass
class OriginReconciler:
    known_compatible_deltas: set = field(default_factory=set)

    def _verify_binding(self, rec: CompletionRecord, warrant_hash: str) -> bool:
        expected = hashlib.sha256(
            f"{rec.payload_hash}:{rec.warrant_epoch}".encode()
        ).hexdigest()
        # signature must bind the completion to the warrant epoch, not just payload
        return rec.signature.startswith(expected[:8]) and rec.payload_hash == warrant_hash

    def reconcile(self, rec: CompletionRecord, warrant_hash: str) -> str:
        if not self._verify_binding(rec, warrant_hash):
            raise EpochDivergenceError(
                f"completion {rec.task_id} not bound to warrant epoch "
                f"{rec.warrant_epoch}; audit trail cannot be trusted"
            )

        if rec.applied_epoch == rec.warrant_epoch:
            return "COMPLETED"

        # epoch skew: inspect delta manifest
        if not rec.delta_manifest:
            raise EpochDivergenceError(
                f"task {rec.task_id}: epoch skew {rec.warrant_epoch} -> "
                f"{rec.applied_epoch} with no delta manifest; "
                f"divergence undetectable, halting"
            )

        for obligation, kind in rec.delta_manifest.items():
            if kind is DeltaKind.ADDITIVE and obligation not in self.known_compatible_deltas:
                raise EpochDivergenceError(
                    f"task {rec.task_id}: executor applied additive obligation "
                    f"'{obligation}' under epoch {rec.applied_epoch} not modeled "
                    f"in origin epoch {rec.warrant_epoch}; audit trails diverge, "
                    f"marking COMPLETED_DIVERGENT"
                )

        # subtractive or known-compatible additive deltas: audit union is sound
        return "COMPLETED"
