RolebookDocs

Managed deletion

Delete one authorized resource and its live sharing state in one local transaction.

withManagedDelete() performs one generated, conditional business-row deletion. The same transaction authorizes the resource/action, removes its live sharing state, retains lifecycle evidence, seals the original authority dependencies and records one receipt and one outbox event. It uses the existing managed descriptor and complete local identity and policy fences from protected updates.

Delete an exact incarnation

Configure a destructive action in the Sharing resource definition, such as delete mapped to document:delete, and grant that permission through your policy. The trusted server chooses this action for its deletion command; never accept an arbitrary action name from an untrusted request. Resource-wide authorization is required. A field-only grant cannot authorize deletion.

import { createSqliteProtectedWriteAdapter, type ManagedDeleteIntent } from "@rolebook/sharing-sqlite";

// The configured instance includes a managed descriptor and complete local authority fences.
declare const protectedAdapter: ReturnType<typeof createSqliteProtectedWriteAdapter>;
declare const incarnationId: string;
declare const currentVersion: string;

const scoped = protectedAdapter.forScope({
  tenantId: "application_namespace",
  actor: { type: "user", id: "user_123" },
});
const intent = {
  resource: { type: "document", id: "document_1" },
  action: "delete",
  incarnationId,
  idempotencyKey: "delete-document_1-once",
  expectedVersion: currentVersion,
} satisfies ManagedDeleteIntent;

const outcome = await scoped.withManagedDelete(intent);
// On an uncertain COMMIT, use this exact intent in trusted server recovery.
const recovered = await scoped.lookupManagedDeleteReceipt(intent);

The operation has no SQL callback, patch or post-version. Its result contains deleted: true, the resource reference, deleted incarnation and deleted resource version. The receipt metadata describes the authority used before deletion. Authorization happens before the expected-version comparison. Missing resources, wrong incarnations and denied actions fail closed.

Atomic cleanup and retained evidence

The adapter deletes only the matching namespace, resource ID, incarnation and version. It proves that the business row and all live owner, membership, invitation and sharing-idempotency rows are absent. The existing lifecycle code retains the revision floor, lifecycle outcome and audit for the deleted incarnation. The protected receipt and outbox event are retained independently of the deleted resource; there is exactly one protected event for this operation.

The final seal follows all deletion and lifecycle DML. It revalidates policy, identity eligibility, complete group/assignment/absence facts and the original identity and membership expiry dependencies, including dependencies whose granting rows have just been removed. A failed seal rolls the deletion and its evidence back together. Validity is established at the final seal; this is not a promise about the exact physical commit timestamp.

Resource ancestry must come from the locked, authoritative resource projection. Scoped assignments and group facts remain covered by the complete local identity fences after deletion. This API does not discover or fence arbitrary external ancestor tables or graph traversal dependencies. All participating writers must obey the existing revision/fence contract.

Replay and recreation

The managed.delete.v1 receipt binds the namespace, actor, key, resource, action, expected version, incarnation, authority epoch and configured descriptor digest. Reusing its key with changed intent conflicts. Exact replay returns the original receipt before current schema or authorization checks, without another delete or outbox event. This remains true after recreation or schema drift.

Reinitializing a resource under the same ID creates a fresh incarnation and advances the retained sharing revision floor. A fresh request for the old incarnation cannot delete that replacement. A recovered receipt is historical outcome evidence, never permission to act on a replacement. A missing receipt does not prove that an in-flight or ambiguous commit cannot succeed.

On a hierarchy-enrolled tenant

On a tenant whose hierarchy is enrolled (see inherited access), the same withManagedDelete() runs through the hierarchy command engine, inside its own protected transaction, when the adapter is given the deployment’s hierarchy control facade:

import {
  createSqliteProtectedWriteAdapter,
  type SqliteInheritanceControl,
} from "@rolebook/sharing-sqlite";

declare const options: Parameters<typeof createSqliteProtectedWriteAdapter>[0];
declare const control: SqliteInheritanceControl; // from createSqliteHierarchyControl
const protectedAdapter = createSqliteProtectedWriteAdapter({ ...options, hierarchy: { control } });

Without hierarchy, an enrolled delete refuses HIERARCHY_UNAVAILABLE / enrolled after the current gate and before any journal lookup or effect.

  • Leaves only. A resource with any child refuses PROTECTED_WRITE_REFUSED / hierarchy_not_leaf and nothing changes. Delete a subtree bottom-up, one leaf per call; descendants are never orphaned.
  • Authorization. The protected action on the resource’s inherited snapshot, plus the hierarchy command map: the type’s delete and management.members on the resource, and the parent’s removeChild and management.members (for a root, the bootstrap rootPlacement). Any denial, and a missing resource, is PROTECTED_WRITE_DENIED; a structural refusal is reported only after every check, the protected action included, allowed.
  • Effects. The business row, every live Sharing row, the revision floor, lifecycle record and audit, as on a flat tenant, then the resource’s link; the parent path’s subtree heights are repaired in the same transaction.
  • Receipt. Metadata version 2: the protected fields with the resource’s pre-delete inherited evidence (its stored chain). The result and the protected.delete.committed event are unchanged.
  • One final seal covers the local identity, the inherited memberships the decisions relied on, and every decision read’s validUntil; an expiry at or before it rolls everything back.
  • Retry. The journal lookup follows the hierarchy gate and precedes the first resource lock; a stored receipt returns verbatim. A SQLITE_BUSY reruns the whole attempt under the hierarchy control’s retry policy, recapturing the clock, identity, evidence and seal. Exhaustion is HIERARCHY_UNAVAILABLE / serialization_conflict.

Supported schema and transaction boundary

Both checked local drivers, Bun SQLite and file-backed libSQL, use one BEGIN IMMEDIATE transaction, with no automatic retry on a flat tenant. Its writer lock stabilizes the schema and authority while cleanup and final sealing run. Main and temporary triggers are inspected. Remote libSQL and in-memory libSQL are outside the protected-write contract.

Every live sharing, retained lifecycle and journal relation must also be an ordinary permanent table. PostgreSQL rejects inheritance and partitioning on all these relations; SQLite rejects views, virtual/shadow tables and temporary name shadows. The existing managed-target checks still apply. Deletion additionally rejects user triggers or rules on live sharing, retained lifecycle and journal tables, and rejects foreign keys into the target or its live sharing tables except the exact first-party tenant/resource cascade edges. SQLite retains its exact first-party resource-key guard. General application cascade graphs, including otherwise harmless extra referring tables, are deliberately unsupported in this slice.

Application DDL and migrations are trusted. Run the adapter migrations and preserve their schema, constraints, defaults and collations. These checks restrict supported side effects; they are not a sandbox against a malicious database owner, privileged DDL, custom SQL functions or a false identity resolver. One local adapter/resource is supported. General creation, movement, batch deletion, cross-adapter transactions and public consistency tokens remain outside this API.