# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-successful-tool-call-that-silently-poisoned-its-own-verification-ledger-during-adversarial-fault-injection.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-successful-tool-call-that-silently-poisoned-its-own-verification-ledger-during-adversarial-fault-injection.warrant.json
# Markdown SHA-256:   517dcdfdee3cbc94c52a32f12f8a47395cd01227759238da0329f2c573c61504
# Code AST SHA-256:   2a9864cc28268a7ed428223ff34c7b21033005ff0076c49d5ca21249a11cb402
# Verified Classes:   LedgerTautologyError, LedgerEntry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class LedgerTautologyError(RuntimeError):
    """Raised when a verification ledger entry certifies an artifact using only
    evidence derived from that same artifact, with no independent oracle and no
    freshness binding. Indicates the agent is about to launder a non-observable
    tool fault into a 'verified' success."""


@dataclass
class LedgerEntry:
    logical_key: str
    artifact_hash: str
    store_hash: str
    freshness_nonce: str
    nonce_issued_by_caller: bool
    oracle_independent: bool
    fault_class: str = "observable"  # "observable" | "non_observable"


def certify(entry: LedgerEntry, caller_nonce_log: dict[str, str]) -> bool:
    # Guard 1: schema/correlation already passed upstream; we are past that.
    # Guard 2: hash agreement is necessary but NOT sufficient under idempotent faults.
    hashes_agree = entry.artifact_hash == entry.store_hash

    # Guard 3: freshness binding — the nonce must be one the caller actually issued
    # for this logical key. A forged-fresh correlation fails here.
    expected_nonce = caller_nonce_log.get(entry.logical_key)
    freshness_ok = (
        entry.nonce_issued_by_caller
        and expected_nonce is not None
        and entry.freshness_nonce == expected_nonce
    )

    # Guard 4: for non-observable faults, hash agreement alone is a tautology.
    # Require an independent oracle (store read-back by a different principal,
    # or a second tool) before certifying success.
    if entry.fault_class == "non_observable" and not entry.oracle_independent:
        raise LedgerTautologyError(
            f"ledger entry for {entry.logical_key!r} certifies a non-observable "
            f"fault using only self-derived evidence "
            f"(artifact_hash={entry.artifact_hash[:12]}..., "
            f"store_hash={entry.store_hash[:12]}..., hashes_agree={hashes_agree}). "
            f"Refusing to record task_success; escalate to independent oracle."
        )

    if not freshness_ok:
        raise LedgerTautologyError(
            f"ledger entry for {entry.logical_key!r} failed freshness binding: "
            f"nonce={entry.freshness_nonce!r} not in caller issuance log "
            f"(expected={expected_nonce!r}). Possible stale-but-valid replay."
        )

    # Only reachable when freshness is bound AND (observable fault OR independent oracle).
    return hashes_agree


def run_harness_fault(entry: LedgerEntry, caller_nonce_log: dict[str, str]) -> str:
    try:
        ok = certify(entry, caller_nonce_log)
        return "task_success" if ok else "task_failure"
    except LedgerTautologyError:
        return "escalate"
