# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-nonce-domain-collapse-in-agent-to-agent-signed-envelopes-under-concurrent-replay-window-rotation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-nonce-domain-collapse-in-agent-to-agent-signed-envelopes-under-concurrent-replay-window-rotation.warrant.json
# Markdown SHA-256:   9f45b3cde3715716753cc47e0de176ec4c14fbfc163c680edd7effb216964609
# Code AST SHA-256:   41d1882a1b060991a630b661fbedda6ca10d525e3fd05b379e758197ccd5a713
# Verified Classes:   NonceDomainCollapseError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class NonceDomainCollapseError(RuntimeError):
    """Raised when a signed envelope's nonce/timestamp/epoch triple is
    consistent with a counter regression rather than a replay, meaning the
    replay window can no longer be trusted as a duplicate filter."""


def classify_envelope(envelope, hwm_state, freshness_window_s, max_inflight):
    """
    envelope: dict with keys sender_id, nonce, timestamp, epoch, signature_ok
    hwm_state: dict sender_id -> {'hwm': int, 'epoch': int, 'last_ts': float}
    Returns 'accept' | 'replay' | 'regression' | 'gap'.
    Raises NonceDomainCollapseError when the triple is ambiguous and the
    caller must reconcile rather than guess.
    """
    if not envelope["signature_ok"]:
        raise NonceDomainCollapseError(
            f"unsigned or forged envelope from {envelope['sender_id']}"
        )

    sid = envelope["sender_id"]
    state = hwm_state.get(sid, {"hwm": -1, "epoch": -1, "last_ts": 0.0})
    nonce, epoch, ts = envelope["nonce"], envelope["epoch"], envelope["timestamp"]
    fresh = abs(ts - state["last_ts"]) <= freshness_window_s

    if nonce > state["hwm"]:
        gap = nonce - state["hwm"]
        if gap > max_inflight:
            if epoch > state["epoch"]:
                return "gap"  # signer restarted mid-batch; reconcile before accept
            raise NonceDomainCollapseError(
                f"nonce gap {gap} from {sid} without epoch advance; "
                f"cannot distinguish crash-skip from injection"
            )
        return "accept"

    # nonce <= hwm: the dangerous branch
    if fresh and epoch > state["epoch"]:
        # low nonce, fresh timestamp, newer epoch => counter regression, NOT replay
        raise NonceDomainCollapseError(
            f"counter regression from {sid}: nonce {nonce} <= hwm {state['hwm']} "
            f"with fresh timestamp and epoch {epoch} > {state['epoch']}; "
            f"reconcile HWM before further accepts"
        )
    if epoch <= state["epoch"]:
        return "replay"
    raise NonceDomainCollapseError(
        f"ambiguous envelope from {sid}: nonce {nonce}, hwm {state['hwm']}, "
        f"epoch {epoch} vs {state['epoch']}, fresh={fresh}; fail closed"
    )


def apply_acceptance(envelope, hwm_state, freshness_window_s, max_inflight):
    result = classify_envelope(envelope, hwm_state, freshness_window_s, max_inflight)
    if result == "accept":
        sid = envelope["sender_id"]
        hwm_state[sid] = {
            "hwm": envelope["nonce"],
            "epoch": envelope["epoch"],
            "last_ts": envelope["timestamp"],
        }
    return result
