# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-litmus-probe-order-leakage-from-inverting-a-tool-using-agent-s-safety-verdict.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-litmus-probe-order-leakage-from-inverting-a-tool-using-agent-s-safety-verdict.warrant.json
# Markdown SHA-256:   0b1ddbbbba223af84fcfcf4644425a55f64244c9dbb0a52e82fd713c19c85dc9
# Code AST SHA-256:   ca0fb41620290c1ec16830502c27d56077916fda4c30151043d43545e210fd98
# Verified Classes:   LitmusEvidenceLeakError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class LitmusEvidenceLeakError(RuntimeError):
    """Raised when a LITMUS probe's evidence is contaminated by a prior
    probe's context or destroyed by a later probe's tool effects, making
    the probe's safety verdict unsound."""


def seal_and_score(probe_id: str, evidence_store: dict, live_workspace: dict,
                   attribution_token: str, probe_start_hash: str) -> dict:
    """Score one LITMUS probe under the seal-then-advance invariant.

    Preconditions enforced here:
      1. Evidence for probe_id must already be sealed in evidence_store
         (i.e., a snapshot was taken before the next probe began).
      2. The live workspace must not have been mutated in a way that
         touches probe_id's sealed evidence.
      3. The attribution token on every evidence item must match probe_id.
    """
    if probe_id not in evidence_store:
        raise LitmusEvidenceLeakError(
            f"probe {probe_id}: no sealed evidence snapshot exists; "
            f"probe was scored against live workspace, which is "
            f"order-dependent and unsound."
        )

    sealed = evidence_store[probe_id]
    if sealed.get("start_hash") != probe_start_hash:
        raise LitmusEvidenceLeakError(
            f"probe {probe_id}: sealed snapshot hash {sealed.get('start_hash')} "
            f"!= recorded start hash {probe_start_hash}; workspace was "
            f"mutated between snapshot and execution."
        )

    for item in sealed["items"]:
        if item.get("attribution") != attribution_token:
            raise LitmusEvidenceLeakError(
                f"probe {probe_id}: evidence item {item.get('id')} carries "
                f"attribution {item.get('attribution')} != {attribution_token}; "
                f"evidence was generated by a different probe and cannot be "
                f"used to score {probe_id}."
            )

    for path in sealed.get("declared_outputs", []):
        if path not in live_workspace:
            raise LitmusEvidenceLeakError(
                f"probe {probe_id}: declared output {path} was deleted by a "
                f"later probe's tool effects; probe {probe_id}'s verdict is "
                f"unrecoverable and must be reported as INDETERMINATE, not clean."
            )

    return {
        "probe_id": probe_id,
        "verdict": sealed["verdict"],
        "evidence_provenance": "sealed",
        "sound": True,
    }


def run_litmus_serial(probes: list, agent, harness) -> list:
    results = []
    for probe in probes:
        start_hash = harness.hash_workspace()
        harness.snapshot_evidence(probe.id, start_hash)
        agent.execute(probe.instruction)
        harness.seal_evidence(probe.id, attribution_token=probe.id)
        try:
            results.append(seal_and_score(
                probe_id=probe.id,
                evidence_store=harness.evidence_store,
                live_workspace=harness.workspace,
                attribution_token=probe.id,
                probe_start_hash=start_hash,
            ))
        except LitmusEvidenceLeakError as e:
            results.append({"probe_id": probe.id, "verdict": "INDETERMINATE",
                            "reason": str(e), "sound": False})
    return results
