# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-mid-trajectory-system-prompt-mutation-against-a-toolset-that-was-compiled-under-the-old-policy.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-mid-trajectory-system-prompt-mutation-against-a-toolset-that-was-compiled-under-the-old-policy.warrant.json
# Markdown SHA-256:   1a9204cad987a42253f674462435014a30b9c5500f92e1f6efe84b932d283e72
# Code AST SHA-256:   0b745f99e896dc539f652325dab3c0af28dae7e567dcc6208edf5b7464df786e
# Verified Classes:   ManifestSkewError, ManifestVersion, ReasoningStep
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ManifestSkewError(RuntimeError):
    """Raised when a reasoning step's believed manifest version diverges
    from the live manifest version at the point of memory distillation."""


@dataclass
class ManifestVersion:
    version: int
    tool_names: frozenset[str]


@dataclass
class ReasoningStep:
    index: int
    believed_manifest_version: int
    referenced_tools: list[str]
    self_reported_compliance: Optional[str] = None
    executed_calls: list[str] = field(default_factory=list)


def distill_to_semantic_memory(
    step: ReasoningStep,
    live_manifest: ManifestVersion,
    call_ledger: dict[int, list[str]],
) -> Optional[str]:
    """Promote a step's self-report to semantic memory only if the belief
    matches the live manifest and every referenced tool was actually called
    under that same manifest version."""
    if step.believed_manifest_version != live_manifest.version:
        raise ManifestSkewError(
            f"step {step.index} believed manifest v{step.believed_manifest_version} "
            f"but live manifest is v{live_manifest.version}; narrative untrustworthy"
        )

    for tool in step.referenced_tools:
        if tool not in live_manifest.tool_names:
            raise ManifestSkewError(
                f"step {step.index} references tool {tool!r} absent from live "
                f"manifest v{live_manifest.version}; decoder would have pruned it, "
                f"so any compliance claim is fabricated"
            )
        if tool not in call_ledger.get(step.index, []):
            raise ManifestSkewError(
                f"step {step.index} claims compliance via {tool!r} but no call "
                f"record exists in the ledger; quarantining instead of distilling"
            )

    return step.self_reported_compliance


def apply_mid_trajectory_mutation(
    current: ManifestVersion,
    new_tool_names: frozenset[str],
    decoder_recompilable: bool,
    pending_intent_uses_new_tools: bool,
) -> ManifestVersion:
    """Recompile-and-continue only if the decoder can be rebuilt and no
    in-flight intent already leads the manifest. Otherwise reject."""
    if pending_intent_uses_new_tools and not decoder_recompilable:
        raise ManifestSkewError(
            "model intent references tools not yet in the compiled grammar and "
            "the decoder cannot be recompiled mid-turn; force replan, do not defer"
        )
    if not decoder_recompilable:
        raise ManifestSkewError(
            "decoder cannot recompile; mutation must be deferred to a "
            "trajectory boundary rather than applied live"
        )
    return ManifestVersion(version=current.version + 1, tool_names=new_tool_names)
