Managed same-tenant moves
Reparent one leaf resource using SQL-authoritative parent permissions in one transaction.
withManagedMove() moves one existing leaf between two distinct root parents in the same
namespace. The adapter reads both parents from one configured SQL table, checks the source
remove and destination accept permissions, changes the child parent column and version, and
advances its sharing revision. Owner, incarnation, direct memberships, invitations and previous
sharing-idempotency records remain intact.
This API requires the complete local identity and policy fences described in
protected updates, plus the existing managed descriptor.
The parent column belongs in the full child projection but must not be writable through ordinary
managed patches. The application resource projection must return exactly the SQL parent as the
child’s immediate ancestor; the adapter checks this agreement before and after the move.
Configure authoritative parents
import type { PostgresManagedMoveDescriptor } from "@rolebook/sharing-postgres";
const managedMove = {
parentIdColumn: "folder_id",
parent: {
resourceType: "folder", schema: "public", table: "folder",
tenantColumn: "tenant_id", idColumn: "id",
versionColumn: "version", incarnationColumn: "incarnation",
userColumns: ["tenant_id", "id", "version", "incarnation", "enabled"],
fields: [{ field: "enabled", column: "enabled", codec: "boolean" }],
},
sourceAction: "remove",
destinationAction: "accept",
} satisfies PostgresManagedMoveDescriptor; Pass managedMove to the protected adapter factory beside managed. Parent IDs, versions and
incarnations use text columns. Map policy attributes explicitly with text, boolean or
safe-integer codecs; nullable attributes require nullable: true. Enumerate every physical
column in order in userColumns. Optional expiresAtColumn uses timestamptz, retained at microsecond precision.
The policy must declare folder as a root and the child as its immediate leaf. Parent permissions
come from the complete fenced local identity assignments and groups. A parent type with its own
Sharing membership configuration is unsupported and rejected. The adapter constructs parent
resources directly from SQL, without a caller-provided parent projection. It checks whole-resource
folder:remove and folder:accept; field-only allows do not suffice. Parent condition context
contains the tenant ID, without an invented parent sharing revision.
Move an exact incarnation
import { createPostgresProtectedWriteAdapter, type ManagedMoveIntent } from "@rolebook/sharing-postgres";
declare const adapter: ReturnType<typeof createPostgresProtectedWriteAdapter>;
const scoped = adapter.forScope({ tenantId: "namespace_1", actor: { type: "user", id: "alice" } });
const intent = {
resource: { type: "document", id: "doc_1" }, action: "move",
incarnationId: "document-incarnation", expectedVersion: "1", postVersion: "2",
idempotencyKey: "move-doc_1-once",
sourceParent: { id: "folder_a", incarnationId: "folder-a-incarnation", version: "1" },
destinationParent: { id: "folder_b", incarnationId: "folder-b-incarnation", version: "3" },
} satisfies ManagedMoveIntent;
const outcome = await scoped.withManagedMove(intent);
const recovered = await scoped.lookupManagedMoveReceipt(intent); The trusted application chooses the child action mapped to its move command. Caller versions and incarnations are expectations checked against locked authoritative rows, not permission evidence. The child must be allowed both before and after movement. Both parent permissions, unchanged parent snapshots, policy and complete identity/group/absence facts are revalidated. Original parent, identity and membership expiry dependencies survive until the advancing final seal. Validity is established at that seal, not at the physical COMMIT timestamp.
The generated conditional update and existing lifecycle bookkeeping run in the same owned transaction. Failed authorization, stale expectations, schema drift or a failed final seal rolls back the move, lifecycle audit, protected receipt and outbox event together. The result records the child version/incarnation/sharing revision and both parent version/incarnation tuples.
On a hierarchy-enrolled tenant
On a tenant whose hierarchy is enrolled (see inherited access), the stored hierarchy, not the application’s parent column, is the ancestry Rolebook decides with. Give the protected adapter the deployment’s hierarchy control facade and, if the application keeps one, its parent column:
import {
createPostgresProtectedWriteAdapter,
type ManagedMoveIntent,
type PostgresInheritanceControl,
} from "@rolebook/sharing-postgres";
declare const options: Parameters<typeof createPostgresProtectedWriteAdapter>[0];
declare const control: PostgresInheritanceControl; // from createPostgresHierarchyControl
const adapter = createPostgresProtectedWriteAdapter({
...options,
hierarchy: { control, parentIdColumn: "folder_id" },
});
const intent = {
resource: { type: "folder", id: "folder_7" }, action: "move",
incarnationId: "folder-7-incarnation", expectedVersion: "4", postVersion: "5",
idempotencyKey: "move-folder_7-once",
// A recursive type names its parent type; otherwise it defaults to the declared parent type.
sourceParent: { type: "folder", id: "folder_a", incarnationId: "a-incarnation", version: "2" },
destinationParent: { type: "folder", id: "folder_b", incarnationId: "b-incarnation", version: "9" },
} satisfies ManagedMoveIntent;
await adapter.forScope({ tenantId: "namespace_1", actor: { type: "user", id: "alice" } }).withManagedMove(intent); The move runs through the hierarchy command engine inside the protected transaction. Without
hierarchy it refuses HIERARCHY_UNAVAILABLE / enrolled after the current gate. The flat
managedMove descriptor is not used on an enrolled tenant.
- Parents are placed resources of the hierarchy. Each expectation’s
versionis the parent’s resource version andincarnationIdits Sharing incarnation, compared on the stored bytes; the source must be the stored parent. A wrong source is rejected before the adapter looks up any parent by the source id the request names, so an existing and an absent id answer the same. A stale target, a stale parent or a wrong source isPROTECTED_WRITE_POSTCONDITION_FAILED. An omittedtypeis the moved type’s declared parent type. - Subtrees. The resource moves with everything below it: its link is re-parented, heights are repaired on the old path and then the new one, and descendants follow the moved link. Stored memberships stay where they are; what changes is the ancestry the subtree inherits from. Members of the destination’s ancestors gain inherited access to the moved subtree; the move proof constrains only the actor.
- Refusals (only after every authorization check, the protected action included, allowed;
with no effect):
PROTECTED_WRITE_REFUSEDwithhierarchy_cycle(the destination is the resource or below it),ancestry_cap(the subtree would end below 16 ancestors),hierarchy_edge_refused(the policy does not allow that parent type) orhierarchy_exists(the destination is the current parent). A parenttypeoutside the hierarchy command map is refusedhierarchy_edge_refusedbefore authorization: that answer depends only on the request and the configuration. - Authorization. The protected action on the resource before the move and again on its new
chain; the type’s
moveandmanagement.memberson the resource;removeChildon the source andaddChildon the destination, each with that parent’smanagement.members; and the move proof: for every permission of every type at or below the moved type, the actor must already hold an unrestricted allow at a common ancestor of both positions (with no common ancestor, also the bootstraprootPlacement), and no actor role may carry a deny for those permissions. A move can never extend the actor’s authority over the subtree. Any denial isPROTECTED_WRITE_DENIED. - Effects and receipt. The business row’s version advances to
postVersion(andparentIdColumnto the destination); key, incarnation, sharing revision, owner and members are unchanged. The receipt records metadata version 2 with the pre-move inherited evidence; the result and theprotected.move.committedevent name both parents and the unchanged sharing revision. Moves never cross tenants and never move to or from the root position (usestructure.moveof the control facade for that). - One final seal covers the local identity, the inherited memberships every decision relied on,
and the pre- and post-move evidence. A serialization failure or deadlock reruns the whole attempt with fresh capture;
exhaustion is
HIERARCHY_UNAVAILABLE/serialization_conflict.
Recovery and boundaries
The managed.move.v1 receipt binds the complete intent, configured mappings and authority epoch.
A changed intent with the same key conflicts. Exact replay recovers the historical receipt before
current authorization or schema validation and never executes a second move. After an uncertain
COMMIT use the exact-intent lookup; no receipt is not proof that an in-flight commit aborted.
Historical receipt recovery never grants access to a replacement incarnation.
Only one child, one namespace, one mapped root-parent table and one adapter-owned local transaction are supported. IDs are opaque within their resource types: equal child and parent IDs do not form a hierarchy cycle because these are distinct types. Same source/destination parent IDs are rejected. There is no create, subtree or multi-level move, batch move, cross-tenant/cross-adapter operation, remote authority, parent Sharing membership source or public consistency token in this API.
Ordinary permanent tables and exact projections are required. Existing managed safeguards reject unsupported triggers, rules, generated columns, RLS, inheritance, partitioning, temporary shadows and cascade graphs where applicable. All participating writers must honor the identity/revision contract. SQL mapping is trusted server configuration; it is not accepted from the request.