RolebookDocs

@rolebook/sharing API

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

import { ... } from "@rolebook/sharing". Signatures are checked against the package’s built declarations. For concepts and usage, start at Resource sharing.

Creating sharing

defineSharing

function defineSharing<
  const TPolicy extends RolebookPolicy,
  const TResources extends SharingResourceConfigurations<
    PolicyRole<TPolicy>,
    PolicyPermission<TPolicy>
  >,
>(input: {
  readonly policy: TPolicy;
  readonly resources: TResources;
}): SharingDefinition<TPolicy, TResources>;

Validates the catalog that maps storage labels to policy values, canonicalizes the policy as definePolicy() does, and freezes the result. Throws an Error for an unknown or non-lowercase resource type, an ownership or member role that is missing or at another scope, the ownership role listed as a member role, an empty memberRoles or actions, or an action or management permission that is not a concrete, declared permission of the type. management.inspect defaults to management.members. See define and create.

createSharing

function createSharing<TResources extends SharingResourceConfigurations>(
  options: CreateSharingOptions<TResources>,
): ResourceSharingWithDiagnostics<TResources>;

Creates the sharing module over the definition’s exact policy, with one Rolebook authorizer. The definition is validated again. Options are captured once; throws for an invalid mutationRetries, mutationBackoffMs, mutationWait, maxInvitationTtlMs, or cursor key, and a TypeError for invalid diagnostics. The returned instance also has a synchronous, factory-local diagnostics() snapshot.

CreateSharingOptions

interface CreateSharingOptions<TResources extends SharingResourceConfigurations = SharingResourceConfigurations> {
  readonly definition: SharingDefinition<RolebookPolicy<string, string>, TResources>;
  readonly identity: TenantIdentityAdapter;
  readonly invitationTokens: InvitationTokenProtector;
  readonly clock?: SharingClock;
  readonly ids?: SharingIdGenerator;
  readonly mutationRetries?: number;
  readonly mutationBackoffMs?: (retry: number) => number;
  readonly mutationWait?: (milliseconds: number) => Promise<void>;
  readonly maxInvitationTtlMs?: number;
  readonly listingCursorKey?: string | Uint8Array | readonly (string | Uint8Array)[];
  readonly inspection?: {
    readonly audit: InspectionAuditSink;
    readonly limiter: InspectionLimiter;
  };
  readonly diagnostics?: SharingDiagnosticsOptions | undefined;
  readonly governance?: GovernanceAttachment;
}

See the options table. mutationRetries is an integer from 0 to 10 (default 3); maxInvitationTtlMs defaults to 30 days; listingCursorKey is one key or an ordered list of at most 8. inspection enables explain; omit it to leave inspection disabled. When it is present, construction throws a TypeError unless audit.append and limiter.acquire are functions. diagnostics enables operational diagnostics; omit it and every operation, promise and rejection is exactly as without it.

createVersionedSharing

function createVersionedSharing<TResources extends SharingResourceConfigurations>(
  options: CreateVersionedSharingOptions<TResources>,
): Promise<VersionedResourceSharingWithDiagnostics<TResources>>;

Async constructor of sharing that evaluates the policy store’s active policy and per-tenant custom roles. Refuses to start (PolicyStoreError) unless every adapter reports policyFence: "enforced". See policy versions.

CreateVersionedSharingOptions

interface CreateVersionedSharingOptions<
  TResources extends SharingResourceConfigurations = SharingResourceConfigurations,
> extends CreateSharingOptions<TResources> {
  readonly policyStore: PolicyStore;
  readonly refreshIntervalMs?: number;
  readonly maxStalenessMs?: number;
  readonly seed?: "activate-if-empty" | "require-active";
  readonly requiredPolicyRoles?: readonly string[];
  readonly tenantCacheSize?: number;
  readonly monotonicNow?: () => number;
  readonly onSeedDrift?: (input: {
    readonly seedDigest: string;
    readonly activeDigest: string;
    readonly generation: string;
  }) => void;
  readonly onInternalError?: PolicyErrorReporter;
}

CreateSharingOptions plus the policy store and freshness settings: refreshIntervalMs (100 to 60,000, default 5,000), maxStalenessMs (up to 300,000, default 30,000, clamped up to the refresh interval), seed (default "activate-if-empty"), requiredPolicyRoles, tenantCacheSize (1 to 65,536, default 1,024), monotonicNow, onSeedDrift, and onInternalError.

PolicyErrorReporter

type PolicyErrorReporter = (
  error: unknown,
  context: {
    readonly reason: PolicyUnavailableReason;
    readonly tenantId?: string;
  },
) => void;

Receives the original error behind a PolicyUnavailableError, once per failed load, with the reason it was reported under. tenantId is present when the failure was loading that tenant’s custom roles. A reporter that throws or rejects is ignored and cannot change the outcome.

VersionedResourceSharing

interface VersionedResourceSharing<TResources extends SharingResourceConfigurations>
  extends ResourceSharing<TResources> {
  readonly policies: PolicyAdministration;
  readonly customRoles: CustomRoleAdministration;
  current(): ActivePolicyState;
  refresh(): Promise<ActivePolicyState>;
}

ResourceSharing plus policies and customRoles administration, current() (the active policy state, synchronously) and refresh() (re-reads the pointer now).

VersionedResourceSharingWithDiagnostics

interface VersionedResourceSharingWithDiagnostics<TResources extends SharingResourceConfigurations>
  extends VersionedResourceSharing<TResources>, SharingDiagnosticsSource {}

What createVersionedSharing() returns. One diagnostics recorder serves the instance for its whole lifetime: a policy activation, a tenant reload or a refresh never resets it.

ResourceSharing

interface ResourceSharing<TResources extends SharingResourceConfigurations> {
  forTenant(context: TenantContext): TenantSharing<TResources>;
  readonly inspectionEnabled?: boolean;
}

The module: forTenant(context) returns a TenantSharing bound to one tenant and actor. inspectionEnabled is true exactly when the instance was created with a valid inspection configuration, and is fixed for the instance’s lifetime. createSharing() and createVersionedSharing() always set it. Absent, as on an older structural implementation of the interface, it means disabled.

ResourceSharingWithDiagnostics

interface ResourceSharingWithDiagnostics<TResources extends SharingResourceConfigurations>
  extends ResourceSharing<TResources>, SharingDiagnosticsSource {}

What createSharing() returns. ResourceSharing itself is unchanged, so a structural or third-party implementation does not need diagnostics().

TenantSharing

interface TenantSharing<TResources extends SharingResourceConfigurations> {
  authorize<TType extends ResourceType<TResources>>(input: {
    readonly resource: ResourceKey<TType>;
    readonly action: ActionFor<TResources, TType>;
  }): Promise<SharingDecision>;
  execute<TType extends ResourceType<TResources>>(command: SharingCommand<TResources, TType>): Promise<SharingMutationResult>;
  readonly conditionalExecution?: true;
  lookupExecution?<TType extends ResourceType<TResources>>(command: SharingCommand<TResources, TType>): Promise<SharingExecutionLookupResult>;
  readonly governance?: GovernedSharing;
  listAccessible<TType extends ResourceType<TResources>>(input: {
    readonly type: TType;
    readonly action: ActionFor<TResources, TType>;
    readonly limit: number;
    readonly cursor?: string;
  }): Promise<AccessiblePage<TType>>;
  describeAccess<TType extends ResourceType<TResources>>(input: {
    readonly resource: ResourceKey<TType>;
  }): Promise<AccessDescriptionResult<RoleFor<TResources, TType>, TType>>;
  permissions<TType extends ResourceType<TResources>>(input: {
    readonly resource: ResourceKey<TType>;
  }): Promise<ResourcePermissionsResult<ActionFor<TResources, TType>, TType>>;
  listAccess<TType extends ResourceType<TResources>>(input: {
    readonly type: TType;
    readonly limit: number;
    readonly cursor?: string;
  }): Promise<AccessPage<ActionFor<TResources, TType>, TType>>;
  auditHistory<TType extends ResourceType<TResources>>(input: {
    readonly resource: ResourceKey<TType>;
    readonly limit: number;
    readonly cursor?: string;
  }): Promise<AuditHistoryResult<TType>>;
  explain(input: {
    readonly resource: ResourceKey;
    readonly action: string;
    readonly subject?: ResourceRef;
    readonly field?: string;
  }): Promise<InspectionResult>;
}

The tenant-scoped operations: authorize, execute, listAccessible, describeAccess, permissions, listAccess, auditHistory, and explain. The context is captured when the facade is created. explain’s input is not narrowed by the catalog’s types; it is validated at run time, and an unknown type or action answers INVALID_REQUEST.

explain and listAccess are required members. A TenantSharing built by hand, such as a wrapper or a test double, must add both and decide what each does, normally forwarding to the same bound tenant: listAccess: (input) => tenant.listAccess(input).

conditionalExecution is true on every tenant createSharing() and createVersionedSharing() build: their execute honours a command’s expectedSharingRevision. @rolebook/server and the Better Auth plugin run an HTTP sharing.executeIfUnchanged request only on a tenant whose conditionalExecution reads as exactly true. For any other tenant (one built by hand, a wrapper that rebuilds the object without the flag, or one from an older @rolebook/sharing) they answer 404 UNKNOWN_OPERATION, as a server without the operation does, and never call execute, so a runtime that would ignore the precondition never applies a conditional command unconditionally. In-process execute() calls do not consult the flag. A wrapper that spreads a tenant keeps the flag, and must then pass commands to execute unchanged.

lookupExecution(command) reads what an earlier execute of the same command left in Sharing’s idempotency record, and executes nothing: it never calls the adapter’s applyMutation, and changes no membership, revision or audit event. Pass the command execute was given; its idempotency key, resource and every field the idempotency fingerprint covers bind the lookup, together with the tenant and actor of this facade. expectedSharingRevision does not. It runs the gates execute runs before a versioned instance replays a record: a configured resource type, a well-formed tenant and actor, and an actor the identity adapter resolves as a tenant member. The record is then read through the adapter’s lookupMutationIdempotency, a pure read: on the memory, SQLite and PostgreSQL adapters that read takes no lock a writer takes, runs on a read-only connection, and writes nothing, not even the bookkeeping a writer creates for a tenant or resource that has no rows yet. It does not take the replay’s writer route, so on a tenant whose hierarchy enrollment has started it reads nothing and answers refused with HIERARCHY_UNAVAILABLE.

Only that read is lock-free. The call as a whole may also resolve the actor through the identity adapter; on a versioned instance, load the tenant’s policy, which reads the policy store (on SQLite in a BEGIN IMMEDIATE transaction, on PostgreSQL with FOR SHARE on the policy pointer); and, when the key holds another command’s record, check the actor’s access through permissions, which runs the membership fence (on PostgreSQL a SELECT … FOR SHARE). On PostgreSQL every read runs in a SERIALIZABLE transaction, so none of it runs on a hot standby. Nothing here writes. An access check that fails, as one does in a read-only PostgreSQL transaction, answers as one that denies: not_found, so an actor without access gets the same answer for another command’s record as for an unused key in every case. As with a replay, an exact fingerprint match answers committed to the actor who committed the command even after that actor has lost access to the resource. Only committed proves anything; see SharingExecutionLookupResult. createSharing() and createVersionedSharing() tenants have it when every resource adapter implements lookupMutationIdempotency, as the first-party adapters do; it is optional on the interface, so a tenant built by hand, over another adapter, or from an older @rolebook/sharing may not, and a wrapper that spreads a tenant keeps it. Its calls are not counted in the diagnostics snapshot.

governance is the server-side façade on that tenant. Its six methods are request(command), approve(requestId), reject(requestId), cancel(requestId), apply(requestId), and resolve(requestId). Each returns precisely { status }, where status is PENDING, APPROVED, REJECTED, APPLIED, VOID, REFUSED, UNAVAILABLE, or UNKNOWN_REQUEST.

A transfer is authorized in one of two modes, and recipient acceptance is not required. A non-owner request requires a counted direct-owner sponsor. An owner request records payload-bound, non-counting owner consent and needs an independent eligible quorum. Direct execute() returns GOVERNANCE_REQUIRED whenever governance applies and does not bypass approval effects.

TenantContext

interface TenantContext {
  readonly tenantId: string;
  readonly actor: ResourceRef;
}

The explicit tenant ID and the authenticated actor. A malformed tenant or actor fails closed before any callback runs.

Operational diagnostics

Optional, factory-local and redacted. With diagnostics set, each call to a TenantSharing method is observed exactly once, at the public boundary, after any versioned conversion (a PolicyUnavailableError that execute returns as POLICY_UNAVAILABLE is a returned unavailable result, not a rejection). A rejection is only classified rejected: the caller still receives the identical exception object, a synchronous throw stays synchronous, and a floating failed call is still exactly one unhandled rejection. Mutation retries and candidate scans are separate intermediate events and never count as final results. Durations come from a separately captured performance.now, never the sharing clock or monotonicNow; a faulty reading is timing: "unavailable", never NaN, infinite or negative. Observations carry fixed enums and counts only: no tenant, actor, resource, role, action or query names, IDs, tokens, cursors, revisions, policy versions, decisions, traces, context, facts or exception text.

The observer gets one call at a time from a later timer turn, as a plain function. Observations wait in a FIFO of at most queueLimit; the oldest drops first and drops are counted. A call that exceeds observerTimeoutMs is reported as timed out but never cancelled: it keeps the single slot until it settles, and there is no abort signal. Synchronous CPU work in the observer cannot be preempted in the same process, so the observer must return or yield promptly. A throwing or rejecting observer is counted as failed and changes nothing else. Calls the observer makes into the same instance are recorded and queued, never delivered recursively. At most one observation is delivered per timer turn, so a burst larger than queueLimit drops the oldest even when the observer resolves at once. The snapshot counters are updated before an observation is queued, so they still count every processed event when observations drop.

The observer runs from a timer that this or another call scheduled, so ambient asynchronous context (AsyncLocalStorage, OpenTelemetry) may belong to an unrelated request; Rolebook does not detach it. Never add tenant, request, subject or trace identifiers from ambient context to an exported observation, and never treat that context as the event’s attribution.

The snapshot describes this instance in this process. It is not global or production health, not an authorization, admission, fencing or retry input, and it proves nothing about reachability, current permission, completeness or backlog. Counts saturate at Number.MAX_SAFE_INTEGER. See the runbook.

import { createSharing, type CreateSharingOptions } from "@rolebook/sharing";

declare const options: CreateSharingOptions;
declare const metrics: { increment(name: string, labels: Record<string, string>): void };

const sharing = createSharing({
  ...options,
  diagnostics: {
    observe(observation) {
      if (observation.type === "operation")
        metrics.increment("rolebook.sharing.operation", {
          operation: observation.operation,
          result: observation.result,
        });
    },
  },
});
const snapshot = sharing.diagnostics();
snapshot.operations.authorize.rejected;

SharingDiagnosticsOptions

interface SharingDiagnosticsOptions {
  readonly observe?: SharingObserver;
  readonly queueLimit?: number;
  readonly observerTimeoutMs?: number;
}

Exactly these keys, as own enumerable data properties of a plain object; an accessor is rejected without being invoked, and null, unknown keys and symbols are rejected. observe is optional: without it the instance only counts. queueLimit is an integer 1–1024 (default 64); observerTimeoutMs an integer 1–60,000 (default 1,000), reporting only. Every failure is TypeError("Invalid sharing diagnostics options").

SharingObserver

type SharingObserver = (observation: SharingObservation) => void | PromiseLike<void>;

Diagnostics only: nothing awaits it or uses its result.

SharingObservation

type SharingObservation =
  | SharingOperationObservation
  | SharingRetryObservation
  | SharingScanObservation;

sequence is a local ordinal per instance; a gap means dropped observations.

SharingOperationObservation

interface SharingOperationObservation {
  readonly type: "operation";
  readonly sequence: number;
  readonly operation: SharingOperationName;
  readonly settlement: "returned" | "rejected";
  readonly result: SharingResultClass;
  readonly code: SharingResultCode | "unknown" | null;
  readonly timing: "measured" | "unavailable";
  readonly durationMs: number | null;
}

One settled public call. code is a known public code, "unknown" for a returned value this build does not recognise, or null for a page or a rejection. Classification reads only own data properties (allowed, ok, code, resources, exhausted) and never invokes a getter. A duration is an observation, not a performance bound.

SharingOperationName

type SharingOperationName =
  | "authorize"
  | "execute"
  | "listAccessible"
  | "listAccess"
  | "describeAccess"
  | "permissions"
  | "auditHistory"
  | "explain";

SharingResultClass

type SharingResultClass =
  | "allowed"
  | "denied"
  | "succeeded"
  | "refused"
  | "unavailable"
  | "page"
  | "unknown"
  | "rejected";

allowed and denied exist only for authorize. refused is any other known ok: false code; unavailable is POLICY_UNAVAILABLE, RATE_LIMITED or INSPECTION_UNAVAILABLE. unknown is never read as an allow or a deny. rejected means the call threw or rejected; it mixes caller and input errors with operational faults, is not an authorization denial, and does not say which dependency failed. On a versioned instance an unusable policy is classified per method: execute returns POLICY_UNAVAILABLE (unavailable); authorize, describeAccess, permissions and auditHistory reject with PolicyUnavailableError (rejected); listAccessible and listAccess reject with it for a sticky or per-tenant failure and otherwise with AccessListingUnavailableError (rejected); explain returns INSPECTION_UNAVAILABLE (unavailable), a code that also covers limiter, audit, identity and deadline faults. A malformed context or request answers before any policy load.

SharingResultCode

type SharingResultCode =
  | SharingDecision["code"]
  | SharingMutationResult["code"]
  | AccessDescriptionResult["code"]
  | ResourcePermissionsResult["code"]
  | AuditHistoryResult["code"]
  | InspectionResult["code"];

SharingRetryObservation

interface SharingRetryObservation {
  readonly type: "retry";
  readonly sequence: number;
  readonly operation: "mutationRetry";
  readonly reason: "revision-conflict";
  readonly phase: "scheduled" | "backoff-failed" | "exhausted";
  readonly retry: number;
}

An intermediate event inside one execute, recorded where a revision conflict leads to another attempt. scheduled: retry number retry is next (its backoff pause first). backoff-failed: that pause threw or rejected, and execute rejects with the same exception. exhausted: every attempt conflicted (retry is the configured mutationRetries), and execute returns CONFLICT.

SharingScanObservation

interface SharingScanObservation {
  readonly type: "scan";
  readonly sequence: number;
  readonly operation: "candidateScan";
  readonly listing: SharingScanListing;
  readonly status: SharingScanStatus;
  readonly scanned: number;
  readonly matched: number;
  readonly pages: number;
}

One bounded candidate scan inside a listing page: candidates examined (exact), kept by the evaluator, and adapter candidate pages requested. A strict page that retries scans again, and each scan is its own event; an ineligible actor runs no scan.

SharingScanListing

type SharingScanListing = "listAccessible" | "listAccess";

SharingScanStatus

type SharingScanStatus = "exhausted" | "filled" | "scan-cap" | "partial" | "aborted";

exhausted: the adapter reported no further candidates and every offered one was examined; it is the only completeness claim, and only for that scan. filled: the limit was reached. scan-cap: the 2,000-candidate examination cap was reached. partial: the scan stopped without either. aborted: the scan threw, and nothing from it was returned. Its scanned includes the candidate whose evaluation failed, and pages includes an adapter call that failed or returned a refused page, because both are counted before that work runs; matched counts only candidates kept before the failure.

SharingScanTotals

interface SharingScanTotals {
  readonly scans: Readonly<Record<SharingScanStatus, number>>;
  readonly scanned: number;
  readonly matched: number;
  readonly pages: number;
}

SharingDiagnostics

interface SharingDiagnostics {
  readonly scope: "factory-local";
  readonly enabled: boolean;
  readonly operations: Readonly<
    Record<SharingOperationName, Readonly<Record<SharingResultClass, number>>>
  >;
  readonly mutationRetries: {
    readonly scheduled: number;
    readonly backoffFailed: number;
    readonly exhausted: number;
  };
  readonly candidateScans: Readonly<Record<SharingScanListing, SharingScanTotals>>;
  readonly timingUnavailable: number;
  readonly observation: {
    readonly status: "disabled" | "healthy" | "degraded" | "stalled";
    readonly queueLimit: number;
    readonly queued: number;
    readonly outstanding: 0 | 1;
    readonly completed: number;
    readonly failed: number;
    readonly timedOut: number;
    readonly dropped: number;
  };
}

Frozen, recomputed on every call. enabled is false without diagnostics, and every count is then 0. observation describes observer delivery (observer faults), never operation results: degraded after a drop or a failed or timed-out call until a later call completes, stalled while a timed-out call still holds the slot.

SharingDiagnosticsSource

interface SharingDiagnosticsSource {
  diagnostics(): SharingDiagnostics;
}

Synchronous and side-effect free; it never calls the observer.

Definitions and typing

SharingDefinition

interface SharingDefinition<
  TPolicy extends RolebookPolicy = RolebookPolicy,
  TResources extends SharingResourceConfigurations<
    PolicyRole<TPolicy>,
    PolicyPermission<TPolicy>
  > = SharingResourceConfigurations<PolicyRole<TPolicy>, PolicyPermission<TPolicy>>,
> {
  readonly policy: TPolicy;
  readonly resources: TResources;
}

The frozen result of defineSharing(): the canonical policy and the resource catalog.

SharingResourceConfiguration

interface SharingResourceConfiguration<
  TRole extends string = string,
  TPermission extends string = string,
  TAdapter extends SharingAdapter = SharingAdapter,
> {
  readonly memberRoles: Readonly<Record<string, TRole>>;
  readonly ownershipRole: TRole;
  readonly actions: Readonly<Record<string, TPermission>>;
  readonly management: {
    readonly members: TPermission;
    readonly invitations: TPermission;
    readonly ownership: TPermission;
    readonly inspect?: TPermission;
  };
  readonly adapter: TAdapter;
  readonly inheritance?: "ancestors";
}

One shareable resource type: member-role labels to policy roles, the ownership role, action labels to permissions, the management permissions, and its storage adapter. inheritance: "ancestors" opts the type in to inherited access: it is required for a recursive type or one below a recursive type, and only a first-party PostgreSQL or SQLite adapter accepts it.

SharingResourceConfigurations

type SharingResourceConfigurations<
  TRole extends string = string,
  TPermission extends string = string,
> = Readonly<Record<string, SharingResourceConfiguration<TRole, TPermission>>>;

The resource catalog: resource type to configuration.

PolicyRole

type PolicyRole<TPolicy extends RolebookPolicy> =
  TPolicy extends RolebookPolicy<infer TRole, string> ? TRole : never;

The role names of a policy type.

PolicyPermission

type PolicyPermission<TPolicy extends RolebookPolicy> =
  TPolicy extends RolebookPolicy<string, infer TPermission>
    ? ConcretePermission<TPermission>
    : never;

The concrete permissions of a policy type (wildcards removed).

ResourceType

type ResourceType<TResources extends SharingResourceConfigurations> = keyof TResources & string;

The configured resource type names of a catalog.

RoleFor

type RoleFor<
  TResources extends SharingResourceConfigurations,
  TType extends ResourceType<TResources>,
> = keyof TResources[TType]["memberRoles"] & string;

The member-role labels configured for one resource type.

ActionFor

type ActionFor<
  TResources extends SharingResourceConfigurations,
  TType extends ResourceType<TResources>,
> = keyof TResources[TType]["actions"] & string;

The action labels configured for one resource type.

ResourceKey

interface ResourceKey<TType extends string = string> {
  readonly type: TType;
  readonly id: string;
}

A { type, id } reference to a shareable resource.

Commands and decisions

SharingCommand

type SharingCommand<
  TResources extends SharingResourceConfigurations,
  TType extends ResourceType<TResources> = ResourceType<TResources>,
> = SharingCommandPrecondition &
  (
  | {
      readonly kind: "grantRole";
      readonly resource: ResourceKey<TType>;
      readonly subject: ResourceRef;
      readonly role: RoleFor<TResources, TType> | CustomRoleLabel;
      readonly expiresAt?: Date;
      readonly idempotencyKey: string;
    }
  | {
      readonly kind: "changeRole";
      readonly resource: ResourceKey<TType>;
      readonly subject: ResourceRef;
      readonly role: RoleFor<TResources, TType> | CustomRoleLabel;
      readonly expiresAt?: Date | null;
      readonly idempotencyKey: string;
    }
  | {
      readonly kind: "revokeMember";
      readonly resource: ResourceKey<TType>;
      readonly subject: ResourceRef;
      readonly idempotencyKey: string;
    }
  | {
      readonly kind: "transferOwnership";
      readonly resource: ResourceKey<TType>;
      readonly to: OwnerRef;
      readonly formerOwnerRole?: RoleFor<TResources, TType> | CustomRoleLabel;
      readonly idempotencyKey: string;
    }
  | {
      readonly kind: "issueInvitation";
      readonly resource: ResourceKey<TType>;
      readonly recipient: InvitationRecipient;
      readonly role: RoleFor<TResources, TType> | CustomRoleLabel;
      readonly expiresAt: Date;
      readonly membershipExpiresAt?: Date;
      readonly idempotencyKey: string;
    }
  | {
      readonly kind: "acceptInvitation";
      readonly resource: ResourceKey<TType>;
      readonly token: string;
      readonly idempotencyKey: string;
    }
  | {
      readonly kind: "revokeInvitation";
      readonly resource: ResourceKey<TType>;
      readonly invitationId: string;
      readonly idempotencyKey: string;
    }
  );

The seven commands execute() accepts. Role fields take a configured label or a custom role label. Any command may carry a SharingCommandPrecondition. See commands.

SharingCommandPrecondition

interface SharingCommandPrecondition {
  readonly expectedSharingRevision?: string;
}

With expectedSharingRevision, a command applies only while the resource’s sharing revision is still that value. The revision is checked against the state the command was authorized on, and the write commits under that same revision, so a change that lands at any moment before the commit answers SHARING_REVISION_CHANGED and nothing changes. Authorization is decided first, so a caller who may not make the change gets the same refusal as without a precondition. A retry whose idempotency key already committed still answers ALREADY_APPLIED, since its own write moved the revision; the precondition is not part of the command’s idempotency identity. A value that is not a 1 to 128 character string, a present undefined included, is refused as NOT_FOUND_OR_DENIED, never ignored: omit the key for an unconditional command. Over HTTP the precondition travels as its own operation; see Conditional commands.

SharingMutationResult

type SharingMutationResult = {
  readonly ok: true;
  readonly code: "APPLIED" | "ALREADY_APPLIED";
  readonly sharingRevision: string;
  readonly invitation?: {
    readonly id: string;
    readonly token: string;
  };
  readonly policyVersion?: string;
} | {
  readonly ok: false;
  readonly code: "NOT_FOUND_OR_DENIED" | "FORBIDDEN" | "NOT_TENANT_MEMBER" | "ROLE_NOT_ALLOWED" | "SELF_PROMOTION" | "OWNER_TRANSFER_REQUIRED" | "GROUP_CANNOT_OWN" | "MEMBER_ALREADY_EXISTS" | "INVITATION_EXPIRED" | "INVITATION_RECIPIENT_INVALID" | "INVITATION_UNAVAILABLE" | "INVITATION_RECIPIENT_MISMATCH" | "MEMBERSHIP_EXPIRY_INVALID" | "CONFLICT" | "SHARING_REVISION_CHANGED" | "POLICY_GENERATION_CHANGED" | "TENANT_ROLES_CHANGED" | "POLICY_UNAVAILABLE" | "HIERARCHY_UNAVAILABLE" | "DELEGATION_UNAVAILABLE" | "INHERITED_SCOPE_UNSUPPORTED" | "GOVERNANCE_REQUIRED";
};

execute()’s answer: APPLIED or ALREADY_APPLIED with the sharing revision (plus the invitation token on an applied issueInvitation, and policyVersion on a versioned instance), or a stable failure code; see result codes.

SharingExecutionLookupResult

type SharingExecutionLookupResult =
  | {
      readonly status: "committed";
      readonly result: {
        readonly ok: true;
        readonly code: "ALREADY_APPLIED";
        readonly sharingRevision: string;
        readonly policyVersion?: string;
      };
    }
  | { readonly status: "not_found" }
  | { readonly status: "different_command" }
  | {
      readonly status: "refused";
      readonly code: Extract<SharingMutationResult, { ok: false }>["code"];
    };

The answer of lookupExecution. Only committed is proof of an outcome.

  • committed: this command, by this actor in this tenant, committed under this key. result is exactly what execute answers when it replays the record: ALREADY_APPLIED, the revision the commit produced and, on a versioned instance, the policy version stored with it. It never carries an invitation token. The fingerprint binds the record to the actor, so no other actor gets this answer.
  • not_found: no record of this key is readable for this resource in this tenant now. It is never proof that the command did not run. The record may have been pruned by pruneSettledRecords (no sooner than MIN_IDEMPOTENCY_RETENTION_MS, one day, after the commit); it is removed with the resource by a delete, and at the source by a move of the resource to another tenant; and a command still running can commit after the lookup. It is also the answer for a record of another command when the actor has no access to the resource (permissions answers NOT_FOUND_OR_DENIED), so the lookup does not disclose that the resource exists.
  • different_command: the key is recorded for this resource under another fingerprint: another command, or this command by another actor. It is answered only to an actor permissions answers for the resource; when that check cannot run, the answer is not_found. It proves only that the key does not hold this command now: a record pruned and then reused by another command answers it too.
  • refused: no record was read. A command that does not capture answers the refusal execute gives it; an unknown resource type answers NOT_FOUND_OR_DENIED; an actor that is not a tenant member, or a malformed tenant or actor, NOT_TENANT_MEMBER; a versioned instance that cannot load the tenant’s policy, POLICY_UNAVAILABLE; a tenant whose hierarchy enrollment has started, HIERARCHY_UNAVAILABLE. A DelegationUnavailableError or InheritedScopeUnsupportedError thrown while it reads answers DELEGATION_UNAVAILABLE or INHERITED_SCOPE_UNSUPPORTED, and any other HierarchyUnavailableError is thrown on, as from execute.

SharingDecision

type SharingDecision =
  | {
      readonly allowed: true;
      readonly code: "ALLOWED";
      readonly decision: AuthorizationDecision;
    }
  | {
      readonly allowed: false;
      readonly code: "NOT_FOUND_OR_DENIED" | "FORBIDDEN";
      readonly decision?: AuthorizationDecision;
    };

authorize()’s answer: ALLOWED with the Rolebook decision, FORBIDDEN (usually with the decision), or NOT_FOUND_OR_DENIED (never with one).

InvitationRecipient

type InvitationRecipient = InvitationRecipientSubject | InvitationRecipientEmail;

Who an invitation is for: an exact subject, or a verified email address.

InvitationRecipientSubject

interface InvitationRecipientSubject {
  readonly type: "subject";
  readonly subject: ResourceRef;
}

An invitation bound to one immutable subject reference.

InvitationRecipientEmail

interface InvitationRecipientEmail {
  readonly type: "email";
  readonly email: string;
}

An invitation bound to an email address, at most MAX_INVITATION_EMAIL_LENGTH characters. Accepting it requires the identity adapter’s verified-email match and the storage adapter’s recipient fence.

Reads

AccessiblePage

interface AccessiblePage<TType extends string = string> {
  readonly resources: readonly AccessibleResource<TType>[];
  readonly nextCursor?: string;
  readonly exhausted: boolean;
  readonly policyVersion?: string;
}

One page of listAccessible(), read at one coherent point. nextCursor is sealed and present until exhausted; a page may be empty and not exhausted. policyVersion is present on a versioned instance: the policy version the page was decided under.

AccessibleResource

interface AccessibleResource<TType extends string = string> {
  readonly resource: ResourceKey<TType>;
  readonly snapshot: TrustedResource;
}

A listed resource key with the trusted snapshot Rolebook decided on.

AccessDescriptionResult

type AccessDescriptionResult<TRole extends string = string, TType extends string = string> =
  | {
      readonly ok: true;
      readonly code: "DESCRIBED";
      readonly access: AccessDescription<TRole, TType>;
    }
  | {
      readonly ok: false;
      readonly code: "NOT_FOUND_OR_DENIED";
    };

describeAccess()’s answer: DESCRIBED with the description, or NOT_FOUND_OR_DENIED.

AccessDescription

interface AccessDescription<TRole extends string = string, TType extends string = string> {
  readonly resource: ResourceKey<TType>;
  readonly sharingRevision: string;
  readonly owner: SharingOwnership;
  readonly members: readonly AccessMember<TRole>[];
  readonly invitations?: readonly PendingInvitation<TRole>[];
  readonly inherited?: readonly InheritedAccessMember[];
  readonly policyVersion?: string;
}

Who has access: the owner, live members, and (when the actor may manage invitations) pending invitations, with the sharing revision of the snapshot. inherited is present only when the resource was read from an enrolled, activated hierarchy: the live memberships stored on its ancestors that apply to it, nearest first.

InheritedAccessMember

interface InheritedAccessMember {
  readonly from: ResourceRef;
  readonly depth: number;
  readonly subject: ResourceRef;
  readonly role: string;
  readonly roleUnavailable?: true;
  readonly expiresAt?: Date;
}

One live membership stored on an ancestor: the ancestor it comes from, how many levels up it is (1 is the parent), the subject (individual or group) and the ancestor type’s role label, with roleUnavailable for a retired custom role (it grants nothing). Show it as “editor, inherited from folder X”.

AccessMember

interface AccessMember<TRole extends string = string> {
  readonly subject: ResourceRef;
  readonly role: TRole | CustomRoleLabel;
  readonly roleUnavailable?: true;
  readonly createdAt: Date;
  readonly createdBy: ResourceRef;
  readonly expiresAt?: Date;
}

One live membership: subject (individual or group), role label, roleUnavailable for an unavailable custom role, creation, and optional expiry.

PendingInvitation

interface PendingInvitation<TRole extends string = string> {
  readonly id: string;
  readonly recipient: InvitationRecipient;
  readonly role: TRole | CustomRoleLabel;
  readonly roleUnavailable?: true;
  readonly expiresAt: Date;
  readonly membershipExpiresAt?: Date;
  readonly createdAt: Date;
  readonly createdBy: ResourceRef;
}

One pending invitation, without its token digest.

ResourcePermissionsResult

type ResourcePermissionsResult<TAction extends string = string, TType extends string = string> =
  | {
      readonly ok: true;
      readonly code: "EVALUATED";
      readonly permissions: ResourcePermissions<TAction, TType>;
    }
  | {
      readonly ok: false;
      readonly code: "NOT_FOUND_OR_DENIED";
    };

permissions()’s answer: EVALUATED with every action decided, or NOT_FOUND_OR_DENIED.

ResourcePermissions

interface ResourcePermissions<TAction extends string = string, TType extends string = string> {
  readonly resource: ResourceKey<TType>;
  readonly sharingRevision: string;
  readonly allowed: Readonly<Record<TAction, boolean>>;
  readonly decisions: Readonly<Record<TAction, AuthorizationDecision>>;
  readonly policyVersion?: string;
}

Every configured action decided at one sharing revision: allowed (serializable booleans) and decisions (the Rolebook decisions).

AccessPage

interface AccessPage<TAction extends string = string, TType extends string = string> {
  readonly resources: readonly ResourcePermissions<TAction, TType>[];
  readonly nextCursor?: string;
  readonly exhausted: boolean;
}

One page of listAccess(): the resources with at least one allowed action, in listAccessible()’s order, each the ResourcePermissions that permissions() builds from the same evaluator inputs. A page is read at one coherent point and sealed before it is returned. nextCursor is sealed under its own label and present until exhausted; a page may be empty and not exhausted.

AuditHistoryResult

type AuditHistoryResult<TType extends string = string> =
  | {
      readonly ok: true;
      readonly code: "LISTED";
      readonly page: AuditHistoryPage<TType>;
    }
  | {
      readonly ok: false;
      readonly code: "NOT_FOUND_OR_DENIED";
    };

auditHistory()’s answer: LISTED with one page, or NOT_FOUND_OR_DENIED.

AuditHistoryPage

interface AuditHistoryPage<TType extends string = string> {
  readonly resource: ResourceKey<TType>;
  readonly events: readonly AuditHistoryEvent[];
  readonly nextCursor?: string;
  readonly exhausted: boolean;
}

One page of audit events, newest first, with a sealed nextCursor until exhausted.

AuditHistoryEvent

type AuditHistoryEvent = Omit<SharingAuditEvent, "idempotencyKey">;

A SharingAuditEvent without the caller-chosen idempotencyKey.

Inspection

The types of current-state inspection, TenantSharing.explain().

InspectionResult

type InspectionResult =
  | {
      readonly ok: true;
      readonly code: "EXPLAINED";
      readonly explanation: InspectionEnvelope;
    }
  | {
      readonly ok: false;
      readonly code: InspectionError;
    };

explain()’s answer, deeply frozen: EXPLAINED with a redacted explanation, or a fixed failure code with no message, cause, or partial trace. It is never a permission: do not authorize with it or cache it as a decision.

InspectionError

type InspectionError =
  | "INVALID_REQUEST"
  | "INSPECTION_DISABLED"
  | "NOT_FOUND_OR_DENIED"
  | "TARGET_UNAVAILABLE"
  | "RATE_LIMITED"
  | "INSPECTION_UNAVAILABLE";

Why explain() produced no explanation. INVALID_REQUEST: the input is not the exact bounded shape. INSPECTION_DISABLED: no inspection configuration. NOT_FOUND_OR_DENIED: the resource is missing or in another tenant, or the inspector is ineligible or not allowed the inspection permission. TARGET_UNAVAILABLE: the inspector was authorized but the target is absent or ineligible. RATE_LIMITED: the host limiter refused, or the instance already runs 32 inspections. INSPECTION_UNAVAILABLE: any operational fault, the deadline, or a failed audit append. See errors.

InspectionEnvelope

interface InspectionEnvelope {
  readonly schema: "rolebook-inspection";
  readonly version: 1;
  readonly inspectionId: string;
  readonly mode: "current-state";
  readonly evaluatedAt: number;
  readonly resource: ResourceKey;
  readonly target: ResourceRef;
  readonly action: string;
  readonly field?: string;
  readonly sharingRevision: string;
  readonly policyVersion?: string;
  readonly policyDigest: string;
  readonly redactionVersion: 1;
  readonly capture: {
    readonly consistency: "captured-inputs";
  };
  readonly decision: InspectionDecision;
}

One redacted current-state explanation. inspectionId is 128 random bits as 32 lowercase hex characters; evaluatedAt is the single sharing-clock reading in Unix milliseconds; target is the requested subject or the bound actor; policyVersion is present on a versioned instance; policyDigest is the SHA-256 of the effective policy’s canonical JSON as 64 lowercase hex characters. captured-inputs is not a transaction-wide snapshot or a freshness token. See the explanation.

InspectionDecision

interface InspectionDecision {
  readonly allowed: boolean;
  readonly code: DecisionCode;
  readonly permission: string;
  readonly matched?: {
    readonly effect: "allow" | "deny";
    readonly role: string;
    readonly permission: string;
    readonly via?: ResourceRef;
  };
  readonly trace: readonly {
    readonly outcome: "matched" | "not_matched";
    readonly effect: "allow" | "deny";
    readonly role: string;
    readonly permission: string;
    readonly via?: ResourceRef;
    readonly details: DecisionTraceDetails;
  }[];
  readonly traceTruncated: boolean;
  readonly conditionTraceTruncated: boolean;
}

The target decision, projected from the one Core explain(request, { detail: "conditions" }) call that decided it. Core’s free-text reason fields are omitted; details is Core’s DecisionTraceDetails unchanged. code is ALLOWED, EXPLICIT_DENY, or NOT_GRANTED. Rule IDs are local to policyDigest, not durable grant IDs.

InspectionLimiter

interface InspectionLimiter {
  acquire(input: {
    readonly tenantId: string;
    readonly actor: ResourceRef;
    readonly inspectionId: string;
    readonly signal: AbortSignal;
  }): Promise<
    | {
        readonly allowed: false;
      }
    | {
        readonly allowed: true;
        readonly release: () => void | Promise<void>;
      }
  >;
}

The host rate limiter, called before any resource, identity, or target load. Answer exactly { allowed: false } or { allowed: true, release }; any other shape is INSPECTION_UNAVAILABLE. release is called exactly once when the call’s work settles. signal aborts at the deadline. See the limiter contract.

InspectionAuditSink

interface InspectionAuditSink {
  append(
    event: InspectionAuditEvent,
    options: {
      readonly signal: AbortSignal;
    },
  ): Promise<void>;
}

The host audit sink. append must record the event durably, idempotently by inspectionId, before it resolves: no inspection detail is returned until it does. See the audit contract.

InspectionAuditEvent

interface InspectionAuditEvent {
  readonly schema: "rolebook-inspection-audit";
  readonly version: 1;
  readonly inspectionId: string;
  readonly tenantId: string;
  readonly actor: ResourceRef;
  readonly resource: ResourceKey;
  readonly target: ResourceRef;
  readonly action: string;
  readonly field?: string;
  readonly evaluatedAt: number;
  readonly outcome: "explained" | "target_unavailable" | "unavailable";
  readonly allowed?: boolean;
  readonly decisionCode?: DecisionCode;
  readonly policyDigest?: string;
  readonly redactionVersion: 1;
}

The minimal record of one authorized inspection attempt. allowed and decisionCode appear only when outcome is explained. It never carries a trace, a fact, or a literal.

Errors

AccessibleListingError

class AccessibleListingError extends RangeError {
  readonly code: AccessibleListingErrorCode;
  constructor(code: AccessibleListingErrorCode, message: string);
}

Thrown by listAccessible() and listAccess() for a request they cannot answer completely. A RangeError with a stable code; listAccess() has no action, so never UNKNOWN_ACTION.

AccessibleListingErrorCode

type AccessibleListingErrorCode =
  | "INVALID_LIMIT"
  | "UNKNOWN_RESOURCE_TYPE"
  | "UNKNOWN_ACTION"
  | "TOO_MANY_ASSIGNMENTS";

InvalidCursorError

class InvalidCursorError extends RangeError {
  readonly code: "INVALID_CURSOR";
  constructor(message?: string);
}

Thrown for a listing or audit cursor that does not open, and by adapters for a malformed raw cursor. A RangeError with code: "INVALID_CURSOR"; adapters may subclass it.

AccessListingUnavailableError

class AccessListingUnavailableError extends Error {
  readonly code: "ACCESS_LISTING_UNAVAILABLE";
  readonly reason: AccessListingUnavailableReason;
  constructor(reason?: AccessListingUnavailableReason);
}

Thrown by listAccessible() and listAccess() when no consistent page could be read in at most three attempts. No page, partial page, or weaker page is returned. reason is non-sensitive and can be branched on like code; the message names only the reason. The constructor’s default reason is changed. See when no consistent page can be read.

AccessListingUnavailableReason

type AccessListingUnavailableReason =
  | "capability_missing"
  | "identity_evidence_missing"
  | "policy_evidence_missing"
  | "unrepresentable_identity"
  | "expiry_crossed"
  | "session_expired"
  | "snapshot_unavailable"
  | "changed";

Why a listing was unavailable. It names a cause only, never a tenant, subject, resource ID, attribute, revision, or expiry value. capability_missing, identity_evidence_missing, and policy_evidence_missing end the call at once; the others are retried within the call’s three attempts.

InvalidCandidatePageError

class InvalidCandidatePageError extends TypeError {
  readonly code: "INVALID_CANDIDATE_PAGE";
  constructor(message: string);
}

Thrown when an adapter violates its output contract (malformed page, events, or cursor). A TypeError with code: "INVALID_CANDIDATE_PAGE": fix the adapter, do not retry.

AuditHistoryError

class AuditHistoryError extends RangeError {
  readonly code: AuditHistoryErrorCode;
  constructor(code: AuditHistoryErrorCode, message: string);
}

Thrown by auditHistory() for an invalid limit or an unknown resource type. A RangeError.

AuditHistoryErrorCode

type AuditHistoryErrorCode = "INVALID_LIMIT" | "UNKNOWN_RESOURCE_TYPE";

RetentionError

class RetentionError extends RangeError {
  readonly code: RetentionErrorCode;
  constructor(code: RetentionErrorCode, message: string);
}

Thrown by pruneSettledRecords() for a request it will not run, before any delete. A RangeError.

RetentionErrorCode

type RetentionErrorCode =
  | "INVALID_INPUT"
  | "INVALID_SCOPE"
  | "INVALID_LIMIT"
  | "INVALID_RETENTION"
  | "RETENTION_TOO_SHORT";

RetentionSchemaError

class RetentionSchemaError extends Error {
  readonly code: "SCHEMA_NOT_UPGRADED";
  constructor(message: string);
}

Thrown by pruneSettledRecords() when the database is not ready to prune (missing created_at, its index, or on PostgreSQL its default). code: "SCHEMA_NOT_UPGRADED". Run the adapter’s migrations.

PolicyStoreError

class PolicyStoreError extends Error {
  readonly code: PolicyStoreErrorCode;
  constructor(code: PolicyStoreErrorCode, message?: string);
}

Thrown while constructing a versioned sharing instance; no instance is returned.

PolicyStoreErrorCode

type PolicyStoreErrorCode =
  | "INVALID_OPTIONS"
  | "ADAPTER_NOT_FENCED"
  | "SEED_INVALID"
  | "NO_ACTIVE_POLICY"
  | "ACTIVE_VERSION_INVALID";

PolicyUnavailableError

class PolicyUnavailableError extends Error {
  readonly code: "POLICY_UNAVAILABLE";
  readonly reason: PolicyUnavailableReason;
  constructor(
    reason: PolicyUnavailableReason,
    message?: PolicyUnavailableReason,
    options?: {
      readonly cause?: unknown;
    },
  );
}

The active policy or a tenant’s custom roles cannot be used. execute() maps it to POLICY_UNAVAILABLE and explain() to INSPECTION_UNAVAILABLE; the other tenant reads, refresh(), policies.* and customRoles.* reject with it, and the listings reject with it for a sticky or per-tenant failure (other policy state they cannot use inside their page snapshot is AccessListingUnavailableError). Some reasons are sticky until a new instance is constructed. The error that caused it, such as a store rejection, is kept as cause.

PolicyUnavailableReason

type PolicyUnavailableReason =
  | "STORE_UNREACHABLE"
  | "STALE"
  | "INTERNAL_ERROR"
  | "CLOCK_FAULT"
  | "POINTER_INVALID"
  | "POINTER_REGRESSED"
  | "POINTER_DIGEST_MISMATCH"
  | "VERSION_INVALID"
  | "REVISION_REGRESSED"
  | "TENANT_ROLES_INVALID";

INTERNAL_ERROR reports a failure that did not come from a store call, such as a fault while building a tenant’s runtime. It is never served from the last good state: it fails closed at once, and it is not sticky, so the next operation loads again. A store that stays unreachable past maxStalenessMs reports STORE_UNREACHABLE. STALE means the instance knows the state it would decide under is superseded (a tenant’s custom roles invalidated there by a define or remove that applied or an execute result TENANT_ROLES_CHANGED, or the active generation reported as no longer active by a publish GENERATION_CONFLICT, a custom-role generation conflict or POLICY_GENERATION_CHANGED) and every reload the operation ran, at most three, was overtaken by a further report there; it is not sticky.

PolicyAdministrationError

class PolicyAdministrationError extends RangeError {
  readonly code: PolicyAdministrationErrorCode;
  constructor(code: PolicyAdministrationErrorCode, message: string);
}

A policy-administration request refused before any read or write. A RangeError.

PolicyAdministrationErrorCode

type PolicyAdministrationErrorCode =
  | "INVALID_LIMIT"
  | "INVALID_CURSOR"
  | "INVALID_DIGEST"
  | "INVALID_TENANT"
  | "INVALID_AUDIT_EVENT";

isPolicyStoreRowError

function isPolicyStoreRowError(error: unknown): boolean;

Whether an error is a first-party store’s PolicyStoreRowError (a row that does not decode), recognized by its name so this package needs no database import.

HierarchyUnavailableError

class HierarchyUnavailableError extends Error {
  readonly reason: HierarchyUnavailableReason;
  readonly code: "HIERARCHY_UNAVAILABLE";
  constructor(reason: HierarchyUnavailableReason, options?: {
    readonly cause?: unknown;
  });
}

A closed, tenant-level hierarchy refusal (R6 §7) with an exact reason. execute, authorize, permissions and strict listing pages rethrow it unchanged: it is never turned into a result, an ordinary denial or a retry. Over HTTP it is a 503 HIERARCHY_UNAVAILABLE with an allowlisted reason.

HierarchyUnavailableReason

type HierarchyUnavailableReason = "not_enrolled" | "enrolled" | "building" | "quarantined" | "epoch_mismatch" | "lifecycle_mismatch" | "protocol_floor" | "corrupt" | "barrier_missing" | "profile_unbound" | "profile_mismatch" | "budget_exhausted" | "policy_incompatible" | "unsupported_isolation" | "serialization_conflict" | "policy_identity_unresolved" | "policy_profile_mismatch" | "identity_unavailable" | "graph_quarantined" | "graph_corrupt" | "principal_cap" | "registry_unavailable" | "lineage_invalid" | "budget";

Why a tenant’s hierarchy is unavailable. Inherited reads and the hierarchy control facade raise these, and storage adapters bound to a hierarchy control profile raise them too (for example profile_unbound before resource migrations are rerun). not_enrolled also answers a flat read of an opted-in type whose application-supplied ancestors include a recursive type.

Nested-team lineage and the group-graph command facades raise the graph reasons. graph_quarantined means the group-graph admission is quarantined, which is separate from hierarchy quarantined. graph_corrupt means stored graph evidence is inconsistent. principal_cap means a resolution would pass 64 groups; it refuses the resolution and does not quarantine the graph. registry_unavailable means a group endpoint or its incarnation cannot be confirmed. lineage_invalid means lineage evidence failed validation. budget means a graph allocator or repair batch cannot continue, and is separate from hierarchy budget_exhausted.

isHierarchyUnavailableError

function isHierarchyUnavailableError(error: unknown): error is HierarchyUnavailableError;

Narrows an unknown thrown value to HierarchyUnavailableError.

DelegationUnavailableError

class DelegationUnavailableError extends Error {
  readonly reason: DelegationUnavailableReason;
  readonly code: "DELEGATION_UNAVAILABLE";
  constructor(reason: DelegationUnavailableReason);
}

A closed refusal when delegable-scope evidence cannot be decided from complete, bounded evidence. execute answers it as the DELEGATION_UNAVAILABLE result.

DelegationUnavailableReason

type DelegationUnavailableReason = "evidence_incomplete" | "assignment_cap" | "unknown_role" | "evidence_pending";

Why delegable-scope evidence was unavailable.

InheritedScopeUnsupportedError

class InheritedScopeUnsupportedError extends Error {
  readonly resourceType: string;
  readonly code: "INHERITED_SCOPE_UNSUPPORTED";
  constructor(resourceType: string);
}

Authority at an inherited scope that this path does not support. The protected-content prefix and hierarchy commands such as ownership transfer throw it before any effect. The protected write adapter does not: an inheriting enrolled type is classified and authorized through the locked inherited read. execute answers the error as the INHERITED_SCOPE_UNSUPPORTED result.

AdapterContractError

class AdapterContractError extends Error {
  constructor();
}

Thrown when a storage adapter answers a rejection reason outside its closed contract. Such a reason used to become OWNER_TRANSFER_REQUIRED.

Keys, clocks, and IDs

createHmacInvitationTokens

function createHmacInvitationTokens(key: string | Uint8Array): InvitationTokenProtector;

An InvitationTokenProtector that issues 32-byte random secrets and digests them with HMAC-SHA256. The key is a generateInvitationTokenKey() string or at least 32 random bytes as a Uint8Array, copied at construction; see secret keys.

generateInvitationTokenKey

function generateInvitationTokenKey(): string;

A new 32-byte random key in the checked rbk1_ text form.

generateListingCursorKey

function generateListingCursorKey(): string;

A new 32-byte random key in the same checked rbk1_ form, for listingCursorKey.

InvitationTokenProtector

interface InvitationTokenProtector {
  issue(): {
    readonly secret: string;
    readonly digest: string;
  };
  digest(secret: string): string;
}

Issues an invitation secret with its digest, and digests a presented secret.

SharingClock

interface SharingClock {
  now(): Date;
}

The wall clock the module and adapters use for expiry and timestamps.

systemClock

const systemClock: SharingClock;

The default clock: new Date().

SharingIdGenerator

interface SharingIdGenerator {
  next(): string;
}

Generates invitation and audit event IDs.

randomIdGenerator

const randomIdGenerator: SharingIdGenerator;

The default generator: crypto.randomUUID().

Identity

TenantIdentityAdapter

interface TenantIdentityAdapter {
  resolvePagePrincipal?(input: {
    readonly tenantId: string;
    readonly subject: ResourceRef;
  }): Promise<PagePrincipalEvidence>;
  capturePagePrincipal?(input: {
    readonly tenantId: string;
    readonly subject: ResourceRef;
    readonly evaluatedAt: string;
  }): PagePrincipalSnapshot;
  resolvePrincipal(input: {
    readonly tenantId: string;
    readonly subject: ResourceRef;
  }): Promise<TenantPrincipal>;
  matchesInvitationRecipient(input: {
    readonly tenantId: string;
    readonly principal: TenantPrincipal;
    readonly recipient: InvitationRecipient;
  }): Promise<boolean>;
}

Resolves a subject’s eligibility, assignments, facts, and groups in an explicit tenant, and matches invitation recipients. See identity adapters.

The two optional methods supply identity evidence for listing pages. resolvePagePrincipal is for an external source with a non-repeating revision: Rolebook calls it before a page’s snapshot opens and after the page was read, and accepts the page only when both answers match. Implement it only when the source has such a revision. capturePagePrincipal is for the in-memory adapter: it answers synchronously from in-process state, judged at evaluatedAt, and must not perform I/O, return a promise, or write. An identity adapter with neither needs the storage adapter’s pageIdentity option.

PagePrincipalSnapshot

interface PagePrincipalSnapshot {
  readonly principal: TenantPrincipal;
  readonly expiryDependencies: readonly string[];
}

A complete principal captured at one instant, with the expiry of every time-sensitive fact as ISO 8601 UTC instants with exactly three fractional digits. What capturePagePrincipal returns.

PagePrincipalEvidence

interface PagePrincipalEvidence extends PagePrincipalSnapshot {
  readonly epoch: string;
  readonly revision: string;
}

What resolvePagePrincipal returns. revision never repeats within epoch and changes on every relevant change, including a change that is later restored and a set going from empty to non-empty. epoch changes whenever the provider’s store is restored or re-created. Equal values, timestamps, and ETags are not substitutes.

TenantPrincipal

interface TenantPrincipal {
  readonly eligible: boolean;
  readonly subject: Subject;
  readonly tenantScope: ResourceRef;
  readonly assignments: readonly RoleAssignment[];
  readonly authorizationFacts?: readonly TransactionalAuthorizationFact[];
  readonly attributes?: Readonly<Record<string, unknown>>;
  readonly groups?: readonly ResourceRef[];
  readonly group?: boolean;
}

What an identity adapter returns for one subject in one tenant.

TransactionalAuthorizationFact

interface TransactionalAuthorizationFact {
  readonly type: string;
  readonly tenantId: string;
  readonly subject: ResourceRef;
  readonly values: Readonly<Record<string, string>>;
  readonly group?: ResourceRef;
}

A provider-owned fact behind an assignment or a group membership. The module transports it unchanged; the storage adapter locks and compares it inside the mutation transaction. group names the group it attests.

GroupPrincipalRef

type GroupPrincipalRef = ResourceRef & {
  readonly [groupPrincipalBrand]: true;
};

A reference branded as a flat group principal (a team). Build one with groupPrincipal().

OwnerRef

type OwnerRef = ResourceRef & {
  readonly [groupPrincipalBrand]?: never;
};

A reference that may own a resource. A GroupPrincipalRef does not satisfy it.

groupPrincipal

function groupPrincipal(ref: ResourceRef): GroupPrincipalRef;

Brands a bounded { type, id } as a group principal (a frozen copy). Throws TypeError otherwise.

createWorkspaceIdentityAdapter

function createWorkspaceIdentityAdapter<
  TUser extends {
    readonly id: string;
  },
>(options: WorkspaceIdentityAdapterOptions<TUser>): TenantIdentityAdapter;

The shared implementation behind the Better Auth, Clerk, and WorkOS adapters. See createWorkspaceIdentityAdapter.

WorkspaceIdentityAdapterOptions

interface WorkspaceIdentityAdapterOptions<
  TUser extends {
    readonly id: string;
  },
> {
  readonly authorizationFactType: string;
  readonly getMember: (input: {
    readonly organizationId: string;
    readonly userId: string;
  }) => Promise<WorkspaceMemberRecord | undefined>;
  readonly getUser: (input: { readonly userId: string }) => Promise<TUser | undefined>;
  readonly snapshotUser: (user: TUser) => TUser | undefined;
  readonly verifiedEmail: (user: TUser) => string | undefined;
  readonly requireUser?: boolean | undefined;
  readonly principalAttributes?:
    | ((input: {
        readonly user: TUser;
        readonly member: WorkspaceMemberRecord;
      }) => Readonly<Record<string, unknown>>)
    | undefined;
  readonly subjectType?: string | undefined;
  readonly workspaceResourceType?: string | undefined;
  readonly mapWorkspaceAssignments?:
    | ((input: {
        readonly tenantId: string;
        readonly subject: ResourceRef;
        readonly member: WorkspaceMemberRecord;
      }) => readonly RoleAssignment[])
    | undefined;
  readonly normalizeEmail?: ((email: string) => string) | undefined;
}

The provider-specific parts: the fact type, exact membership and user lookups, user snapshot and verified-email functions, and optional requireUser, principalAttributes, subjectType, workspaceResourceType, mapWorkspaceAssignments, and normalizeEmail.

WorkspaceMemberRecord

interface WorkspaceMemberRecord {
  readonly id: string;
  readonly organizationId: string;
  readonly userId: string;
  readonly role: string;
}

The authority-bearing part of a provider membership: member ID, organization, user, role.

createWorkspaceMemberRemovedHandler

function createWorkspaceMemberRemovedHandler(input: {
  readonly provider: string;
  readonly onMemberRemoved: (event: WorkspaceMemberRemovedEvent) => void | Promise<void>;
}): (event: WorkspaceMemberRemovedEvent) => Promise<void>;

Wraps a member-removal callback so it receives a validated, frozen event. Cleanup only: membership is still checked on every operation.

WorkspaceMemberRemovedEvent

interface WorkspaceMemberRemovedEvent {
  readonly organizationId: string;
  readonly userId: string;
}

A provider member-removal notification: organization and user IDs.

Storage adapter contract

What a storage adapter implements and exchanges with the module. See storage adapters.

SharingAdapter

interface SharingAdapter {
  runConsistentPage?<T>(input: ConsistentPageInput, operation: (page: ConsistentPage) => Promise<T>): Promise<T>;
  readonly policyFence?: "enforced";
  readonly governanceGate?: GovernanceDirectGate;
  readonly governanceBinding?: GovernanceBinding;
  readAccess(input: {
    readonly tenantId: string;
    readonly resourceId: string;
    readonly requiredEligibleSubjects: readonly ResourceRef[];
    readonly requestingPrincipals?: readonly ResourceRef[];
    readonly hierarchy?: HierarchyReadRuntime;
  }): Promise<SharingAccessSnapshot | undefined>;
  readAccessBatch(input: {
    readonly tenantId: string;
    readonly resourceIds: readonly string[];
    readonly requiredEligibleSubjects: readonly ResourceRef[];
    readonly requestingPrincipals?: readonly ResourceRef[];
    readonly hierarchy?: HierarchyReadRuntime;
  }): Promise<readonly SharingAccessSnapshot[]>;
  readInvitation(input: {
    readonly tenantId: string;
    readonly resourceId: string;
    readonly invitationId: string;
  }): Promise<SharingInvitation | undefined>;
  listPendingInvitations(input: {
    readonly tenantId: string;
    readonly resourceId: string;
    readonly incarnationId?: string;
  }): Promise<readonly SharingInvitation[] | undefined>;
  listAuditEvents(input: {
    readonly tenantId: string;
    readonly resourceId: string;
    readonly limit: number;
    readonly cursor?: string;
    readonly incarnationId?: string;
  }): Promise<AuditEventPage | undefined>;
  readMutationIdempotency(input: ReadMutationIdempotencyRequest): Promise<ReadMutationIdempotencyResult>;
  lookupMutationIdempotency?(input: ReadMutationIdempotencyRequest): Promise<ReadMutationIdempotencyResult>;
  applyMutation(input: ApplyMutationRequest): Promise<ApplyMutationResult>;
  listCandidates(input: {
    readonly tenantId: string;
    readonly principals: readonly ResourceRef[];
    readonly includeAllTenantResources: boolean;
    readonly resourceIds: readonly string[];
    readonly memberRoles?: readonly string[];
    readonly cursor?: string;
    readonly limit: number;
    readonly hierarchy?: HierarchyReadRuntime;
  }): Promise<AccessibleCandidatePage>;
  resourceDeleted(input: {
    readonly tenantId: string;
    readonly resourceId: string;
    readonly actor: ResourceRef;
    readonly idempotencyKey: string;
    readonly occurredAt: Date;
  }): Promise<"applied" | "already_applied" | "not_found" | "unsupported">;
  resourceMoved(input: {
    readonly fromTenantId: string;
    readonly toTenantId: string;
    readonly resourceId: string;
    readonly actor: ResourceRef;
    readonly idempotencyKey: string;
    readonly occurredAt: Date;
  }): Promise<"applied" | "already_applied" | "not_found" | "unsupported">;
}

The storage contract for one resource type.

runConsistentPage reads one listing page at one coherent point. It opens one snapshot, calls operation exactly once with a session whose candidate and hydration reads, principal, policy state, and evaluatedAt all belong to that snapshot, seals every live expiry the page depended on, and closes. It has a finite lifetime, its reads are sequential, and it never retries operation. Whatever it cannot establish throws AccessListingUnavailableError with a reason; it never returns a weaker page. The member is optional so that existing custom adapters still compile: an adapter without it makes listAccessible() and listAccess() answer capability_missing. Every first-party adapter implements it.

lookupMutationIdempotency answers what readMutationIdempotency answers, as a pure read for lookupExecution: it writes nothing (not even bookkeeping a writer would create for a tenant or resource with no rows yet), takes no write lock, and works on a read-only connection where the adapter supports one. A tenant whose hierarchy enrollment has started is refused with HierarchyUnavailableError (reason enrolled), never read flat. On PostgreSQL a tenant ID that cannot be a value of the tenant column answers missing without a transaction; any other tenant is probed first, so an enrolled tenant is refused whatever the resource ID, as on SQLite, and an alias spelling of an enrolled tenant (a non-canonical form of a uuid tenant ID) is refused with reason profile_mismatch, which lookupExecution throws on. readMutationIdempotency keeps the replay route: on SQLite and PostgreSQL it runs the writer barrier, which can create a tenant’s barrier row. The member is optional; a tenant offers lookupExecution only when every resource adapter of its instance implements it. The memory, SQLite and PostgreSQL adapters do, and sharingAdapterContract fails for an adapter without it.

ConsistentPageInput

interface ConsistentPageInput {
  readonly tenantId: string;
  readonly subject: ResourceRef;
  readonly identity: TenantIdentityAdapter;
  readonly policyStore?: PolicyStore;
}

What Rolebook asks an adapter to read one page for: the tenant, the actor whose principal the page resolves, the identity adapter the sharing instance was created with, and, on a versioned instance, the policy store whose state the page must read in its snapshot.

ConsistentPage

interface ConsistentPage {
  readonly evaluatedAt: string;
  readonly principal: TenantPrincipal;
  readonly policyState?: PagePolicyState;
  listCandidates: SharingAdapter["listCandidates"];
  readAccessBatch: SharingAdapter["readAccessBatch"];
}

One page session. Its reads are sequential and see one snapshot, and every method throws once the callback has settled or the session has closed, so never retain it. evaluatedAt is the ISO 8601 UTC millisecond instant every expiry comparison of the page uses. principal is the actor’s complete principal at the snapshot, which may be ineligible. policyState is present exactly when the input named a policy store.

readAccessBatch returns every requested resource, projected to requestingPrincipals (required here), with memberships live at evaluatedAt; a requested resource that is missing or corrupt makes the call throw. It is narrower than the adapter’s own method on requiredEligibleSubjects: the session proves eligibility only for its own actor. Requiring that actor reads nothing when the snapshot found it ineligible, and requiring any other subject throws AccessListingUnavailableError with identity_evidence_missing.

PagePolicyState

interface PagePolicyState {
  readonly pointer: ActivePolicyPointer;
  readonly version: StoredPolicyVersion | undefined;
  readonly tenantRoles: TenantCustomRoles;
}

Versioned policy state as read inside a page’s snapshot: the active pointer, the stored version it names, and the tenant’s custom roles.

SharingAccessSnapshot

interface SharingAccessSnapshot {
  readonly tenantId: string;
  readonly resourceId: string;
  readonly resource: TrustedResource;
  readonly resourceVersion: string;
  readonly sharingRevision: string;
  readonly ownership: SharingOwnership;
  readonly memberships: readonly SharingMembership[];
  readonly incarnationId?: string;
}

One resource’s authoritative state: the trusted snapshot, resource version, sharing revision, ownership, memberships, and incarnation ID.

SharingOwnership

interface SharingOwnership {
  readonly subject: ResourceRef;
  readonly createdAt: Date;
  readonly createdBy: ResourceRef;
}

The owner and when and by whom ownership was recorded.

SharingMembership

interface SharingMembership {
  readonly subject: ResourceRef;
  readonly role: string;
  readonly createdAt: Date;
  readonly createdBy: ResourceRef;
  readonly expiresAt?: Date;
}

One membership: subject, role label, creation, optional expiry.

SharingInvitation

interface SharingInvitation {
  readonly id: string;
  readonly recipient: InvitationRecipient;
  readonly role: string;
  readonly tokenDigest: string;
  readonly expiresAt: Date;
  readonly createdAt: Date;
  readonly createdBy: ResourceRef;
  readonly consumedAt?: Date;
  readonly consumedBy?: ResourceRef;
  readonly revokedAt?: Date;
  readonly revokedBy?: ResourceRef;
  readonly membershipExpiresAt?: Date;
}

A stored invitation: recipient, role, token digest, expiry, and its lifecycle timestamps.

SharingAuditEvent

interface SharingAuditEvent {
  readonly id: string;
  readonly tenantId: string;
  readonly resourceType: string;
  readonly resourceId: string;
  readonly actor: ResourceRef;
  readonly action:
    | "member.granted"
    | "member.role_changed"
    | "member.revoked"
    | "ownership.transferred"
    | "invitation.issued"
    | "invitation.consumed"
    | "invitation.revoked"
    | "resource.initialized"
    | "resource.deleted"
    | "resource.moved";
  readonly subject?: ResourceRef;
  readonly invitationId?: string;
  readonly fromTenantId?: string;
  readonly toTenantId?: string;
  readonly occurredAt: Date;
  readonly idempotencyKey: string;
  readonly lineageDirect?: string;
  readonly lineageWitness?: string;
}

One audit event, committed with the mutation it records. lineageDirect is the canonical JSON of every contributing direct group for an invitation issued or consumed under a nested-team profile. lineageWitness is the lineage witness encoding from that same subject fact. Flat events, and historical rows written before those fields existed, omit both.

AdapterMutation

type AdapterMutation =
  | {
      readonly kind: "grantRole";
      readonly subject: ResourceRef;
      readonly role: string;
      readonly expiresAt?: Date;
    }
  | {
      readonly kind: "changeRole";
      readonly subject: ResourceRef;
      readonly role: string;
      readonly expiresAt?: Date | null;
    }
  | {
      readonly kind: "revokeMember";
      readonly subject: ResourceRef;
    }
  | {
      readonly kind: "transferOwnership";
      readonly to: ResourceRef;
      readonly formerOwnerRole?: string;
    }
  | {
      readonly kind: "issueInvitation";
      readonly invitation: SharingInvitation;
    }
  | {
      readonly kind: "consumeInvitation";
      readonly invitationId: string;
      readonly tokenDigest: string;
      readonly recipient: InvitationRecipient;
      readonly subject: ResourceRef;
      readonly consumedAt: Date;
    }
  | {
      readonly kind: "revokeInvitation";
      readonly invitationId: string;
      readonly revokedAt: Date;
      readonly revokedBy: ResourceRef;
    };

The storage-level form of a command, prepared by the module after authorization.

ApplyMutationRequest

interface ApplyMutationRequest {
  readonly tenantId: string;
  readonly resourceId: string;
  readonly expectedResourceVersion: string;
  readonly expectedSharingRevision: string;
  readonly actor: ResourceRef;
  readonly requiredEligibleSubjects: readonly ResourceRef[];
  readonly requiredAuthorizationFacts?: readonly TransactionalAuthorizationFact[];
  readonly mutation: AdapterMutation;
  readonly audit: SharingAuditEvent;
  readonly idempotencyKey: string;
  readonly idempotencyFingerprint: string;
  readonly expectedPolicy?: ExpectedPolicy;
  readonly policyVersion?: string;
  readonly reliedAuthorityExpiries?: readonly number[];
}

Everything applyMutation needs: expected version and revision, subjects and facts to fence, the mutation, its audit event, idempotency key and fingerprint, and, when versioned, the expected policy.

ApplyMutationResult

type ApplyMutationResult = {
  readonly status: "applied";
  readonly sharingRevision: string;
  readonly policyVersion?: string;
} | {
  readonly status: "already_applied";
  readonly sharingRevision: string;
  readonly policyVersion?: string;
} | {
  readonly status: "conflict";
} | {
  readonly status: "not_found";
} | {
  readonly status: "invalid";
  readonly reason: "last_owner" | "group_owner" | "member_exists" | "invitation_unavailable" | "invitation_recipient_mismatch" | "identity_ineligible" | "policy_generation_changed" | "tenant_roles_changed" | "policy_unfenced" | "hierarchy_unavailable" | "delegation_unavailable" | "inherited_scope_unsupported" | "governance_required";
};

applied, already_applied, conflict, not_found, or invalid with a reason.

ReadMutationIdempotencyRequest

interface ReadMutationIdempotencyRequest {
  readonly tenantId: string;
  readonly resourceId: string;
  readonly idempotencyKey: string;
  readonly idempotencyFingerprint: string;
}

A lookup of a committed idempotency record by key and fingerprint.

ReadMutationIdempotencyResult

type ReadMutationIdempotencyResult =
  | {
      readonly status: "already_applied";
      readonly sharingRevision: string;
      readonly policyVersion?: string;
    }
  | {
      readonly status: "conflict";
    }
  | {
      readonly status: "missing";
    };

already_applied, conflict (another fingerprint), or missing.

AccessibleCandidate

interface AccessibleCandidate {
  readonly resourceId: string;
  readonly cursor: string;
}

One listing candidate: a resource ID and the cursor just after it.

AccessibleCandidatePage

interface AccessibleCandidatePage {
  readonly candidates: readonly AccessibleCandidate[];
  readonly nextCursor?: string;
  readonly exhausted: boolean;
}

One page of candidates; non-exhausted pages carry an advancing nextCursor.

AuditEventPage

interface AuditEventPage {
  readonly events: readonly SharingAuditEvent[];
  readonly nextCursor?: string;
  readonly exhausted: boolean;
}

One page of an adapter’s audit events, newest first, with a raw cursor.

InvitationRecipientFenceInput

interface InvitationRecipientFenceInput {
  readonly tenantId: string;
  readonly resourceId: string;
  readonly invitationId: string;
  readonly tokenDigest: string;
  readonly recipient: InvitationRecipient;
  readonly subject: ResourceRef;
}

The exact recipient assertion an adapter checks while consuming an invitation, bound to the invitation, digest, tenant, resource, and accepting subject.

Adapter helpers

Shared by the module and every first-party adapter, so a custom adapter can apply exactly the same rules.

validOpaqueId

function validOpaqueId(value: unknown): value is string;

Whether a value is a string of 1 to MAX_OPAQUE_ID_LENGTH (128) UTF-16 units.

validAuditEventId

function validAuditEventId(value: unknown): value is string;

Whether a value is a valid audit event ID: 1 to MAX_AUDIT_EVENT_ID_LENGTH units whose JSON encoding fits the audit cursor budget.

sameRef

function sameRef(left: ResourceRef, right: ResourceRef): boolean;

Whether two references have the same type and id.

dedupeRefs

function dedupeRefs(refs: readonly ResourceRef[]): readonly ResourceRef[];

Drops later duplicate references, keeping first-seen order (frozen).

captureRequestingPrincipals

function captureRequestingPrincipals(
  principals: readonly ResourceRef[] | undefined,
): readonly ResourceRef[] | undefined | null;

Snapshots a read’s requestingPrincipals: undefined when absent, null when malformed (adapters then answer an empty read), otherwise a deduplicated frozen list.

captureMemberRoleHint

function captureMemberRoleHint(value: unknown): readonly string[] | undefined | null;

Snapshots listCandidates.memberRoles: undefined when absent, null when malformed (first-party adapters throw RangeError), otherwise a deduplicated frozen list.

missingFactFenceMessage

function missingFactFenceMessage(
  adapter: string,
  facts: readonly {
    readonly type: string;
  }[],
  hint?: string,
): string;

The operator message an adapter logs once when a mutation carries authorization facts but no fact fence is configured. The mutation still fails closed.

In-memory adapter

createMemorySharingAdapter

function createMemorySharingAdapter(
  options?: CreateMemorySharingAdapterOptions,
): MemorySharingAdapter;

A deterministic in-memory adapter for tests and the contract kit. Not for production: it takes no locks. See the in-memory adapter.

CreateMemorySharingAdapterOptions

interface CreateMemorySharingAdapterOptions {
  readonly clock?: SharingClock;
  readonly fenceEligibleSubjects?: (input: {
    readonly tenantId: string;
    readonly subjects: readonly ResourceRef[];
  }) => boolean | Promise<boolean>;
  readonly readEligibleSubjects?: MemoryEligibilityReader;
  readonly fenceInvitationRecipient?: (input: InvitationRecipientFenceInput) => boolean;
  readonly groupSubjectTypes?: readonly string[];
  readonly revalidateAuthorizationFacts?: (input: {
    readonly tenantId: string;
    readonly facts: readonly TransactionalAuthorizationFact[];
  }) => boolean | Promise<boolean>;
  readonly fencePolicy?: (input: {
    readonly tenantId: string;
    readonly expectedPolicy: ExpectedPolicy;
  }) => PolicyFenceResult;
  readonly governanceGate?: GovernanceDirectGate;
  readonly governanceBinding?: GovernanceBinding;
}

clock, fenceEligibleSubjects, readEligibleSubjects, fenceInvitationRecipient, groupSubjectTypes (default ["team"]), revalidateAuthorizationFacts, and fencePolicy.

readEligibleSubjects is the evidence form of fenceEligibleSubjects for listing pages. When fenceEligibleSubjects is configured without it, listAccessible() and listAccess() answer identity_evidence_missing; ordinary reads and mutations keep using fenceEligibleSubjects.

MemoryEligibilityReader

type MemoryEligibilityReader = (input: {
  readonly tenantId: string;
  readonly subjects: readonly ResourceRef[];
  readonly evaluatedAt: string;
}) => MemoryEligibilityEvidence;

Answers synchronously whether every subject is eligible at evaluatedAt, the adapter clock’s reading for the page. Judge by that instant; do not read a clock.

MemoryEligibilityEvidence

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

eligible must be exactly a boolean. expiryDependencies lists every instant at which the answer could change on its own, as ISO 8601 UTC instants with exactly three fractional digits; it is empty only when the answer depends on no time.

MemorySharingAdapter

interface MemorySharingAdapter extends SharingAdapter, SettledRecordPruner {
  seed(seed: MemorySharingSeed): void;
  readAudit(): readonly SharingAuditEvent[];
  advanceResourceVersion(input: {
    readonly tenantId: string;
    readonly resourceId: string;
    readonly resource: TrustedResource;
  }): void;
}

The memory adapter, with seed(), readAudit(), advanceResourceVersion(), and pruning.

MemorySharingSeed

interface MemorySharingSeed {
  readonly tenantId: string;
  readonly resourceId: string;
  readonly resource: TrustedResource;
  readonly owner: OwnerRef;
  readonly createdAt?: Date;
  readonly createdBy?: ResourceRef;
  readonly resourceVersion?: string;
  readonly memberships?: readonly Omit<SharingMembership, "createdAt" | "createdBy">[];
}

A resource to place in the memory adapter, with its owner and optional memberships.

Retention

See retention and pruning.

SettledRecordPruner

interface SettledRecordPruner {
  pruneSettledRecords(input: PruneSettledRecordsInput): Promise<PruneSettledRecordsResult>;
}

The pruning method of the first-party adapters. Not part of SharingAdapter.

PruneSettledRecordsInput

type PruneSettledRecordsInput =
  | PruneWithDefaultsInput
  | PruneIdempotencyInput
  | PruneInvitationsInput
  | PruneBothInput;

One pruning request: defaults for both kinds, or named kinds with their retentions.

PruneWithDefaultsInput

type PruneWithDefaultsInput = PruneSettledRecordsBase & {
  readonly kinds?: never;
  readonly idempotencyRetentionMs?: never;
  readonly invitationRetentionMs?: never;
};

Both kinds at their 30-day defaults.

PruneIdempotencyInput

type PruneIdempotencyInput = PruneSettledRecordsBase &
  IdempotencyRetention & {
    readonly kinds: readonly ["idempotency"];
    readonly invitationRetentionMs?: never;
  };

Idempotency records only.

PruneInvitationsInput

type PruneInvitationsInput = PruneSettledRecordsBase &
  InvitationRetention & {
    readonly kinds: readonly ["invitations"];
    readonly idempotencyRetentionMs?: never;
  };

Settled invitations only.

PruneBothInput

type PruneBothInput = PruneSettledRecordsBase &
  IdempotencyRetention &
  InvitationRetention & {
    readonly kinds:
      | readonly ["idempotency", "invitations"]
      | readonly ["invitations", "idempotency"];
  };

Both kinds, each with its own retention.

RetentionScope

type RetentionScope =
  | {
      readonly tenantId: string;
      readonly allTenants?: never;
    }
  | {
      readonly allTenants: true;
      readonly tenantId?: never;
    };

One tenant, or { allTenants: true }. There is no implicit all.

SettledRecordKind

type SettledRecordKind = "idempotency" | "invitations";

PruneSettledRecordsResult

interface PruneSettledRecordsResult {
  readonly deleted: {
    readonly idempotency: number;
    readonly invitations: number;
  };
  readonly exhausted: boolean;
  readonly cutoffs: {
    readonly idempotency?: Date;
    readonly invitations?: Date;
  };
}

Rows deleted per kind, whether the backlog is exhausted, and the cutoffs used.

PruneSettledRecordsRequest

interface PruneSettledRecordsRequest {
  readonly tenantId: string | undefined;
  readonly idempotencyRetentionMs: number | undefined;
  readonly invitationRetentionMs: number | undefined;
  readonly limit: number;
}

A validated, captured pruning request.

capturePruneSettledRecordsInput

function capturePruneSettledRecordsInput(input: unknown): PruneSettledRecordsRequest;

Validates and captures a pruning request, throwing RetentionError for anything invalid.

pruneCutoffs

function pruneCutoffs(
  request: PruneSettledRecordsRequest,
  now: number,
): {
  readonly idempotency?: Date;
  readonly invitations?: Date;
};

The cutoff instants for a captured request, measured back from now.

pruneResult

function pruneResult(
  request: PruneSettledRecordsRequest,
  cutoffs: PruneSettledRecordsResult["cutoffs"],
  deleted: {
    readonly idempotency: number;
    readonly invitations: number;
  },
): PruneSettledRecordsResult;

Assembles a result: exhausted when every pruned kind deleted fewer rows than the limit.

invitationSettledBefore

function invitationSettledBefore(invitation: SharingInvitation, cutoff: Date): boolean;

Whether an invitation was consumed, revoked, or expired strictly before the cutoff.

DEFAULT_IDEMPOTENCY_RETENTION_MS

const DEFAULT_IDEMPOTENCY_RETENTION_MS: number;

30 days.

DEFAULT_INVITATION_RETENTION_MS

const DEFAULT_INVITATION_RETENTION_MS: number;

30 days.

MIN_IDEMPOTENCY_RETENTION_MS

const MIN_IDEMPOTENCY_RETENTION_MS = 86400000;

One day.

MIN_INVITATION_RETENTION_MS

const MIN_INVITATION_RETENTION_MS = 86400000;

One day.

MAX_RETENTION_MS

const MAX_RETENTION_MS = 3153600000000;

100 years of 365 days.

MAX_PRUNE_BATCH

const MAX_PRUNE_BATCH = 1000;

The largest limit of one pruning call.

Policy versions and custom roles

See policy versions and custom roles.

PolicyAdministration

interface PolicyAdministration {
  saveDraft(input: {
    readonly policy: RolebookPolicy;
    readonly label?: string;
    readonly actor: ResourceRef;
  }): Promise<
    | {
        readonly ok: true;
        readonly code: "SAVED" | "EXISTS";
        readonly digest: string;
      }
    | {
        readonly ok: false;
        readonly code:
          | "POLICY_TOO_LARGE"
          | "POLICY_INVALID"
          | "RESERVED_ROLE_NAME"
          | "DEFINITION_INCOMPATIBLE"
          | "INVALID_ACTOR"
          | "INVALID_LABEL";
        readonly reason?: string;
      }
  >;
  readVersion(input: { readonly digest: string }): Promise<
    | {
        readonly ok: true;
        readonly code: "FOUND";
        readonly version: PolicyVersionSummary;
        readonly policy: Readonly<RolebookPolicy>;
        readonly active: boolean;
      }
    | {
        readonly ok: false;
        readonly code: "VERSION_NOT_FOUND" | "VERSION_CORRUPT";
      }
  >;
  listVersions(input: { readonly limit: number; readonly cursor?: string }): Promise<{
    readonly versions: readonly PolicyVersionSummary[];
    readonly nextCursor?: string;
  }>;
  listActivations(input: { readonly limit: number; readonly cursor?: string }): Promise<{
    readonly activations: readonly PolicyActivation[];
    readonly nextCursor?: string;
  }>;
  diff(input: { readonly from: string | "active"; readonly to: string | "active" }): Promise<
    | {
        readonly ok: true;
        readonly code: "DIFFED";
        readonly diff: PolicyDiff;
      }
    | {
        readonly ok: false;
        readonly code: "VERSION_NOT_FOUND" | "VERSION_CORRUPT";
      }
  >;
  previewImpact(input: ImpactInput): Promise<ImpactResult>;
  previewCustomRoles(input: CustomRolePreviewInput): Promise<CustomRolePreviewResult>;
  publish(input: {
    readonly digest: string;
    readonly expectedGeneration: string;
    readonly actor: ResourceRef;
  }): Promise<
    | {
        readonly ok: true;
        readonly code: "ACTIVATED";
        readonly generation: string;
        readonly digest: string;
      }
    | {
        readonly ok: false;
        readonly code: "GENERATION_CONFLICT";
        readonly activeGeneration: string;
      }
    | {
        readonly ok: false;
        readonly code: "ALREADY_ACTIVE";
        readonly activeGeneration: string;
      }
    | {
        readonly ok: false;
        readonly code:
          | "VERSION_NOT_FOUND"
          | "VERSION_CORRUPT"
          | "DEFINITION_INCOMPATIBLE"
          | "INVALID_ACTOR"
          | "GENERATION_EXHAUSTED";
      }
  >;
}

Version administration: saveDraft, readVersion, listVersions, listActivations, diff, previewImpact, previewCustomRoles, publish. It records the actor but does not authorize it.

CustomRoleAdministration

interface CustomRoleAdministration {
  list(input: { readonly tenantId: string }): Promise<
    | {
        readonly ok: true;
        readonly code: "LISTED";
        readonly revision: string;
        readonly generation: string;
        readonly roles: readonly CustomRoleView[];
      }
    | {
        readonly ok: false;
        readonly code: "INVALID_TENANT";
      }
  >;
  define(input: {
    readonly tenantId: string;
    readonly resourceType: string;
    readonly name: CustomRoleLabel;
    readonly template: string;
    readonly rules: readonly PolicyRule[];
    readonly expectedRevision: string;
    readonly actor: ResourceRef;
  }): Promise<
    | {
        readonly ok: true;
        readonly code: "DEFINED";
        readonly revision: string;
      }
    | {
        readonly ok: false;
        readonly code: "CEILING_EXCEEDED";
        readonly permissions: readonly string[];
      }
    | {
        readonly ok: false;
        readonly code: "CUSTOM_ROLE_INVALID";
        readonly reason: "name" | "rules" | "limits";
      }
    | {
        readonly ok: false;
        readonly code:
          | "INVALID_TENANT"
          | "INVALID_ACTOR"
          | "UNKNOWN_RESOURCE_TYPE"
          | "TEMPLATE_UNKNOWN"
          | "TOO_MANY_CUSTOM_ROLES"
          | "CUSTOM_ROLE_NAME_RETIRED"
          | "REVISION_CONFLICT"
          | "GENERATION_CONFLICT"
          | "REVISION_EXHAUSTED";
      }
  >;
  remove(input: {
    readonly tenantId: string;
    readonly resourceType: string;
    readonly name: CustomRoleLabel;
    readonly expectedRevision: string;
    readonly actor: ResourceRef;
  }): Promise<
    | {
        readonly ok: true;
        readonly code: "REMOVED";
        readonly revision: string;
      }
    | {
        readonly ok: false;
        readonly code:
          | "INVALID_TENANT"
          | "INVALID_ACTOR"
          | "NOT_FOUND"
          | "REVISION_CONFLICT"
          | "REVISION_EXHAUSTED";
      }
  >;
  set?(input: CustomRoleSetInput): Promise<CustomRoleSetResult>;
}

Tenant custom roles: list, define, remove, and set. It records the actor but does not authorize it.

set makes roles the tenant’s complete set of live custom roles in one write. Its checks run in this order and the first failure answers, with nothing written: the input (INVALID_TENANT, INVALID_ACTOR, INVALID_ROLES for a value that is not an array of plain role records, TOO_MANY_CUSTOM_ROLES for more than MAX_CUSTOM_ROLES_PER_TENANT roles); then the stored roles, read in one consistent read: a revision other than expectedRevision is REVISION_CONFLICT, and any stored row that does not decode is CUSTOM_ROLE_UNREADABLE, naming it; then each role, in the order given, with the checks define makes before it reads the stored roles (resource type, name, a role named twice as CUSTOM_ROLE_INVALID with reason duplicate, template, rules, and the role on its own beside the base policy); then the rest of the stored roles: a role whose name is retired is CUSTOM_ROLE_NAME_RETIRED, and a result over MAX_CUSTOM_ROLE_RECORDS_PER_TENANT rows is TOO_MANY_CUSTOM_ROLES; then each role’s template-derived rules, the whole set beside the base policy (CUSTOM_ROLE_INVALID with reason limits or rules and no role), and each role’s template ceiling (CEILING_EXCEEDED). The limits are counted on the result, so a set that removes one role and adds another at the live limit applies, where a define of the addition alone is refused. A refusal about one role names it in role.

Every role in the set gets these checks, including one that is already live and unchanged: an unchanged role that the active policy no longer admits (its template’s ceiling narrowed, say) refuses the set. A live role the set does not name is removed: it is tombstoned, as by remove, so its name is retired. A role that is live with the same template and rules is not rewritten, and keeps its definedAtRevision, and so does a removed one; every role the set defines or replaces gets the new revision. A row that does not decode cannot be judged live or retired, so no set can say what keeping, replacing or omitting it would do: every set is refused CUSTOM_ROLE_UNREADABLE until the row is repaired in the database (remove does not help: it tombstones the row, and the tombstone still does not decode). Every change, one revision bump and one policy audit event per change (custom_role.defined or custom_role.deleted) are written by one writeTenantRoleSet call, fenced on expectedRevision and on the generation the checks used: a define, remove, set or policy publish that commits between the set’s reads and its write makes it answer REVISION_CONFLICT or GENERATION_CONFLICT and write nothing; it never interleaves with them. A set that changes nothing writes nothing and answers UNCHANGED with the revision it read; it holds no fence, so a change committed after that read is not reported. set is present only when the instance’s policy store implements writeTenantRoleSet, as the memory, SQLite and PostgreSQL stores do.

CustomRoleSetInput

interface CustomRoleSetInput {
  readonly tenantId: string;
  readonly roles: readonly CustomRoleSetEntry[];
  readonly expectedRevision: string;
  readonly expectedGeneration?: string;
  readonly actor: ResourceRef;
}

One set call: the tenant, the complete desired set of live roles, the revision it was decided from, and the actor recorded on every change. With expectedGeneration (for example list()’s generation), the set answers GENERATION_CONFLICT and writes nothing unless it validates under exactly that generation; a present value that is not a string conflicts too. Before any role is checked, the named generation is compared with the store’s active generation, not with the instance’s cached view (which is reloaded when the store has moved on), so every refusal is computed under exactly the generation the caller named: after a publish through another instance the answer is GENERATION_CONFLICT, never a refusal computed under either policy. Without it, the set validates under whatever generation is active after its refresh.

CustomRoleSetEntry

interface CustomRoleSetEntry {
  readonly resourceType: string;
  readonly name: CustomRoleLabel;
  readonly template: string;
  readonly rules: readonly PolicyRule[];
}

One role of a set, as define takes it.

CustomRoleSetResult

type CustomRoleSetResult =
  | { readonly ok: true; readonly code: "SET" | "UNCHANGED"; readonly revision: string }
  | {
      readonly ok: false;
      readonly code: "CEILING_EXCEEDED";
      readonly role: CustomRoleSetRoleRef;
      readonly permissions: readonly string[];
    }
  | {
      readonly ok: false;
      readonly code: "CUSTOM_ROLE_INVALID";
      readonly reason: "name" | "rules" | "limits" | "duplicate";
      readonly role?: CustomRoleSetRoleRef;
    }
  | {
      readonly ok: false;
      readonly code:
        | "UNKNOWN_RESOURCE_TYPE"
        | "TEMPLATE_UNKNOWN"
        | "CUSTOM_ROLE_NAME_RETIRED"
        | "CUSTOM_ROLE_UNREADABLE";
      readonly role: CustomRoleSetRoleRef;
    }
  | {
      readonly ok: false;
      readonly code:
        | "INVALID_TENANT"
        | "INVALID_ACTOR"
        | "INVALID_ROLES"
        | "TOO_MANY_CUSTOM_ROLES"
        | "REVISION_CONFLICT"
        | "GENERATION_CONFLICT"
        | "REVISION_EXHAUSTED";
    };

SET with the new revision, UNCHANGED with the revision read, or the first refusal. The store’s conflict, and a retired, not_found or too_many that the checks above already ruled out at the revision read, answer REVISION_CONFLICT; nothing was written.

CustomRoleSetRoleRef

interface CustomRoleSetRoleRef {
  readonly resourceType: string;
  readonly name: string;
}

The role a set refusal is about.

ActivePolicyState

interface ActivePolicyState {
  readonly generation: string;
  readonly digest: string;
  readonly label?: string;
  readonly confirmedAt: Date;
  readonly seedMatchesActive: boolean;
}

The active generation, digest, label, when it was confirmed, and whether the code seed still matches.

ImpactInput

type ImpactInput = {
  readonly candidate: string;
  readonly tenantId: string;
} & (
  | {
      readonly pairs: readonly {
        readonly subject: ResourceRef;
        readonly resource: ResourceKey;
      }[];
    }
  | {
      readonly sample: {
        readonly subjects: readonly ResourceRef[];
        readonly resourceType: string;
        readonly perSubjectLimit: number;
      };
    }
);

Explicit subject and resource pairs, or a sample of subjects and a resource type.

ImpactChange

interface ImpactChange {
  readonly subject: ResourceRef;
  readonly resource: ResourceKey;
  readonly label: string;
  readonly permission: string;
  readonly before: {
    readonly allowed: boolean;
    readonly code: string;
  };
  readonly after: {
    readonly allowed: boolean;
    readonly code: string;
  };
}

One decision that changes between the active and the candidate policy.

ImpactResult

type ImpactResult =
  | {
      readonly ok: true;
      readonly code: "PREVIEWED";
      readonly active: {
        readonly generation: string;
        readonly digest: string;
      };
      readonly candidate: {
        readonly digest: string;
      };
      readonly exhaustive: boolean;
      readonly changes: readonly ImpactChange[];
      readonly unevaluable: readonly {
        readonly subject: ResourceRef;
        readonly resource?: ResourceKey;
        readonly reason: "SUBJECT_INELIGIBLE" | "RESOURCE_NOT_FOUND";
      }[];
      readonly summary: {
        readonly pairsEvaluated: number;
        readonly grantsGained: number;
        readonly grantsLost: number;
        readonly subjectsGaining: number;
        readonly subjectsLosing: number;
      };
      readonly customRolesLosingAvailability: readonly CustomRoleLabel[];
    }
  | {
      readonly ok: false;
      readonly code:
        | "PREVIEW_TOO_LARGE"
        | "INVALID_PREVIEW_INPUT"
        | "VERSION_NOT_FOUND"
        | "VERSION_CORRUPT"
        | "DEFINITION_INCOMPATIBLE";
    };

The changes, the pairs that could not be evaluated, a summary, and custom roles losing availability.

CustomRolePreviewInput

interface CustomRolePreviewInput {
  readonly candidate: string;
  readonly limit: number;
  readonly cursor?: string;
}

A candidate digest and a page of tenants.

CustomRolePreviewResult

type CustomRolePreviewResult =
  | {
      readonly ok: true;
      readonly code: "PREVIEWED";
      readonly tenants: readonly {
        readonly tenantId: string;
        readonly roles: readonly {
          readonly resourceType: string;
          readonly name: CustomRoleLabel;
          readonly activeStatus: CustomRoleStatus;
          readonly candidateStatus: CustomRoleStatus;
          readonly permissionsAboveTemplate?: readonly string[];
        }[];
      }[];
      readonly nextCursor?: string;
    }
  | {
      readonly ok: false;
      readonly code: "VERSION_NOT_FOUND" | "VERSION_CORRUPT" | "DEFINITION_INCOMPATIBLE";
    };

Per tenant, each custom role’s status under the active and the candidate policy.

CustomRoleStatus

type CustomRoleStatus =
  | "available"
  | "retired"
  | "template_missing"
  | "invalid"
  | "exceeds_template";

CustomRoleView

interface CustomRoleView {
  readonly resourceType: string;
  readonly name: CustomRoleLabel;
  readonly template: string;
  readonly rules: readonly PolicyRule[];
  readonly effectiveRules: readonly PolicyRule[];
  readonly status: CustomRoleStatus;
  readonly permissionsAboveTemplate?: readonly string[];
  readonly definedAtRevision: string;
  readonly createdAt: Date;
  readonly createdBy: ResourceRef;
  readonly updatedAt: Date;
  readonly updatedBy: ResourceRef;
  readonly deletedAt?: Date;
}

One custom role as listed, with its status and, for exceeds_template, the permissions above it.

CustomRoleLabel

type CustomRoleLabel = `custom:${string}`;

A custom:<name> label. Valid names match CUSTOM_ROLE_LABEL.

policyDigest

function policyDigest(policy: RolebookPolicy): string;

sha256: plus the hex SHA-256 of the policy’s canonical JSON. The version label is excluded.

parseCounter

function parseCounter(value: unknown): bigint | undefined;

A decimal generation or revision as a bigint, or undefined when it is not a canonical counter within MAX_POLICY_COUNTER.

Policy store

PolicyStore

interface PolicyStore {
  readActivePointer(): Promise<ActivePolicyPointer>;
  readVersion(input: { readonly digest: string }): Promise<StoredPolicyVersion | undefined>;
  listVersions(input: { readonly limit: number; readonly cursor?: string }): Promise<{
    readonly versions: readonly PolicyVersionSummary[];
    readonly nextCursor?: string;
  }>;
  listActivations(input: { readonly limit: number; readonly cursor?: string }): Promise<{
    readonly activations: readonly PolicyActivation[];
    readonly nextCursor?: string;
  }>;
  saveVersion(input: {
    readonly version: StoredPolicyVersion;
    readonly audit: PolicyAuditEvent;
  }): Promise<"saved" | "exists">;
  activate(input: {
    readonly digest: string;
    readonly expectedGeneration: string;
    readonly activatedAt: Date;
    readonly activatedBy: ResourceRef;
    readonly audit: PolicyAuditEvent;
  }): Promise<
    | {
        readonly status: "activated";
        readonly generation: string;
      }
    | {
        readonly status: "conflict";
        readonly generation: string;
      }
    | {
        readonly status: "already_active";
        readonly generation: string;
      }
    | {
        readonly status: "not_found";
      }
    | {
        readonly status: "exhausted";
      }
  >;
  readTenantRolesRevision(input: { readonly tenantId: string }): Promise<string>;
  readTenantRoles(input: { readonly tenantId: string }): Promise<TenantCustomRoles>;
  writeTenantRole(input: {
    readonly role: Omit<StoredCustomRole, "definedAtRevision" | "deletedAt">;
    readonly expectedRevision: string;
    readonly expectedGeneration: string;
    readonly audit: PolicyAuditEvent;
  }): Promise<
    | {
        readonly status: "applied";
        readonly revision: string;
      }
    | {
        readonly status: "conflict";
      }
    | {
        readonly status: "generation_conflict";
      }
    | {
        readonly status: "retired";
      }
    | {
        readonly status: "too_many";
      }
    | {
        readonly status: "exhausted";
      }
  >;
  deleteTenantRole(input: {
    readonly tenantId: string;
    readonly resourceType: string;
    readonly name: CustomRoleLabel;
    readonly expectedRevision: string;
    readonly deletedAt: Date;
    readonly deletedBy: ResourceRef;
    readonly audit: PolicyAuditEvent;
  }): Promise<
    | {
        readonly status: "applied";
        readonly revision: string;
      }
    | {
        readonly status: "conflict";
      }
    | {
        readonly status: "not_found";
      }
    | {
        readonly status: "exhausted";
      }
  >;
  writeTenantRoleSet?(input: TenantRoleSetWrite): Promise<
    | { readonly status: "applied"; readonly revision: string }
    | { readonly status: "conflict" }
    | { readonly status: "generation_conflict" }
    | { readonly status: "retired" }
    | { readonly status: "not_found" }
    | { readonly status: "too_many" }
    | { readonly status: "exhausted" }
  >;
  listAudit(input: {
    readonly limit: number;
    readonly cursor?: string;
    readonly tenantId?: string;
  }): Promise<{
    readonly events: readonly PolicyAuditEvent[];
    readonly nextCursor?: string;
  }>;
  listTenantsWithCustomRoles(input: { readonly limit: number; readonly cursor?: string }): Promise<{
    readonly tenantIds: readonly string[];
    readonly nextCursor?: string;
  }>;
}

The policy store contract: the active pointer, versions, activations, tenant custom roles, the policy audit, and tenant listing. activate, writeTenantRole, deleteTenantRole, and writeTenantRoleSet compare-and-swap. The first-party stores are createPostgresPolicyStore, createSqlitePolicyStore, and createMemoryPolicyStore; each implements the optional writeTenantRoleSet.

writeTenantRoleSet applies several role changes as one write: every define (insert or replace a live role) and remove (tombstone a live role), one revision bump and every audit event commit in one transaction, or nothing does. It compares the active generation and then the tenant’s revision before anything else, under the same locks writeTenantRole takes (on PostgreSQL the pointer FOR SHARE and the revision row FOR UPDATE; on SQLite one BEGIN IMMEDIATE transaction), so a concurrent role write or publish answers generation_conflict or conflict. Only then is a define of a tombstone retired, a remove of no live role not_found, and a result over the live or record limit too_many. Every defined role’s definedAtRevision is the new revision; a removed role keeps its own, as deleteTenantRole leaves it. The SQLite and PostgreSQL stores decide every refusal before they create a tenant’s first revision row, so any answer other than applied leaves the store exactly as it was. A store without it leaves customRoles.set absent; policyStoreContract in @rolebook/sharing-testkit fails for such a store.

TenantRoleSetWrite

interface TenantRoleSetWrite {
  readonly tenantId: string;
  readonly define: readonly Omit<StoredCustomRole, "definedAtRevision" | "deletedAt">[];
  readonly remove: readonly { readonly resourceType: string; readonly name: CustomRoleLabel }[];
  readonly expectedRevision: string;
  readonly expectedGeneration: string;
  readonly removedAt: Date;
  readonly removedBy: ResourceRef;
  readonly audit: readonly PolicyAuditEvent[];
}

One writeTenantRoleSet call. removedAt and removedBy are the tombstone time and actor of every removed role; audit holds one event per change.

assertTenantRoleSetWrite

function assertTenantRoleSetWrite(input: TenantRoleSetWrite): void;

The input rules every store applies before it writes: a valid tenant id, at least one change, each (resourceType, name) at most once across both lists and a valid custom-role name, every defined role in the call’s tenant, and exactly one audit event per change, each passing assertPolicyAuditEventFields, naming that tenant, that change’s resource type and role name as strings, and custom_role.defined for a definition or custom_role.deleted for a removal; every change must be matched by exactly one event. Nothing is written when a rule fails. An invalid tenant ID, on the call or on an event, throws PolicyAdministrationError with code INVALID_TENANT; any other invalid audit event field throws PolicyAdministrationError with code INVALID_AUDIT_EVENT; every other failure (no change, a role named twice, an invalid role name, a role or event in another tenant, an event that names no role change or matches no change, a change with no event) throws TypeError.

ActivePolicyPointer

interface ActivePolicyPointer {
  readonly generation: string;
  readonly digest: string | null;
}

The active generation and digest; the digest is null exactly at generation "0".

StoredPolicyVersion

interface StoredPolicyVersion {
  readonly digest: string;
  readonly document: string;
  readonly label?: string;
  readonly createdAt: Date;
  readonly createdBy: ResourceRef;
}

A stored version: digest, canonical document, optional label, creation.

PolicyVersionSummary

type PolicyVersionSummary = Omit<StoredPolicyVersion, "document">;

A stored version without its document.

PolicyActivation

interface PolicyActivation {
  readonly generation: string;
  readonly digest: string;
  readonly activatedAt: Date;
  readonly activatedBy: ResourceRef;
}

One activation: generation, digest, when, and by whom.

StoredCustomRole

interface StoredCustomRole {
  readonly tenantId: string;
  readonly resourceType: string;
  readonly name: CustomRoleLabel;
  readonly template: string;
  readonly rules: string;
  readonly definedAtRevision: string;
  readonly createdAt: Date;
  readonly createdBy: ResourceRef;
  readonly updatedAt: Date;
  readonly updatedBy: ResourceRef;
  readonly deletedAt?: Date;
}

A stored custom role row, including tombstones.

UndecodableCustomRole

interface UndecodableCustomRole {
  readonly resourceType: string;
  readonly name: string;
  readonly undecodable: true;
}

An identifiable custom-role row whose other columns do not decode.

TenantCustomRoles

interface TenantCustomRoles {
  readonly revision: string;
  readonly roles: readonly (StoredCustomRole | UndecodableCustomRole)[];
}

A tenant’s custom-role revision and every row, tombstones included.

ExpectedPolicy

interface ExpectedPolicy {
  readonly generation: string;
  readonly tenantRolesRevision: string;
}

The generation and tenant-role revision a versioned mutation started under.

PolicyFenceResult

type PolicyFenceResult = true | "policy_generation_changed" | "tenant_roles_changed";

true, or why a versioned mutation’s policy no longer holds.

PolicyAuditEvent

interface PolicyAuditEvent {
  readonly id: string;
  readonly tenantId?: string;
  readonly action:
    | "policy.version_saved"
    | "policy.activated"
    | "custom_role.defined"
    | "custom_role.deleted";
  readonly digest?: string;
  readonly generation?: string;
  readonly resourceType?: string;
  readonly roleName?: string;
  readonly actor: ResourceRef;
  readonly occurredAt: Date;
}

One policy-administration audit event.

createMemoryPolicyStore

function createMemoryPolicyStore(): MemoryPolicyStore;

An in-memory PolicyStore for tests, with a synchronous fence for the memory adapter.

MemoryPolicyStore

interface MemoryPolicyStore extends PolicyStore {
  fence(input: {
    readonly tenantId: string;
    readonly expectedPolicy: ExpectedPolicy;
  }): PolicyFenceResult;
  failWith(error: Error | undefined): void;
  readAudit(): readonly PolicyAuditEvent[];
  setCounters(input: {
    readonly generation?: string;
    readonly tenantRevisions?: Readonly<Record<string, string>>;
  }): void;
  failNextAudit(): void;
}

The memory store, with fence, failWith, readAudit, setCounters, and failNextAudit.

assertPolicyTenantId

function assertPolicyTenantId(tenantId: unknown): asserts tenantId is string;

Throws PolicyAdministrationError (INVALID_TENANT) unless the value is a valid opaque ID.

assertPolicyAuditEvent

function assertPolicyAuditEvent(event: Pick<PolicyAuditEvent, "id" | "tenantId">): void;

Throws PolicyAdministrationError for an audit ID or tenant ID a policy cursor cannot carry.

assertPolicyAuditEventFields

function assertPolicyAuditEventFields(event: PolicyAuditEvent): void;

Every field of a policy audit event: assertPolicyAuditEvent’s ID and tenant ID, a known action, an actor whose type and id are opaque IDs, an occurredAt that is a valid Date, and, when present, a POLICY_DIGEST digest, a POLICY_GENERATION generation of at most MAX_POLICY_COUNTER, and string resourceType and roleName. An invalid tenant ID throws PolicyAdministrationError with code INVALID_TENANT; any other invalid field, the ID included, throws PolicyAdministrationError with code INVALID_AUDIT_EVENT. writeTenantRole, deleteTenantRole and assertTenantRoleSetWrite apply it to every event, in the memory, SQLite and PostgreSQL stores, before anything is written.

assertPolicyDigest

function assertPolicyDigest(digest: unknown): asserts digest is string;

Throws PolicyAdministrationError (INVALID_DIGEST) unless the value matches POLICY_DIGEST.

Hierarchy command configuration

The command map the hierarchy control facades of @rolebook/sharing-postgres and @rolebook/sharing-sqlite run. See inherited access.

defineHierarchyCommands

function defineHierarchyCommands(policy: RolebookPolicy, graph: HierarchyTypeGraph, input: HierarchyCommandsInput): HierarchyCommands;

Validates a hierarchy command configuration against a policy and its hierarchy type graph and returns it frozen. Configured actions must be concrete, declared and distinct, and the bootstrap type is restricted. Validation alone enables nothing; the control facades validate the same map.

HierarchyCommandsInput

interface HierarchyCommandsInput {
  readonly bootstrap: {
    readonly type: string;
    readonly actions: Readonly<Record<HierarchyBootstrapAction, string>>;
  };
  readonly types: Readonly<Record<string, HierarchyTypeCommands>>;
}

The configuration defineHierarchyCommands validates: the bootstrap authority type with one action per HierarchyBootstrapAction, and the structural actions of each hierarchy type.

HierarchyCommands

interface HierarchyCommands {
  readonly bootstrap: HierarchyCommandsInput["bootstrap"];
  readonly types: Readonly<Record<string, HierarchyTypeCommands>>;
}

The validated, frozen configuration.

HierarchyTypeCommands

interface HierarchyTypeCommands {
  readonly delete: string;
  readonly move: string;
  readonly createChild?: string;
  readonly addChild?: string;
  readonly removeChild?: string;
}

The actions that authorize deleting or moving a resource of a type, and creating, adding or removing its children.

HierarchyBootstrapAction

type HierarchyBootstrapAction = (typeof HIERARCHY_BOOTSTRAP_ACTIONS)[number];

One bootstrap action name.

HIERARCHY_BOOTSTRAP_ACTIONS

const HIERARCHY_BOOTSTRAP_ACTIONS: readonly [
  "rootCreate",
  "rootPlacement",
  "enrollment",
  "activation",
  "quarantineRelease",
  "heightRepair"
];

Every bootstrap action a configuration must map.

HierarchyTypeGraph

interface HierarchyTypeGraph {
  declared(type: string): boolean;
  parentOf(type: string): string | undefined;
  recursive(type: string): boolean;
}

The immutable hierarchy type graph of a policy: which types it declares, each type’s declared parent, and whether a type may nest under itself. Build it with hierarchyTypeGraph; it exposes no store, lock, issuer or control state.

hierarchyTypeGraph

function hierarchyTypeGraph(resources: Readonly<Record<string, ResourceDefinition>>): HierarchyTypeGraph;

Builds the graph from a validated policy’s resources. Pass the same policy to defineHierarchyCommands: defineHierarchyCommands(policy, hierarchyTypeGraph(policy.resources), input).

HierarchyConfigurationError

class HierarchyConfigurationError extends TypeError {
  constructor(message: string);
}

Thrown by defineHierarchyCommands for an invalid configuration.

hierarchyConfigurationGeneration

function hierarchyConfigurationGeneration(input: {
  readonly label: string;
  readonly definition: SharingDefinition;
  readonly commands: HierarchyCommandsInput;
}): string;

The configuration generation of one inherited-access deployment: `${label}#cmd-${digest}`, where the digest binds the validated command map and each type’s management.members. Pass the same value to the adapter’s enable…InheritedReads and to its hierarchy control facade. The command types must be exactly the types with inheritance: "ancestors". label is 1 to 48 characters of letters, digits, ., _ and -; change it to force re-activation.

InheritanceConfigurationError

class InheritanceConfigurationError extends TypeError {
  constructor(message: string);
}

Thrown when the hierarchy command types and the opted-in types differ, or no type opted in.

Limits

MAX_OPAQUE_ID_LENGTH

const MAX_OPAQUE_ID_LENGTH = 128;

The longest tenant, resource, subject, idempotency, and cursor ID: 128 characters.

MAX_INVITATION_EMAIL_LENGTH

const MAX_INVITATION_EMAIL_LENGTH = 320;

The longest invitation email address: 320 characters.

MAX_GROUP_PRINCIPALS

const MAX_GROUP_PRINCIPALS: typeof MAX_PRINCIPALS;

The most groups one principal may carry: Rolebook’s MAX_PRINCIPALS (64).

MAX_ACCESS_BATCH_SIZE

const MAX_ACCESS_BATCH_SIZE = 200;

The most resource IDs one readAccessBatch call accepts.

MAX_CANDIDATE_HINT_SIZE

const MAX_CANDIDATE_HINT_SIZE = 256;

The most resource-scoped candidate hints, and member-role hints, one listing sends.

MAX_AUDIT_PAGE_LIMIT

const MAX_AUDIT_PAGE_LIMIT = 100;

The largest limit of auditHistory() and listAuditEvents.

MAX_AUDIT_CURSOR_LENGTH

const MAX_AUDIT_CURSOR_LENGTH = 512;

The longest raw cursor listAuditEvents may issue or receive.

MAX_AUDIT_EVENT_ID_LENGTH

const MAX_AUDIT_EVENT_ID_LENGTH = 256;

The longest audit event ID read back.

MAX_POLICY_CURSOR_LENGTH

const MAX_POLICY_CURSOR_LENGTH: number;

The longest policy-store cursor a first-party store issues; longer input is rejected.

MAX_POLICY_DOCUMENT_BYTES

const MAX_POLICY_DOCUMENT_BYTES = 1048576;

The largest stored policy document: 1 MiB.

MAX_POLICY_LABEL_LENGTH

const MAX_POLICY_LABEL_LENGTH = 128;

The longest version label.

MAX_POLICY_PAGE_LIMIT

const MAX_POLICY_PAGE_LIMIT = 100;

The largest page of versions, activations, or policy audit.

MAX_CUSTOM_ROLES_PER_TENANT

const MAX_CUSTOM_ROLES_PER_TENANT = 32;

Available, exceeding, and invalid custom roles per tenant.

MAX_CUSTOM_ROLE_RECORDS_PER_TENANT

const MAX_CUSTOM_ROLE_RECORDS_PER_TENANT = 256;

Custom-role rows per tenant, tombstones included.

MAX_CUSTOM_ROLE_RULES

const MAX_CUSTOM_ROLE_RULES = 64;

Operator rules on one custom role.

MAX_IMPACT_PAIRS

const MAX_IMPACT_PAIRS = 200;

Pairs one impact preview evaluates.

MAX_IMPACT_SUBJECTS

const MAX_IMPACT_SUBJECTS = 20;

Subjects one sampled impact preview takes.

MAX_IMPACT_CANDIDATES_PER_SUBJECT

const MAX_IMPACT_CANDIDATES_PER_SUBJECT = 50;

Candidate resources per sampled subject.

MAX_POLICY_COUNTER

const MAX_POLICY_COUNTER = 9223372036854775807n;

The largest generation or revision.

CUSTOM_ROLE_LABEL

const CUSTOM_ROLE_LABEL: RegExp;

/^custom:[a-z][a-z0-9_]{0,47}$/

CUSTOM_POLICY_ROLE_PREFIX

const CUSTOM_POLICY_ROLE_PREFIX = "rolebook.custom.";

The reserved prefix of derived custom-role policy roles. Published policies may not use it.

POLICY_DIGEST

const POLICY_DIGEST: RegExp;

/^sha256:[0-9a-f]{64}$/

POLICY_GENERATION

const POLICY_GENERATION: RegExp;

/^(0|[1-9][0-9]{0,18})$/; callers also require the value to be at most MAX_POLICY_COUNTER.

Decision metadata 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.

AuthorityRevision

interface AuthorityRevision {
    readonly domain: "policy" | "tenantRoles" | "sharing" | "identityProjection" | "groupMembership";
    /** Identifies the revision's scope (a resource for sharing, not a global counter). */
    readonly scope: string;
    /** Decimal or source-owned revision; compare only within the same domain/scope/epoch. */
    readonly revision: string;
}

A revision in one authority domain and scope. Compare it only within that same domain, scope and authority epoch; a resource sharing revision is not a global checkpoint.

AchievedConsistency

type AchievedConsistency = {
    readonly mode: "consistentLocalSnapshot";
    /** Opaque database snapshot identity, not an atLeast checkpoint. */
    readonly snapshotId: string;
    readonly snapshotObservedAt: string;
} | {
    readonly mode: "boundedStale";
    readonly authorityReadAt: string;
    readonly maxAgeMs: number;
};

Describes the consistency actually established by the producer. A local snapshot ID is opaque evidence, not a reusable checkpoint. Bounded-stale evidence records the authority read time and maximum permitted age; it does not attest remote identity freshness.

AuthorizationDecisionMetadata

interface AuthorizationDecisionMetadata {
    readonly schemaVersion: 1;
    readonly scopeId: string;
    readonly authorityEpoch: string;
    readonly policyVersion: string;
    readonly revisions: readonly AuthorityRevision[];
    readonly evaluatedAt: string;
    readonly consistency: AchievedConsistency;
}

Versioned internal/operator evidence for a decision. This is descriptive metadata, not a bearer capability, and must not be automatically serialized to untrusted clients.

ConsistencyUnavailableReason

type ConsistencyUnavailableReason = "unsupported_mode" | "unsupported_isolation" | "dependency_unavailable" | "unmet_floor" | "incompatible_checkpoint" | "projection_expired";

The reason requested consistency could not be established. These variants describe refusal conditions; their presence does not mean every consistency mode has an implementation.

ConsistencyUnavailableError

class ConsistencyUnavailableError extends Error {
    readonly reason: ConsistencyUnavailableReason;
    readonly code: "CONSISTENCY_UNAVAILABLE";
    constructor(reason: ConsistencyUnavailableReason);
}

Reports CONSISTENCY_UNAVAILABLE with a structured reason. Callers must treat unavailable consistency as a refusal rather than falling back to a stale allow.

captureAuthorizationDecisionMetadata

function captureAuthorizationDecisionMetadata(value: unknown): AuthorizationDecisionMetadata;

Validates the version-one metadata contract, copies JSON-compatible values and freezes the captured evidence. Rejects malformed fields, unsupported domains, invalid timestamps and bounded-staleness evidence outside its permitted age window with a TypeError. It validates supplied evidence; it does not establish the authority of the producer.

compareBatchResource

function compareBatchResource(left: {
    readonly id: string;
}, right: {
    readonly id: string;
}): number;

UTF-16 code-unit order of resource ids. Batch capture, target locks, the stored result, version-3 targets and the decoder use this comparison. Locale and database collation do not.

compareAuthorityRevisionIdentity

function compareAuthorityRevisionIdentity(left: {
    readonly domain: string;
    readonly scope: string;
}, right: {
    readonly domain: string;
    readonly scope: string;
}): number;

UTF-16 order of JSON.stringify([domain, scope]), the order of a version-3 revision union.

decisionMetadataUtf8Bytes

function decisionMetadataUtf8Bytes(value: unknown): number;

Canonical UTF-8 size of decision metadata. The version-3 cap is this length, not a column’s physical width.

HIERARCHY_BATCH_METADATA_MAX_BYTES

const HIERARCHY_BATCH_METADATA_MAX_BYTES = 262144;

256 KiB. 262,144 canonical UTF-8 bytes passes; 262,145 fails on both write and decode.

HierarchyBatchAuthorizationDecisionMetadata

interface HierarchyBatchAuthorizationDecisionMetadata extends Omit<AuthorizationDecisionMetadata, "schemaVersion"> {
    readonly schemaVersion: 3;
    readonly targets: readonly {
        readonly resource: {
            readonly type: string;
            readonly id: string;
        };
        readonly hierarchy: HierarchyDecisionEvidence;
    }[];
}

Stored metadata version 3 for an enrolled batch of 2–32 targets. schemaVersion is a metadata version, not a journal-table schema. Each hierarchy block is evidence for its own target, not a capability. There is no top-level hierarchy.

captureHierarchyBatchDecisionMetadata

function captureHierarchyBatchDecisionMetadata(value: unknown): HierarchyBatchAuthorizationDecisionMetadata;

Captures metadata version 3. It checks nested version-2 evidence, canonical target and revision order, and the 256 KiB canonical UTF-8 cap. It does not read admission, policy, or the clock. A non-null validUntil is compared only with the stored evaluatedAt.

assertHierarchyBatchReceiptResult

function assertHierarchyBatchReceiptResult(result: unknown, metadata: HierarchyBatchAuthorizationDecisionMetadata): void;

Aligns a stored batch result with stored version-3 targets. It compares only those stored values.

assertSameProtectedAdmissionBundle

function assertSameProtectedAdmissionBundle(captured: HierarchyAdmissionRow, current: HierarchyAdmissionRow): void;

The final enrolled-batch admission fence. The batch-receipt floor, epoch, profile, and bootstrap authority must still equal the bundle captured before the first target effect.

OutboxDeliveryEvent

interface OutboxDeliveryEvent {
  readonly environmentId: string;
  readonly eventId: string;
  readonly kind: string;
  readonly payload: unknown;
}

Immutable sink envelope. Deduplicate external effects by environmentId/eventId; the trusted port supplies an immutable payload.

OutboxDeliveryToken

interface OutboxDeliveryToken {
  readonly environmentId: string;
  readonly eventId: string;
  readonly generation: string;
}

Exact environment/event/generation storage fence. It is not a sink deduplication key or authentication credential.

OutboxDeliveryClaim

interface OutboxDeliveryClaim {
  readonly eventId: string;
  readonly kind: string;
  readonly payload: unknown;
  readonly deliveryToken: OutboxDeliveryToken;
}

Trusted committed event and current delivery token returned after the claim transaction releases its connection.

OutboxDeliveryPort

interface OutboxDeliveryPort {
  claim(input: {
    readonly limit: number;
    readonly leaseMs: number;
  }): Promise<readonly OutboxDeliveryClaim[]>;
  acknowledge(token: OutboxDeliveryToken): Promise<boolean>;
  retry(token: OutboxDeliveryToken, input: {
    readonly delayMs: number;
  }): Promise<boolean>;
  quarantine(token: OutboxDeliveryToken, input: {
    readonly reason: string;
  }): Promise<OutboxDeliveryToken | undefined>;
}

Trusted storage interface used by the shared worker. Claim must release its transaction and return immutable payload snapshots; settlement methods must enforce exact current-token eligibility. First-party SQL outboxes implement this port.

OutboxDeliveryDecision

type OutboxDeliveryDecision = {
  readonly status: "delivered";
} | {
  readonly status: "retry";
  readonly delayMs: number;
} | {
  readonly status: "quarantine";
  readonly reason: string;
} | {
  readonly status: "unresolved";
};

Explicit caller policy. Only delivered permits ACK; retry delay is an integer0–300000ms; quarantine reason is nonblank, at most1024 characters, and contains no NUL. Exceptions, malformed decisions and unresolved outcomes cause no storage settlement.

OutboxDeliverySink

type OutboxDeliverySink = (event: OutboxDeliveryEvent, input: {
  readonly signal: AbortSignal;
}) => Promise<OutboxDeliveryDecision>;

Caller-supplied sink invoked outside the claim transaction. The signal requests cooperative cancellation; external effects are not undone. Return a plain data decision and deduplicate by environment/event.

OutboxDeliveryOptions

interface OutboxDeliveryOptions {
  readonly batchSize: number;
  readonly leaseMs: number;
  readonly deliveryTimeoutMs: number;
  readonly deliver: OutboxDeliverySink;
  readonly diagnostics?: OutboxDeliveryDiagnosticsOptions | undefined;
}

Required finite integer bounds: batchSize1–32, leaseMs1–300000, deliveryTimeoutMs1–leaseMs. Callback reference and options are captured at construction. diagnostics is optional; the PostgreSQL and SQLite facades forward it.

OutboxDeliveryOutcome

type OutboxDeliveryOutcome = {
  readonly environmentId: string;
  readonly eventId: string;
  readonly generation: string;
} & ({
  readonly status: "acknowledged" | "retried" | "quarantined" | "stale";
} | {
  readonly status: "unresolved";
  readonly reason: "sink-error" | "invalid-result" | "sink-unresolved" | "aborted" | "timeout" | "settlement-error";
});

Frozen identity and status in claim order. Unresolved reasons describe uncertainty without raw exceptions or payloads. Stale means the original token was no longer eligible. An ambiguous ACK can already have committed.

OutboxDeliveryBatch

interface OutboxDeliveryBatch {
  readonly stopped: boolean;
  readonly outcomes: readonly OutboxDeliveryOutcome[];
}

Frozen bounded per-pass report. stopped records cancellation/timeout; a previously submitted settlement may still have a known successful outcome.

OutboxDeliveryWorker

interface OutboxDeliveryWorker {
  runOnce(input?: {
    readonly signal?: AbortSignal;
  }): Promise<OutboxDeliveryBatch>;
}

One claim call per run, no refill/daemon/lease renewal. Overlapping runs reject before claiming, including while an abandoned sink is still pending. Sink calls are concurrent; settlements are serialized and check cancellation before submission.

createOutboxDeliveryWorker

function createOutboxDeliveryWorker(options: OutboxDeliveryOptions & {
  readonly outbox: OutboxDeliveryPort;
}): OutboxDeliveryWorkerWithDiagnostics;

Creates a bounded run-once worker over a trusted storage port. Claim errors throw a generic reconciliation error; no automatic retries or classifications are made. Database calls use executor time limits. Invalid diagnostics options throw a TypeError at construction. See bounded delivery for cancellation, late effects, queued settlement, diagnostics and source-compatible SQL facades.

OutboxDeliveryWorkerWithDiagnostics

interface OutboxDeliveryWorkerWithDiagnostics extends OutboxDeliveryWorker {
  diagnostics(): OutboxDeliveryDiagnostics;
}

The value createOutboxDeliveryWorker and the PostgreSQL and SQLite delivery facades return; existing OutboxDeliveryWorker implementations are unaffected. diagnostics() is available with or without an observer and never changes run admission or settlement. runOnce resolves and rejects as without diagnostics: a failure rethrows the identical exception, and a floating rejected run is still an unhandled rejection.

OutboxDeliveryDiagnosticsOptions

interface OutboxDeliveryDiagnosticsOptions {
  readonly observe: OutboxDeliveryObserver;
  readonly queueLimit?: number;
  readonly observerTimeoutMs?: number;
}

Optional observer configuration, validated and captured at construction. queueLimit is an integer 1–1024 and observerTimeoutMs an integer 1–60000; omitting either uses its default, while null or an unknown key throws. The defaults are configuration choices, not performance claims.

DEFAULT_OUTBOX_OBSERVER_QUEUE_LIMIT

const DEFAULT_OUTBOX_OBSERVER_QUEUE_LIMIT: number;

64 observations.

DEFAULT_OUTBOX_OBSERVER_TIMEOUT_MS

const DEFAULT_OUTBOX_OBSERVER_TIMEOUT_MS: number;

1,000 ms.

OutboxDeliveryObserver

type OutboxDeliveryObserver = (observation: OutboxDeliveryObservation) => void | PromiseLike<void>;

Called asynchronously after a run settles, at most one call at a time, as a plain function (this is undefined; bind a class method yourself) with the observation as its only argument. Throws, rejections and timeouts are counted, never propagated. A call counts as timed out once when the timer fires first or when its measured duration exceeded observerTimeoutMs at settlement, which is how synchronous overruns are counted. The timeout only reports: nothing cancels the call, and it keeps the single slot until it settles. Return or yield promptly; same-process code cannot preempt synchronous CPU work.

OutboxDeliveryObservation

interface OutboxDeliveryObservation {
  readonly type: "run";
  readonly sequence: number;
  readonly result: OutboxDeliveryRunResult;
  readonly claimed: number;
  readonly acknowledged: number;
  readonly retried: number;
  readonly quarantined: number;
  readonly stale: number;
  readonly unresolved: number;
  readonly unresolvedReasons: Readonly<Record<OutboxDeliveryUnresolvedReason, number>>;
}

Frozen per-run counts. No environment, event, tenant or subject identifier, generation, kind, payload, exception text or quarantine reason. sequence is a local per-worker ordinal; a gap means observations were dropped. claimed counts claims this pass processed; 0 after claim-failed does not prove that no lease was taken.

OutboxDeliveryRunResult

type OutboxDeliveryRunResult = "completed" | "stopped" | "busy" | "invalid-input" | "claim-failed" | "claim-overflow";

How one runOnce call ended on this worker. claim-failed: the claim call failed or returned a malformed batch, so leases may have committed. claim-overflow: the claim returned more than batchSize rows. invalid-input: the caller’s input or signal was rejected before the claim.

OutboxDeliveryUnresolvedReason

type OutboxDeliveryUnresolvedReason = Extract<OutboxDeliveryOutcome, {
  status: "unresolved";
}>["reason"];

The six unresolved reasons of OutboxDeliveryOutcome.

OutboxDeliveryDiagnostics

interface OutboxDeliveryDiagnostics {
  readonly scope: "worker-local";
  readonly worker: "idle" | "running" | "draining";
  readonly detachedSinks: number;
  readonly delivery: "no-runs" | "clear" | "attention";
  readonly lastRun: OutboxDeliveryObservation | null;
  readonly totals: {
    readonly runs: Readonly<Record<OutboxDeliveryRunResult, number>>;
    readonly claimed: number;
    readonly acknowledged: number;
    readonly retried: number;
    readonly quarantined: number;
    readonly stale: number;
    readonly unresolved: Readonly<Record<OutboxDeliveryUnresolvedReason, number>>;
  };
  readonly observation: {
    readonly status: "disabled" | "healthy" | "degraded" | "stalled";
    readonly queueLimit: number;
    readonly queued: number;
    readonly outstanding: 0 | 1;
    readonly completed: number;
    readonly failed: number;
    readonly timedOut: number;
    readonly dropped: number;
  };
}

Frozen snapshot of this worker instance only: not backlog size, database, sink or global production health. delivery reflects the last local run; observation reports observer trouble separately. Totals saturate at Number.MAX_SAFE_INTEGER. observation.dropped, failed and timedOut are lifetime totals for the worker and never reset, while observation.status returns to healthy after the next prompt, successful call. See worker diagnostics.

Governed sharing

Governed sharing turns a sensitive membership or ownership command into a closed request lifecycle. Use request to record a command, approve, reject, or cancel to move the request, apply only after approval, and resolve to read its current outcome. A direct governed mutation returns GOVERNANCE_REQUIRED; it cannot bypass the approval and effect path.

For a non-owner transfer, the request needs a counted direct-owner sponsor. For an owner transfer, the request writes a payload-bound, non-counting consent and needs an independent eligible quorum; the recipient does not accept the transfer separately.

createGovernanceRequestId

function createGovernanceRequestId(context: TenantContext): string;

Generate an opaque request ID from the requester’s authenticated tenant context before submitting a governed command. Keep the ID for retries and follow-up calls.

GOVERNANCE_PUBLIC_STATUSES

const GOVERNANCE_PUBLIC_STATUSES: readonly [
  "PENDING",
  "APPROVED",
  "REJECTED",
  "APPLIED",
  "VOID",
  "REFUSED",
  "UNAVAILABLE",
  "UNKNOWN_REQUEST"
];

GovernancePublicStatus

type GovernancePublicStatus = GovernanceFoundationPublicStatus;

GovernancePublicResult

interface GovernancePublicResult {
  readonly status: GovernancePublicStatus;
}

GovernanceSubject

interface GovernanceSubject {
  readonly type: string;
  readonly id: string;
}

GovernanceResource

interface GovernanceResource extends GovernanceSubject {
  readonly incarnation: string;
}

GovernanceMembershipPrior

interface GovernanceMembershipPrior {
  readonly kind: "membership";
  readonly membershipId: string;
  readonly role: string;
  readonly expiresAt: number | null;
}

GovernanceCommand

type GovernanceCommand = {
  readonly requestId: string;
  readonly resource: GovernanceResource;
  readonly target: GovernanceSubject;
} & ({
  readonly kind: "grantRole";
  readonly role: string;
  readonly expiresAt: number | null;
  readonly prior: {
    readonly kind: "absent";
  };
} | {
  readonly kind: "changeRole";
  readonly role: string;
  readonly expiresAt: number | null;
  readonly prior: GovernanceMembershipPrior;
} | {
  readonly kind: "revokeMember";
  readonly prior: GovernanceMembershipPrior;
} | {
  readonly kind: "transferOwnership";
  readonly formerOwner: {
    readonly mode: "none";
  } | {
    readonly mode: "role";
    readonly role: string;
  };
  readonly prior: {
    readonly kind: "ownership";
    readonly owner: GovernanceSubject;
    readonly ownershipRevision: string;
  };
});

GovernedSharing

interface GovernedSharing {
  request(command: GovernanceCommand): Promise<GovernancePublicResult>;
  approve(requestId: string): Promise<GovernancePublicResult>;
  reject(requestId: string): Promise<GovernancePublicResult>;
  cancel(requestId: string): Promise<GovernancePublicResult>;
  apply(requestId: string): Promise<GovernancePublicResult>;
  resolve(requestId: string): Promise<GovernancePublicResult>;
}

GovernanceAttachment

interface GovernanceAttachment {
  readonly binding: GovernanceBinding;
  readonly gate: GovernanceDirectGate;
  readonly requestTtlMs: number;
  run<T>(context: TenantContext, work: (session: GovernanceSession) => Promise<GovernanceWork<T>>): Promise<T>;
}

GovernanceBinding

interface GovernanceBinding {
  readonly executor: object;
  readonly policyFence?: object;
  readonly identity: object;
}

GovernanceRuleSnapshot

interface GovernanceRuleSnapshot {
  readonly policyRevision: string;
  readonly tenantRoleRevision: string;
  readonly governanceRuleId: string;
  readonly governanceRuleRevision: string;
  readonly threshold: number;
}

Access-change delivery

Shared types for draining committed access changes into a delivery queue that createOutboxDeliveryWorker runs. See access-change webhooks.

ACCESS_CHANGE_ACTIONS

const ACCESS_CHANGE_ACTIONS: readonly [
  "member.granted",
  "member.role_changed",
  "member.revoked",
  "ownership.transferred",
  "invitation.issued",
  "invitation.consumed"
];

The six audit actions delivered as access changes, in this order. Every other audit action (invitation.revoked, resource.initialized, resource.deleted, resource.moved) is never queued.

ACCESS_CHANGE_LIMITS

const ACCESS_CHANGE_LIMITS: Readonly<{
  maxDrainLimit: 1000;
  maxClaimLimit: 1000;
  maxLeaseMs: 300000;
  maxDelayMs: 300000;
  maxReasonLength: 1024;
  maxInspectLimit: 1000;
  maxPruneLimit: 1000;
  maxRetainMs: 31536000000;
}>;

Bounds the storage adapters’ delivery stores enforce: drain, claim, prune and inspection limits of 1–1000, leases and retry delays of at most 300000 ms, a delivered-entry retention of at most a year, and dead-letter reasons of at most 1024 characters.

accessChangeAction

function accessChangeAction(value: unknown): AccessChangeAction | undefined;

Returns the action when it is one of ACCESS_CHANGE_ACTIONS, otherwise undefined.

accessChangeDeliveryId

function accessChangeDeliveryId(input: {
  readonly resourceType: string;
  readonly tenantId: string;
  readonly resourceId: string;
  readonly auditEventId: string;
}): Promise<string>;

The delivery ID of one access change: evt_ and 32 lowercase hex characters of SHA-256 over the resource type, tenant, resource ID and audit event ID. The same audit event always gets the same ID, across retries, requeues and drains; the same audit event ID on another resource, tenant or type gets a different one.

captureAccessChangeEvent

function captureAccessChangeEvent(value: unknown): AccessChangeEvent | undefined;

Validates an access change and copies exactly the allow-listed fields into a new frozen object. Unknown fields are dropped; a missing or malformed required field returns undefined.

validDeadLetterReason

function validDeadLetterReason(value: unknown): value is string;

True for a non-blank string of at most 1024 characters without NUL.

validSubscriptionId

function validSubscriptionId(value: unknown): value is string;

True for 1–64 characters of A-Z a-z 0-9 . _ -, starting with a letter or digit.

AccessChangeAction

type AccessChangeAction = (typeof ACCESS_CHANGE_ACTIONS)[number];

One of ACCESS_CHANGE_ACTIONS.

AccessChangeClaim

interface AccessChangeClaim extends OutboxDeliveryClaim {
  readonly kind: AccessChangeAction;
  readonly payload: AccessChangeEvent;
  readonly attempt: number;
}

A leased queue entry. eventId is the delivery ID, payload the allow-listed event, and attempt counts claims of this entry, this one included.

AccessChangeDeadLetter

interface AccessChangeDeadLetter {
  readonly eventId: string;
  readonly kind?: AccessChangeAction;
  readonly resourceType: string;
  readonly resourceId: string;
  readonly attempts: number;
  readonly reason: string;
  readonly deadAt: string;
  readonly token: AccessChangeDeadLetterToken;
}

One dead-lettered entry of the subscription’s tenant, with the exact token (subscription, tenant, generation) requeue and discardDeadLetter need. It carries the attempt count and reason, never the payload; kind is absent when the stored entry did not decode.

AccessChangeDeadLetterToken

interface AccessChangeDeadLetterToken extends OutboxDeliveryToken {
  readonly subscriptionId: string;
  readonly tenantId: string;
}

A dead-lettered entry’s subscription and exact current generation.

AccessChangeDeliveryPort

interface AccessChangeDeliveryPort extends OutboxDeliveryPort {
  takeDeadLettered?(): readonly string[];
  claim(input: {
    readonly limit: number;
    readonly leaseMs: number;
  }): Promise<readonly AccessChangeClaim[]>;
}

One subscription’s queue as an OutboxDeliveryPort, bound to its tenant, so createOutboxDeliveryWorker can run it. claim returns at most one entry per resource of that tenant: the oldest undelivered one, and only when it is not leased, not waiting for its retry time and not dead-lettered. Settlement needs a token this port issued, its current generation, and a lease that has not expired.

AccessChangeDeliveryStore

interface AccessChangeDeliveryStore {
  readonly environmentId: string;
  readonly resourceTypes: readonly string[];
  drain(input: {
    readonly subscriptionId: string;
    readonly tenantId: string;
    readonly limit: number;
  }): Promise<AccessChangeDrainResult>;
  outbox(input: {
    readonly subscriptionId: string;
    readonly tenantId: string;
  }): AccessChangeDeliveryPort;
  pruneDelivered(input: {
    readonly subscriptionId: string;
    readonly tenantId: string;
    readonly retainMs: number;
    readonly limit: number;
  }): Promise<number>;
  inspectDeadLetters(input: {
    readonly subscriptionId: string;
    readonly tenantId: string;
    readonly limit: number;
  }): Promise<readonly AccessChangeDeadLetter[]>;
  requeue(token: AccessChangeDeadLetterToken): Promise<boolean>;
  discardDeadLetter(token: AccessChangeDeadLetterToken): Promise<boolean>;
}

Delivery state kept apart from the audit tables: a tenant binding per subscription, a cursor per subscription and resource type, and a queue. drain reads at most limit audit rows of one tenant per resource type past the cursor, queues the access changes among them and advances the cursor past all of them in one transaction; a drain never updates or deletes an audit row. A subscription is bound to the tenant of its first drain, for every resource type; drain for another tenant throws, and outbox and pruneDelivered see only the bound tenant’s entries. pruneDelivered deletes delivered entries older than retainMs; discardDeadLetter deletes one dead-lettered entry so its resource moves on. There is no order across resources. See access-change webhooks.

AccessChangeDeliveryErrorCode

type AccessChangeDeliveryErrorCode = "invalid-row" | "tenant-bound" | "tenant-spelling" | "foreign-cluster" | "missing-origin" | "missing-privilege" | "source-conflict";

Why a delivery store refused to continue, carried as code on the adapters’ AccessChangeDeliveryError: a row that does not decode, a subscription bound to another tenant, a tenant ID that is not spelled as stored, PostgreSQL positions from another cluster, no recorded origin for a PostgreSQL audit table, a privilege the drain role, or the executor running adoptCluster or rebaseline, lacks (the message names the grant), or a resource type that another audit table already delivers under the same delivery prefix.

INVALID_ENTRY_REASON

const INVALID_ENTRY_REASON = "dead-lettered: the stored entry does not decode";

The reason a store records when it dead-letters a claimed entry that does not decode or names another tenant. The rest of the batch is still handed out.

AccessChangeDrainResult

interface AccessChangeDrainResult {
  readonly enqueued: number;
  readonly caughtUp: boolean;
}

How many entries one drain queued, and whether every resource type’s scan returned fewer rows than the limit and no page was discarded because another drain moved the cursor first, or a concurrent rebaseline or halt intervened.

AccessChangeEvent

interface AccessChangeEvent {
  readonly id: string;
  readonly tenantId: string;
  readonly resourceType: string;
  readonly resourceId: string;
  readonly actor: AccessChangeRef;
  readonly action: AccessChangeAction;
  readonly subject?: AccessChangeRef;
  readonly invitationId?: string;
  readonly fromTenantId?: string;
  readonly toTenantId?: string;
  readonly occurredAt: string;
}

One committed access change, restricted to the fields of the Sharing HTTP API’s audit event. The audit row’s idempotency key, incarnation and lineage are never copied, and invitation tokens are never stored in the audit table.

AccessChangeRef

interface AccessChangeRef {
  readonly type: string;
  readonly id: string;
}

An actor or subject as the audit row recorded it.

On this page

Creating sharingdefineSharingcreateSharingCreateSharingOptionscreateVersionedSharingCreateVersionedSharingOptionsPolicyErrorReporterVersionedResourceSharingVersionedResourceSharingWithDiagnosticsResourceSharingResourceSharingWithDiagnosticsTenantSharingTenantContextOperational diagnosticsSharingDiagnosticsOptionsSharingObserverSharingObservationSharingOperationObservationSharingOperationNameSharingResultClassSharingResultCodeSharingRetryObservationSharingScanObservationSharingScanListingSharingScanStatusSharingScanTotalsSharingDiagnosticsSharingDiagnosticsSourceDefinitions and typingSharingDefinitionSharingResourceConfigurationSharingResourceConfigurationsPolicyRolePolicyPermissionResourceTypeRoleForActionForResourceKeyCommands and decisionsSharingCommandSharingCommandPreconditionSharingMutationResultSharingExecutionLookupResultSharingDecisionInvitationRecipientInvitationRecipientSubjectInvitationRecipientEmailReadsAccessiblePageAccessibleResourceAccessDescriptionResultAccessDescriptionInheritedAccessMemberAccessMemberPendingInvitationResourcePermissionsResultResourcePermissionsAccessPageAuditHistoryResultAuditHistoryPageAuditHistoryEventInspectionInspectionResultInspectionErrorInspectionEnvelopeInspectionDecisionInspectionLimiterInspectionAuditSinkInspectionAuditEventErrorsAccessibleListingErrorAccessibleListingErrorCodeInvalidCursorErrorAccessListingUnavailableErrorAccessListingUnavailableReasonInvalidCandidatePageErrorAuditHistoryErrorAuditHistoryErrorCodeRetentionErrorRetentionErrorCodeRetentionSchemaErrorPolicyStoreErrorPolicyStoreErrorCodePolicyUnavailableErrorPolicyUnavailableReasonPolicyAdministrationErrorPolicyAdministrationErrorCodeisPolicyStoreRowErrorHierarchyUnavailableErrorHierarchyUnavailableReasonisHierarchyUnavailableErrorDelegationUnavailableErrorDelegationUnavailableReasonInheritedScopeUnsupportedErrorAdapterContractErrorKeys, clocks, and IDscreateHmacInvitationTokensgenerateInvitationTokenKeygenerateListingCursorKeyInvitationTokenProtectorSharingClocksystemClockSharingIdGeneratorrandomIdGeneratorIdentityTenantIdentityAdapterPagePrincipalSnapshotPagePrincipalEvidenceTenantPrincipalTransactionalAuthorizationFactGroupPrincipalRefOwnerRefgroupPrincipalcreateWorkspaceIdentityAdapterWorkspaceIdentityAdapterOptionsWorkspaceMemberRecordcreateWorkspaceMemberRemovedHandlerWorkspaceMemberRemovedEventStorage adapter contractSharingAdapterConsistentPageInputConsistentPagePagePolicyStateSharingAccessSnapshotSharingOwnershipSharingMembershipSharingInvitationSharingAuditEventAdapterMutationApplyMutationRequestApplyMutationResultReadMutationIdempotencyRequestReadMutationIdempotencyResultAccessibleCandidateAccessibleCandidatePageAuditEventPageInvitationRecipientFenceInputAdapter helpersvalidOpaqueIdvalidAuditEventIdsameRefdedupeRefscaptureRequestingPrincipalscaptureMemberRoleHintmissingFactFenceMessageIn-memory adaptercreateMemorySharingAdapterCreateMemorySharingAdapterOptionsMemoryEligibilityReaderMemoryEligibilityEvidenceMemorySharingAdapterMemorySharingSeedRetentionSettledRecordPrunerPruneSettledRecordsInputPruneWithDefaultsInputPruneIdempotencyInputPruneInvitationsInputPruneBothInputRetentionScopeSettledRecordKindPruneSettledRecordsResultPruneSettledRecordsRequestcapturePruneSettledRecordsInputpruneCutoffspruneResultinvitationSettledBeforeDEFAULT_IDEMPOTENCY_RETENTION_MSDEFAULT_INVITATION_RETENTION_MSMIN_IDEMPOTENCY_RETENTION_MSMIN_INVITATION_RETENTION_MSMAX_RETENTION_MSMAX_PRUNE_BATCHPolicy versions and custom rolesPolicyAdministrationCustomRoleAdministrationCustomRoleSetInputCustomRoleSetEntryCustomRoleSetResultCustomRoleSetRoleRefActivePolicyStateImpactInputImpactChangeImpactResultCustomRolePreviewInputCustomRolePreviewResultCustomRoleStatusCustomRoleViewCustomRoleLabelpolicyDigestparseCounterPolicy storePolicyStoreTenantRoleSetWriteassertTenantRoleSetWriteActivePolicyPointerStoredPolicyVersionPolicyVersionSummaryPolicyActivationStoredCustomRoleUndecodableCustomRoleTenantCustomRolesExpectedPolicyPolicyFenceResultPolicyAuditEventcreateMemoryPolicyStoreMemoryPolicyStoreassertPolicyTenantIdassertPolicyAuditEventassertPolicyAuditEventFieldsassertPolicyDigestHierarchy command configurationdefineHierarchyCommandsHierarchyCommandsInputHierarchyCommandsHierarchyTypeCommandsHierarchyBootstrapActionHIERARCHY_BOOTSTRAP_ACTIONSHierarchyTypeGraphhierarchyTypeGraphHierarchyConfigurationErrorhierarchyConfigurationGenerationInheritanceConfigurationErrorLimitsMAX_OPAQUE_ID_LENGTHMAX_INVITATION_EMAIL_LENGTHMAX_GROUP_PRINCIPALSMAX_ACCESS_BATCH_SIZEMAX_CANDIDATE_HINT_SIZEMAX_AUDIT_PAGE_LIMITMAX_AUDIT_CURSOR_LENGTHMAX_AUDIT_EVENT_ID_LENGTHMAX_POLICY_CURSOR_LENGTHMAX_POLICY_DOCUMENT_BYTESMAX_POLICY_LABEL_LENGTHMAX_POLICY_PAGE_LIMITMAX_CUSTOM_ROLES_PER_TENANTMAX_CUSTOM_ROLE_RECORDS_PER_TENANTMAX_CUSTOM_ROLE_RULESMAX_IMPACT_PAIRSMAX_IMPACT_SUBJECTSMAX_IMPACT_CANDIDATES_PER_SUBJECTMAX_POLICY_COUNTERCUSTOM_ROLE_LABELCUSTOM_POLICY_ROLE_PREFIXPOLICY_DIGESTPOLICY_GENERATIONDecision metadata foundationsAuthorityRevisionAchievedConsistencyAuthorizationDecisionMetadataConsistencyUnavailableReasonConsistencyUnavailableErrorcaptureAuthorizationDecisionMetadatacompareBatchResourcecompareAuthorityRevisionIdentitydecisionMetadataUtf8BytesHIERARCHY_BATCH_METADATA_MAX_BYTESHierarchyBatchAuthorizationDecisionMetadatacaptureHierarchyBatchDecisionMetadataassertHierarchyBatchReceiptResultassertSameProtectedAdmissionBundleOutboxDeliveryEventOutboxDeliveryTokenOutboxDeliveryClaimOutboxDeliveryPortOutboxDeliveryDecisionOutboxDeliverySinkOutboxDeliveryOptionsOutboxDeliveryOutcomeOutboxDeliveryBatchOutboxDeliveryWorkercreateOutboxDeliveryWorkerOutboxDeliveryWorkerWithDiagnosticsOutboxDeliveryDiagnosticsOptionsDEFAULT_OUTBOX_OBSERVER_QUEUE_LIMITDEFAULT_OUTBOX_OBSERVER_TIMEOUT_MSOutboxDeliveryObserverOutboxDeliveryObservationOutboxDeliveryRunResultOutboxDeliveryUnresolvedReasonOutboxDeliveryDiagnosticsGoverned sharingcreateGovernanceRequestIdGOVERNANCE_PUBLIC_STATUSESGovernancePublicStatusGovernancePublicResultGovernanceSubjectGovernanceResourceGovernanceMembershipPriorGovernanceCommandGovernedSharingGovernanceAttachmentGovernanceBindingGovernanceRuleSnapshotAccess-change deliveryACCESS_CHANGE_ACTIONSACCESS_CHANGE_LIMITSaccessChangeActionaccessChangeDeliveryIdcaptureAccessChangeEventvalidDeadLetterReasonvalidSubscriptionIdAccessChangeActionAccessChangeClaimAccessChangeDeadLetterAccessChangeDeadLetterTokenAccessChangeDeliveryPortAccessChangeDeliveryStoreAccessChangeDeliveryErrorCodeINVALID_ENTRY_REASONAccessChangeDrainResultAccessChangeEventAccessChangeRef