# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-model-authored-pruning-journal-as-a-non-authoritative-index-rather-than-a-ground-truth-record-of-its-ow.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-model-authored-pruning-journal-as-a-non-authoritative-index-rather-than-a-ground-truth-record-of-its-ow.warrant.json
# Markdown SHA-256:   49ebc03c22ee59e2bf2cfa81c6678697a7fcee9d208f1b4b5ac34b17671fba00
# Code AST SHA-256:   2cf03d54d3d26abeaf3585a45632f77304eebb0b0afd8e795e23d36ceec0d57a
# Verified Classes:   JournalFidelityError, UnrecoverableSpanError, JournalEntry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional

class JournalFidelityError(RuntimeError):
    """Raised when a journal entry is asked to substitute for recovered bytes."""
    pass

class UnrecoverableSpanError(RuntimeError):
    """Raised when re-expansion is impossible and the fact must be treated as unknown."""
    pass

@dataclass
class JournalEntry:
    entry_id: int
    spans: list[tuple[int, int]]          # pre-prune buffer offsets
    span_hashes: list[str]                # sha256 of each removed span
    summary: str                          # model-authored, NON-load-bearing
    summary_derived: bool = True
    tombstoned: bool = False              # entry itself pruned; offsets lost

def reexpand(entry: JournalEntry, buffer: bytes) -> bytes:
    if entry.tombstoned:
        raise UnrecoverableSpanError(
            f"entry {entry.entry_id} tombstoned; offsets unrecoverable"
        )
    out = bytearray()
    for (start, end), expected in zip(entry.spans, entry.span_hashes):
        span = buffer[start:end]
        if hashlib.sha256(span).hexdigest() != expected:
            raise JournalFidelityError(
                f"entry {entry.entry_id} span {start}-{end} hash mismatch; "
                f"buffer drifted, summary cannot be trusted as substitute"
            )
        out.extend(span)
    return bytes(out)

def resolve_fact_for_action(
    entry: JournalEntry,
    buffer: bytes,
    fact_used: str,
    irreversible: bool,
) -> bytes:
    if entry.summary_derived and irreversible:
        # Summary is a pointer label, not evidence. Force re-expansion.
        try:
            recovered = reexpand(entry, buffer)
        except UnrecoverableSpanError:
            raise JournalFidelityError(
                f"irreversible action '{fact_used}' rests on summary of "
                f"unrecoverable entry {entry.entry_id}; downgrade to unverified"
            )
        if fact_used.lower() not in recovered.decode("utf-8", "replace").lower():
            raise JournalFidelityError(
                f"summary claimed '{fact_used}' but re-expanded bytes contradict it; "
                f"bytes win, flag pruning policy for fidelity review"
            )
        return recovered
    try:
        return reexpand(entry, buffer)
    except UnrecoverableSpanError:
        raise JournalFidelityError(
            f"cannot re-expand entry {entry.entry_id}; treat fact as unknown, "
            f"require fresh tool observation before proceeding"
        )
