RolebookDocs

@rolebook/sharing-postgres API

Every export of @rolebook/sharing-postgres, with its signature and behaviour.

import { ... } from "@rolebook/sharing-postgres". Signatures are checked against the package’s built declarations. Start with the PostgreSQL adapter guide.

Adapter

createPostgresSharingAdapter

function createPostgresSharingAdapter(
  options: CreatePostgresSharingAdapterOptions,
): PostgresSharingAdapter;

Creates the adapter for one concrete resource table. Validates the descriptor and options before any SQL runs. See setup.

CreatePostgresSharingAdapterOptions

interface CreatePostgresSharingAdapterOptions {
  readonly executor: ParameterizedSqlExecutor;
  readonly resource: PostgresResourceDescriptor;
  readonly clock?: SharingClock;
  readonly lockEligibleSubjects: PostgresEligibilityFence;
  readonly readEligibleSubjects?: PostgresEligibilityReader;
  readonly lockInvitationRecipient?: PostgresInvitationRecipientFence;
  readonly revalidateAuthorizationFacts?: PostgresAuthorizationFactFence;
  readonly groupSubjectTypes?: readonly string[];
  readonly fencePolicy?: PostgresPolicyFence;
  readonly governanceGate?: GovernanceDirectGate;
  readonly governanceBinding?: GovernanceBinding;
  readonly serializableRetry?: SerializableRetryOptions;
  readonly pageIdentity?: PostgresPageIdentity;
  readonly groupGraph?: import("./group-graph-fence.js").PostgresGroupGraphOption;
}

executor, resource, and the required lockEligibleSubjects; optional lockInvitationRecipient (email invitations), revalidateAuthorizationFacts (mapped roles, teams), groupSubjectTypes (default ["team"]), fencePolicy, clock, and serializableRetry.

Two options matter only to listAccessible() and listAccess(), which read each page in one SERIALIZABLE READ ONLY transaction:

  • readEligibleSubjects is the read-only form of lockEligibleSubjects; see PostgresEligibilityReader. The first-party fences carry their own, so set it only beside a fence you wrote yourself. A custom fence without it makes every listing answer identity_evidence_missing.
  • pageIdentity names the identity adapter of the sharing instance and the local projection it answers from; see PostgresPageIdentity. Without it, the identity adapter must implement resolvePagePrincipal, or listings answer identity_evidence_missing. A malformed value throws a TypeError when the adapter is created.

Listing also requires executor to be the executor createPgExecutor(pool) returned, recognized by provenance and not by shape, and text tenant and resource ID columns. Any other executor or column type answers capability_missing. The page reads its clocks as timestamptz values, which the pool must decode as finite Date objects (the node-postgres default); a custom timestamptz type parser that returns anything else makes every page snapshot_unavailable. An adapter clock does not apply to listing pages: they judge expiry by the database clock. With versioned sharing, the policy store must be the one createPostgresPolicyStore() returned, created with this same executor object, so the page can read policy state in its own transaction; a wrapped store or one on another executor answers policy_evidence_missing.

groupGraph binds one nested-team profile. Set teamType, an explicit identityStability (registry_incarnation or ids_never_reused), and a directory whose readDirectTeams and readEndpoint run in the adapter’s transaction. teamIdsGloballyUnique does not select ids_never_reused. When a graph row exists and groupGraph is omitted, direct-only reads and writes refuse. Optional integrity is that deployment’s bootstrap provider. When it is set, a read or mutation that finds structural corruption confirms the finding after the detecting transaction settles, with no user actor. A failed confirmation makes no quarantine claim. Build the commands with createPostgresGroupGraphControl().

PostgresSharingAdapter

interface PostgresSharingAdapter extends SharingAdapter, SettledRecordPruner {
  withLifecycleTransaction<T>(
    operation: (transaction: SerializablePostgresTransaction) => Promise<T>,
  ): Promise<T>;
  resourceDeletedInTransaction(
    transaction: SerializablePostgresTransaction,
    input: DeletePostgresResourceInTransactionInput,
  ): Promise<PostgresLifecycleResult>;
  resourceMovedInTransaction(
    transaction: SerializablePostgresTransaction,
    input: MovePostgresResourceInTransactionInput,
  ): Promise<PostgresLifecycleResult>;
  initializeResource(
    input: InitializePostgresSharingResourceInput,
  ): Promise<InitializePostgresSharingResourceResult>;
  initializeResourceInTransaction(
    executor: SerializablePostgresTransaction,
    input: InitializePostgresSharingResourceInput,
  ): Promise<InitializePostgresSharingResourceResult>;
}

A SharingAdapter and SettledRecordPruner, plus withLifecycleTransaction, the two ...InTransaction lifecycle methods, and initializeResource / initializeResourceInTransaction. See lifecycle.

PostgresResourceDescriptor

interface PostgresResourceDescriptor {
  readonly resourceType: string;
  readonly table: QualifiedIdentifier;
  readonly tenantColumn: string;
  readonly idColumn: string;
  readonly tenantSqlType?: PostgresResourceSqlType;
  readonly resourceSqlType?: PostgresResourceSqlType;
  readonly resourceVersionColumn: string;
  readonly sharingRevisionColumn?: string;
  readonly resourceFromRow: (row: Readonly<Record<string, unknown>>) => TrustedResource;
  readonly resourceVersion?: (row: Readonly<Record<string, unknown>>) => string;
  readonly resourceColumns?: readonly string[];
  readonly sharingTablePrefix: string;
  readonly hierarchyControl?: {
    readonly schema: string;
    readonly prefix?: string;
  };
  readonly governance?: {
    readonly tablePrefix: string;
  };
}

The application table and how to snapshot its row. See the descriptor. hierarchyControl names the schema (and table prefix, default rolebook_control) of the schema-qualified hierarchy control tables this descriptor is permanently bound to. It is required when table is unqualified and defaults to the table’s schema otherwise; search_path is never consulted. See hierarchy control tables.

PostgresResourceSqlType

type PostgresResourceSqlType = "text" | "uuid";

The accepted tenant and resource ID column types.

NormalizedPostgresResourceSqlTypes

interface NormalizedPostgresResourceSqlTypes {
  readonly tenantSqlType: PostgresResourceSqlType;
  readonly resourceSqlType: PostgresResourceSqlType;
}

Both SQL types with their text defaults applied.

normalizePostgresResourceSqlTypes

function normalizePostgresResourceSqlTypes(
  descriptor: Pick<PostgresResourceDescriptor, "tenantSqlType" | "resourceSqlType">,
): NormalizedPostgresResourceSqlTypes;

Applies the text defaults and rejects any value other than text or uuid.

Nested team commands

groupGraph on the adapter recomputes lineage inside a sharing mutation. Graph commands change the graph itself. createPostgresGroupGraphControl() builds the facade from the deployment policy, six action permissions, two distinct binding ids, and the bootstrap row descriptor. The branded bootstrap provider and the compiled command object stay inside that call. Each facade method runs in one SERIALIZABLE transaction: the hierarchy barrier and admission, the graph row, the policy loaded by the versioned sharing instance, then the planner. The facade has no confirm method. Structural confirmation is the adapter’s later transaction when groupGraph.integrity is the integrity object this call returns.

hierarchyControlTables() names the control tables for a schema and prefix. Resource migrations install that same profile when the descriptor sets hierarchyControl. createHierarchyControlMigrations() installs the profile on its own, and createPolicyCatalogRegistrationMigrations() appends the profile to the policy catalog.

Activation stores control_configuration as sha256: plus 64 hexadecimal characters. That digest is the canonical identity of the profile, team type, identity stability, bootstrap type, both binding ids, the six permissions, the graph-independent providers, and the first-party local projection. Provider order, and the order of each provider’s fact paths and fact types, do not change it. A later command whose action map differs throws HierarchyUnavailableError with reason profile_mismatch and does not write the edge.

createPostgresGroupGraphControl

function createPostgresGroupGraphControl(options: PostgresGroupGraphControlOptions): Readonly<{
  tables: HierarchyControlTableNames;
  integrity: PostgresBootstrapIntegrity;
  facade: Readonly<{
    activate(tenantId: string): Promise<PostgresGroupGraphOutcome>;
    link(tenantId: string, child: ResourceRef, parent: ResourceRef): Promise<PostgresGroupGraphOutcome>;
    unlink(tenantId: string, child: ResourceRef, parent: ResourceRef): Promise<PostgresGroupGraphOutcome>;
    repairUnlink(tenantId: string, child: ResourceRef, parent: ResourceRef): Promise<PostgresGroupGraphOutcome>;
    repairBatch(tenantId: string, start: boolean, limit: number): Promise<PostgresGroupGraphOutcome>;
    release(tenantId: string): Promise<PostgresGroupGraphOutcome>;
  }>;
}>;

activate inserts the graph admission. link and unlink change one direct edge. repairUnlink, repairBatch, and release run only while the graph is quarantined. repairBatch reads at most limit rows; limit has to be an integer of at least 1, and a smaller or fractional limit is refused with invalid_batch. A Core denial comes back as status: "denied" and decision. A structural refusal comes back as status: "refused". An unavailable graph throws HierarchyUnavailableError.

import { HierarchyUnavailableError, type PolicyStore } from "@rolebook/sharing";
import {
  createPostgresGroupGraphControl,
  createPostgresLocalIdentityProjection,
  type ParameterizedSqlExecutor,
} from "@rolebook/sharing-postgres";
import type { RolebookPolicy } from "rolebook";

declare const executor: ParameterizedSqlExecutor;
declare const policy: RolebookPolicy;
declare const policyStore: PolicyStore;
declare const sharing: object;
declare const identity: ReturnType<typeof createPostgresLocalIdentityProjection>;

const graph = createPostgresGroupGraphControl({
  executor,
  profile: { schema: "public", prefix: "rolebook_control" },
  teamType: "team",
  identityStability: "registry_incarnation",
  actor: { type: "user", id: "ada" },
  policy,
  bootstrapType: "tenant_admin",
  actions: {
    activate: "tenant_admin:graph_activate",
    link: "tenant_admin:graph_link",
    unlink: "tenant_admin:graph_unlink",
    repairUnlink: "tenant_admin:graph_repair_unlink",
    heightRepair: "tenant_admin:graph_height_repair",
    release: "tenant_admin:graph_release",
  },
  controlBindingId: "control-binding",
  normalBindingId: "graph-binding",
  providers: [
    {
      id: "local",
      graphIndependent: true,
      factPaths: ["subject.attribute"],
      factTypes: ["attribute"],
    },
  ],
  policyStore,
  sharing,
  identity,
  bootstrap: {
    policyStore: { schema: "public", tablePrefix: "rolebook" },
    descriptor: {
      resourceType: "tenant_admin",
      schema: "public",
      table: "tenant_admin",
      tenantColumn: "workspace_id",
      idColumn: "id",
      versionColumn: "version",
      incarnationColumn: "incarnation",
    },
  },
  registry(tx, tenantId) {
    return {
      async readEndpoint(group) {
        const result = await tx.query<{ incarnation: string }>(
          "SELECT incarnation FROM public.team WHERE tenant_id = $1 AND id = $2",
          [tenantId, group.id],
        );
        const row = result.rows[0];
        return row
          ? { present: true as const, incarnation: row.incarnation }
          : { present: false as const };
      },
    };
  },
});

const child = { type: "team", id: "design" };
const parent = { type: "team", id: "product" };
try {
  const outcome = await graph.facade.link("ws_456", child, parent);
  if (outcome.status === "denied") outcome.decision.allowed;
  if (outcome.status === "refused") outcome.refusal;
  if (outcome.status === "applied") outcome.effect;
} catch (error) {
  if (error instanceof HierarchyUnavailableError) error.reason;
}
graph.tables.names.groupGraph;
graph.integrity.descriptorDigest;

executor, policy, policyStore, sharing, and identity are the objects the rest of the deployment already constructed: the same executor as the policy store, the active policy, the store createVersionedSharing() reads, that sharing instance, and the object createPostgresLocalIdentityProjection() returns. registry reads one group endpoint inside the command transaction. The two binding ids are distinct opaque ids. Omit providers when the deployment declares no graph-independent fact paths.

PostgresGroupGraphControlOptions

interface PostgresGroupGraphControlOptions {
  readonly executor: ParameterizedSqlExecutor;
  readonly tenantSqlType?: PostgresTenantCodec;
  readonly teamType: string;
  readonly identityStability: "registry_incarnation" | "ids_never_reused";
  readonly actor: ResourceRef;
  readonly policy: RolebookPolicy;
  readonly bootstrapType: string;
  readonly actions: {
    readonly activate: string;
    readonly link: string;
    readonly unlink: string;
    readonly repairUnlink: string;
    readonly heightRepair: string;
    readonly release: string;
  };
  readonly controlBindingId: string;
  readonly normalBindingId: string;
  readonly providers?: readonly {
    readonly id: string;
    readonly graphIndependent: true;
    readonly factPaths: readonly string[];
    readonly factTypes: readonly string[];
  }[];
  readonly profile: HierarchyControlProfile;
  readonly policyStore: PolicyStore;
  readonly sharing: object;
  readonly identity: ReturnType<typeof createPostgresLocalIdentityProjection>;
  readonly bootstrap: {
    readonly policyStore: {
      readonly schema: string;
      readonly tablePrefix: string;
    };
    readonly descriptor: PostgresBootstrapRowDescriptor;
  };
  registry(tx: ParameterizedSqlExecutor, tenantId: string): GroupRegistryReader;
}

tenantSqlType selects the tenant key codec (text or uuid) for the control tables. It has to agree with the codec the profile already bound. identityStability is the same explicit declaration the lineage directory was built with. actor is the control subject. A control actor whose groups include teamType, or a lineage fact, is identity_unavailable.

hierarchyControlTables

function hierarchyControlTables(profile: HierarchyControlProfile): HierarchyControlTableNames;

HierarchyControlProfile

interface HierarchyControlProfile {
  readonly schema: string;
  readonly prefix: string;
}

prefix defaults to rolebook_control on a resource descriptor. Pass the same schema and prefix here.

HierarchyControlTableNames

interface HierarchyControlTableNames {
  readonly profile: HierarchyControlProfile;
  readonly profileId: string;
  readonly barrier: string;
  readonly admission: string;
  readonly hierarchyTenant: string;
  readonly link: string;
  readonly inventory: string;
  readonly principalGeneration: string;
  readonly descriptorProfile: string;
  readonly policyIssuer: string;
  readonly tenantKeyCodec: string;
  readonly controlReceipt: string;
  readonly verifierProgress: string;
  readonly groupGraph: string;
  readonly groupNode: string;
  readonly groupEdge: string;
  readonly groupRepair: string;
  readonly names: {
    readonly barrier: string;
    readonly admission: string;
    readonly hierarchyTenant: string;
    readonly link: string;
    readonly inventory: string;
    readonly principalGeneration: string;
    readonly descriptorProfile: string;
    readonly policyIssuer: string;
    readonly tenantKeyCodec: string;
    readonly controlReceipt: string;
    readonly verifierProgress: string;
    readonly groupGraph: string;
    readonly groupNode: string;
    readonly groupEdge: string;
    readonly groupRepair: string;
  };
}

The table fields are schema-qualified dotted names. names holds the same identifiers without the schema. profileId is the canonical JSON of [schema, prefix].

createHierarchyControlMigrations

function createHierarchyControlMigrations(profile: HierarchyControlProfile): readonly ResourceSharingMigration[];

These statements create the control tables, including the group-graph tables. Resource migrations install this same profile for a descriptor that sets hierarchyControl.

createPolicyCatalogRegistrationMigrations

function createPolicyCatalogRegistrationMigrations(input: {
  readonly policyStore: QualifiedPolicyStoreConfig;
  readonly profiles: readonly HierarchyControlProfile[];
}): readonly ResourceSharingMigration[];

QualifiedPolicyStoreConfig

interface QualifiedPolicyStoreConfig {
  readonly schema: string;
  readonly tablePrefix: string;
}

schema and tablePrefix name the policy store whose catalog receives the control profiles.

PostgresBootstrapIntegrity

interface PostgresBootstrapIntegrity {
  readonly resourceType: string;
  readonly descriptorDigest: string;
  readonly profileId: string;
  readonly policyStoreId: string;
}

descriptorDigest is the sha256: identity of the bootstrap row. Pass this object as groupGraph.integrity when the adapter confirms structural corruption after the detecting transaction.

createPostgresGroupGraphFacade

function createPostgresGroupGraphFacade(options: PostgresGroupGraphFacadeOptions): Readonly<{
  activate(tenantId: string): Promise<PostgresGroupGraphOutcome>;
  link(tenantId: string, child: ResourceRef, parent: ResourceRef): Promise<PostgresGroupGraphOutcome>;
  unlink(tenantId: string, child: ResourceRef, parent: ResourceRef): Promise<PostgresGroupGraphOutcome>;
  repairUnlink(tenantId: string, child: ResourceRef, parent: ResourceRef): Promise<PostgresGroupGraphOutcome>;
  repairBatch(tenantId: string, start: boolean, limit: number): Promise<PostgresGroupGraphOutcome>;
  release(tenantId: string): Promise<PostgresGroupGraphOutcome>;
}>;

activate inserts the graph admission. link and unlink change one direct edge. repairUnlink, repairBatch, and release run only while the graph is quarantined, and each one is authorized for authority.actor. repairBatch reads at most limit rows; limit has to be an integer of at least 1, and a smaller or fractional limit is refused with invalid_batch. A Core denial comes back as status: "denied" and decision. The facade does not turn that decision into an allow. A structural refusal comes back as status: "refused". An unavailable graph throws HierarchyUnavailableError (the outcome type also names status: "unavailable", and the facade throws that reason before returning it). Build a new graph with createPostgresGroupGraphControl(). This function is the lower facade for a caller that already holds tables and an authority object.

PostgresGroupGraphFacadeOptions

interface PostgresGroupGraphFacadeOptions {
  readonly executor: ParameterizedSqlExecutor;
  readonly tables: HierarchyControlTableNames;
  readonly tenantSqlType?: PostgresTenantCodec;
  readonly teamType: string;
  readonly identityStability: "registry_incarnation" | "ids_never_reused";
  readonly authority: PostgresGroupGraphAuthority;
  readonly serializableRetry?: SerializableRetryOptions;
}

tenantSqlType selects the tenant key codec (text or uuid) for the control tables. It has to agree with the codec the profile already bound. identityStability is the same explicit declaration the lineage directory was built with. The bootstrap descriptor is authority.integrity’s digest. serializableRetry bounds how many times a serialization failure starts that transaction again.

PostgresGroupGraphAuthority

interface PostgresGroupGraphAuthority {
  readonly actor: ResourceRef;
  readonly commands: GroupGraphCommands;
  readonly integrity: PostgresBootstrapIntegrity;
  readonly policyStore: PolicyStore;
  readonly sharing: object;
  readonly identity: ReturnType<typeof createPostgresLocalIdentityProjection>;
  registry(tx: ParameterizedSqlExecutor, tenantId: string): GroupRegistryReader;
}

actor is the control subject. commands is the compiled control object for this bootstrap resource. integrity is the first-party bootstrap provider, and its profile id matches tables. policyStore is the store createVersionedSharing() reads, and sharing is that instance. identity is the object createPostgresLocalIdentityProjection() returns; the command reads it inside the transaction and revalidates its facts. A control actor whose groups include teamType, or a lineage fact, is identity_unavailable. registry reads group endpoints in that same transaction. createPostgresGroupGraphControl() compiles that provider and those commands from the policy, the six permissions, the binding ids, and the bootstrap descriptor.

PostgresGroupGraphOutcome

type PostgresGroupGraphOutcome = (GroupGraphApplyResult & {
  readonly progress?: GroupGraphRepairProgress;
}) | {
  readonly status: "denied";
  readonly decision: AuthorizationDecision;
};

progress is present on a repair batch. denied carries the Core decision unchanged.

Inherited access

The supported way to switch on inherited access (sharing.inheritance/1).

enablePostgresInheritedReads

function enablePostgresInheritedReads(options: EnablePostgresInheritedReadsOptions): void;

Enables inherited reads on every type of definition that sets inheritance: "ancestors", replacing the internal readiness gate. Call it once, after defineSharing and before createVersionedSharing. Every option is read once and every adapter is validated before any is changed. It throws when an inheriting type is not on a first-party PostgreSQL adapter or its adapter has no pageIdentity, when the inheriting types do not share one control profile (the bootstrap provider’s), when the definition also holds a first-party type that does not inherit, when identity is not a first-party local identity projection, when the command map’s types differ from the opted-in types, or when configurationGeneration does not bind this definition and command map. Once a Sharing instance is built from a definition that opts a type in, that type’s storage refuses every tenant that is not enrolled (not_enrolled) on every read, listing, command, protected write and governed call (lifecycle writers that initialize, delete or move a resource are not refused); enroll a tenant before it uses the type. See inherited access.

EnablePostgresInheritedReadsOptions

interface EnablePostgresInheritedReadsOptions {
  readonly definition: SharingDefinition;
  readonly commands: HierarchyCommandsInput;
  readonly configurationGeneration: string;
  readonly authorityEpoch: string;
  readonly identity: ReturnType<typeof createPostgresLocalIdentityProjection>;
  readonly bootstrap: PostgresBootstrapIntegrity;
}

configurationGeneration comes from hierarchyConfigurationGeneration. identity is the complete local identity projection; an enrolled tenant’s reads resolve the actor from it in the read transaction and never consult the generic identity adapter. bootstrap is the profile’s one bootstrap provider; pass the same object to the control facade.

createPostgresHierarchyControl

function createPostgresHierarchyControl(options: CreatePostgresHierarchyControlOptions): PostgresInheritanceControl;

The actor-authorized hierarchy control facade. forTenant({ tenantId, actor }) returns enroll, activate, releaseQuarantine and repairHeights (each needs the matching bootstrap action) and structure with create, move and delete (each needs the configured command permissions on the resources involved). Every action is one transaction decided by Rolebook; a non-applied outcome rolls back. It throws when the Sharing definition’s opted-in types and the command map differ.

CreatePostgresHierarchyControlOptions

interface CreatePostgresHierarchyControlOptions {
  readonly sharing: VersionedResourceSharing<SharingResourceConfigurations>;
  readonly policy: RolebookPolicy;
  readonly commands: HierarchyCommandsInput;
  readonly bootstrap: PostgresBootstrapIntegrity;
  readonly authorityEpoch: string;
  readonly configurationGeneration: string;
  readonly serializableRetry?: SerializableRetryOptions;
}

Use the same bootstrap, authorityEpoch and configurationGeneration as the inherited read configuration.

PostgresInheritanceControl

interface PostgresInheritanceControl {
  forTenant(scope: {
    readonly tenantId: string;
    readonly actor: ResourceRef;
  }): {
    enroll(input: {
      readonly idempotencyKey: string;
    }): Promise<PostgresHierarchyControlResult>;
    activate(input: {
      readonly idempotencyKey: string;
    }): Promise<PostgresHierarchyControlResult>;
    releaseQuarantine(input: {
      readonly idempotencyKey: string;
    }): Promise<HierarchyControlResult>;
    repairHeights(): Promise<HierarchyControlResult>;
    readonly structure: ReturnType<PostgresHierarchyControl["forTenant"]>["structure"];
  };
}

The facade createPostgresHierarchyControl returns. After the actor is authorized, enroll and activate answer unlinked_resources, on the same control transaction and before changing tenant state, while the tenant has a row of an inheriting type that the managed hierarchy does not place: existing resources are not adopted.

PostgresHierarchyControlResult

type PostgresHierarchyControlResult = HierarchyControlResult;

An actor control action’s answer. Through this facade enroll and activate may also answer unlinked_resources with the first unplaced type, after the actor is authorized.

runPostgresHierarchyInventory

function runPostgresHierarchyInventory(control: PostgresInheritanceControl, tenantId: string, batchSize?: number): Promise<HierarchyControlJobResult>;

One bounded, resumable batch of the activation inventory for a tenant in building: call it until it answers complete, then activate. An operator job, not an actor command; it changes no authority. Activation refuses while any stored membership on a would-be inheriting scope carries an allow that would reach further.

createPostgresBootstrapIntegrity

function createPostgresBootstrapIntegrity(options: {
  readonly profile: HierarchyControlProfile;
  readonly policyStore: QualifiedPolicyStoreConfig;
  readonly descriptor: PostgresBootstrapRowDescriptor;
}): PostgresBootstrapIntegrity;

The profile’s bootstrap integrity provider over the application table that holds each tenant’s bootstrap row (the resource the bootstrap actions are checked on). Inherited reads prove the row in their own snapshot; commands lock it.

PostgresBootstrapRowDescriptor

interface PostgresBootstrapRowDescriptor {
  readonly resourceType: string;
  readonly schema: string;
  readonly table: string;
  readonly tenantColumn: string;
  readonly idColumn: string;
  readonly versionColumn: string;
  readonly incarnationColumn: string;
  readonly fields?: readonly {
    readonly field: string;
    readonly column: string;
    readonly codec: "text" | "boolean" | "safe-integer";
    readonly nullable?: boolean;
  }[];
}

Where the bootstrap row lives: its table and the tenant, id, version and incarnation columns, plus optional fields the bootstrap resource exposes to policy conditions.

HierarchyControlResult

An actor control action’s answer (enrolled, already_enrolled, activated, inventory_incomplete, released, verifying, repairing, repaired, not_enrolled, denied, conflict, unlinked_resources). denied and conflict are ordinary outcomes; tenant-level unavailability throws HierarchyUnavailableError. Declared by the control runtime this package bundles; it has no signature block here.

HierarchyControlJobResult

An operator job’s answer. The inventory answers progress until it is complete. Declared by the control runtime this package bundles; it has no signature block here.

Lifecycle

InitializePostgresSharingResourceInput

interface InitializePostgresSharingResourceInput {
  readonly tenantId: string;
  readonly resourceId: string;
  readonly owner: OwnerRef;
  readonly actor: ResourceRef;
  readonly occurredAt: Date;
}

Tenant, resource, intended owner, actor, and time of an initialization.

InitializePostgresSharingResourceResult

type InitializePostgresSharingResourceResult =
  | "applied"
  | "already_initialized"
  | "identity_ineligible"
  | "owner_mismatch"
  | "group_owner"
  | "not_found";

DeletePostgresResourceInTransactionInput

interface DeletePostgresResourceInTransactionInput extends PostgresLifecycleInput {
  readonly tenantId: string;
  readonly resourceId: string;
  readonly deleteResource: (
    transaction: SerializablePostgresTransaction,
  ) => Promise<PostgresLifecycleApplicationResult>;
}

A deletion: the key, the actor and subjects to fence, idempotency key and fingerprint, the expected resource version and sharing revision, and your deleteResource callback.

MovePostgresResourceInTransactionInput

interface MovePostgresResourceInTransactionInput extends PostgresLifecycleInput {
  readonly fromTenantId: string;
  readonly toTenantId: string;
  readonly resourceId: string;
  readonly resultingResourceVersion: string;
  readonly moveResource: (
    transaction: SerializablePostgresTransaction,
  ) => Promise<PostgresLifecycleApplicationResult>;
}

A move: source and destination tenant, the resulting resource version, the same fencing and idempotency fields, and your moveResource callback.

PostgresLifecycleApplicationResult

type PostgresLifecycleApplicationResult = "applied" | "not_found" | "conflict";

What your lifecycle callback returns.

PostgresLifecycleResult

type PostgresLifecycleResult =
  | "applied"
  | "already_applied"
  | "not_found"
  | "conflict"
  | "identity_ineligible";

What a lifecycle method returns.

Fences

PostgresEligibilityFence

type PostgresEligibilityFence = (input: {
  readonly executor: ParameterizedSqlExecutor;
  readonly tenantId: string;
  readonly subjects: readonly ResourceRef[];
  readonly ownerCandidates?: readonly ResourceRef[];
}) => Promise<boolean>;

Locks and verifies tenant eligibility of subjects inside the mutation transaction, and may refuse ownerCandidates. Only true counts as eligible.

PostgresEligibilityReader

type PostgresEligibilityReader = (input: {
  readonly executor: ParameterizedSqlExecutor;
  readonly tenantId: string;
  readonly subjects: readonly ResourceRef[];
  readonly evaluatedAt: string;
}) => Promise<PostgresEligibilityEvidence>;

The read-only form of a PostgresEligibilityFence, used by listing pages. It gives the same answer from the same authoritative rows, read through executor, which is the page’s SERIALIZABLE READ ONLY transaction. It must not lock or write: FOR SHARE cannot run there, and a reader that tries makes the page snapshot_unavailable. Judge every time-dependent fact at evaluatedAt, the page’s instant, and never read another clock.

createPostgresMembershipEligibilityFence() and createPostgresLocalIdentityProjection().lockEligibleSubjects carry their own reader, recognized by provenance. If you wrap one of them in a function of your own, the wrapper is a custom fence: pass a reader wrapped the same way as readEligibleSubjects.

PostgresEligibilityEvidence

interface PostgresEligibilityEvidence {
  readonly eligible: boolean;
  readonly expiryDependencies: readonly string[];
}

What a reader returns. eligible must be a boolean, and only true makes the subjects eligible; an actor it refuses receives an empty exhausted page. expiryDependencies lists every instant at which a time-sensitive fact behind the answer changes it: a membership or projection expiry, and equally the end of a refusing condition. Each is an ISO 8601 UTC instant with three or six fractional digits, compared in SQL at microsecond precision. Leave it empty only when the answer depends on no time. The page seals all of them, and one that passes before the seal refuses the page with expiry_crossed. A boolean, a missing field, or a malformed instant is identity_evidence_missing, never a page.

createPostgresMembershipEligibilityFence

function createPostgresMembershipEligibilityFence(
  descriptor: PostgresMembershipEligibilityDescriptor,
): PostgresEligibilityFence;

A fence over an organization-member table: locks each member row FOR SHARE and requires the exact tenant and subject. It carries its own listing reader, which reads the same rows unlocked and declares no expiry, because row existence depends on no time.

PostgresMembershipEligibilityDescriptor

interface PostgresMembershipEligibilityDescriptor {
  readonly table: QualifiedIdentifier;
  readonly tenantColumn: string;
  readonly subjectIdColumn: string;
  readonly subjectType?: string;
}

The member table, its tenant and subject ID columns, and the subject type.

PostgresInvitationRecipientFence

type PostgresInvitationRecipientFence = (input: {
  readonly executor: ParameterizedSqlExecutor;
  readonly verification: InvitationRecipientFenceInput;
}) => Promise<boolean>;

Checks an email invitation’s recipient while it is consumed.

createPostgresEmailInvitationRecipientFence

function createPostgresEmailInvitationRecipientFence(
  descriptor: PostgresEmailInvitationRecipientFenceDescriptor,
): PostgresInvitationRecipientFence;

Locks the membership and user rows FOR SHARE and requires a verified email equal to the invitation’s, under lower_trim (default) or exact normalization.

PostgresEmailInvitationRecipientFenceDescriptor

interface PostgresEmailInvitationRecipientFenceDescriptor {
  readonly membershipTable: QualifiedIdentifier;
  readonly membershipTenantColumn: string;
  readonly membershipSubjectIdColumn: string;
  readonly userTable: QualifiedIdentifier;
  readonly userIdColumn: string;
  readonly userEmailColumn: string;
  readonly userEmailVerifiedColumn: string;
  readonly subjectType?: string;
  readonly emailNormalization?: "lower_trim" | "exact";
}

Membership and user tables and their columns, subject type, email normalization.

PostgresAuthorizationFactFence

type PostgresAuthorizationFactFence = (input: {
  readonly executor: ParameterizedSqlExecutor;
  readonly tenantId: string;
  readonly facts: readonly TransactionalAuthorizationFact[];
}) => Promise<PostgresAuthorizationFactFenceResult>;

Revalidates a mutation’s authorization facts in its transaction: true proceeds, "conflict" re-authorizes, anything else is identity_ineligible.

PostgresAuthorizationFactFenceResult

type PostgresAuthorizationFactFenceResult = boolean | "conflict";

createPostgresWorkspaceRoleAuthorizationFactFence

function createPostgresWorkspaceRoleAuthorizationFactFence(
  descriptor: PostgresWorkspaceRoleAuthorizationFactDescriptor,
): PostgresAuthorizationFactFence;

Locks member rows and compares the exact tenant, subject, membership ID, and role behind mapped workspace assignments.

PostgresWorkspaceRoleAuthorizationFactDescriptor

interface PostgresWorkspaceRoleAuthorizationFactDescriptor
  extends PostgresMembershipEligibilityDescriptor {
  readonly factType: string;
  readonly memberIdColumn: string;
  readonly roleColumn: string;
}

The member-table descriptor plus the fact type, member ID column, and role column.

Migrations

createResourceSharingMigrations

function createResourceSharingMigrations(
  descriptor: PostgresResourceDescriptor,
): readonly ResourceSharingMigration[];

The ordered, idempotent migration steps for one descriptor. See migrations.

createResourceSharingRollbackMigrations

function createResourceSharingRollbackMigrations(
  descriptor: PostgresResourceDescriptor,
  options?: ResourceSharingRollbackOptions,
): readonly ResourceSharingRollbackMigration[];

Ordered DROP steps for sharing-owned state. Keeps audit history unless dropAudit is true; never drops the application’s revision column or unique index.

ResourceSharingMigration

interface ResourceSharingMigration {
  readonly name: string;
  readonly sql: string;
  readonly apply?: (executor: Pick<ParameterizedSqlExecutor, "query">) => Promise<void>;
}

One named migration step.

ResourceSharingRollbackMigration

interface ResourceSharingRollbackMigration {
  readonly name: string;
  readonly sql: string;
  readonly dataLoss?: string;
}

One named rollback step, with a dataLoss note when it destroys data.

ResourceSharingRollbackOptions

interface ResourceSharingRollbackOptions {
  readonly dropAudit?: boolean;
}

dropAudit: true also drops the audit table.

applyPostgresMigrations

function applyPostgresMigrations(executor: MigrationExecutor, steps: readonly PostgresMigrationStep[], options?: ApplyPostgresMigrationsOptions): Promise<void>;

Applies steps one transaction each, with SET LOCAL lock_timeout, retrying lock timeouts, deadlocks, and serialization failures with backoff. Throws PostgresMigrationError.

ApplyPostgresMigrationsOptions

interface ApplyPostgresMigrationsOptions {
  readonly lockTimeoutMs?: number;
  readonly attempts?: number;
  readonly backoffMs?: (retry: number) => number;
  readonly wait?: (milliseconds: number) => Promise<void>;
}

lockTimeoutMs (default 5,000), attempts (default 5), backoffMs, wait.

PostgresMigrationStep

interface PostgresMigrationStep {
  readonly name: string;
  readonly sql: string;
  readonly apply?: (executor: Pick<ParameterizedSqlExecutor, "query">) => Promise<void>;
}

A named SQL step applyPostgresMigrations accepts.

PostgresMigrationError

class PostgresMigrationError extends Error {
  readonly code: "POSTGRES_MIGRATION_FAILED";
  readonly step: string;
  readonly attempts: number;
  readonly sqlState: string | undefined;
  constructor(step: string, attempts: number, cause: unknown);
}

The step that failed, after how many attempts, its SQLSTATE, and the driver error as cause.

sharingTables

function sharingTables(descriptor: PostgresResourceDescriptor): SharingTableNames;

The sharing table names for a descriptor’s sharingTablePrefix.

SharingTableNames

interface SharingTableNames {
  readonly binding: string;
  readonly owner: string;
  readonly member: string;
  readonly invitation: string;
  readonly audit: string;
  readonly idempotency: string;
  readonly lifecycle: string;
  readonly revisionFloor: string;
}

quoteIdentifier

function quoteIdentifier(identifier: QualifiedIdentifier): string;

Validates and double-quotes an identifier or a qualified [schema, name].

QualifiedIdentifier

type QualifiedIdentifier = string | readonly string[];

assertPostgresSharingSearchPath

function assertPostgresSharingSearchPath(
  executor: ParameterizedSqlExecutor,
  options: PostgresSearchPathCheckOptions,
): Promise<readonly PostgresSearchPathResolution[]>;

Checks that the adapter-owned tables resolve to expectedSchema for the connection’s search_path. The adapter names its sharing, policy store, and journal tables without a schema, so a migration role and an application role with different search_path settings could otherwise create and read different tables. Resolves with one entry per table checked, and throws PostgresSearchPathError when a table is missing, resolves to another schema, or is shadowed by an earlier schema or a temporary table. Run it at startup with the application’s own connection settings.

PostgresSearchPathCheckOptions

interface PostgresSearchPathCheckOptions {
  readonly expectedSchema: string;
  readonly resources?: readonly Pick<PostgresResourceDescriptor, "sharingTablePrefix">[];
  readonly policyStoreTablePrefix?: string;
  readonly journalPrefix?: string;
}

Names the schema the tables must resolve to and which table sets to check: the sharing tables of each resource, the policy store tables, and the protected-write journal tables.

PostgresSearchPathResolution

interface PostgresSearchPathResolution {
  readonly table: string;
  readonly resolvedSchema: string | null;
}

The schema one table name resolves to, or null when the name does not resolve.

PostgresSearchPathError

class PostgresSearchPathError extends Error {
  readonly expectedSchema: string;
  readonly mismatches: readonly PostgresSearchPathResolution[];
  readonly code: "SEARCH_PATH_MISMATCH";
  constructor(expectedSchema: string, mismatches: readonly PostgresSearchPathResolution[]);
}

Thrown by assertPostgresSharingSearchPath. mismatches lists every table that did not resolve to expectedSchema.

Policy store

createPostgresPolicyStore

function createPostgresPolicyStore(options: CreatePostgresPolicyStoreOptions): PolicyStore;

A PolicyStore over the policy-store tables, with serializable retries.

CreatePostgresPolicyStoreOptions

interface CreatePostgresPolicyStoreOptions {
  readonly executor: ParameterizedSqlExecutor;
  readonly tablePrefix?: string;
  readonly schema?: string;
  readonly serializableRetry?: SerializableRetryOptions;
}

executor, tablePrefix (default rolebook), schema, serializableRetry. With schema every statement is qualified by it and the store has a known issuer [schema, tablePrefix]; protected writes and authorized queries require it. Without it the tables resolve through the search path.

createPostgresPolicyFence

function createPostgresPolicyFence(options?: {
  readonly tablePrefix?: string;
  readonly schema?: string;
}): PostgresPolicyFence;

The policy fence for fencePolicy. Use the store’s tablePrefix and schema. Protected writes and authorized queries accept the adapter only when its fence and the policy store were both constructed with the same explicit schema and tablePrefix; a fence without schema never matches.

PostgresPolicyFence

type PostgresPolicyFence = (input: {
  readonly executor: ParameterizedSqlExecutor;
  readonly tenantId: string;
  readonly expectedPolicy: ExpectedPolicy;
}) => Promise<PolicyFenceResult>;

Reads the active generation and tenant-role revision through the mutation’s own executor.

createPolicyStoreMigrations

function createPolicyStoreMigrations(options?: {
  readonly tablePrefix?: string;
}): readonly ResourceSharingMigration[];

Migration steps for the policy-store tables.

createPolicyStoreRollbackMigrations

function createPolicyStoreRollbackMigrations(options?: {
  readonly tablePrefix?: string;
}): readonly ResourceSharingRollbackMigration[];

Rollback for the policy-store tables: one step whose first statement refuses while the hierarchy policy catalog is not empty, then drops the header, catalog and policy tables in one transaction.

policyStoreTables

function policyStoreTables(tablePrefix?: string): PolicyStoreTableNames;

The policy-store table names for a prefix.

PolicyStoreTableNames

interface PolicyStoreTableNames {
  readonly version: string;
  readonly active: string;
  readonly activation: string;
  readonly tenantRole: string;
  readonly tenantRoleRevision: string;
  readonly audit: string;
}

Executor and transactions

ParameterizedSqlExecutor

interface ParameterizedSqlExecutor {
  query<TRow extends SqlRow = SqlRow>(
    sql: string,
    values?: readonly SqlValue[],
  ): Promise<SqlResult<TRow>>;
  transaction<T>(
    options: PostgresTransactionOptions,
    operation: (transaction: SerializablePostgresTransaction) => Promise<T>,
  ): Promise<T>;
}

The executor seam: parameterized queries and SERIALIZABLE transactions.

PostgresTransactionOptions

interface PostgresTransactionOptions {
  readonly isolationLevel: "serializable";
}

SerializablePostgresTransaction

type SerializablePostgresTransaction = ParameterizedSqlExecutor & {
  readonly [serializableTransaction]: true;
};

An executor branded as a SERIALIZABLE transaction.

SqlResult

interface SqlResult<TRow extends SqlRow = SqlRow> {
  readonly rows: readonly TRow[];
  readonly rowCount: number;
}

SqlRow

type SqlRow = Readonly<Record<string, unknown>>;

SqlValue

type SqlValue = string | number | boolean | Date | null | readonly string[];

The values the adapter binds.

asSerializablePostgresTransaction

function asSerializablePostgresTransaction(
  transaction: ParameterizedSqlExecutor,
): SerializablePostgresTransaction;

Compile-time assertion that an ORM transaction you opened is SERIALIZABLE. It inspects nothing; lifecycle methods still require withLifecycleTransaction()’s transaction.

withSerializableRetry

function withSerializableRetry<T>(
  executor: ParameterizedSqlExecutor,
  operation: (transaction: SerializablePostgresTransaction) => Promise<T>,
  options?: SerializableRetryOptions,
): Promise<T>;

Runs an idempotent unit of work in a retried SERIALIZABLE transaction.

withSerializableTransaction

function withSerializableTransaction<T>(
  executor: ParameterizedSqlExecutor,
  operation: (transaction: SerializablePostgresTransaction) => Promise<T>,
  options?: SerializableRetryOptions,
): Promise<T>;

Runs caller-owned application and sharing work in one retried SERIALIZABLE transaction.

SerializableRetryOptions

interface SerializableRetryOptions {
  readonly attempts?: number;
  readonly wait?: (milliseconds: number) => Promise<void>;
  readonly backoffMs?: (retry: number) => number;
}

attempts (default 3, including the first), backoffMs (0 to 1,000 ms), wait.

isRetryableSerializationError

function isRetryableSerializationError(error: unknown): boolean;

True for SQLSTATE 40001 or 40P01, also when wrapped in an error’s cause chain.

Errors

InvalidPostgresCursorError

class InvalidPostgresCursorError extends InvalidCursorError {
  constructor(resourceSqlType: "text" | "uuid");
}

A listing cursor the ID column cannot hold. An InvalidCursorError.

InvalidPostgresAuditCursorError

class InvalidPostgresAuditCursorError extends InvalidCursorError {
  constructor(message?: string);
}

An audit cursor that is malformed or names no event of this incarnation. An InvalidCursorError.

PostgresSharingRowError

class PostgresSharingRowError extends Error {
  readonly code: "POSTGRES_SHARING_ROW_INVALID";
  readonly table: string;
  readonly reason: string;
  constructor(table: string, reason: string);
}

An invitation or audit row that does not decode, or an audit page whose cursor cannot be issued.

PostgresLifecycleConflictError

class PostgresLifecycleConflictError extends Error {
  readonly code: "POSTGRES_LIFECYCLE_CONFLICT";
  constructor(message: string);
}

A lifecycle postcondition failed. The transaction is rollback-only.

PolicyStoreRowError

class PolicyStoreRowError extends Error {
  readonly table: string;
  readonly reason: string;
  constructor(table: string, reason: string);
}

A policy-store row that does not decode. isPolicyStoreRowError recognizes it.

Transaction and clock foundations

These supporting exports are used by the PostgreSQL protected application update API. Metadata and fixtures alone do not authorize an application write. The supported wrapper is resource/action scoped; field-mediated post-state enforcement and application operational integration are separate contracts.

PostgresAuthorizationClock

interface PostgresAuthorizationClock {
    readonly snapshotId: string;
    /** Observation time, not a claim of an exact MVCC snapshot creation timestamp. */
    readonly snapshotObservedAt: string;
    readonly evaluatedAt: string;
}

Descriptive timing and bounded snapshot evidence from a serializable PostgreSQL transaction. snapshotObservedAt is observation time, not the exact creation time of the MVCC snapshot.

readPostgresAuthorizationClock

function readPostgresAuthorizationClock(transaction: SerializablePostgresTransaction): Promise<PostgresAuthorizationClock>;

Read immediately after isolation verification on the same transaction connection that will load authority. Verifies serializable isolation and hashes the raw PostgreSQL snapshot into a bounded opaque identifier. Throws ConsistencyUnavailableError when isolation or clock evidence is unavailable. It does not attest the provenance of facts loaded later.

readPostgresSealTime

function readPostgresSealTime(transaction: SerializablePostgresTransaction): Promise<string>;

Reads the advancing database clock_timestamp() on the supplied transaction and returns its ISO timestamp. This is descriptive evidence: driver Date values lose PostgreSQL microseconds, so a production expiry fence must compare in SQL against the advancing database clock. This helper alone does not seal a protected write.

PgPoolConnection

interface PgPoolConnection {
  query(sql: string, values?: unknown[]): Promise<{
    rows: Record<string, unknown>[];
    rowCount: number | null;
    command?: string;
  }>;
  release(error?: Error | boolean): void;
  on?(event: "error", listener: (error: Error) => void): unknown;
  removeListener?(event: "error", listener: (error: Error) => void): unknown;
}

The structural connection boundary accepted by the executor, compatible with a checked-out pg client. The executor uses parameterized queries and releases the connection when the transaction completes.

For event-emitting drivers, wrappers must forward both on and removeListener from the same checked-out client, preserving the receiver. They are optional only for connections that do not emit errors. A wrapper that hides both methods also hides transport/session errors from the executor; exposing only one method is rejected before a query is issued.

import type { PgPoolConnection } from "@rolebook/sharing-postgres";
function wrapEventEmittingClient(client: Required<PgPoolConnection>): PgPoolConnection {
  return {
    query: client.query.bind(client),
    release: client.release.bind(client),
    on: client.on.bind(client),
    removeListener: client.removeListener.bind(client),
  };
}

The executor observes checked-out client errors for both standalone queries (including receipt lookup and outbox operations) and transactions. A client error observed before query/transaction completion prevents a successful result and discards the connection. Its listener remains attached through release and is then removed; a driver error during COMMIT remains an uncertain outcome requiring receipt reconciliation. Applications still own pool-level idle-error handling and pool shutdown. No automatic replay of queries, callbacks or external delivery is introduced.

PgPoolSource

interface PgPoolSource {
    connect(): Promise<PgPoolConnection>;
}

A pool-like source of checked-out connections. The application retains ownership of pool creation and shutdown.

DetachedPostgresTransactionError

class DetachedPostgresTransactionError extends Error {
    readonly code: "GUARD_DETACHED";
    constructor();
}

Rejects use of a transaction handle outside its active callback lifetime with GUARD_DETACHED.

PostgresTransactionRolledBackError

class PostgresTransactionRolledBackError extends Error {
    readonly code: "TRANSACTION_ROLLED_BACK";
    constructor();
}

Reports a ROLLBACK completion tag where commit success was expected. The executor does not treat that outcome as a successful transaction.

PostgresCommitOutcomeUnknownError

class PostgresCommitOutcomeUnknownError extends Error {
    readonly code: "COMMIT_OUTCOME_UNKNOWN";
    constructor(cause: unknown);
}

Reports an unacknowledged commit outcome. The connection is discarded without another statement; do not interpret this as proof of rollback or blindly replay the callback. Use the protected adapter’s scoped lookupReceipt() with the exact original intent to reconcile a durable receipt before deciding whether to retry. Absence alone does not prove an in-flight commit cannot succeed.

createPgExecutor

function createPgExecutor(pool: PgPoolSource): ParameterizedSqlExecutor;

Adapts a pool to the parameterized SQL executor. Each transaction uses one checked-out client; nested and detached transaction use is rejected. Accepted queries are drained before rollback and release, and there is no automatic callback replay. This is an executor, not an authorization guard: application SQL is trusted and must not issue COMMIT, ROLLBACK or isolation changes itself.

Protected application updates

The public PostgreSQL wrapper supports one resource/action SQL update with complete local authority. It is not a field-mediated API or a transaction spanning HTTP calls. See the guide for the retained-authority postcondition, explicit migration ownership, receipt reconciliation and separate-worker delivery.

TransactionalTenantIdentityResolver

interface TransactionalTenantIdentityResolver {
    resolvePrincipalInTransaction(input: {
        readonly executor: ParameterizedSqlExecutor;
        readonly tenantId: string;
        readonly subject: ResourceRef;
    }): Promise<{
        readonly principal: TenantPrincipal;
        /** Attests complete eligibility, assignments, groups and policy-visible attributes, including absence. */
        readonly authority: "complete-local-projection";
        /** Exact PostgreSQL timestamp text for every identity/group/projection expiry; empty only when none exist. */
        readonly expiryDependencies: readonly string[];
        /** Counters actually read locally, including a subject projection covering absent assignments/groups. */
        readonly revisions: readonly AuthorityRevision[];
    }>;
}

Trusted transaction-local identity boundary. Reads through the supplied executor and attests the complete local eligibility, assignments, groups and policy-visible attributes, including absence. Every contributing source must participate in the fence protocol. Exact expiry dependencies are PostgreSQL timestamp strings; an empty array is valid only when none exist. Prefer createPostgresLocalIdentityProjection() for its complete-row contract; this interface does not attest remote-provider freshness.

ProtectedUpdateIntent

interface ProtectedUpdateIntent {
    readonly resource: ResourceRef;
    readonly action: string;
    readonly incarnationId: string;
    readonly idempotencyKey: string;
    /** Complete application intent; captured and hashed before SQL. */
    readonly payload: unknown;
    /** The callback must advance to this version without changing incarnation, ancestry, owner or sharing. */
    readonly postVersion: string;
}

Captured resource/action intent bound to the incarnation, idempotency key, complete application payload and resulting resource version. The callback must reach postVersion while retaining incarnation, ancestry, owner and sharing state. Hashing payload establishes replay identity; it does not map fields to columns or enforce field-level post-state policy.

ProtectedUpdateGuard

interface ProtectedUpdateGuard {
    /** Cooperative cancellation; SQL containment is also enforced independently. */
    readonly signal: AbortSignal;
    readonly executor: ParameterizedSqlExecutor;
    readonly resource: TrustedResource;
    readonly resourceVersion: string;
    readonly incarnationId: string;
    readonly metadata: AuthorizationDecisionMetadata | HierarchyAuthorizationDecisionMetadata;
    readonly payload: unknown;
}

The callback-scoped executor, trusted resource snapshot, pre-version, incarnation, captured payload and decision metadata. All queries must finish before the callback returns. The executor detaches before sealing and cannot be reused later. Observe signal for cooperative cancellation; arbitrary JavaScript CPU cannot be preempted.

ProtectedWriteDeniedError

class ProtectedWriteDeniedError extends Error {
    readonly code = "PROTECTED_WRITE_DENIED";
    constructor();
}

Resource/action authorization refused before the callback. Field-only permission cannot admit this raw SQL path. Reports PROTECTED_WRITE_DENIED.

ProtectedWriteTimeoutError

class ProtectedWriteTimeoutError extends Error {
    readonly code = "PROTECTED_WRITE_TIMEOUT";
    constructor(options?: {
        readonly cause?: unknown;
    });
}

A lock wait that PostgreSQL ends during the managed delete or move lock phase also reports this error, with the driver error as cause.

The protected scope exceeded its configured execution lifetime. Reports PROTECTED_WRITE_TIMEOUT; later guarded SQL rejects and database work is drained before rollback/release. Pool acquisition and driver setup precede this deadline, and COMMIT follows it; applications also need connection/request bounds.

ProtectedWritePostconditionError

class ProtectedWritePostconditionError extends Error {
    readonly code = "PROTECTED_WRITE_POSTCONDITION_FAILED";
    constructor();
}

The update violated its declared postcondition or retained authority. The application write and journal roll back. Reports PROTECTED_WRITE_POSTCONDITION_FAILED.

ProtectedWriteRefusedError

class ProtectedWriteRefusedError extends Error {
  readonly code = "PROTECTED_WRITE_REFUSED";
  readonly refusal: "hierarchy_not_leaf" | "hierarchy_cycle" | "ancestry_cap" | "hierarchy_edge_refused" | "hierarchy_exists";
  constructor(refusal: ProtectedWriteRefusedError["refusal"]);
}

An enrolled managed delete or move that every authorization check (the protected action on the target included) allowed, refused by the stored hierarchy: hierarchy_not_leaf (the resource has children), hierarchy_cycle (the destination is the resource or below it), ancestry_cap (the moved subtree would end below 16 ancestors), hierarchy_edge_refused (the policy does not allow that parent type) or hierarchy_exists (the destination is the current parent). Nothing was changed and no receipt was written.

CreatePostgresProtectedWriteAdapterOptions

interface CreatePostgresProtectedWriteAdapterOptions {
  readonly adapter: PostgresSharingAdapter;
  readonly sharing: VersionedResourceSharing<SharingResourceConfigurations>;
  readonly identity: TransactionalTenantIdentityResolver;
  readonly environmentId: string;
  readonly authorityEpoch: string;
  readonly journalPrefix: string;
  readonly maxLifetimeMs?: number;
  readonly managed?: PostgresManagedWriteDescriptor;
  readonly managedMove?: PostgresManagedMoveDescriptor;
  readonly hierarchy?: {
    readonly control: PostgresInheritanceControl;
    readonly parentIdColumn?: string;
  };
}

hierarchy enables managed delete and managed move on hierarchy-enrolled tenants. control is the deployment’s hierarchy control facade (createPostgresHierarchyControl), built from the same versioned Sharing instance passed as sharing (not another instance over the same adapters and store) and the same authority epoch and configuration generation as the adapters’ inherited reads; anything else throws at construction. This adapter’s maxLifetimeMs bounds the whole write; the control’s own lifetime does not apply. When managedMove is also configured, a move is captured under each route’s own mapping, so adding either option keeps every existing receipt key, and the flat descriptor applies only on a flat tenant. parentIdColumn, when the application keeps its own parent column, is rewritten by an enrolled move; it must be projected by managed and not be a patchable field. Without hierarchy, an enrolled delete or move refuses HIERARCHY_UNAVAILABLE / enrolled. See managed deletion and managed moves.

The original resource adapter and its versioned Sharing instance must share the checked createPgExecutor() and matching PostgreSQL policy fence. Configure complete local identity and authorization-fact fences. environmentId, namespace, actor and idempotency key scope durable outcomes; authorityEpoch scopes revision evidence. journalPrefix must match the separately applied migrations. maxLifetimeMs is an integer from 1 through 60,000, defaults to 5,000, and bounds execution, not pool acquisition, driver setup or COMMIT.

createPostgresProtectedWriteAdapter

function createPostgresProtectedWriteAdapter(options: CreatePostgresProtectedWriteAdapterOptions): Readonly<{
  receiptRoute(): object;
  forScope(value: TenantContext): Readonly<{
    withManagedMove(value: ManagedMoveIntent): Promise<{
      readonly status: "committed" | "replayed";
      readonly receipt: MutationReceipt;
    }>;
    lookupManagedMoveReceipt(value: ManagedMoveIntent): Promise<MutationReceipt | undefined>;
    withManagedDelete(value: ManagedDeleteIntent): Promise<{
      readonly status: "committed" | "replayed";
      readonly receipt: MutationReceipt;
    }>;
    lookupManagedDeleteReceipt(value: ManagedDeleteIntent): Promise<MutationReceipt | undefined>;
    withManagedUpdates(value: ManagedUpdateBatchIntent): Promise<Readonly<{
      status: "replayed";
      receipt: MutationReceipt;
    }> | Readonly<{
      status: "committed";
      receipt: Readonly<{
        receiptId: `${string}-${string}-${string}-${string}-${string}`;
        result: {
          updates: {
            resource: Readonly<{
              type: string;
              id: string;
            }>;
            version: string;
          }[];
        };
        metadata: HierarchyAuthorizationDecisionMetadata | import("@rolebook/sharing").HierarchyBatchAuthorizationDecisionMetadata;
        sealedAt: string;
      }>;
    }> | Readonly<{
      status: "committed";
      receipt: Readonly<{
        receiptId: `${string}-${string}-${string}-${string}-${string}`;
        result: {
          updates: {
            resource: ResourceRef;
            version: string;
          }[];
        };
        metadata: AuthorizationDecisionMetadata;
        sealedAt: string;
      }>;
    }>>;
    lookupManagedUpdatesReceipt(value: ManagedUpdateBatchIntent): Promise<MutationReceipt | undefined>;
    withManagedUpdate(value: ManagedUpdateIntent): Promise<{
      readonly status: "committed" | "replayed";
      readonly receipt: MutationReceipt;
    }>;
    lookupManagedReceipt(value: ManagedUpdateIntent): Promise<MutationReceipt | undefined>;
    lookupReceipt(value: ProtectedUpdateIntent): Promise<MutationReceipt | undefined>;
    withAuthorizedTransaction(value: ProtectedUpdateIntent, operation: (guard: ProtectedUpdateGuard) => Promise<unknown>): Promise<{
      readonly status: "committed" | "replayed";
      readonly receipt: MutationReceipt;
    }>;
  }>;
}>;

Creates the embedded PostgreSQL resource/action facade. forScope() captures namespace and actor. withAuthorizedTransaction() owns a SERIALIZABLE transaction, admits only a resource-wide allow, invokes the callback once without automatic replay, seals authority and commits the application result, receipt and outbox event together. Returns committed or an exact durable replayed receipt. lookupReceipt() is trusted server recovery for the exact original intent; absence does not prove an in-flight commit cannot succeed. HTTP SDK calls do not extend this SQL transaction. See Protected application updates for setup, supported postconditions and operational boundaries.

ManagedScalarCodec

type ManagedScalarCodec = "text" | "boolean" | "safe-integer";

PostgresManagedField

interface PostgresManagedField {
  readonly field: string;
  readonly column: string;
  readonly codec: ManagedScalarCodec;
  readonly nullable?: boolean;
}

PostgresManagedWriteDescriptor

interface PostgresManagedWriteDescriptor {
  readonly target: {
    readonly schema: string;
    readonly table: string;
    readonly userColumns: readonly string[];
  };
  readonly fields: readonly PostgresManagedField[];
}

ManagedUpdateIntent

interface ManagedUpdateIntent extends Omit<ProtectedUpdateIntent, "payload"> {
  readonly expectedVersion: string;
  readonly patch: Readonly<Record<string, string | boolean | number | null>>;
}

createPostgresLocalIdentityProjection

function createPostgresLocalIdentityProjection(options: {
    readonly table: QualifiedIdentifier;
    readonly groupSubjectTypes?: readonly string[];
}): {
    readonly identity: TransactionalTenantIdentityResolver & QueryIdentityResolver<ParameterizedSqlExecutor>;
    readonly lockEligibleSubjects: PostgresEligibilityFence;
    readonly readEligibleSubjects: PostgresEligibilityReader;
    readonly revalidateAuthorizationFacts: PostgresAuthorizationFactFence;
};

Builds a resolver plus eligibility and authorization-fact fences for a complete application-owned local identity row. The table contract is described in Complete local identity authority. Writers must advance the row revision for every relevant change, including absent-to-present assignments/groups. External identity freshness and facts in additional unfenced tables are outside the contract.

identity also has resolveQueryPrincipalInTransaction (see QueryIdentityResolver) for named authorized queries: the same complete local projection, with every expiry judged against the page’s captured database time.

For listing, identity is the resolver of PostgresPageIdentity. lockEligibleSubjects already carries its listing reader. readEligibleSubjects is that reader on its own, for an adapter whose lockEligibleSubjects wraps this projection’s fence: pass it, wrapped the same way, as the adapter’s readEligibleSubjects. It reads the rows unlocked, judges expiry at the page’s instant, and reports each eligible row’s expiry.

PostgresPageIdentity

interface PostgresPageIdentity {
  readonly source: TenantIdentityAdapter;
  readonly resolver: QueryIdentityResolver<ParameterizedSqlExecutor>;
}

Identity evidence for listing pages, passed as the adapter’s pageIdentity. source is the exact identity adapter object the sharing instance is created with. resolver reads that identity’s complete local projection through the page’s transaction; use createPostgresLocalIdentityProjection().identity.

Supplying both is your attestation that source answers from exactly that projection. Rolebook checks only that the sharing instance’s identity is this same object; it does not check what a remote provider behind it would answer. A sharing instance created with a different object, including a copy or a wrapper of source, does not match, and its listings need bracketed evidence from the identity adapter or answer identity_evidence_missing. An eligible principal must come from a projection row with a revision; a row the resolver cannot decode is identity_evidence_missing, and an absent row is an ordinary ineligible principal.

The projection row and the adapter’s eligibility authority are separate checks. A projection that says the actor is eligible does not override an eligibility fence that refuses the actor: the page is empty.

ProtectedWriteOutboxClaim

type ProtectedWriteOutboxClaim = OutboxClaim;

A committed event with stable eventId, kind and payload, plus a deliveryToken containing environmentId, eventId and claim generation. Preserve the exact token for acknowledgement. The underlying alias is an implementation type; applications use this exported claim type.

createPostgresProtectedWriteOutbox

function createPostgresProtectedWriteOutbox(options: {
  readonly executor: ParameterizedSqlExecutor;
  readonly tablePrefix: string;
  readonly environmentId: string;
  readonly operator?: ProtectedWriteOperator;
}): Readonly<{
  claim(input: {
    readonly limit: number;
    readonly leaseMs: number;
  }): Promise<readonly ProtectedWriteOutboxClaim[]>;
  inspectPending(input: {
    readonly limit: number;
  }): Promise<readonly Readonly<{
    eventId: string;
    kind: string;
    generation: string;
    state: "leased" | "ready";
  }>[]>;
  retry(token: ProtectedWriteOutboxClaim["deliveryToken"], input: {
    readonly delayMs: number;
  }): Promise<boolean>;
  claimForInspection(input: {
    readonly eventId: string;
    readonly leaseMs: number;
  }): Promise<{
    readonly environmentId: string;
    readonly eventId: string;
    readonly generation: string;
  } | undefined>;
  quarantine(token: ProtectedWriteOutboxClaim["deliveryToken"], input: {
    readonly reason: string;
  }): Promise<{
    readonly environmentId: string;
    readonly eventId: string;
    readonly generation: string;
  } | undefined>;
  inspectOperatorActions(input: {
    readonly eventId: string;
    readonly limit: number;
    readonly afterGeneration?: string;
  }): Promise<readonly ProtectedWriteOperatorAction[]>;
  inspectDeadLetters(input: {
    readonly limit: number;
  }): Promise<readonly ProtectedWriteDeadLetter[]>;
  requeue(token: ProtectedWriteOutboxClaim["deliveryToken"]): Promise<boolean>;
  acknowledge(token: ProtectedWriteOutboxClaim["deliveryToken"]): Promise<boolean>;
}>;

Trusted separate-worker API. Claim committed events with a bounded limit and lease, deliver outside the protected transaction, deduplicate by eventId at the sink and acknowledge only after delivery. Tokens are environment-bound; expired or superseded leases cannot acknowledge a later claim. Delivery is at least once. This does not register a worker, external sink, Sharing listAudit() integration or console audit route.

inspectPending({ limit }) returns 1–1000 oldest pending rows, including leased rows, with eventId, kind, generation and state. It omits payload decoding and is a bounded snapshot, not pagination or a delivery watermark. A future retry delay also appears as leased.

retry(deliveryToken, { delayMs }) accepts 0–300000ms and only a current unexpired lease. It advances the fencing generation immediately, so the old ACK fails even during the delay. Stale, expired, delivered or foreign-environment claims return false; invalid bounds throw. Normal claim recovers expired leases after worker crashes. The generation is fencing metadata, not an authentication secret or exact attempt count; restrict inspection to trusted operators. Deduplicate destination effects by (environmentId, eventId).

Receipts and outbox rows are retained indefinitely. Explicit quarantine/requeue is available after the additive migration described below. No pruning, scheduler, HTTP route or console integration is provided.

claimForInspection({ eventId, leaseMs }) acquires one exact event’s lease without decoding its payload. It cannot steal a live lease or claim a quarantined/delivered event; lease bounds are 1–300000ms. quarantine(currentToken, { reason }) requires that current unexpired lease and a nonblank reason of 1–1024 characters without NUL. It returns a new quarantine token or undefined for an ineligible/stale/foreign claim. Quarantine advances the generation and suppresses delivery; it does not mark the event delivered or change its payload.

inspectDeadLetters({ limit }) returns 1–1000 oldest active quarantines without decoding payloads. requeue(quarantineToken) requires the exact active quarantine generation, advances it again and makes the event available for normal claim. It returns false for stale/foreign/already-requeued state. Invalid input throws. Quarantine requires generation below 9223372036854775805 to leave headroom for requeue and a subsequent claim; no operation wraps or resets the counter.

These are trusted environment-wide operator methods, not authenticated tenant-user endpoints. They preserve at-least-once delivery and stable event IDs through recovery. Requeue leaves corrupt payloads corrupt; resolve the producer/decoder/destination problem before redelivery.

Migration required: stop/drain old workers, explicitly run the protected-write migrations to add <prefix>_dead_v1, then start only upgraded workers. Old binaries ignore quarantine and must not run concurrently. New worker paths fail closed if the table is absent. The original receipt and outbox schemas are unchanged. See operator recovery.

operator is optional application-attested attribution copied at factory construction, not a credential or authorization bypass. Omitted identity records null. Each successful quarantine or requeue appends history atomically; append failure rolls back the transition. Failed/stale/foreign operations append nothing. Apply the explicit <prefix>_actions_v1 migration before using upgraded operator workers, and stop/drain old binaries. Existing factory calls remain compatible after migration. History starts at upgraded-worker rollout: prior transitions are not fabricated, and mixed-version operator execution cannot claim complete history.

inspectOperatorActions({ eventId, limit, afterGeneration? }) reads immutable successful actions for one exact event in the bound environment. Limit is an integer 1–1000. The exclusive cursor is "0" (default) or a canonical positive signed-64-bit decimal generation. Use the last returned generation for the next page. Numeric generation order is independent of timestamps; gaps are normal because claims/retries also advance fencing generations. This is live per-event pagination, not a frozen or cross-event feed. Corrupt returned records fail closed. Retention is indefinite; append-only is an API guarantee under trusted DB ownership, not tamper evidence against database administrators. See operator history.

createProtectedWriteMigrations

function createProtectedWriteMigrations(options: {
    readonly tablePrefix: string;
}): readonly ResourceSharingMigration[];

Returns repeatable, schema-validating receipt/outbox migration steps for applyPostgresMigrations(). The application migration owner must run them explicitly; adapter construction does not. Existing incompatible schemas fail closed. Resource/projection/policy setup, retention and operator recovery remain application responsibilities.

MutationReceipt

interface MutationReceipt {
    readonly receiptId: string;
    readonly result: unknown;
    readonly metadata: AuthorizationDecisionMetadata | HierarchyAuthorizationDecisionMetadata | HierarchyBatchAuthorizationDecisionMetadata;
    /** Seal time recorded inside the transaction, not an exact COMMIT timestamp. */
    readonly sealedAt: string;
}

Durable committed callback result and captured decision metadata. metadata.schemaVersion is the stored metadata version, not a journal-table schema: 1 for a flat write, 2 for one enrolled target or a legacy multi-target batch, and 3 for an enrolled batch of 2–32 targets. A version-3 hierarchy block is evidence for its own target, not a capability. sealedAt is the time recorded at the common seal, not the exact COMMIT timestamp. A matching receipt can reconcile an uncertain commit; keep it for the full retry/reconciliation horizon.

IdempotencyConflictError

class IdempotencyConflictError extends Error {
    readonly code: "IDEMPOTENCY_CONFLICT";
    constructor();
}

The durable key was already used with a different complete intent. Reports IDEMPOTENCY_CONFLICT; do not reinterpret the existing outcome as the new request.

MutationJournalRowError

class MutationJournalRowError extends Error {
    readonly code: "MUTATION_JOURNAL_CORRUPT";
    constructor(cause: unknown);
}

Stored journal evidence is malformed or violates the decoding contract. Reports MUTATION_JOURNAL_CORRUPT. Recovery fails closed instead of trusting corrupted receipt or delivery data.

ManagedUpdateBatchIntent

interface ManagedUpdateBatchIntent {
  readonly idempotencyKey: string;
  readonly updates: readonly Omit<ManagedUpdateIntent, "idempotencyKey">[];
}

An atomic batch of 1–32 distinct existing resources through one configured adapter in one tenant. Each update has the single-update fields except its idempotency key; the outer key binds the whole batch. Use withManagedUpdates(intent) and lookupManagedUpdatesReceipt(intent). Input order is canonicalized by resource ID; reordered identical intent replays the same receipt. Create/delete/move and cross-adapter transactions are outside this contract.

createPostgresProtectedWriteReceipts

function createPostgresProtectedWriteReceipts(options: {
    readonly receiptRoute: object;
}): Readonly<{
    forScope(scope: ReceiptLookupScope): Readonly<{
        lookup(input: {
            readonly idempotencyKey: string;
        }): Promise<MutationReceipt | undefined>;
    }>;
}>;

Trusted server lookup of a committed outcome by key. receiptRoute is the opaque object from createPostgresProtectedWriteAdapter(...).receiptRoute(). It captures that adapter’s resource type, journal prefix and environment. A missing, cloned or foreign route throws before any journal read. Bind tenant and actor from authenticated server context and enforce application access policy before calling lookup. Every query includes environment, tenant, actor type, actor ID and key. It returns an immutable receipt or undefined; absence does not prove rollback. This does not validate a proposed retry payload: use the protected adapter’s exact-intent receipt lookup for that. Receipt access can expose sensitive historical business results.

ProtectedWriteDeadLetter

type ProtectedWriteDeadLetter = OutboxDeadLetter;

An immutable diagnostic record with eventId, kind, reason, ISO quarantinedAt, and quarantineToken (environment/event/generation). It contains no payload or receipt result. The underlying alias is an implementation type; applications use this exported type. Inspection returns only active quarantines and fails closed on inconsistent generation/identity evidence. The retained side row stores the latest quarantine/requeue state. The separate operator-action history retains successful transitions after the history upgrade.

ManagedDeleteIntent

interface ManagedDeleteIntent extends Omit<ProtectedUpdateIntent, "payload" | "postVersion"> {
  readonly expectedVersion: string;
}

One callback-free deletion of an exact existing resource incarnation and version, using the configured managed descriptor. withManagedDelete(intent) authorizes the resource/action and atomically removes the business row and live sharing state while retaining lifecycle evidence, a receipt and one outbox event. lookupManagedDeleteReceipt(intent) recovers the original outcome; it does not authorize a replacement incarnation. See Managed deletion.

ProtectedWriteOperator

type ProtectedWriteOperator = OutboxOperator;

An optional application-attested { type, id } identity copied and frozen at worker construction. Both fields are nonblank strings of at most 1024 characters without NUL. The library does not authenticate or authorize this identity. Omitted identity is recorded as null.

ProtectedWriteOperatorAction

type ProtectedWriteOperatorAction = OutboxOperatorAction;

An immutable retained successful-action record with environmentId, eventId, stable actionId, resulting decimal generation, action (quarantine or requeue), nullable operator, nullable reason, and ISO recordedAt. Requeue reasons are null. The timestamp describes the transition inside its transaction, not exact COMMIT time. The action ID is a digest identifier, not a signature. No receipt or event payload is included.

ManagedMoveIntent

interface ManagedMoveIntent extends Omit<ProtectedUpdateIntent, "payload"> {
  readonly expectedVersion: string;
  readonly sourceParent: ManagedParentExpectation;
  readonly destinationParent: ManagedParentExpectation;
}

ManagedParentExpectation

interface ManagedParentExpectation {
  readonly type?: string;
  readonly id: string;
  readonly incarnationId: string;
  readonly version: string;
}

ManagedParentField

interface ManagedParentField {
  readonly field: string;
  readonly column: string;
  readonly codec: "text" | "boolean" | "safe-integer";
  readonly nullable?: boolean;
}

PostgresManagedMoveDescriptor

interface PostgresManagedMoveDescriptor {
  readonly parentIdColumn: string;
  readonly parent: {
    readonly resourceType: string;
    readonly schema: string;
    readonly table: string;
    readonly tenantColumn: string;
    readonly idColumn: string;
    readonly versionColumn: string;
    readonly incarnationColumn: string;
    readonly expiresAtColumn?: string;
    readonly userColumns: readonly string[];
    readonly fields: readonly ManagedParentField[];
  };
  readonly sourceAction: string;
  readonly destinationAction: string;
}

createPostgresProtectedWriteDeliveryWorker

function createPostgresProtectedWriteDeliveryWorker(options: OutboxDeliveryOptions & {
  readonly executor: ParameterizedSqlExecutor;
  readonly tablePrefix: string;
  readonly environmentId: string;
  readonly operator?: ProtectedWriteOperator;
}): OutboxDeliveryWorkerWithDiagnostics;

Creates the shared bounded delivery worker over this adapter’s existing protected-write outbox. Apply explicit journal/operator-history migrations first. Operator identity is copied at construction as application-attested attribution; omitted identity remains null. No authentication, daemon, scheduler, actual sink service or payload/receipt mutation is added.

One pass claims batchSize1–32 events, starts at most that many concurrent sinks after releasing the claim connection, and serializes exact-token settlements. Lease bounds are1–300000ms and callback timeout is1–leaseMs. Only explicit delivered results permit ACK. Caller-selected retry/quarantine, unknown outcomes, stale leases and ambiguous ACKs follow the shared delivery contract. Cancellation prevents future queued settlements but cannot undo submitted DB work or external sink effects. A worker stays busy while abandoned sink work remains. No automatic retry occurs. The optional diagnostics option is forwarded to the shared worker unchanged and validated at construction; diagnostics() returns the worker-local, redacted snapshot described in worker diagnostics.

Named authorized queries

A small, fixed set of named queries over the adapter’s own resource table that return only the resource keys the actor is allowed. The contract, bounds and guarantees are in the named authorized queries guide.

createPostgresAuthorizedQueries

function createPostgresAuthorizedQueries(options: CreatePostgresAuthorizedQueriesOptions): AuthorizedQueries;

Checks every capability without database I/O and throws QueryConfigurationError before serving a request: the original adapter on an original createPgExecutor executor, with an enforced fencePolicy for the policy store of sharing, which must use that same executor; a resolver with resolveQueryPrincipalInTransaction; text tenant and resource SQL types (an adapter with resourceSqlType: "uuid" is refused); and a registry whose unqualified table, tenant and ID columns equal the adapter’s descriptor. One page is one SERIALIZABLE READ ONLY transaction on one pool connection, which also checks that those columns are non-null text or varchar.

CreatePostgresAuthorizedQueriesOptions

interface CreatePostgresAuthorizedQueriesOptions {
  readonly adapter: PostgresSharingAdapter;
  readonly sharing: VersionedResourceSharing<SharingResourceConfigurations>;
  readonly identity: QueryIdentityResolver<ParameterizedSqlExecutor>;
  readonly queries: readonly QueryDefinition[];
  readonly listingCursorKey: string | Uint8Array | readonly (string | Uint8Array)[];
  readonly environmentId: string;
}

queries holds 1 to 64 definitions. listingCursorKey is one key or 1 to 8 keys: the first seals and every key opens, and there is no random default. environmentId matches [A-Za-z][A-Za-z0-9_-]{0,63} and is bound into every cursor. identity is usually createPostgresLocalIdentityProjection().identity.

The shapes below are declared once in @rolebook/sharing and re-exported from this package and from @rolebook/sharing-sqlite. Import them from the driver package: @rolebook/sharing does not export them from its root.

AuthorizedQueries

interface AuthorizedQueries {
  forTenant(binding: QueryTenantBinding): TenantAuthorizedQueries;
  close(): Promise<void>;
}

The factory. forTenant(binding) captures the trusted binding synchronously and throws QueryConfigurationError when it is invalid. close() rejects new requests, ends the pages in flight and resolves once they have settled; when that takes longer than 1,000 ms it rejects with QueryCloseError, and a later call waits on the same cleanup again.

TenantAuthorizedQueries

interface TenantAuthorizedQueries {
  query(request: QueryRequest): Promise<QueryResult>;
}

query() never throws for an operational failure: every failure is a coded QueryResult.

QueryTenantBinding

interface QueryTenantBinding {
  readonly tenantId: string;
  readonly actor: ResourceRef;
  readonly context?: Readonly<Record<string, unknown>>;
  readonly sessionBinding: string;
}

Trusted server facts, never client input. context is plain JSON within Core’s context bounds (default {}) and may not contain tenantId or sharingRevision. sessionBinding is your session or authority incarnation, 1 to 128 UTF-16 units; it is bound into every cursor and never returned.

QueryRequest

interface QueryRequest {
  readonly name: string;
  readonly filters?: readonly QueryPredicate[];
  readonly limit?: number;
  readonly cursor?: string;
}

name selects a registered query. filters is a conjunction (default none), limit an integer from 1 to 100 (default 25, not bound to the cursor), and cursor the previous page’s nextCursor.

QueryPredicate

type QueryPredicate = {
  readonly field: string;
  readonly op: "eq" | "gt" | "gte" | "lt" | "lte";
  readonly value: QueryScalar;
} | {
  readonly field: string;
  readonly op: "in";
  readonly value: readonly QueryScalar[];
} | {
  readonly field: string;
  readonly op: "isNull";
  readonly value: boolean;
};
type QueryScalar = string | number | boolean;

field is a registered filter name and op one of its registered operators. in takes 1 to 32 distinct values of one type, ranges take integers or strings, and isNull is the only way to test for null. QueryScalar is not exported by name.

QueryResult

type QueryResult = {
  readonly ok: true;
  readonly page: {
    readonly items: readonly ResourceKey[];
    readonly nextCursor?: string;
    readonly exhausted: boolean;
    readonly completion: "complete" | "budget_limited";
    readonly evaluatedAt: number;
    readonly queryVersion: string;
    readonly schemaVersion: string;
    readonly consistency: "local-snapshot";
    readonly traversal: "live";
  };
} | {
  readonly ok: false;
  readonly code: QueryErrorCode;
};
type QueryErrorCode = "INVALID_REQUEST" | "INVALID_CURSOR" | "CURSOR_STALE_RESTART" | "QUERY_UNAVAILABLE";

items are resource keys only. exhausted: true comes with no nextCursor; otherwise nextCursor is present, even when items is empty. evaluatedAt is the page’s database time in epoch milliseconds. QueryErrorCode is not exported by name. The codes are described in the guide.

QueryDefinition

interface QueryDefinition {
  readonly name: string;
  readonly version: string;
  readonly resourceType: string;
  readonly action: string;
  readonly schemaVersion: string;
  readonly table: string;
  readonly tenantColumn: string;
  readonly idColumn: string;
  readonly filters: Readonly<Record<string, FilterColumn>>;
  readonly sort: QuerySort;
}

One trusted, server-registered query. table, tenantColumn and idColumn must equal the adapter’s resource descriptor. Names, versions and filter names match [A-Za-z][A-Za-z0-9_-]{0,63}; SQL identifiers are unqualified [A-Za-z_][A-Za-z0-9_]{0,62}.

FilterColumn

interface FilterColumn {
  readonly column: string;
  readonly type: ColumnType;
  readonly operators: readonly QueryFilterOperator[];
  readonly disclosable: true;
}
type QueryFilterOperator = "eq" | "in" | "gt" | "gte" | "lt" | "lte" | "isNull";

operators is non-empty and unique; range operators are invalid for boolean. disclosable: true attests that every subject who may run the query and receive this action’s resources may learn the column’s values by inference. QueryFilterOperator is not exported by name.

QuerySort

interface QuerySort {
  readonly column: string;
  readonly type: ColumnType;
  readonly direction: "asc" | "desc";
  readonly nulls: "first" | "last";
  readonly disclosable: true;
}

The one sort. Resource IDs always break ties, ascending in binary order, whatever direction is.

ColumnType

type ColumnType = "integer" | "string" | "boolean";

integer is a safe integer, string compares in binary UTF-8 order, and boolean sorts false before true. Every registered column may be nullable except the tenant and ID columns.

QueryIdentityResolver

interface QueryIdentityResolver<TExecutor = unknown> {
  resolveQueryPrincipalInTransaction(input: {
    readonly executor: TExecutor;
    readonly tenantId: string;
    readonly subject: ResourceRef;
    readonly evaluatedAt: string;
  }): Promise<QueryPrincipalResolution>;
}
interface QueryPrincipalResolution {
  readonly principal: TenantPrincipal;
  readonly authority: "complete-local-projection";
  readonly expiryDependencies: readonly string[];
  readonly revisions: readonly AuthorityRevision[];
}

Resolves the actor inside the page transaction. evaluatedAt is the page’s captured database time (ISO 8601 UTC, milliseconds), and the resolver must judge every expiry against it. The local identity projection’s identity implements it. QueryPrincipalResolution is not exported by name.

QueryConfigurationError

class QueryConfigurationError extends Error {
  readonly code: "QUERY_CONFIGURATION_INVALID";
  constructor();
}

Thrown by the factory and by forTenant() for an invalid or unsupported configuration or binding. Its message is fixed and it carries no cause. instanceof across separately bundled copies of @rolebook/sharing is not promised, so branch on code.

QueryCloseError

class QueryCloseError extends Error {
  readonly code: "QUERY_CLOSE_FAILED";
  constructor();
}

close() could not confirm within 1,000 ms that every owned page had been cleaned up. Its message is fixed and it carries no cause.

Governance attachment

Create a PostgreSQL governance attachment once for a sharing resource configuration. Give its adapterOptions to the PostgreSQL sharing adapter and its attachment to the sharing configuration. The governing-rule resolver receives both tenant and resource identifiers, preserving tenant isolation when resource IDs overlap.

createPostgresGovernanceAttachment

function createPostgresGovernanceAttachment(options: PostgresGovernanceAttachmentOptions): PostgresGovernanceAttachmentBundle;

PostgresGovernanceAdapterOptions

interface PostgresGovernanceAdapterOptions {
  readonly governanceGate: GovernanceDirectGate;
  readonly governanceBinding: GovernanceBinding;
  readonly lockEligibleSubjects: PostgresEligibilityFence;
  readonly fencePolicy?: PostgresPolicyFence;
}

PostgresGovernanceAttachmentBundle

interface PostgresGovernanceAttachmentBundle {
  readonly attachment: GovernanceAttachment;
  readonly adapterOptions: PostgresGovernanceAdapterOptions;
}

PostgresGovernanceAttachmentOptions

Bind the identity assignment table and group graph that this tenant uses. For a source the application does not use, declare evidenceSources.identity or evidenceSources.groups as "none". If a required source is missing, governed decisions return UNAVAILABLE. With groups: "none", governance cannot see anyone’s teams: wherever a group holds any role on the resource (or on a parent the resource inherits from, or anywhere in the tenant when the resource passes access down), approvals and rejections cannot be confirmed and answer UNKNOWN_REQUEST, so such a request cannot complete. Bind a group graph to govern resources that teams hold roles on. Without a group graph, a request whose target is a group also cannot complete, because nobody’s membership of that group can be seen: an approval or rejection from someone who would otherwise count answers UNAVAILABLE, and from anyone else UNKNOWN_REQUEST, as for a request that does not exist.

interface PostgresGovernanceAttachmentOptions {
  readonly executor: ParameterizedSqlExecutor;
  readonly schema: string;
  readonly tablePrefix: string;
  readonly requestTtlMs: number;
  readonly restoreEpoch: string | (() => string | "pending" | "unavailable" | Promise<string | "pending" | "unavailable">);
  readonly governingRule: (tenantId: string, resourceId: string, command: GovernanceFoundationCommandKind, scope: PostgresGovernanceRuleScope) => GovernanceRuleSnapshot | "clear" | "unavailable" | Promise<GovernanceRuleSnapshot | "clear" | "unavailable">;
  readonly binding: GovernanceBinding;
  readonly eligibility: PostgresEligibilityFence;
  readonly policyFence?: PostgresPolicyFence;
  readonly policyStore?: PolicyStore;
  readonly policy: RolebookPolicy;
  readonly sharing: PostgresGovernanceSharingConfig;
  readonly groupGraph?: PostgresGovernanceGroupSource;
  readonly identityAssignmentTable?: string;
  readonly evidenceSources?: {
    readonly identity?: "none";
    readonly groups?: "none";
  };
  readonly outbox?: {
    readonly tablePrefix: string;
    readonly environmentId: string;
  };
}

PostgresGovernanceSharingConfig

interface PostgresGovernanceSharingConfig {
  readonly resourceType: string;
  readonly memberRoles: Readonly<Record<string, string>>;
  readonly ownershipRole: string;
  readonly management: {
    readonly members: string;
    readonly ownership: string;
  };
  readonly parents?: readonly GovernanceFoundationRef[];
  readonly attributes?: Readonly<Record<string, unknown>>;
  readonly inheritingTypes?: readonly string[];
}

Access-change delivery

The delivery cursor and queue behind access-change webhooks.

AccessChangeDeliveryError

class AccessChangeDeliveryError extends Error {
  readonly code: AccessChangeDeliveryErrorCode;
  constructor(code: AccessChangeDeliveryErrorCode, message: string);
}

Thrown when delivery storage returns a row that does not decode, or when a subscription is bound to another tenant. Each resource type is drained in its own transaction: a drain that fails on one resource type keeps what earlier ones queued, and a failed page queues nothing and leaves its cursor where it was. On PostgreSQL it is also thrown when a cursor or audit row holds a transaction ID at or beyond the cluster’s next one, as after a logical restore.

createAccessChangeDeliveryMigrations

function createAccessChangeDeliveryMigrations(options: {
  readonly tablePrefix: string;
}): readonly ResourceSharingMigration[];

Idempotent steps that create the delivery subscription, cursor and queue tables, for applyPostgresMigrations. Never run automatically. The audit tables’ commit-order column and its index come from createResourceSharingMigrations (steps <owner>:audit-delivery-position and <owner>:audit-delivery-index).

createPostgresAccessChangeDeliveryStore

function createPostgresAccessChangeDeliveryStore(options: {
  readonly executor: ParameterizedSqlExecutor;
  readonly tablePrefix: string;
  readonly environmentId: string;
  readonly resources: readonly PostgresResourceDescriptor[];
}): PostgresAccessChangeDeliveryStore;

The PostgreSQL delivery store over the audit tables of resources (the descriptors passed to createResourceSharingMigrations). It drains rows in (delivery_xid, resource_id, event_id) order, and only those whose writing transaction is older than every running transaction, so a row that commits later never falls behind the cursor. It reads the audit table outside any transaction and queues in one short transaction. Bound to one environmentId.

PostgresAccessChangeDeliveryStore

interface PostgresAccessChangeDeliveryStore extends AccessChangeDeliveryStore {
  adoptCluster(): Promise<{
    readonly adopted: boolean;
  }>;
  rebaseline(input?: {
    readonly force?: boolean;
  }): Promise<RebaselineResult>;
}

The PostgreSQL store, with the operator actions for a cluster whose identity changed. The sharing migration records, per audit table, the cluster its positions belong to; on another cluster a drain throws with code foreign-cluster. After pg_upgrade or a physical copy call adoptCluster, which keeps every cursor; it refuses when a position is ahead of the counter or a subscription is halted, and success does not prove the counter was continuous. After a logical restore, before the application writes anything, call rebaseline. It queues the outstanding restored changes of the subscriptions that exist at that moment, in order, clears every position, and advances the epoch, so other cursors start again from changes committed afterwards. It records this cluster and reports what it did. Restored changes reach only the subscriptions that existed when it ran, and only for resources whose audit table the subscription already had a cursor for; a subscription that never drained a resource gets none of its restored changes. A change committed on the new cluster before it is not delivered, or is delivered out of order, and a subscription created afterwards starts from later changes. It refuses a missing origin row unless forced, because that is usually a missing grant, fixed by running the migration again. Both need the schema owner’s executor. See access-change webhooks.

RebaselineResult

interface RebaselineResult {
  readonly rebaselined: boolean;
  readonly subscriptions: number;
  readonly entries: number;
  readonly positionsCleared: number;
  readonly rowsSkipped: number;
}

What rebaseline did: the subscriptions of the environment that had at least one restored change queued, the entries it queued, the audit rows (of every tenant) whose position it cleared, and the restored access changes it set aside because they did not decode.

On this page

AdaptercreatePostgresSharingAdapterCreatePostgresSharingAdapterOptionsPostgresSharingAdapterPostgresResourceDescriptorPostgresResourceSqlTypeNormalizedPostgresResourceSqlTypesnormalizePostgresResourceSqlTypesNested team commandscreatePostgresGroupGraphControlPostgresGroupGraphControlOptionshierarchyControlTablesHierarchyControlProfileHierarchyControlTableNamescreateHierarchyControlMigrationscreatePolicyCatalogRegistrationMigrationsQualifiedPolicyStoreConfigPostgresBootstrapIntegritycreatePostgresGroupGraphFacadePostgresGroupGraphFacadeOptionsPostgresGroupGraphAuthorityPostgresGroupGraphOutcomeInherited accessenablePostgresInheritedReadsEnablePostgresInheritedReadsOptionscreatePostgresHierarchyControlCreatePostgresHierarchyControlOptionsPostgresInheritanceControlPostgresHierarchyControlResultrunPostgresHierarchyInventorycreatePostgresBootstrapIntegrityPostgresBootstrapRowDescriptorHierarchyControlResultHierarchyControlJobResultLifecycleInitializePostgresSharingResourceInputInitializePostgresSharingResourceResultDeletePostgresResourceInTransactionInputMovePostgresResourceInTransactionInputPostgresLifecycleApplicationResultPostgresLifecycleResultFencesPostgresEligibilityFencePostgresEligibilityReaderPostgresEligibilityEvidencecreatePostgresMembershipEligibilityFencePostgresMembershipEligibilityDescriptorPostgresInvitationRecipientFencecreatePostgresEmailInvitationRecipientFencePostgresEmailInvitationRecipientFenceDescriptorPostgresAuthorizationFactFencePostgresAuthorizationFactFenceResultcreatePostgresWorkspaceRoleAuthorizationFactFencePostgresWorkspaceRoleAuthorizationFactDescriptorMigrationscreateResourceSharingMigrationscreateResourceSharingRollbackMigrationsResourceSharingMigrationResourceSharingRollbackMigrationResourceSharingRollbackOptionsapplyPostgresMigrationsApplyPostgresMigrationsOptionsPostgresMigrationStepPostgresMigrationErrorsharingTablesSharingTableNamesquoteIdentifierQualifiedIdentifierassertPostgresSharingSearchPathPostgresSearchPathCheckOptionsPostgresSearchPathResolutionPostgresSearchPathErrorPolicy storecreatePostgresPolicyStoreCreatePostgresPolicyStoreOptionscreatePostgresPolicyFencePostgresPolicyFencecreatePolicyStoreMigrationscreatePolicyStoreRollbackMigrationspolicyStoreTablesPolicyStoreTableNamesExecutor and transactionsParameterizedSqlExecutorPostgresTransactionOptionsSerializablePostgresTransactionSqlResultSqlRowSqlValueasSerializablePostgresTransactionwithSerializableRetrywithSerializableTransactionSerializableRetryOptionsisRetryableSerializationErrorErrorsInvalidPostgresCursorErrorInvalidPostgresAuditCursorErrorPostgresSharingRowErrorPostgresLifecycleConflictErrorPolicyStoreRowErrorTransaction and clock foundationsPostgresAuthorizationClockreadPostgresAuthorizationClockreadPostgresSealTimePgPoolConnectionPgPoolSourceDetachedPostgresTransactionErrorPostgresTransactionRolledBackErrorPostgresCommitOutcomeUnknownErrorcreatePgExecutorProtected application updatesTransactionalTenantIdentityResolverProtectedUpdateIntentProtectedUpdateGuardProtectedWriteDeniedErrorProtectedWriteTimeoutErrorProtectedWritePostconditionErrorProtectedWriteRefusedErrorCreatePostgresProtectedWriteAdapterOptionscreatePostgresProtectedWriteAdapterManagedScalarCodecPostgresManagedFieldPostgresManagedWriteDescriptorManagedUpdateIntentcreatePostgresLocalIdentityProjectionPostgresPageIdentityProtectedWriteOutboxClaimcreatePostgresProtectedWriteOutboxcreateProtectedWriteMigrationsMutationReceiptIdempotencyConflictErrorMutationJournalRowErrorManagedUpdateBatchIntentcreatePostgresProtectedWriteReceiptsProtectedWriteDeadLetterManagedDeleteIntentProtectedWriteOperatorProtectedWriteOperatorActionManagedMoveIntentManagedParentExpectationManagedParentFieldPostgresManagedMoveDescriptorcreatePostgresProtectedWriteDeliveryWorkerNamed authorized queriescreatePostgresAuthorizedQueriesCreatePostgresAuthorizedQueriesOptionsAuthorizedQueriesTenantAuthorizedQueriesQueryTenantBindingQueryRequestQueryPredicateQueryResultQueryDefinitionFilterColumnQuerySortColumnTypeQueryIdentityResolverQueryConfigurationErrorQueryCloseErrorGovernance attachmentcreatePostgresGovernanceAttachmentPostgresGovernanceAdapterOptionsPostgresGovernanceAttachmentBundlePostgresGovernanceAttachmentOptionsPostgresGovernanceSharingConfigAccess-change deliveryAccessChangeDeliveryErrorcreateAccessChangeDeliveryMigrationscreatePostgresAccessChangeDeliveryStorePostgresAccessChangeDeliveryStoreRebaselineResult