# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-rewrite-its-own-context-window-into-a-state-it-can-no-longer-verify.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-rewrite-its-own-context-window-into-a-state-it-can-no-longer-verify.warrant.json
# Markdown SHA-256:   e417417adc605f549373fd9c4a259c8482920699d31aacbfdb7e545f42bc2da4
# Code AST SHA-256:   6300f96ac36f3da7ec57fa14de5c2f6ed2041af7760175ba990260f94c414cfd
# Verified Classes:   ProvenanceError, SegmentKind, ToolDeterminism, Segment, ColdStore, Observation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ProvenanceError(RuntimeError):
    """Raised when an agent attempts to adjudicate with a derived segment
    whose primary backing is not reachable, or to launder a derived segment
    into a primary via a fresh-observation comparison."""


class SegmentKind(Enum):
    PRIMARY = "primary"
    DERIVED = "derived"


class ToolDeterminism(Enum):
    DETERMINISTIC = "deterministic"
    NON_DETERMINISTIC = "non_deterministic"


@dataclass
class Segment:
    seg_id: str
    kind: SegmentKind
    content: str
    derived_from: list[str] = field(default_factory=list)
    timestamp: int = 0


@dataclass
class ColdStore:
    _store: dict[str, Segment] = field(default_factory=dict)

    def put(self, seg: Segment) -> None:
        self._store[seg.seg_id] = seg

    def get(self, seg_id: str) -> Optional[Segment]:
        return self._store.get(seg_id)


@dataclass
class Observation:
    tool: str
    determinism: ToolDeterminism
    value: str
    timestamp: int


def adjudicate(
    derived: Segment,
    fresh: Observation,
    cold: ColdStore,
    prior_primary_id: Optional[str],
) -> dict:
    """Reconcile a derived segment against a fresh observation.

    Returns a CONFLICT record. Never returns RESOLVED unless the primary
    backing `derived` was rehydrated and found consistent.
    """
    if derived.kind is not SegmentKind.DERIVED:
        raise ProvenanceError(
            f"adjudicate called on non-derived segment {derived.seg_id!r}; "
            "adjudication is only defined for derived segments"
        )

    # Attempt to rehydrate the primary backing the derived segment.
    primary: Optional[Segment] = None
    for pid in derived.derived_from:
        candidate = cold.get(pid)
        if candidate is not None and candidate.kind is SegmentKind.PRIMARY:
            primary = candidate
            break

    if primary is None:
        # No primary reachable: we may record a conflict but must not resolve.
        return {
            "status": "CONFLICT",
            "reason": "primary_unreachable",
            "derived_id": derived.seg_id,
            "fresh_tool": fresh.tool,
            "action": "refuse_resolution; mark derived UNVERIFIED",
        }

    # Fresh observation vs derived claim, with primary as the anchor.
    if fresh.determinism is ToolDeterminism.NON_DETERMINISTIC:
        # A re-run that disagrees is a NEW observation, not a correction.
        return {
            "status": "COEXIST",
            "reason": "non_deterministic_tool_disagreement",
            "primary_id": primary.seg_id,
            "derived_id": derived.seg_id,
            "fresh_tool": fresh.tool,
            "action": "record both with timestamps; do not overwrite primary",
        }

    # Deterministic tool: re-run is a valid re-verification.
    if primary.content != fresh.value:
        raise ProvenanceError(
            f"deterministic tool {fresh.tool!r} disagrees with stored primary "
            f"{primary.seg_id!r}: stored={primary.content!r} fresh={fresh.value!r}; "
            "refusing to resolve — primary integrity violated"
        )
    return {
        "status": "RESOLVED",
        "reason": "deterministic_reverification",
        "primary_id": primary.seg_id,
        "derived_id": derived.seg_id,
        "action": "derived may be re-tagged with verified primary",
    }
