# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-a-scoped-memory-write-has-silently-committed-to-the-wrong-retrieval-tier.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-a-scoped-memory-write-has-silently-committed-to-the-wrong-retrieval-tier.warrant.json
# Markdown SHA-256:   8a4c4b3566fbae6253891961583d68a4753e85d5e2ba2035e8df9a1bd671d775
# Code AST SHA-256:   70721a5440f3b70271d00cc7f07dba1e15ab5c4e4582e8bc22b7422fb42b9e3c
# Verified Classes:   ScopePlacementError, WriteResponse, TierPolicy
# Defensive Guards:   5 fail-closed invariants (zero external deps)
# Governance:         Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com)

from dataclasses import dataclass
from typing import Optional


class ScopePlacementError(RuntimeError):
    """Raised when a memory write commits to a tier that its retrieval policy will hide."""
    pass


@dataclass
class WriteResponse:
    ok: bool
    tier: str
    expires_at: Optional[str]
    stored_salience: Optional[float]


@dataclass
class TierPolicy:
    demotion_salience_floor: float
    default_ttl_minutes: Optional[int]


TIER_POLICIES = {
    "session": TierPolicy(demotion_salience_floor=0.0, default_ttl_minutes=None),
    "episodic": TierPolicy(demotion_salience_floor=0.5, default_ttl_minutes=60),
    "durable": TierPolicy(demotion_salience_floor=0.0, default_ttl_minutes=None),
}


def verify_write_placement(
    requested_scope: str,
    requested_salience: float,
    response: WriteResponse,
) -> None:
    """Reconcile a write acknowledgment against the read-side retrieval contract.

    Call this immediately after every scoped write. It converts a silent
    tier misplacement into a hard, catchable failure before the agent's
    reasoning loop can treat the later read miss as 'never known'.
    """
    if not response.ok:
        raise ScopePlacementError(f"write rejected outright: {response}")

    requested_tier = requested_scope.split(":", 1)[0]
    if requested_tier != response.tier:
        raise ScopePlacementError(
            f"scope {requested_scope!r} normalized to tier {response.tier!r}; "
            f"readers filtering on {requested_tier!r} will never see this record"
        )

    policy = TIER_POLICIES.get(response.tier)
    if policy is None:
        raise ScopePlacementError(f"unknown tier {response.tier!r}: cannot bound retrieval")

    if requested_salience < policy.demotion_salience_floor:
        raise ScopePlacementError(
            f"salience {requested_salience} below {response.tier!r} demotion floor "
            f"{policy.demotion_salience_floor}; record will rank under top-K cutoff"
        )

    if policy.default_ttl_minutes is not None and response.expires_at is None:
        raise ScopePlacementError(
            f"tier {response.tier!r} carries a TTL but response omitted expires_at"
        )


def write_and_confirm(api, key: str, value, scope: str, salience: float) -> None:
    raw = api.write(key=key, value=value, scope=scope, salience=salience)
    response = WriteResponse(
        ok=raw.get("ok", False),
        tier=raw.get("tier", ""),
        expires_at=raw.get("expires_at"),
        stored_salience=raw.get("stored_salience"),
    )
    verify_write_placement(scope, salience, response)
