# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-capability-grant-under-a-policy-epoch-that-expires-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-capability-grant-under-a-policy-epoch-that-expires-mid-handoff.warrant.json
# Markdown SHA-256:   e9891e7ada06e46d6712bd4ed8c561ebcde08315c29da2324e2187b7eb363a5a
# Code AST SHA-256:   ffbddfd100844c54de51ffc6edd9a1242151f6bec9fbffef4839c41a8a4e25ca
# Verified Classes:   RetentionFloorViolation, PolicyEpoch, WarrantRequest
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timedelta


class RetentionFloorViolation(RuntimeError):
    """Raised when a warrant's audit-reconstructability horizon exceeds the
    grantor's guaranteed retention for the authorizing policy artifact."""
    pass


@dataclass(frozen=True)
class PolicyEpoch:
    epoch_id: str
    valid_until: datetime
    # Full text retained only until this instant; after this, only a hash remains.
    retained_until: datetime


@dataclass(frozen=True)
class WarrantRequest:
    capability: str
    scope: str
    requested_not_after: datetime
    audit_retention_window: timedelta


def mint_warrant(epoch: PolicyEpoch, req: WarrantRequest) -> dict:
    """Mint a warrant only if the authorizing epoch's full text (or predicate
    commitment) will outlive the grant plus the audit retention window.

    Invariant enforced:
        epoch.retained_until >= req.requested_not_after + req.audit_retention_window
    """
    required_horizon = req.requested_not_after + req.audit_retention_window

    if epoch.retained_until < required_horizon:
        raise RetentionFloorViolation(
            f"Cannot mint warrant for capability={req.capability!r} "
            f"scope={req.scope!r} under epoch={epoch.epoch_id!r}: "
            f"epoch text retained only until {epoch.retained_until.isoformat()}, "
            f"but audit reconstructability requires retention through "
            f"{required_horizon.isoformat()} "
            f"(not_after={req.requested_not_after.isoformat()} + "
            f"audit_window={req.audit_retention_window}). "
            f"Remediation: shorten grant lifetime, reduce audit window, "
            f"or require a predicate-committed grant (Discipline 2)."
        )

    # Clamp grant to epoch validity so routing and authorization epochs cannot diverge.
    effective_not_after = min(req.requested_not_after, epoch.valid_until)

    return {
        "capability": req.capability,
        "scope": req.scope,
        "policy_epoch": epoch.epoch_id,
        "not_after": effective_not_after,
        "audit_reconstructable_until": epoch.retained_until,
    }


def negotiate(epoch: PolicyEpoch, req: WarrantRequest) -> dict:
    """Entry point used by the federation negotiation layer. On violation,
    the caller receives a typed error it can recover from by re-negotiating
    under a shorter grant or a predicate-committed grant."""
    return mint_warrant(epoch, req)


if __name__ == "__main__":
    now = datetime(2025, 6, 14, 12, 0, 0)
    # Epoch rotates soon and its full text is evicted shortly after rotation.
    epoch = PolicyEpoch(
        epoch_id="E7",
        valid_until=now + timedelta(hours=1),
        retained_until=now + timedelta(hours=2),
    )
    # Grantee asks for a 40-minute grant with a 24-hour audit window.
    req = WarrantRequest(
        capability="record.read",
        scope="dataset:fin-2024",
        requested_not_after=now + timedelta(minutes=40),
        audit_retention_window=timedelta(hours=24),
    )

    try:
        warrant = negotiate(epoch, req)
        print("minted:", warrant)
    except RetentionFloorViolation as e:
        # Expected path: audit horizon (24h) exceeds epoch retention (2h).
        print("rejected at negotiation:", e)
