# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-torn-scoped-deletion-commit-when-memory-tool-audit-trails-disagree-with-live-store-state.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-torn-scoped-deletion-commit-when-memory-tool-audit-trails-disagree-with-live-store-state.warrant.json
# Markdown SHA-256:   4dad11b17fac4c5c64421021199dbb91b5ce48ec8771456c344271e6b20b9390
# Code AST SHA-256:   086a60c5e3376ef05e6f6027b1b42e52bdadb3ac62a9cab3a0ed264464c43c53
# Verified Classes:   TornScopedDeleteError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TornScopedDeleteError(RuntimeError):
    """Raised when a scoped forget's audit trail and live store disagree."""


def reconcile_scoped_delete(
    audit_records: list[dict],
    live_read: callable,
    scope: dict,
    delete_audit_id: str,
) -> dict:
    """
    Verify that a forget(scope) actually removed every record the scope can reach.
    Returns a reconciliation record to append to the audit trail.
    Raises TornScopedDeleteError if the store still yields scoped records
    after a terminal 'committed' audit record for the same scope.
    """
    terminal = [r for r in audit_records
                if r.get("scope") == scope and r.get("status") == "committed"]
    if not terminal:
        raise TornScopedDeleteError(
            f"no terminal audit record for scope {scope}; delete state unknown"
        )
    if len(terminal) > 1 and not any(r.get("supersedes") for r in terminal[1:]):
        raise TornScopedDeleteError(
            f"multiple terminal records for scope {scope} with no supersession: "
            f"{[r['audit_id'] for r in terminal]}"
        )

    target = next(r for r in terminal if r["audit_id"] == delete_audit_id)
    survivors = live_read(scope=scope)

    if survivors:
        raise TornScopedDeleteError(
            f"scope {scope} still yields {len(survivors)} records after "
            f"committed delete {delete_audit_id} (audit claimed "
            f"deleted_count={target['deleted_count']}); "
            f"survivor_ids={[r['id'] for r in survivors][:8]}"
        )

    return {
        "type": "reconciliation",
        "references": delete_audit_id,
        "scope": scope,
        "survivors": 0,
        "verified": True,
    }
