# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-forget-scope-it-cannot-prove-it-satisfies-tombstone-divergence-in-scoped-memory-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-forget-scope-it-cannot-prove-it-satisfies-tombstone-divergence-in-scoped-memory-tool-apis.warrant.json
# Markdown SHA-256:   3620d0f0f27f23af8c3a71e1d9cac112b9cfd90ef00f5e1853cfe02fad29eeb6
# Code AST SHA-256:   e64d4b22c008ca2e293f568e35f36eb5465e94d7a7e6f127a569b9d8a206dbb5
# Verified Classes:   UnverifiableForgetScope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UnverifiableForgetScope(RuntimeError):
    """Raised when a predicate-scoped forget cannot be verified by the granting agent."""


CONTROL_NAMESPACE = "__control__"  # structurally excluded from all forget predicates


def forget_scoped(store, subject: str, tier: str, before: str, agent_ns: str) -> dict:
    # Precondition 1: the agent must be able to enumerate the predicate's candidates.
    if not store.capabilities(agent_ns).get("list_by_predicate", False):
        raise UnverifiableForgetScope(
            f"store cannot list candidates for subject={subject} tier={tier}; "
            "predicate-scoped forget would be an unverifiable assertion"
        )

    # Precondition 2: control records must live in a namespace disjoint from any
    # subject a forget predicate can range over. If the agent's only writable
    # namespace is one the predicate can match, its own tombstone is at risk.
    if CONTROL_NAMESPACE not in store.writable_namespaces(agent_ns):
        raise UnverifiableForgetScope(
            "no control namespace disjoint from forget predicates; "
            "agent's own tombstone could be erased by the forget it records"
        )

    # Precondition 3: derived-index hits must be labeled with tombstone state,
    # otherwise a lagging index feeds deleted content back as live context.
    if not store.capabilities(agent_ns).get("per_record_tombstone_flag", False):
        raise UnverifiableForgetScope(
            "retrieved records do not carry tombstone flags; "
            "index-lag hits are indistinguishable from live content"
        )

    # Phase 1: enumerate (identifiers only, no payload).
    candidates = store.list_keys(subject=subject, tier=tier, before=before)

    # Phase 2: key-exact delete + read-back verification.
    deleted, unverified = [], []
    for key in candidates:
        store.delete_key(key)
        if store.get_key(key) is not None:
            unverified.append(key)
        else:
            deleted.append(key)
    if unverified:
        raise UnverifiableForgetScope(
            f"read-back found {len(unverified)} keys still present after delete: {unverified[:5]}"
        )

    # Phase 3: write the tombstone to the control namespace BEFORE the sweep,
    # so that even if the sweep fails, the intent survives.
    tombstone = store.write(
        namespace=CONTROL_NAMESPACE,
        record={
            "kind": "forget_intent",
            "subject": subject,
            "tier": tier,
            "before": before,
            "deleted_keys": deleted,
            "epoch": store.epoch(),
        },
    )

    # Phase 4: predicate sweep for keys that appeared between list and delete.
    # Logged as unverified; the agent does not assert on it.
    sweep = store.forget(scope=subject, tier=tier, before=before)
    store.write(
        namespace=CONTROL_NAMESPACE,
        record={"kind": "forget_sweep", "tombstone_id": tombstone["id"], "result": sweep},
    )

    return {
        "status": "verified",
        "deleted_keys": deleted,
        "tombstone_id": tombstone["id"],
        "sweep": "unverified",
    }
