# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scoped-forget-from-leaving-orphaned-derivations-in-agent-memory-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scoped-forget-from-leaving-orphaned-derivations-in-agent-memory-stores.warrant.json
# Markdown SHA-256:   6b8da4c4d9706e6875452b304b49df3a0daf708cb5557a11318dc250c6032699
# Code AST SHA-256:   5278c320aac492ac751a23d18a96a6aac42eb76f122b8d2c003d2a1a99983fc2
# Verified Classes:   OrphanedDerivationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class OrphanedDerivationError(RuntimeError):
    """Raised when a forget would leave a live record citing a tombstoned source."""
    pass


def scoped_forget(store, scope, *, cascade=False, snapshot_derivations=True):
    """
    Forget every record in `scope`, enforcing the scope-monotone derivation
    invariant: no live record may retain a derived_from edge into `scope`.
    """
    doomed = {r.key for r in store.live_records(scope)}
    if not doomed:
        return {"forgotten": 0, "cascaded": 0, "reclassified": 0}

    # Pre-commit closure check: find live derivations outside `scope` that
    # cite any doomed key. This must run BEFORE the tombstone is written,
    # because after commit the edge is unrecoverable.
    orphans = store.live_derivations_citing(doomed, exclude_scope=scope)

    if orphans and not cascade and not snapshot_derivations:
        raise OrphanedDerivationError(
            f"forget(scope={scope!r}) would orphan {len(orphans)} live "
            f"derivation(s): {[o.key for o in orphans]}. "
            f"Enable cascade or snapshot_derivations, or widen the scope."
        )

    cascaded = 0
    reclassified = 0
    for d in orphans:
        sources = set(d.derived_from)
        if cascade and sources <= doomed:
            store.tombstone(d.key)
            cascaded += 1
        elif snapshot_derivations:
            # Re-base: pin the source content into the derivation's own scope
            # so the record becomes independent evidence, not an orphan.
            store.pin_snapshot(d.key, sources=[store.snapshot(s) for s in sources])
            store.reclassify(d.key, from_="derived", to="asserted")
            reclassified += 1
        else:
            # Partial survival with cascade on: sources outlive the forget,
            # so the edge is still valid and the record stays `derived`.
            store.flag(d.key, "provenance_partial")

    store.tombstone_scope(scope)

    # Post-commit audit: the invariant must now hold for the whole store.
    residual = store.live_derivations_citing(doomed, exclude_scope=scope)
    if residual:
        raise OrphanedDerivationError(
            f"post-forget audit failed: {[r.key for r in residual]} still cite "
            f"tombstoned keys in {scope!r}; halt further forgets until repaired."
        )

    return {
        "forgotten": len(doomed),
        "cascaded": cascaded,
        "reclassified": reclassified,
    }
