# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-prompt-injection-taint-at-the-tool-output-boundary-when-a-retrieval-context-re-materializes-the-same-bytes.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-prompt-injection-taint-at-the-tool-output-boundary-when-a-retrieval-context-re-materializes-the-same-bytes.warrant.json
# Markdown SHA-256:   d7e4cecddef6bdbeca92f4330ff9d93ea9a709fc5279e5a83804d9fbf72c6524
# Code AST SHA-256:   beaaf6130e69103106be4ba15cef432ffa773a38b3054bd5473b1f41c7691137
# Verified Classes:   TaintCollisionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintCollisionError(RuntimeError):
    """Raised when two provenances collide on content with differing trust tiers."""
    pass


TRUST_RANK = {"untrusted": 0, "internal": 1, "system": 2}


def merge_spans(spans):
    """
    spans: list of dicts with keys 'provenance_id', 'content_hash', 'trust', 'text'.
    Returns a list of merged spans where any content-hash collision is resolved
    under the LEAST-trusted tier (taint monotonic toward untrusted).
    """
    by_hash = {}
    for s in spans:
        h = s["content_hash"]
        if h not in by_hash:
            by_hash[h] = dict(s)
            continue
        prior = by_hash[h]
        if prior["provenance_id"] != s["provenance_id"]:
            # Collision across distinct provenances: merge under least trust.
            if TRUST_RANK[s["trust"]] < TRUST_RANK[prior["trust"]]:
                merged_trust = s["trust"]
            else:
                merged_trust = prior["trust"]
            prior["trust"] = merged_trust
            prior["provenance_id"] = f"{prior['provenance_id']}+{s['provenance_id']}"
        # Same provenance: idempotent, nothing to do.
    return list(by_hash.values())


def assemble_context(spans, require_labels=True):
    merged = merge_spans(spans)
    if require_labels:
        for m in merged:
            if m.get("trust") not in TRUST_RANK:
                raise TaintCollisionError(
                    f"span {m.get('provenance_id')} has no valid taint label; "
                    "refusing to assemble context"
                )
    # Refuse to emit a context that contains untrusted bytes adjacent to
    # trusted bytes without an explicit per-span label carried through.
    untrusted = [m for m in merged if m["trust"] == "untrusted"]
    trusted = [m for m in merged if m["trust"] != "untrusted"]
    if untrusted and trusted:
        for u in untrusted:
            if not u.get("label_emitted", False):
                raise TaintCollisionError(
                    "untrusted span present without emitted per-span label; "
                    "aggregate taint is insufficient"
                )
    return merged
