# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-task-identity-invariants-when-auto-compaction-summarizes-its-own-in-flight-tool-call-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-task-identity-invariants-when-auto-compaction-summarizes-its-own-in-flight-tool-call-ledger.warrant.json
# Markdown SHA-256:   fe2d5c66e402aa0e17ae7713d0cdc1d07e2b80de122c402ed2832cd3ddae34cc
# Code AST SHA-256:   614feddcdb9781b573975ca01b9b80ca08635e206577770e4f9733c9d9fd207f
# Verified Classes:   LedgerAmnesiaError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class LedgerAmnesiaError(RuntimeError):
    """Raised when a side-effecting call is about to be re-issued without
    authoritative ledger resolution after compaction."""
    pass


TERMINAL = {"ACKED", "FAILED", "ABANDONED"}


def guarded_reissue(call_id: str, idem: str, ledger, summary_text: str, reissue_fn):
    """
    ledger: external authoritative store with .status(call_id) -> str | None
    summary_text: compacted transcript prose (UNTRUSTED for state)
    reissue_fn: performs the actual tool call
    """
    status = ledger.status(call_id)

    if status is None:
        # Ledger has no record. Only safe to issue if we are certain the
        # original call never left the process. After compaction we are NOT
        # certain, so refuse.
        if "idem=" + idem in summary_text:
            raise LedgerAmnesiaError(
                f"call {call_id} absent from ledger but referenced in summary; "
                f"cannot distinguish never-issued from lost-ack. Halting."
            )
        # Genuinely new call.
        return reissue_fn(call_id, idem)

    if status in TERMINAL:
        if status == "ACKED":
            return {"deduplicated": True, "call_id": call_id}
        # FAILED / ABANDONED -> safe to re-issue with same idem key
        return reissue_fn(call_id, idem)

    # status == PENDING: outcome unknown. Never re-issue; wait or escalate.
    raise LedgerAmnesiaError(
        f"call {call_id} still PENDING (idem={idem}); re-issue would risk "
        f"duplicate side effect. Blocking until ack or timeout resolution."
    )
