RolebookDocs

@rolebook/sharing-sqlite API

Every export of @rolebook/sharing-sqlite and its /bun, /bun-query and /libsql entry points.

Four entry points: @rolebook/sharing-sqlite, @rolebook/sharing-sqlite/bun, @rolebook/sharing-sqlite/bun-query, and @rolebook/sharing-sqlite/libsql. Signatures are checked against the built declarations. Start with the SQLite adapter guide.

Adapter

createSqliteSharingAdapter

function createSqliteSharingAdapter(
  options: CreateSqliteSharingAdapterOptions,
): SqliteSharingAdapter;

Creates the adapter for one application table. Validates the descriptor and resourceColumns before any SQL runs.

CreateSqliteSharingAdapterOptions

interface CreateSqliteSharingAdapterOptions {
  readonly executor: ParameterizedSqliteExecutor;
  readonly resource: SqliteResourceDescriptor;
  readonly clock?: SharingClock;
  readonly lockEligibleSubjects: SqliteEligibilityFence;
  readonly readEligibleSubjects?: SqliteEligibilityReader;
  readonly lockInvitationRecipient?: SqliteInvitationRecipientFence;
  readonly revalidateAuthorizationFacts?: SqliteAuthorizationFactFence;
  readonly groupSubjectTypes?: readonly string[];
  readonly busyRetry?: ImmediateRetryOptions;
  readonly fencePolicy?: SqlitePolicyFence;
  readonly governanceGate?: GovernanceDirectGate;
  readonly governanceBinding?: GovernanceBinding;
  readonly pageIdentity?: SqlitePageIdentity;
  readonly groupGraph?: import("./group-graph-fence.js").SqliteGroupGraphOption;
}

executor, resource, the required lockEligibleSubjects; optional lockInvitationRecipient, revalidateAuthorizationFacts, groupSubjectTypes (default ["team"]), busyRetry, fencePolicy, and clock.

Two options matter only to listAccessible() and listAccess(), which read each page in one read-only transaction on a worker connection:

  • readEligibleSubjects is the evidence form of lockEligibleSubjects; see SqliteEligibilityReader. 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 SqlitePageIdentity. 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 worker-backed executor createBunSqliteQueryExecutor() returned, recognized by provenance and not by shape. An adapter built on any other executor, including the ones from @rolebook/sharing-sqlite/bun and /libsql, answers capability_missing for listings. This is the listing requirement only; other operations have their own executor requirements, described with each of them. 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 createSqlitePolicyStore() returned, created with this same executor object; a wrapped store or one on another executor answers policy_evidence_missing.

groupGraph binds one nested-team profile: teamType, an explicit identityStability, and a transactional directory. SQLite has no row-share syntax; the directory is read inside the caller’s BEGIN IMMEDIATE transaction. 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 createSqliteGroupGraphControl(). Strict listing pages still require the worker executor createBunSqliteQueryExecutor(); a graph command does not make another executor eligible for those pages.

SqliteSharingAdapter

interface SqliteSharingAdapter extends SharingAdapter, SettledRecordPruner {
  listAuditEvents(
    input: ListAuditEventsInput & {
      readonly incarnationId?: undefined;
    },
  ): Promise<AuditEventPage>;
  listAuditEvents(input: ListAuditEventsInput): Promise<AuditEventPage | undefined>;
  listPendingInvitations(
    input: ListPendingInvitationsInput & {
      readonly incarnationId?: undefined;
    },
  ): Promise<readonly SharingInvitation[]>;
  listPendingInvitations(
    input: ListPendingInvitationsInput,
  ): Promise<readonly SharingInvitation[] | undefined>;
  withLifecycleTransaction<T>(
    operation: (transaction: ImmediateSqliteTransaction) => Promise<T>,
  ): Promise<T>;
  resourceDeletedInTransaction(
    transaction: ImmediateSqliteTransaction,
    input: DeleteSqliteResourceInTransactionInput,
  ): Promise<SqliteLifecycleResult>;
  resourceMovedInTransaction(
    transaction: ImmediateSqliteTransaction,
    input: MoveSqliteResourceInTransactionInput,
  ): Promise<SqliteLifecycleResult>;
  initializeResource(
    input: InitializeSqliteSharingResourceInput,
  ): Promise<InitializeSqliteSharingResourceResult>;
  initializeResourceInTransaction(
    executor: ImmediateSqliteTransaction,
    input: InitializeSqliteSharingResourceInput,
  ): Promise<InitializeSqliteSharingResourceResult>;
}

A SharingAdapter and SettledRecordPruner with withLifecycleTransaction, the two ...InTransaction lifecycle methods, and initializeResource / initializeResourceInTransaction. Its list reads are typed to return a value when no incarnationId is passed.

SqliteResourceDescriptor

interface SqliteResourceDescriptor {
  readonly resourceType: string;
  readonly table: string;
  readonly tenantColumn: string;
  readonly idColumn: string;
  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 prefix?: string;
  };
  readonly governance?: {
    readonly tablePrefix: string;
  };
}

The application table (one unqualified name in main), its key and version columns, the snapshot callbacks, and the sharing table prefix. hierarchyControl.prefix names the hierarchy control profile (default rolebook_control) whose permanent tables in main this descriptor is immutably bound to; the resource migrations install them.

Nested team commands

SQLite graph commands run in one BEGIN IMMEDIATE transaction. There is no SQL row lock; the immediate transaction is the write exclusion. createSqliteGroupGraphControl() 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. The facade has no confirm method. Structural confirmation is the adapter’s later transaction when groupGraph.integrity is the integrity object this call returns. Listing pages stay on the worker executor and are unaffected by a graph command.

hierarchyControlTables() names the main control tables for a prefix. Resource migrations install that same profile when the descriptor sets hierarchyControl. createHierarchyControlMigrations() installs the profile on its own. applyPolicyCatalogRegistration() appends control prefixes to the policy catalog. SQLite has no SQL roles that separate control from the graph.

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.

createSqliteGroupGraphControl

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

The command set matches the PostgreSQL control. repairBatch’s limit is an integer of at least 1. A Core denial is status: "denied" with the decision left intact. A structural problem is status: "refused". An unavailable graph throws HierarchyUnavailableError.

import { HierarchyUnavailableError, type PolicyStore } from "@rolebook/sharing";
import {
  createSqliteGroupGraphControl,
  createSqliteLocalIdentityProjection,
  type ParameterizedSqliteExecutor,
} from "@rolebook/sharing-sqlite";
import type { RolebookPolicy } from "rolebook";

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

const graph = createSqliteGroupGraphControl({
  executor,
  controlPrefix: "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: { tablePrefix: "rolebook" },
    descriptor: {
      resourceType: "tenant_admin",
      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 team WHERE tenant_id = ? AND id = ?",
          [tenantId, group.id],
        );
        const row = result.rows[0];
        return row
          ? { present: true as const, incarnation: row.incarnation }
          : { present: false as const };
      },
    };
  },
});

try {
  const outcome = await graph.facade.repairBatch("ws_456", true, 25);
  if (outcome.status === "denied") outcome.decision.code;
  if (outcome.status === "refused") outcome.refusal;
  if (outcome.status === "applied") outcome.progress?.phase;
} catch (error) {
  if (error instanceof HierarchyUnavailableError) error.reason;
}
graph.tables.groupGraph;
graph.integrity.descriptorDigest;

executor is the command connection. It is not a substitute for createBunSqliteQueryExecutor(), which listing pages require. controlPrefix defaults to rolebook_control when omitted. The two binding ids are distinct opaque ids. Omit providers when the deployment declares no graph-independent fact paths.

SqliteGroupGraphControlOptions

interface SqliteGroupGraphControlOptions {
  readonly executor: ParameterizedSqliteExecutor;
  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 controlPrefix?: string;
  readonly policyStore: PolicyStore;
  readonly sharing: object;
  readonly identity: ReturnType<typeof createSqliteLocalIdentityProjection>;
  readonly bootstrap: {
    readonly policyStore: {
      readonly tablePrefix: string;
    };
    readonly descriptor: SqliteBootstrapRowDescriptor;
  };
  registry(tx: ParameterizedSqliteExecutor, tenantId: string): GroupRegistryReader;
}

actor is the control subject. A control actor whose groups include teamType, or a lineage fact, is identity_unavailable. identity is the object createSqliteLocalIdentityProjection() returns.

hierarchyControlTables

function hierarchyControlTables(tablePrefix?: string): HierarchyControlTableNames;

The returned table fields are unqualified names in main. profileId is the canonical JSON of ["main", prefix].

createHierarchyControlMigrations

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

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

applyPolicyCatalogRegistration

function applyPolicyCatalogRegistration(executor: ParameterizedSqliteExecutor, input: {
  readonly policyStore: SqliteQualifiedPolicyStoreConfig;
  readonly controlPrefixes: readonly string[];
  readonly retry?: ImmediateRetryOptions;
}): Promise<{
  readonly appended: number;
  readonly catalogGeneration: string;
}>;

SqliteQualifiedPolicyStoreConfig

interface SqliteQualifiedPolicyStoreConfig {
  readonly tablePrefix: string;
}

tablePrefix names the policy store whose catalog receives the control prefixes. appended is the number of prefixes this call added. catalogGeneration is the catalog generation after the write.

SqliteBootstrapIntegrity

interface SqliteBootstrapIntegrity {
  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.

createSqliteGroupGraphFacade

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

The command set matches the PostgreSQL facade. repairBatch’s limit is an integer of at least 1. A Core denial is status: "denied" with the decision left intact. A structural problem is status: "refused". An unavailable graph throws HierarchyUnavailableError. Build a new graph with createSqliteGroupGraphControl(). This function is the lower facade for a caller that already holds tables and an authority object. busyRetry bounds retries when the immediate transaction finds the database locked.

SqliteGroupGraphFacadeOptions

interface SqliteGroupGraphFacadeOptions {
  readonly executor: ParameterizedSqliteExecutor;
  readonly tables: HierarchyControlTableNames;
  readonly teamType: string;
  readonly identityStability: "registry_incarnation" | "ids_never_reused";
  readonly authority: SqliteGroupGraphAuthority;
  readonly busyRetry?: ImmediateRetryOptions;
}

executor is the command connection. It is not a substitute for createBunSqliteQueryExecutor(), which listing pages require.

SqliteGroupGraphAuthority

interface SqliteGroupGraphAuthority {
  readonly actor: ResourceRef;
  readonly commands: GroupGraphCommands;
  readonly integrity: SqliteBootstrapIntegrity;
  readonly policyStore: PolicyStore;
  readonly sharing: object;
  readonly identity: ReturnType<typeof createSqliteLocalIdentityProjection>;
  registry(tx: ParameterizedSqliteExecutor, tenantId: string): GroupRegistryReader;
}

actor is the control subject. commands is the compiled control object. integrity is the first-party bootstrap provider, and its profile id matches tables. policyStore is the store the versioned sharing instance reads, and sharing is that instance. identity is the object createSqliteLocalIdentityProjection() returns; the command reads it inside the immediate 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. createSqliteGroupGraphControl() compiles that provider and those commands from the policy, the six permissions, the binding ids, and the bootstrap descriptor.

SqliteGroupGraphOutcome

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

progress is set by a repair batch. denied is the Core decision.

Inherited access

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

enableSqliteInheritedReads

function enableSqliteInheritedReads(options: EnableSqliteInheritedReadsOptions): 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 SQLite 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.

EnableSqliteInheritedReadsOptions

interface EnableSqliteInheritedReadsOptions {
  readonly definition: SharingDefinition;
  readonly commands: HierarchyCommandsInput;
  readonly configurationGeneration: string;
  readonly authorityEpoch: string;
  readonly identity: ReturnType<typeof createSqliteLocalIdentityProjection>;
  readonly bootstrap: SqliteBootstrapIntegrity;
}

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.

createSqliteHierarchyControl

function createSqliteHierarchyControl(options: CreateSqliteHierarchyControlOptions): SqliteInheritanceControl;

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.

CreateSqliteHierarchyControlOptions

interface CreateSqliteHierarchyControlOptions {
  readonly sharing: VersionedResourceSharing<SharingResourceConfigurations>;
  readonly policy: RolebookPolicy;
  readonly commands: HierarchyCommandsInput;
  readonly bootstrap: SqliteBootstrapIntegrity;
  readonly authorityEpoch: string;
  readonly configurationGeneration: string;
  readonly immediateRetry?: ImmediateRetryOptions;
}

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

SqliteInheritanceControl

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

The facade createSqliteHierarchyControl 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.

SqliteHierarchyControlResult

type SqliteHierarchyControlResult = 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.

runSqliteHierarchyInventory

function runSqliteHierarchyInventory(control: SqliteInheritanceControl, 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.

createSqliteBootstrapIntegrity

function createSqliteBootstrapIntegrity(options: {
  readonly controlPrefix?: string;
  readonly policyStore: {
    readonly tablePrefix: string;
  };
  readonly descriptor: SqliteBootstrapRowDescriptor;
}): SqliteBootstrapIntegrity;

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.

SqliteBootstrapRowDescriptor

interface SqliteBootstrapRowDescriptor {
  readonly resourceType: 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

InitializeSqliteSharingResourceInput

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

InitializeSqliteSharingResourceResult

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

DeleteSqliteResourceInTransactionInput

interface DeleteSqliteResourceInTransactionInput extends SqliteLifecycleInput {
  readonly tenantId: string;
  readonly resourceId: string;
  readonly deleteResource: (
    transaction: ImmediateSqliteTransaction,
  ) => Promise<SqliteLifecycleApplicationResult>;
}

A deletion and your deleteResource callback; see lifecycle.

MoveSqliteResourceInTransactionInput

interface MoveSqliteResourceInTransactionInput extends SqliteLifecycleInput {
  readonly fromTenantId: string;
  readonly toTenantId: string;
  readonly resourceId: string;
  readonly resultingResourceVersion: string;
  readonly moveResource: (
    transaction: ImmediateSqliteTransaction,
  ) => Promise<SqliteLifecycleApplicationResult>;
}

A move and your moveResource callback.

SqliteLifecycleApplicationResult

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

What your lifecycle callback returns.

SqliteLifecycleResult

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

What a lifecycle method returns.

Fences

SqliteEligibilityFence

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

Verifies tenant eligibility under the write lock; may refuse ownerCandidates. Only true counts.

SqliteEligibilityReader

type SqliteEligibilityReader = (input: {
  readonly executor: ParameterizedSqliteExecutor;
  readonly tenantId: string;
  readonly subjects: readonly ResourceRef[];
  readonly evaluatedAt: string;
}) => Promise<SqliteEligibilityEvidence>;

The evidence form of a SqliteEligibilityFence, used by listing pages. It gives the same answer from the same authoritative rows, read through executor, which is the page’s read-only transaction; that connection refuses writes. Judge every time-dependent fact at evaluatedAt, the page’s instant, and never by the database’s later clock.

createSqliteMembershipEligibilityFence() and createSqliteLocalIdentityProjection().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.

SqliteEligibilityEvidence

interface SqliteEligibilityEvidence {
  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 exactly three fractional digits; SQLite pages compare whole milliseconds. 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.

createSqliteMembershipEligibilityFence

function createSqliteMembershipEligibilityFence(
  descriptor: SqliteMembershipEligibilityDescriptor,
): SqliteEligibilityFence;

A fence over an organization-member table, requiring exactly one row with the exact tenant and subject. It carries its own listing reader, which reads the same rows and declares no expiry, because row existence depends on no time.

SqliteMembershipEligibilityDescriptor

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

SqliteInvitationRecipientFence

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

createSqliteEmailInvitationRecipientFence

function createSqliteEmailInvitationRecipientFence(
  descriptor: SqliteEmailInvitationRecipientFenceDescriptor,
): SqliteInvitationRecipientFence;

Requires a verified email equal to the invitation’s (the verification flag stored as the integer 1).

SqliteEmailInvitationRecipientFenceDescriptor

interface SqliteEmailInvitationRecipientFenceDescriptor {
  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";
}

SqliteAuthorizationFactFence

type SqliteAuthorizationFactFence = (input: {
  readonly executor: ParameterizedSqliteExecutor;
  readonly tenantId: string;
  readonly facts: readonly TransactionalAuthorizationFact[];
}) => Promise<SqliteAuthorizationFactFenceResult>;

true proceeds, "conflict" re-authorizes, anything else is identity_ineligible.

SqliteAuthorizationFactFenceResult

type SqliteAuthorizationFactFenceResult = boolean | "conflict";

createSqliteWorkspaceRoleAuthorizationFactFence

function createSqliteWorkspaceRoleAuthorizationFactFence(
  descriptor: SqliteWorkspaceRoleAuthorizationFactDescriptor,
): SqliteAuthorizationFactFence;

Compares the exact tenant, subject, membership ID, and role behind mapped workspace assignments.

SqliteWorkspaceRoleAuthorizationFactDescriptor

interface SqliteWorkspaceRoleAuthorizationFactDescriptor
  extends SqliteMembershipEligibilityDescriptor {
  readonly factType: string;
  readonly memberIdColumn: string;
  readonly roleColumn: string;
}

Migrations

applyResourceSharingMigrations

function applyResourceSharingMigrations(
  executor: ParameterizedSqliteExecutor,
  descriptor: SqliteResourceDescriptor,
  retry?: ImmediateRetryOptions,
): Promise<void>;

Validates and migrates one descriptor’s schema in one retried BEGIN IMMEDIATE transaction. See migrations.

applyResourceSharingRollbackMigrations

function applyResourceSharingRollbackMigrations(
  executor: ParameterizedSqliteExecutor,
  descriptor: SqliteResourceDescriptor,
  options?: ResourceSharingRollbackOptions,
  retry?: ImmediateRetryOptions,
): Promise<void>;

Checks the descriptor registry and drops sharing-owned state in one transaction; keeps audit unless dropAudit.

createResourceSharingMigrations

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

The DDL a fresh database receives, for review. Do not run it yourself.

createResourceSharingRollbackMigrations

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

The rollback steps with their data loss, for review.

ResourceSharingMigration

interface ResourceSharingMigration {
  readonly name: string;
  readonly sql: string;
}

ResourceSharingRollbackMigration

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

ResourceSharingRollbackOptions

interface ResourceSharingRollbackOptions {
  readonly dropAudit?: boolean;
}

sharingTables

function sharingTables(descriptor: SqliteResourceDescriptor): SharingTableNames;

The sharing table names for a descriptor.

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.

QualifiedIdentifier

type QualifiedIdentifier = string | readonly string[];

Policy store

createSqlitePolicyStore

function createSqlitePolicyStore(options: CreateSqlitePolicyStoreOptions): PolicyStore;

A PolicyStore on SQLite, with busy retries.

CreateSqlitePolicyStoreOptions

interface CreateSqlitePolicyStoreOptions {
  readonly executor: ParameterizedSqliteExecutor;
  readonly tablePrefix?: string;
  readonly busyRetry?: ImmediateRetryOptions;
}

executor, tablePrefix (default rolebook), busyRetry.

createSqlitePolicyFence

function createSqlitePolicyFence(options?: {
  readonly tablePrefix?: string;
}): SqlitePolicyFence;

The policy fence for fencePolicy. Use the store’s tablePrefix.

SqlitePolicyFence

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

applyPolicyStoreMigrations

function applyPolicyStoreMigrations(
  executor: ParameterizedSqliteExecutor,
  options?: {
    readonly tablePrefix?: string;
    readonly retry?: ImmediateRetryOptions;
  },
): Promise<void>;

Creates or validates the policy-store tables in one BEGIN IMMEDIATE transaction.

createPolicyStoreMigrations

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

The policy-store DDL, for review.

createPolicyStoreRollbackMigrations

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

The policy-store rollback steps. The first step refuses while the hierarchy policy catalog holds any registered descriptor; run every step in one transaction, as applyPolicyStoreRollbackMigrations does.

applyPolicyStoreRollbackMigrations

function applyPolicyStoreRollbackMigrations(
  executor: ParameterizedSqliteExecutor,
  options?: { readonly tablePrefix?: string; readonly retry?: ImmediateRetryOptions },
): Promise<void>;

Runs the guard and every drop in one BEGIN IMMEDIATE 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

ParameterizedSqliteExecutor

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

The executor seam: one-statement queries with ? parameters, and immediate or deferred transactions.

SqliteTransactionOptions

interface SqliteTransactionOptions {
  readonly behavior: "immediate" | "deferred";
}

ImmediateSqliteTransaction

type ImmediateSqliteTransaction = ParameterizedSqliteExecutor & {
  readonly [immediateTransaction]: true;
};

An executor branded as a BEGIN IMMEDIATE 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 | bigint | null | Uint8Array;

asImmediateSqliteTransaction

function asImmediateSqliteTransaction(
  transaction: ParameterizedSqliteExecutor,
): ImmediateSqliteTransaction;

Compile-time assertion that a transaction your driver opened is BEGIN IMMEDIATE.

withImmediateRetry

function withImmediateRetry<T>(
  executor: ParameterizedSqliteExecutor,
  operation: (transaction: ImmediateSqliteTransaction) => Promise<T>,
  options?: ImmediateRetryOptions,
): Promise<T>;

Runs an idempotent unit of work in a busy-retried BEGIN IMMEDIATE transaction.

withImmediateTransaction

function withImmediateTransaction<T>(
  executor: ParameterizedSqliteExecutor,
  operation: (transaction: ImmediateSqliteTransaction) => Promise<T>,
  options?: ImmediateRetryOptions,
): Promise<T>;

Runs caller-owned application and sharing work in one busy-retried BEGIN IMMEDIATE transaction.

ImmediateRetryOptions

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

attempts (default 10, at most 100, including the first), backoffMs (0 to 1,000 ms), wait.

isRetryableBusyError

function isRetryableBusyError(error: unknown): boolean;

True for SQLITE_BUSY and its extended codes and SQLITE_LOCKED_SHAREDCACHE, across drivers and cause chains.

Errors

InvalidSqliteCursorError

class InvalidSqliteCursorError extends InvalidCursorError {
  constructor();
}

A listing cursor that is not a non-empty string of at most 128 characters. An InvalidCursorError.

InvalidSqliteAuditCursorError

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

A refused audit cursor. An InvalidCursorError.

SqliteSharingRowError

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

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

SqliteLifecycleConflictError

class SqliteLifecycleConflictError extends Error {
  readonly code: "SQLITE_LIFECYCLE_CONFLICT";
  constructor(message: string);
}

A lifecycle postcondition failed; the transaction is rollback-only.

SqliteJournalModeError

class SqliteJournalModeError extends Error {
  readonly code: "SQLITE_JOURNAL_MODE_UNSUPPORTED";
  constructor();
}

A file database is not in WAL mode (SQLITE_JOURNAL_MODE_UNSUPPORTED).

SqliteForeignKeysDisabledError

class SqliteForeignKeysDisabledError extends Error {
  readonly code: "SQLITE_FOREIGN_KEYS_DISABLED";
  constructor();
}

A write transaction found PRAGMA foreign_keys off.

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.

@rolebook/sharing-sqlite/bun

import { ... } from "@rolebook/sharing-sqlite/bun". Typed structurally, so it never imports bun:sqlite and type-checks without bun types.

createBunSqliteExecutor

function createBunSqliteExecutor(
  database: BunSqliteDatabaseLike,
  options?: BunSqliteExecutorOptions,
): ParameterizedSqliteExecutor;

An executor over one bun:sqlite Database (or any synchronous driver of the same shape). It queues every statement and transaction on the connection, fails fast instead of deadlocking when code inside a transaction calls the outer executor, prepares a fresh statement for every call, enables foreign keys, and throws unless busy_timeout is 0.

BunSqliteExecutorOptions

interface BunSqliteExecutorOptions {
  readonly enableForeignKeys?: boolean;
  readonly allowBusyTimeout?: boolean;
}

enableForeignKeys (default true) and allowBusyTimeout (default false).

BunSqliteDatabaseLike

interface BunSqliteDatabaseLike {
  prepare(sql: string): BunSqliteStatementLike;
  readonly inTransaction: boolean;
}

prepare(sql) must return a newly prepared statement on every call, never a cached one.

BunSqliteStatementLike

interface BunSqliteStatementLike {
  readonly columnNames: readonly string[];
  all(...values: SqlValue[]): unknown[];
  run(...values: SqlValue[]): {
    readonly changes: number | bigint;
  };
  finalize?(): void;
}

@rolebook/sharing-sqlite/bun-query

import { ... } from "@rolebook/sharing-sqlite/bun-query". Bun only. The executor that named authorized queries require.

createBunSqliteQueryExecutor

function createBunSqliteQueryExecutor(options: {
  readonly filename: string;
  readonly maxConnections?: number;
}): SqliteQueryExecutor;

Runs every connection in a library-owned Bun worker thread: one persistent worker per connection, each running a fixed module shipped in this package and receiving only SQL text and bound values. A synchronous bun:sqlite call cannot be stopped by a timer in the thread that runs it; here a query page’s deadline answers at once while the page’s worker is terminated, which takes effect when its SQLite call returns. filename is an absolute local path in canonical form (URIs, :memory:, relative paths and // or UNC network roots are refused), and maxConnections an integer from 1 to 32 (default 4). Invalid options throw QueryConfigurationError. Construction does no I/O; workers start when work needs them.

The file must already exist with PRAGMA encoding UTF-8 and PRAGMA journal_mode WAL: a worker never creates, converts or migrates it, and any other encoding or journal mode fails with QueryConfigurationError. Each worker turns PRAGMA foreign_keys on and sets PRAGMA synchronous = FULL. It keeps the whole ParameterizedSqliteExecutor contract: deferred and immediate transactions, sticky rollback after a caught SQL error, nested and finished transactions refused, and SqliteCommitOutcomeUnknownError for a COMMIT whose outcome is unknown. query() refuses transaction-control statements, and connection settings, ATTACH and temporary tables apply to one pooled connection only. One message is capped at 2 MiB of UTF-8 in each direction; an oversized request or result fails with code: "QUERY_UNAVAILABLE", and a writing statement outside a transaction whose result is refused this way has still run.

Pass the same object to createSqliteSharingAdapter(), createSqlitePolicyStore() and createSqliteAuthorizedQueries(). createSqliteProtectedWriteAdapter() accepts it too; see on the worker executor.

SqliteQueryExecutor

interface SqliteQueryExecutor extends ParameterizedSqliteExecutor {
  close(): Promise<void>;
  readonly [sqliteQueryExecutor]: true;
}

[sqliteQueryExecutor] is a compile-time brand; the query factory checks provenance against the executors this package created, not the shape. close() refuses new work, terminates the workers this executor owns and resolves once every exit is confirmed; when that takes longer than 1,000 ms it rejects with QueryCloseError, and a later call waits on the same cleanup again. A caller whose COMMIT, or statement outside a transaction, was in flight gets SqliteCommitOutcomeUnknownError: a killed worker may have committed, so reconcile before retrying. Terminating a worker stops it only when the SQLite call it is in returns, so a statement that never returns keeps its connection slot and close() keeps rejecting.

QueryCloseError is also exported here; its declaration is under named authorized queries.

@rolebook/sharing-sqlite/libsql

import { createLibsqlExecutor } from "@rolebook/sharing-sqlite/libsql". Needs the optional peer @libsql/client >=0.17.0 <1.

createLibsqlExecutor

function createLibsqlExecutor(client: Client): ParameterizedSqliteExecutor;

An executor over a local @libsql/client (file: URL or :memory:). Throws a TypeError for a remote client. Binds integral numbers as integers and runs each query behind a schema read so result columns are named from the current schema.

Protected application updates

See the protected and managed update guide for authority setup, transaction guarantees, recovery and supported schema boundaries.

createSqliteProtectedWriteAdapter

function createSqliteProtectedWriteAdapter(options: CreateSqliteProtectedWriteAdapterOptions): 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: ResourceRef;
            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>;
    withAuthorizedTransaction(value: ProtectedUpdateIntent, operation: (guard: ProtectedUpdateGuard) => Promise<unknown>): Promise<{
      readonly status: "committed" | "replayed";
      readonly receipt: MutationReceipt;
    }>;
    withManagedUpdate(value: ManagedUpdateIntent): Promise<{
      readonly status: "committed" | "replayed";
      readonly receipt: MutationReceipt;
    }>;
    lookupManagedReceipt(value: ManagedUpdateIntent): Promise<MutationReceipt | undefined>;
    lookupReceipt(value: ProtectedUpdateIntent): Promise<MutationReceipt | undefined>;
  }>;
}>;

ProtectedWriteDeniedError

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

ProtectedWritePostconditionError

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

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.

ProtectedWriteTimeoutError

class ProtectedWriteTimeoutError extends Error {
  readonly code = "PROTECTED_WRITE_TIMEOUT";
  constructor();
}

CreateSqliteProtectedWriteAdapterOptions

interface CreateSqliteProtectedWriteAdapterOptions {
  readonly adapter: SqliteSharingAdapter;
  readonly sharing: VersionedResourceSharing<SharingResourceConfigurations>;
  readonly identity: TransactionalTenantIdentityResolver;
  readonly environmentId: string;
  readonly authorityEpoch: string;
  readonly journalPrefix: string;
  readonly maxLifetimeMs?: number;
  readonly managed?: ManagedWriteDescriptor;
  readonly managedMove?: SqliteManagedMoveDescriptor;
  readonly hierarchy?: {
    readonly control: SqliteInheritanceControl;
    readonly parentIdColumn?: string;
  };
}

hierarchy enables managed delete and managed move on hierarchy-enrolled tenants. control is the deployment’s hierarchy control facade (createSqliteHierarchyControl), 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.

ProtectedUpdateGuard

interface ProtectedUpdateGuard {
  readonly signal: AbortSignal;
  readonly executor: ParameterizedSqliteExecutor;
  readonly resource: TrustedResource;
  readonly resourceVersion: string;
  readonly incarnationId: string;
  readonly metadata: AuthorizationDecisionMetadata | HierarchyAuthorizationDecisionMetadata;
  readonly payload: unknown;
}

ProtectedUpdateIntent

interface ProtectedUpdateIntent {
  readonly resource: ResourceRef;
  readonly action: string;
  readonly incarnationId: string;
  readonly idempotencyKey: string;
  readonly payload: unknown;
  readonly postVersion: string;
}

TransactionalTenantIdentityResolver

interface TransactionalTenantIdentityResolver {
  resolvePrincipalInTransaction(input: {
    readonly executor: ParameterizedSqliteExecutor;
    readonly tenantId: string;
    readonly subject: ResourceRef;
  }): Promise<{
    readonly principal: TenantPrincipal;
    readonly authority: "complete-local-projection";
    readonly expiryDependencies: readonly number[];
    readonly revisions: readonly AuthorityRevision[];
  }>;
}

createSqliteLocalIdentityProjection

function createSqliteLocalIdentityProjection(options: {
  readonly table: QualifiedIdentifier;
  readonly groupSubjectTypes?: readonly string[];
}): {
  readonly identity: TransactionalTenantIdentityResolver & QueryIdentityResolver<ParameterizedSqliteExecutor>;
  readonly lockEligibleSubjects: SqliteEligibilityFence;
  readonly readEligibleSubjects: SqliteEligibilityReader;
  readonly revalidateAuthorizationFacts: SqliteAuthorizationFactFence;
};

identity also has resolveQueryPrincipalInTransaction (see QueryIdentityResolver) for named authorized queries. It returns the same complete local projection as resolvePrincipalInTransaction, but judges every expiry against the page’s captured database time instead of sampling the clock again, and reports expiries as ISO 8601 millisecond instants.

For listing, identity is the resolver of SqlitePageIdentity. 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 judges expiry at the page’s instant and reports each eligible row’s expiry.

SqlitePageIdentity

interface SqlitePageIdentity {
  readonly source: TenantIdentityAdapter;
  readonly resolver: QueryIdentityResolver<ParameterizedSqliteExecutor>;
}

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 createSqliteLocalIdentityProjection().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. 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. 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.

createSqliteProtectedWriteOutbox

function createSqliteProtectedWriteOutbox(options: {
  readonly executor: ParameterizedSqliteExecutor;
  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>;
}>;

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.

ProtectedWriteOutboxClaim

type ProtectedWriteOutboxClaim = OutboxClaim;

IdempotencyConflictError

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

MutationJournalRowError

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

MutationReceipt

interface MutationReceipt {
  readonly receiptId: string;
  readonly result: unknown;
  readonly metadata: AuthorizationDecisionMetadata | HierarchyAuthorizationDecisionMetadata | HierarchyBatchAuthorizationDecisionMetadata;
  readonly sealedAt: string;
}

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.

createProtectedWriteMigrations

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

applyProtectedWriteMigrations

function applyProtectedWriteMigrations(executor: ParameterizedSqliteExecutor, options: {
  readonly tablePrefix: string;
}): Promise<void>;

ManagedWriteDescriptor

interface ManagedWriteDescriptor {
  readonly target: {
    readonly schema?: string;
    readonly table: string;
    readonly userColumns: readonly string[];
  };
  readonly fields: readonly ManagedWriteField[];
}

ManagedWriteField

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

ManagedUpdateIntent

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

SqliteCommitOutcomeUnknownError

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

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.

createSqliteProtectedWriteReceipts

function createSqliteProtectedWriteReceipts(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 createSqliteProtectedWriteAdapter(...).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, including while a COMMIT may still be in flight. 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;
}

SqliteManagedMoveDescriptor

interface SqliteManagedMoveDescriptor {
  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;
}

createSqliteProtectedWriteDeliveryWorker

function createSqliteProtectedWriteDeliveryWorker(options: OutboxDeliveryOptions & {
  readonly executor: ParameterizedSqliteExecutor;
  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. Bun only, because it requires the worker-backed executor. The contract, bounds and guarantees are in the named authorized queries guide.

createSqliteAuthorizedQueries

function createSqliteAuthorizedQueries(options: CreateSqliteAuthorizedQueriesOptions): AuthorizedQueries;

Checks every capability without database I/O and throws QueryConfigurationError before serving a request: the original adapter on an executor made by createBunSqliteQueryExecutor() (checked by provenance, not by shape), with an enforced fencePolicy for the policy store of sharing, which must use that same executor object; a resolver with resolveQueryPrincipalInTransaction; and a registry whose table, tenant and ID columns equal the adapter’s descriptor. createBunSqliteExecutor(), createLibsqlExecutor() and any other executor are refused here. One page is one read-only BEGIN DEFERRED transaction on one worker connection. close() drains this factory’s pages and never closes the executor.

CreateSqliteAuthorizedQueriesOptions

interface CreateSqliteAuthorizedQueriesOptions {
  readonly adapter: SqliteSharingAdapter;
  readonly sharing: VersionedResourceSharing<SharingResourceConfigurations>;
  readonly identity: QueryIdentityResolver<ParameterizedSqliteExecutor>;
  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 createSqliteLocalIdentityProjection().identity.

The shapes below are declared once in @rolebook/sharing and re-exported from this package and from @rolebook/sharing-postgres. 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 SQLite governance attachment once for a sharing resource configuration. Give its adapterOptions to the SQLite 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.

createSqliteGovernanceAttachment

function createSqliteGovernanceAttachment(options: SqliteGovernanceAttachmentOptions): SqliteGovernanceAttachmentBundle;

SqliteGovernanceAdapterOptions

interface SqliteGovernanceAdapterOptions {
  readonly governanceGate: GovernanceDirectGate;
  readonly governanceBinding: GovernanceBinding;
  readonly lockEligibleSubjects: SqliteEligibilityFence;
  readonly fencePolicy?: SqlitePolicyFence;
}

SqliteGovernanceAttachmentBundle

interface SqliteGovernanceAttachmentBundle {
  readonly attachment: GovernanceAttachment;
  readonly adapterOptions: SqliteGovernanceAdapterOptions;
}

SqliteGovernanceAttachmentOptions

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 SqliteGovernanceAttachmentOptions {
  readonly executor: ParameterizedSqliteExecutor;
  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: SqliteGovernanceRuleScope) => GovernanceRuleSnapshot | "clear" | "unavailable" | Promise<GovernanceRuleSnapshot | "clear" | "unavailable">;
  readonly binding: GovernanceBinding;
  readonly eligibility: SqliteEligibilityFence;
  readonly policyFence?: SqlitePolicyFence;
  readonly policyStore?: PolicyStore;
  readonly policy: RolebookPolicy;
  readonly sharing: SqliteGovernanceSharingConfig;
  readonly groupGraph?: SqliteGovernanceGroupSource;
  readonly identityAssignmentTable?: string;
  readonly evidenceSources?: {
    readonly identity?: "none";
    readonly groups?: "none";
  };
  readonly clock?: () => number;
  readonly outbox?: {
    readonly tablePrefix: string;
    readonly environmentId: string;
  };
}

SqliteGovernanceSharingConfig

interface SqliteGovernanceSharingConfig {
  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.

applyAccessChangeDeliveryMigrations

function applyAccessChangeDeliveryMigrations(executor: ParameterizedSqliteExecutor, options: {
  readonly tablePrefix: string;
  readonly resources: readonly SqliteResourceDescriptor[];
}): Promise<void>;

Creates the delivery tables and, on each audit table of resources, the trigger that positions every new row, in one BEGIN IMMEDIATE transaction, and refuses an existing object whose stored definition differs. Each audit table’s counter starts at its highest existing position. Never run automatically.

createAccessChangeDeliveryMigrations

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

The delivery table and trigger definitions, one object per step, for review. Apply them with applyAccessChangeDeliveryMigrations.

createSqliteAccessChangeDeliveryStore

function createSqliteAccessChangeDeliveryStore(options: {
  readonly executor: ParameterizedSqliteExecutor;
  readonly tablePrefix: string;
  readonly environmentId: string;
  readonly resources: readonly SqliteResourceDescriptor[];
}): AccessChangeDeliveryStore;

The SQLite delivery store over the audit tables of resources. Rows are drained in delivery_seq order, which the delivery trigger assigns from a counter that only grows, under the write lock the inserting transaction holds, and so is commit order. Every write retries SQLITE_BUSY. Bound to one environmentId.

On this page

AdaptercreateSqliteSharingAdapterCreateSqliteSharingAdapterOptionsSqliteSharingAdapterSqliteResourceDescriptorNested team commandscreateSqliteGroupGraphControlSqliteGroupGraphControlOptionshierarchyControlTablescreateHierarchyControlMigrationsapplyPolicyCatalogRegistrationSqliteQualifiedPolicyStoreConfigSqliteBootstrapIntegritycreateSqliteGroupGraphFacadeSqliteGroupGraphFacadeOptionsSqliteGroupGraphAuthoritySqliteGroupGraphOutcomeInherited accessenableSqliteInheritedReadsEnableSqliteInheritedReadsOptionscreateSqliteHierarchyControlCreateSqliteHierarchyControlOptionsSqliteInheritanceControlSqliteHierarchyControlResultrunSqliteHierarchyInventorycreateSqliteBootstrapIntegritySqliteBootstrapRowDescriptorHierarchyControlResultHierarchyControlJobResultLifecycleInitializeSqliteSharingResourceInputInitializeSqliteSharingResourceResultDeleteSqliteResourceInTransactionInputMoveSqliteResourceInTransactionInputSqliteLifecycleApplicationResultSqliteLifecycleResultFencesSqliteEligibilityFenceSqliteEligibilityReaderSqliteEligibilityEvidencecreateSqliteMembershipEligibilityFenceSqliteMembershipEligibilityDescriptorSqliteInvitationRecipientFencecreateSqliteEmailInvitationRecipientFenceSqliteEmailInvitationRecipientFenceDescriptorSqliteAuthorizationFactFenceSqliteAuthorizationFactFenceResultcreateSqliteWorkspaceRoleAuthorizationFactFenceSqliteWorkspaceRoleAuthorizationFactDescriptorMigrationsapplyResourceSharingMigrationsapplyResourceSharingRollbackMigrationscreateResourceSharingMigrationscreateResourceSharingRollbackMigrationsResourceSharingMigrationResourceSharingRollbackMigrationResourceSharingRollbackOptionssharingTablesSharingTableNamesquoteIdentifierQualifiedIdentifierPolicy storecreateSqlitePolicyStoreCreateSqlitePolicyStoreOptionscreateSqlitePolicyFenceSqlitePolicyFenceapplyPolicyStoreMigrationscreatePolicyStoreMigrationscreatePolicyStoreRollbackMigrationsapplyPolicyStoreRollbackMigrationspolicyStoreTablesPolicyStoreTableNamesExecutor and transactionsParameterizedSqliteExecutorSqliteTransactionOptionsImmediateSqliteTransactionSqlResultSqlRowSqlValueasImmediateSqliteTransactionwithImmediateRetrywithImmediateTransactionImmediateRetryOptionsisRetryableBusyErrorErrorsInvalidSqliteCursorErrorInvalidSqliteAuditCursorErrorSqliteSharingRowErrorSqliteLifecycleConflictErrorSqliteJournalModeErrorSqliteForeignKeysDisabledErrorPolicyStoreRowError@rolebook/sharing-sqlite/buncreateBunSqliteExecutorBunSqliteExecutorOptionsBunSqliteDatabaseLikeBunSqliteStatementLike@rolebook/sharing-sqlite/bun-querycreateBunSqliteQueryExecutorSqliteQueryExecutor@rolebook/sharing-sqlite/libsqlcreateLibsqlExecutorProtected application updatescreateSqliteProtectedWriteAdapterProtectedWriteDeniedErrorProtectedWritePostconditionErrorProtectedWriteRefusedErrorProtectedWriteTimeoutErrorCreateSqliteProtectedWriteAdapterOptionsProtectedUpdateGuardProtectedUpdateIntentTransactionalTenantIdentityResolvercreateSqliteLocalIdentityProjectionSqlitePageIdentitycreateSqliteProtectedWriteOutboxProtectedWriteOutboxClaimIdempotencyConflictErrorMutationJournalRowErrorMutationReceiptcreateProtectedWriteMigrationsapplyProtectedWriteMigrationsManagedWriteDescriptorManagedWriteFieldManagedUpdateIntentSqliteCommitOutcomeUnknownErrorManagedUpdateBatchIntentcreateSqliteProtectedWriteReceiptsProtectedWriteDeadLetterManagedDeleteIntentProtectedWriteOperatorProtectedWriteOperatorActionManagedMoveIntentManagedParentExpectationManagedParentFieldSqliteManagedMoveDescriptorcreateSqliteProtectedWriteDeliveryWorkerNamed authorized queriescreateSqliteAuthorizedQueriesCreateSqliteAuthorizedQueriesOptionsAuthorizedQueriesTenantAuthorizedQueriesQueryTenantBindingQueryRequestQueryPredicateQueryResultQueryDefinitionFilterColumnQuerySortColumnTypeQueryIdentityResolverQueryConfigurationErrorQueryCloseErrorGovernance attachmentcreateSqliteGovernanceAttachmentSqliteGovernanceAdapterOptionsSqliteGovernanceAttachmentBundleSqliteGovernanceAttachmentOptionsSqliteGovernanceSharingConfigAccess-change deliveryAccessChangeDeliveryErrorapplyAccessChangeDeliveryMigrationscreateAccessChangeDeliveryMigrationscreateSqliteAccessChangeDeliveryStore