# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-tainted-context-through-a-summarizer-sub-agent-the-taint-label-laundering-boundary-in-quarantined-retrieval-pip.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-tainted-context-through-a-summarizer-sub-agent-the-taint-label-laundering-boundary-in-quarantined-retrieval-pip.warrant.json
# Markdown SHA-256:   167e664b4ca4412de837d3c357bd6290d6e4e2b71e4ee7a7718b9361f1364e65
# Code AST SHA-256:   b562d2b69467c864abd551640e9c0436c5ff16ba3969872aa361f24f1010c943
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a derived artifact with a quarantined ancestor is admitted to the planner."""
    pass


QUARANTINE = {"doc-7f3a", "doc-91bc"}  # objects gated out of the planner

# Lineage store: derived_id -> set of input ids it was computed from.
LINEAGE = {
    "summary-001": {"doc-7f3a"},
    "summary-002": {"doc-cc12"},          # clean ancestor
    "summary-003": {"summary-001"},       # second-order derivation
}


def resolve_ancestors(obj_id, _seen=None):
    """Transitive closure of derivation inputs. Unknown ids yield themselves."""
    _seen = _seen or set()
    if obj_id in _seen:
        return set()
    _seen.add(obj_id)
    parents = LINEAGE.get(obj_id)
    if not parents:
        return {obj_id}
    out = set(parents)
    for p in parents:
        out |= resolve_ancestors(p, _seen)
    return out


def admit_to_planner(obj_id):
    """Fail-closed admission: reject if any ancestor is quarantined or unknown."""
    ancestors = resolve_ancestors(obj_id)
    tainted = ancestors & QUARANTINE
    if tainted:
        raise TaintLaunderingError(
            f"refusing to admit {obj_id!r}: tainted ancestor(s) {sorted(tainted)}"
        )
    if not ancestors:
        # No resolvable lineage: treat as untrusted rather than trusted.
        raise TaintLaunderingError(
            f"refusing to admit {obj_id!r}: unresolvable lineage"
        )
    return True


def assemble_planner_context(candidate_ids):
    admitted = []
    for cid in candidate_ids:
        try:
            admit_to_planner(cid)
            admitted.append(cid)
        except TaintLaunderingError:
            # Route to no-authority scratchpad, not to tool-justifying context.
            continue
    return admitted


if __name__ == "__main__":
    # summary-001 is DERIVED but inherits quarantine via doc-7f3a.
    assert assemble_planner_context(["summary-002", "summary-001"]) == ["summary-002"]
    # summary-003 launders through summary-001 at second order.
    try:
        admit_to_planner("summary-003")
    except TaintLaunderingError as e:
        print("caught:", e)
    else:
        raise TaintLaunderingError("second-order laundering not detected")
