# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-a-litmus-harm-trajectory-checkpoint-after-a-partial-tool-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-a-litmus-harm-trajectory-checkpoint-after-a-partial-tool-side-effect.warrant.json
# Markdown SHA-256:   2324f056a847f2e8c6498b711cdc0383d055bf0124a4629d4a76a47c8147149c
# Code AST SHA-256:   d792bc83ed628a1646edcafb3a69fd1e8cf77c5704bc85c8021952522ada0596
# Verified Classes:   UnreconciledEffectError, EffectRecord, EffectLog
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class UnreconciledEffectError(RuntimeError):
    """Raised when a trajectory resume would cross an unreconciled tool-side effect.

    A resume is only valid if the effect set visible to the agent at the last
    durable checkpoint equals the effect set the tool actually committed.
    Divergence means the agent's context is a lie and any re-issued
    non-idempotent call would double-fire the side effect.
    """


@dataclass
class EffectRecord:
    trajectory_id: str
    step_index: int
    request_hash: str
    committed: bool = False


@dataclass
class EffectLog:
    """Write-ahead log the tool adapter fsyncs before dispatch returns."""
    records: list = field(default_factory=list)

    def commit(self, trajectory_id: str, step_index: int, payload: bytes) -> EffectRecord:
        rh = hashlib.sha256(payload).hexdigest()
        rec = EffectRecord(trajectory_id, step_index, rh, committed=True)
        self.records.append(rec)
        return rec

    def effects_since(self, trajectory_id: str, checkpoint_step: int) -> list:
        return [
            r for r in self.records
            if r.trajectory_id == trajectory_id
            and r.step_index > checkpoint_step
            and r.committed
        ]


def reconcile_and_resume(
    log: EffectLog,
    trajectory_id: str,
    checkpoint_step: int,
    agent_visible_steps: set,
) -> list:
    """Return synthetic observations the agent must be handed before resume.

    Raises UnreconciledEffectError if the log shows a committed effect the
    agent's reconstructed context cannot account for AND the harness has no
    synthetic-observation channel to inject it. Silent resume is forbidden.
    """
    committed = log.effects_since(trajectory_id, checkpoint_step)
    missing = [e for e in committed if e.step_index not in agent_visible_steps]

    if not missing:
        return []

    # The harness MUST be able to inject these as synthetic turns. If it cannot,
    # the resume is a scoring-integrity violation and must abort.
    injectable = all(hasattr(e, "committed") and e.committed for e in missing)
    if not injectable:
        raise UnreconciledEffectError(
            f"trajectory {trajectory_id!r} resume from step {checkpoint_step} "
            f"crosses {len(missing)} committed effect(s) not visible to the agent "
            f"(steps {[e.step_index for e in missing]}); "
            f"refusing silent resume — severity score would be corrupted"
        )

    return [
        {"synthetic": True, "step": e.step_index, "request_hash": e.request_hash}
        for e in missing
    ]


def resume_trajectory(
    log: EffectLog,
    trajectory_id: str,
    checkpoint_step: int,
    agent_visible_steps: set,
    injector: Optional[callable] = None,
) -> list:
    synthetic = reconcile_and_resume(log, trajectory_id, checkpoint_step, agent_visible_steps)
    if synthetic and injector is None:
        raise UnreconciledEffectError(
            f"trajectory {trajectory_id!r}: {len(synthetic)} synthetic observation(s) "
            f"required but no injector wired; aborting resume"
        )
    for obs in synthetic:
        injector(obs)
    return synthetic
