# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-promote-a-fact-into-semantic-memory-before-the-episodic-witness-that-justified-it-has-been-committed-to-durable-storage.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-promote-a-fact-into-semantic-memory-before-the-episodic-witness-that-justified-it-has-been-committed-to-durable-storage.warrant.json
# Markdown SHA-256:   3364afea9608fce8c0a4157cb88554e4463c37adf15c23dfb11d1b28ad7b6e19
# Code AST SHA-256:   a530f3fc0718948fc8c1db8e908aff5c0df41db03a4b64b2fab41711b4f028ad
# Verified Classes:   WitnessIntegrityError, PropositionState, Episode, Proposition, EpisodicStore, SemanticStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class WitnessIntegrityError(RuntimeError):
    """Raised when a semantic proposition references an episodic witness
    that is not durably committed, or when distillation is attempted
    before the witness write has succeeded."""


class PropositionState(Enum):
    PENDING = "pending"          # witness not yet resolved; must not be served
    GROUNDED = "grounded"        # witness committed and resolvable
    UNFOUNDED = "unfounded"      # witness provably absent; quarantine


@dataclass
class Episode:
    episode_id: str
    payload: str
    committed: bool = False


@dataclass
class Proposition:
    key: str
    value: str
    episode_ref: str
    state: PropositionState = PropositionState.PENDING
    written_at: float = field(default_factory=time.time)


class EpisodicStore:
    """Append-only log; the system of record for grounding."""

    def __init__(self, fail_next: bool = False):
        self._log: dict[str, Episode] = {}
        self._fail_next = fail_next

    def append(self, payload: str) -> str:
        episode_id = "ep_" + hashlib.sha1(
            f"{payload}{time.time_ns()}".encode()
        ).hexdigest()[:10]
        if self._fail_next:
            self._fail_next = False
            # Simulates the 503: NOTHING is committed.
            raise WitnessIntegrityError(
                f"episodic append failed for {episode_id}; witness not durable"
            )
        self._log[episode_id] = Episode(episode_id, payload, committed=True)
        return episode_id

    def resolve(self, episode_id: str) -> Optional[Episode]:
        ep = self._log.get(episode_id)
        return ep if ep and ep.committed else None


class SemanticStore:
    """Derived cache. Never an independent source of truth."""

    def __init__(self):
        self._props: dict[str, Proposition] = {}

    def upsert(self, prop: Proposition) -> None:
        if prop.state is PropositionState.GROUNDED:
            self._props[prop.key] = prop
        else:
            # Pending propositions are stored but excluded from retrieval.
            self._props[prop.key] = prop

    def get_grounded(self, key: str, episodic: EpisodicStore) -> Optional[str]:
        prop = self._props.get(key)
        if prop is None:
            return None
        if prop.state is not PropositionState.GROUNDED:
            return None
        # Reference resolution at the trust boundary.
        if episodic.resolve(prop.episode_ref) is None:
            prop.state = PropositionState.UNFOUNDED
            raise WitnessIntegrityError(
                f"proposition {key!r} references missing witness "
                f"{prop.episode_ref!r}; quarantined"
            )
        return prop.value


def distill(
    episodic: EpisodicStore,
    semantic: SemanticStore,
    key: str,
    value: str,
    observation: str,
) -> Proposition:
    """Witness-first distillation: commit the episode, then the proposition.

    Fail-closed: if the episodic append fails, no proposition is written
    in GROUNDED state. The reasoning step is marked degraded.
    """
    try:
        episode_id = episodic.append(observation)
    except WitnessIntegrityError:
        # Do NOT mint a forward-declared episode_ref. Do NOT continue.
        raise WitnessIntegrityError(
            f"distillation of {key!r} aborted: no durable witness; "
            f"agent must proceed without this fact"
        )
    prop = Proposition(
        key=key,
        value=value,
        episode_ref=episode_id,
        state=PropositionState.GROUNDED,
    )
    semantic.upsert(prop)
    return prop


def compact_working_store(
    episodic: EpisodicStore, semantic: SemanticStore, key: str
) -> None:
    """Eviction guard: refuse to evict a raw observation if its distilled
    proposition's witness is not committed."""
    prop = semantic._props.get(key)
    if prop is not None and episodic.resolve(prop.episode_ref) is None:
        raise WitnessIntegrityError(
            f"refusing compaction: {key!r} has dangling witness "
            f"{prop.episode_ref!r}; eviction would make inconsistency permanent"
        )


if __name__ == "__main__":
    ep = EpisodicStore(fail_next=True)
    sem = SemanticStore()

    # Step 14: distillation attempted while the log backend is failing.
    try:
        distill(ep, sem, "deploy_target", "staging-3", "context: staging-3")
    except WitnessIntegrityError as e:
        print(f"[step 14] degraded: {e}")

    # Step 31: agent reads semantic memory; nothing grounded to read.
    assert sem.get_grounded("deploy_target", ep) is None
    print("[step 31] no grounded target; agent must re-query -> staging-7")
