# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-hierarchical-context-compaction-has-silently-orphaned-a-mid-task-subgoal.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-hierarchical-context-compaction-has-silently-orphaned-a-mid-task-subgoal.warrant.json
# Markdown SHA-256:   48e32fe36dd4bf095bc810f912c57519f887c95e1e3c2398e4b382ccd3a5f503
# Code AST SHA-256:   5a1a28c75ece6c1bd26b8129628ec500355d29106a72bff998ca8ed1af71dcd0
# Verified Classes:   OrphanedSubgoalError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class OrphanedSubgoalError(RuntimeError):
    """Raised when a compacted summary drops a gating edge required for safe resume."""
    pass


def validate_resume_graph(summary_items, durable_edges, irreversible_nodes):
    """
    summary_items: list of dicts from the compacted checkpoint, e.g. {"id": ..., "text": ...}
    durable_edges: dict mapping task_id -> set of predecessor task_ids (from durable store)
    irreversible_nodes: set of task_ids whose execution is one-way / non-idempotent
    """
    pending_ids = {item["id"] for item in summary_items}
    summary_edges = {item["id"]: set(item.get("depends_on", [])) for item in summary_items}

    # Level-collapse detection: edges present durably but absent from the summary.
    orphaned = []
    for tid in pending_ids:
        durable_preds = durable_edges.get(tid, set())
        summary_preds = summary_edges.get(tid, set())
        dropped = durable_preds - summary_preds
        if dropped & irreversible_nodes:
            orphaned.append((tid, dropped))

    if orphaned:
        detail = "; ".join(
            f"{tid} lost gating edge(s) to irreversible {sorted(deps)}"
            for tid, deps in orphaned
        )
        raise OrphanedSubgoalError(
            f"Compacted summary orphaned irreversible preconditions: {detail}. "
            f"Refusing resume; re-derive ordering from durable store before executing."
        )

    # If no irreversible edge was dropped, flattening is tolerable; proceed.
    return True
