# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-decay-when-a-delegated-sub-agent-writes-to-a-shared-memory-namespace-it-never-inherited.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-decay-when-a-delegated-sub-agent-writes-to-a-shared-memory-namespace-it-never-inherited.warrant.json
# Markdown SHA-256:   725c208ff0e0e906e17d4a8370127a8f43a382c66476e21c34357dadf8cdf601
# Code AST SHA-256:   37fc2ed59cfc2bd509bc6e507587320ba12ec9a43d5e2e7f01ec6d0acfd127cd
# Verified Classes:   TaintDecayError, Entry, Namespace
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintDecayError(RuntimeError):
    """Raised when a namespace read cannot prove lineage-consistent taint."""
    pass


@dataclass
class Entry:
    key: str
    value: str
    author: str
    taint: bool
    derived_from: frozenset[str] = field(default_factory=frozenset)


class Namespace:
    def __init__(self) -> None:
        self._store: dict[str, Entry] = {}
        self._tainted_sources: set[str] = set()

    def mark_source_tainted(self, source_id: str) -> None:
        self._tainted_sources.add(source_id)

    def put(self, entry: Entry) -> None:
        # Condition 1: provenance-closure. A write with no lineage while the
        # author has read tainted input is a protocol violation, not a clean write.
        if not entry.derived_from and entry.author in self._tainted_sources:
            raise TaintDecayError(
                f"write {entry.key!r} by {entry.author!r} has empty lineage "
                f"but author has read tainted sources"
            )
        # Condition 3: key ownership. Cross-identity overwrite is rejected.
        existing = self._store.get(entry.key)
        if existing is not None and existing.author != entry.author:
            raise TaintDecayError(
                f"key {entry.key!r} owned by {existing.author!r}, "
                f"rejected write by {entry.author!r}"
            )
        self._store[entry.key] = entry

    def read(self, key: str) -> Entry:
        entry = self._store.get(key)
        if entry is None:
            raise TaintDecayError(f"key {key!r} absent")
        # Condition 2: recompute taint as OR over reachable lineage.
        reachable_taint = bool(entry.derived_from & self._tainted_sources)
        if reachable_taint and not entry.taint:
            raise TaintDecayError(
                f"taint decay on {key!r}: lineage reaches tainted source "
                f"but entry.taint is False"
            )
        if not entry.derived_from:
            # Silent decay: no lineage to recompute. Quarantine the namespace.
            raise TaintDecayError(
                f"unlineaged entry {key!r}: namespace trust must be escalated"
            )
        return entry
