# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-memory-poisoning-detection-when-episodic-and-semantic-stores-disagree-and-why-consistency-auditing-must-treat-divergence.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-memory-poisoning-detection-when-episodic-and-semantic-stores-disagree-and-why-consistency-auditing-must-treat-divergence.warrant.json
# Markdown SHA-256:   28cea97d91dac33d638691687ab40cc46a7b568023af2999d6b9c95a93a4d46a
# Code AST SHA-256:   e46a6252a056d8d0a9e4d96a59e558bf37691048686c544a4cbc0d552b9f9d7d
# Verified Classes:   ProvenanceAuditError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProvenanceAuditError(RuntimeError):
    """Raised when a semantic entry's derivability witness fails the consistency audit."""
    pass


def audit_semantic_entry(entry, episodic_index, authority_tokens):
    """
    entry: dict with keys 'fact_id', 'witness' (set of event ids), 'derivable' (bool),
           'principal', 'consolidation_deterministic'
    episodic_index: dict event_id -> event dict (append-only log)
    authority_tokens: set of fact_ids with signed out-of-band authority
    """
    if not entry.get("consolidation_deterministic", True):
        # Beyond the boundary: cannot audit derivability under non-determinism.
        return "DRIFT_ONLY"

    witness = entry.get("witness") or set()
    missing = [eid for eid in witness if eid not in episodic_index]
    if missing:
        raise ProvenanceAuditError(
            f"fact {entry['fact_id']}: witness references nonexistent events {missing}"
        )

    if not entry.get("derivable", False):
        if entry["fact_id"] in authority_tokens:
            return "ACCEPT_OVERRIDE"
        raise ProvenanceAuditError(
            f"fact {entry['fact_id']}: non-derivable with no authority token"
        )

    # Derivable: check provenance for orphaned-island signature.
    principals = {episodic_index[eid]["principal"] for eid in witness}
    timestamps = sorted(episodic_index[eid]["ts"] for eid in witness)
    has_predecessor = any(episodic_index[eid].get("predecessor") for eid in witness)
    clustered = (timestamps[-1] - timestamps[0]) < 0.5 if len(timestamps) > 1 else False

    if len(principals) == 1 and clustered and not has_predecessor:
        return "QUARANTINE_ORPHANED_PROVENANCE"

    return "ACCEPT"
