# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-semantic-compression-spillover-from-silently-mutating-the-agent-s-working-set-during-context-budget-reclamation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-semantic-compression-spillover-from-silently-mutating-the-agent-s-working-set-during-context-budget-reclamation.warrant.json
# Markdown SHA-256:   1099c3d82c7792fb81219e01af42f58cd39cf5bc3e921d47f758986739863144
# Code AST SHA-256:   b442334050a7c55492c0170917c724d163169bb1925f1763a7bb356c513419c4
# Verified Classes:   UnreconciledSpilloverError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class UnreconciledSpilloverError(RuntimeError):
    """Raised when a retrieved artifact shares lineage with a live summary
    clause but no reconciliation record exists. Admitting it would create
    a dual-representation state with conflicting truth values."""
    pass


def admit_retrieved_artifact(artifact, live_summary, reconciliation_log):
    """
    artifact: dict with 'id', 'lineage' (set of source-proposition ids)
    live_summary: dict mapping clause_id -> {'lineage': set, 'text': str}
    reconciliation_log: dict mapping clause_id -> 'confirmed' | 'retracted'
    """
    artifact_lineage = set(artifact["lineage"])

    # Find every live summary clause derived from this artifact's sources.
    overlapping = [
        clause_id
        for clause_id, clause in live_summary.items()
        if artifact_lineage & set(clause["lineage"])
    ]

    if not overlapping:
        # Genuinely new information; append is safe.
        return {"action": "append", "artifact": artifact}

    unresolved = [c for c in overlapping if c not in reconciliation_log]
    if unresolved:
        raise UnreconciledSpilloverError(
            f"Artifact {artifact['id']} shares lineage with live clauses "
            f"{unresolved} but no reconciliation record exists. "
            f"Refusing to admit: would create dual-representation state."
        )

    # Every overlapping clause has an explicit disposition; merge is defined.
    retracted = [c for c in overlapping if reconciliation_log[c] == "retracted"]
    return {
        "action": "merge",
        "artifact": artifact,
        "supersedes": retracted,
        "note": "retracted clauses must be removed from working set before admission",
    }
