# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-procedural-memory-promotion-poisoning-during-hierarchical-consolidation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-procedural-memory-promotion-poisoning-during-hierarchical-consolidation.warrant.json
# Markdown SHA-256:   49384952595b35ac241f59d37c288988997d7e2556dbe2a085f7196b46be5a3b
# Code AST SHA-256:   fa87a96a02a0349d453fbb8ade02088ca90fdd6a332505cf6bc58af138fba32e
# Verified Classes:   PromotionUnverified
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class PromotionUnverified(RuntimeError):
    """Raised when a trace is proposed for procedural promotion without
    independent verification, or when a promoted routine's evidence set
    is retracted by the oracle."""
    pass


def consolidate_to_procedural(candidate_traces, oracle, min_verified=3):
    """
    candidate_traces: list of episodic dicts with keys
      {id, outcome, environment, verification_step_present}
    oracle: object with .confirm(trace_id) -> "CONFIRMED" | "REFUTED" | "UNKNOWN"
    Returns a procedural entry dict, or raises PromotionUnverified.
    """
    verified_ids = []
    for t in candidate_traces:
        if t["outcome"] != "success":
            continue
        if t["environment"] != "production":
            # permissive sandbox traces cannot certify a hot-path routine
            continue
        if not t["verification_step_present"]:
            continue
        verdict = oracle.confirm(t["id"])
        if verdict == "CONFIRMED":
            verified_ids.append(t["id"])
        elif verdict == "REFUTED":
            # retract: this trace was never valid evidence
            continue
        else:  # UNKNOWN
            # cannot certify; do not count, do not promote on unknowns
            continue

    if len(verified_ids) < min_verified:
        raise PromotionUnverified(
            f"only {len(verified_ids)} verified traces; "
            f"need {min_verified}. Unverified traces remain episodic and "
            f"tagged cautionary — they must not count toward promotion."
        )

    return {
        "kind": "procedural",
        "evidence_set": verified_ids,   # set, not counter — supports revocation
        "promoted_at": "now",
    }


def revoke_if_evidence_retracted(routine, oracle):
    """Re-evaluate a promoted routine when any evidence member is retracted."""
    for trace_id in routine["evidence_set"]:
        if oracle.confirm(trace_id) == "REFUTED":
            raise PromotionUnverified(
                f"routine evidence {trace_id} retracted; "
                f"demote to episodic and re-gate behind deliberation."
            )
    return routine
