# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-propagate-information-flow-taint-labels-across-tool-call-returns-and-memory-writes-without-losing-the-taint-at-the-serializatio.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-propagate-information-flow-taint-labels-across-tool-call-returns-and-memory-writes-without-losing-the-taint-at-the-serializatio.warrant.json
# Markdown SHA-256:   0a02dbc494762f3c977acd4ce565985c0a6ad6eee005ca81d53cf52d44cda717
# Code AST SHA-256:   20e33f9d9ac92ec43d6d38c6f7fdff260d3f7c71d342c6292e5755c28ed0a11c
# Verified Classes:   TaintViolation, Tainted, DeclassificationToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Literal, Sequence

Label = Literal["trusted", "untrusted"]


class TaintViolation(RuntimeError):
    """Raised when tainted data reaches a privileged sink without declassification."""


@dataclass(frozen=True)
class Tainted:
    """A value that carries an information-flow label. Never implicitly coercible to str."""
    content: str
    label: Label = "untrusted"
    origin: str = "unknown"

    def __str__(self) -> str:
        # Explicit coercion is a declassification event; forbid it silently.
        raise TaintViolation(
            f"implicit str() of Tainted(origin={self.origin!r}, label={self.label!r}); "
            "use .declassify(reason=...) or .join(other) explicitly"
        )


def join_label(*labels: Label) -> Label:
    return "untrusted" if "untrusted" in labels else "trusted"


@dataclass
class DeclassificationToken:
    reason: str
    scope: str  # e.g. "field:recipient_list"
    approver: str


def declassify(value: Tainted, token: DeclassificationToken) -> str:
    if not token.reason or not token.approver:
        raise TaintViolation("declassification requires non-empty reason and approver")
    return value.content


def harness_model_call(context: Sequence[Tainted], completion: str, origin: str) -> Tainted:
    """Every model call joins the labels of everything it consumed."""
    if not context:
        raise TaintViolation("model call with empty context; label cannot be established")
    joined = join_label(*(c.label for c in context))
    return Tainted(content=completion, label=joined, origin=origin)


def memory_write(store: list[dict], value: Tainted) -> None:
    # Label is persisted with content; never store a bare str.
    store.append({"content": value.content, "label": value.label, "origin": value.origin})


def memory_read(store: list[dict], idx: int) -> Tainted:
    rec = store[idx]
    return Tainted(content=rec["content"], label=rec["label"], origin=rec["origin"])


def privileged_sink_submit_report(body: Tainted, recipient: str, token: DeclassificationToken | None) -> None:
    if body.label == "untrusted" and token is None:
        raise TaintViolation(
            f"submit_report rejected: body tainted (origin={body.origin!r}); "
            "provide a DeclassificationToken scoped to the body"
        )
    if token is not None and token.scope != "body:report":
        raise TaintViolation(f"declassification token scope {token.scope!r} does not cover body:report")
    # ... send ...
