# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-attested-identity-across-a-delegated-workflow-when-its-bearer-token-rotates-but-its-reasoning-thread-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-attested-identity-across-a-delegated-workflow-when-its-bearer-token-rotates-but-its-reasoning-thread-does-not.warrant.json
# Markdown SHA-256:   575b3297f9fcf6a9c9d216bc00c21010be45989ebe63bf7303000eacce738244
# Code AST SHA-256:   2a4cca417e7201a853afed7ebb77afa6c0d1c131f3ff4acda7b453a4144a25da
# Verified Classes:   AttestationContinuityError, Attestation, DelegatorStepLog
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class AttestationContinuityError(RuntimeError):
    """Raised when an attestation rotation severs identity continuity from the delegator's authoritative step log."""
    pass


@dataclass
class Attestation:
    att_id: str
    warrant_id: str
    subject: str
    context_digest: str          # h_n, claimed by the agent
    issued_at: float
    expires_at: float
    countersigned_by_delegator: bool = False


@dataclass
class DelegatorStepLog:
    """A's authoritative record of steps it has authorized under a warrant."""
    warrant_id: str
    authorized_steps: list = field(default_factory=list)   # list of (step_idx, context_digest)

    def authoritative_digest(self) -> str:
        h = hashlib.sha256()
        for idx, digest in self.authorized_steps:
            h.update(f"{idx}:{digest}".encode())
        return h.hexdigest()

    def countersign(self, claimed_digest: str) -> bool:
        """Countersign only if the agent's claimed digest matches A's own record."""
        return claimed_digest == self.authoritative_digest()


def rotate_attestation(
    current: Attestation,
    new_att: Attestation,
    step_log: DelegatorStepLog,
    now: Optional[float] = None,
    grace_window_s: float = 60.0,
) -> Attestation:
    """
    Rotate an attestation mid-task. The ONLY sound path is quiesce-and-countersign:
    the delegator must independently vouch for the new context digest against its
    own step log before the new attestation is accepted.
    """
    now = now if now is not None else time.time()

    if new_att.warrant_id != current.warrant_id:
        raise AttestationContinuityError(
            f"rotation changes warrant {current.warrant_id} -> {new_att.warrant_id}; "
            f"this is a re-delegation, not a refresh"
        )

    if now > current.expires_at + grace_window_s:
        raise AttestationContinuityError(
            f"rotation attempted {now - current.expires_at:.1f}s after expiry, "
            f"beyond {grace_window_s}s grace; credential already invalid"
        )

    # The critical check: the delegator must countersign the agent's claimed
    # context digest against its OWN authoritative step log. A self-attested
    # digest from the agent is necessary but not sufficient.
    if not step_log.countersign(new_att.context_digest):
        raise AttestationContinuityError(
            f"attestation {new_att.att_id} claims context digest "
            f"{new_att.context_digest[:16]}... which does not match delegator's "
            f"authoritative log {step_log.authoritative_digest()[:16]}...; "
            f"refusing silent rotation (would launder unverified context under "
            f"warrant {new_att.warrant_id})"
        )

    new_att.countersigned_by_delegator = True
    return new_att


def execute_step(
    att: Attestation,
    step_idx: int,
    step_digest: str,
    step_log: DelegatorStepLog,
    now: Optional[float] = None,
) -> None:
    """Execute a step under an attestation. Rejects if the attestation is not countersigned."""
    now = now if now is not None else time.time()

    if not att.countersigned_by_delegator:
        raise AttestationContinuityError(
            f"attestation {att.att_id} is not countersigned by delegator; "
            f"executing step {step_idx} would create an unattested provenance gap"
        )

    if now > att.expires_at:
        raise AttestationContinuityError(
            f"attestation {att.att_id} expired at {att.expires_at:.1f}, "
            f"step {step_idx} attempted at {now:.1f}"
        )

    step_log.authorized_steps.append((step_idx, step_digest))
