Sharing testkit
@rolebook/sharing-testkit: the security contract every sharing adapter must pass.
@rolebook/sharing-testkit is the executable form of the adapter contract. It
returns named async test cases that you register with your own runner (Bun, Vitest, Jest, or another): the
kit takes no runner dependency and opens no database. The memory, PGlite, PostgreSQL, and SQLite adapters
all run it.
import { test } from "bun:test";
import { sharingAdapterContract, type SharingAdapterContractFactory } from "@rolebook/sharing-testkit";
declare const createPostgresFixture: SharingAdapterContractFactory["create"];
for (const contract of sharingAdapterContract({ create: createPostgresFixture })) {
test(contract.name, contract.run);
} The adapter contract
sharingAdapterContract(factory) returns 40 cases. Each case calls factory.create() for fresh storage and a
fresh sharing instance. The fixture must:
- use the exported
sharingAdapterContractSubjects,sharingAdapterContractTenants, andsharingAdapterContractProject; - make
owner,editor,viewer, andinviteeeligible intenant_awith empty tenant assignments, and every identity intenant_bineligible; - resolve each subject with the
attributes.emailexported for it, match email recipients by that address, and verify email recipients in the adapter’s recipient fence against the same identity; - inject one clock into the adapter and
createSharing(), starting at2025-01-01T00:00:00.000Z, and move it withsetNow(); - implement
useNonBooleanFences()anduseNonBooleanFactRevalidation()by changing the callbacks the existing adapter holds, so the contract can prove that only a literaltruepasses a fence; - optionally supply
deleteApplicationResource()(for adapters whose lifecycle seam verifies the application row is gone) andseedInTenant()(needed to catch an audit listing that ignores the tenant); - build
sharingso thatlistAccessible()can read a consistent page: the adapter implementsrunConsistentPageon a supported executor, its eligibility fence has evidence for pages, and the identity adapter supplies identity evidence. The listing cases calllistAccessible()on the fixture’s own instance, so a fixture without these fails them withACCESS_LISTING_UNAVAILABLE.
The cases cover tenant isolation at the module and adapter, no implicit workspace grant, self-promotion,
ownership transfer and the single-owner invariant, invitation expiry, recipients, replay, and revocation,
immediate revocation, concurrent single-winner acceptance, competing same-version mutations, lifecycle
deletion and cross-tenant moves, non-boolean fence results failing closed, listing pagination and equality
with authorize(), cursor rejection, time-limited memberships (eight cases), describeAccess(),
permissions(), audit history paging and incarnations, and pruning (for adapters that offer
pruneSettledRecords(); others get a one-time warning).
The suite does not replace database-specific transaction, lock, foreign-key, and application lifecycle tests.
Teams contract
sharingTeamsContract(factory) checks the team rules against an adapter whose identity is
team-aware and whose fences understand teams. The fixture builds sharing with the canonical teams policy
(sharingTeamsContractRoles), makes sharingTeamsContractSubjects eligible in tenant_a only, creates
design and marketing in tenant_a and research in tenant_b, and implements addTeamMember,
removeTeamMember, and deleteTeam against the authoritative team store. It is a separate suite, so adapters
without team support keep running sharingAdapterContract unchanged.
listAccess contract
sharingListAccessContract(factory) takes the adapter contract’s factory and checks
listAccess() over the adapter: ownership, direct
and team memberships, a comment-only role, an assignment, a deny that removes every action, expiry, a pending
and then an accepted invitation, and a second tenant, at limits 1 and 100, each page equal to what
permissions() evaluates, plus cursor isolation from listAccessible(). Register its cases with your test
runner the same way as sharingAdapterContract’s.
Both listAccess() suites build their own sharing instances over the fixture’s adapter, with identity
adapters that supply bracketed evidence. The adapter itself must provide
consistent pages: it implements runConsistentPage
on a supported executor, and its eligibility fence has evidence for pages. An adapter without the capability
fails these cases.
sharingListAccessScopeContract(factory) adds the page-consistency cases. It commits a change to storage
while a page is open and requires the page to be the state before the change and the next page the state
after it; it changes the actor’s principal while a page is open and requires the page to be read again
wholly under the new principal; and it requires expiry to be decided at the page’s own instant, not the
sharing module’s clock.
Passing these suites shows that the adapter you ran them against behaves this way under the schedules they contain, on the database and executor you used. It does not qualify a different executor, database version, or identity source, and a suite that was skipped or run against a substitute database shows nothing about the real one.
Policy contracts
Three suites cover versioned sharing: policyVersionsContract (13 cases) and
customRolesContract (23 cases) on a PolicyVersionsContractFixture built with createVersionedSharing() (use
policyContractPolicies.v1 as the seed and .v2 as the published draft), and policyStoreContract (21 cases)
on any PolicyStore. Nine custom-role cases cover the atomic customRoles.set and seven store cases
writeTenantRoleSet; both fail for a store that does not implement writeTenantRoleSet. One more
store case requires writeTenantRole and deleteTenantRole to refuse an audit event any field of
which fails assertPolicyAuditEventFields, writing nothing. The last
policy-version case scopes lookupExecution() to its tenant for an actor eligible in two tenants.
API
import { ... } from "@rolebook/sharing-testkit". Signatures are checked against the built declarations.
Adapter contract
sharingAdapterContract
function sharingAdapterContract(
factory: SharingAdapterContractFactory,
): readonly SharingAdapterContractCase[]; The 40 adapter cases, in a stable order with stable names; cases added later are appended. The
last two cover lookupExecution() and the adapter’s
lookupMutationIdempotency, and fail for an adapter without it: a committed command found with
what a replay answers, a mismatch reported only to an actor who can see the resource, refusals
before any read, a key recorded in one tenant not readable through another, no write by any lookup
(including one for a resource or a tenant with no rows), and not_found after a record was pruned,
deleted (standalone or through the lifecycle seam) or moved to another tenant.
sharingListAccessContract
function sharingListAccessContract(
factory: SharingAdapterContractFactory,
): readonly SharingAdapterContractCase[]; The listAccess() cases, over the same factory. A separate suite, so sharingAdapterContract keeps its
cases and count. Each case builds its own sharing instance over the fixture’s adapter and now(), seeds a
world through seed (including a team membership) and seedInTenant, and requires every page to equal what
permissions() evaluates, and listAccess() and listAccessible() cursors never to open as each other. The
fixture’s adapter must implement runConsistentPage; each case supplies its own identity evidence.
sharingListAccessScopeContract
function sharingListAccessScopeContract(factory: SharingListAccessScopeFactory): readonly {
readonly name: string;
run(): Promise<void>;
}[]; The listAccess() scope cases: a tenant-wide identity grant of a non-first action on a resource with no
sharing row for the actor, beside ownership, a direct membership, two granting teams, a resource-scoped
assignment and a team deny of every action, at a fixed clock. Every backend must list the same resources with
the same allowed maps and decision codes, and each entry must deep-equal permissions() on that backend.
Nine cases in all. After the grant-source case:
- Four cases commit one storage change while a page is open: a resource changed, a membership revoked, and a membership granted, each after hydration, and a resource that becomes a candidate after candidate selection. The open page must be the state before the change, and the next page the state after it.
- One case changes the actor’s principal while a page is open. The page must be read again wholly under the new principal.
- One case requires membership expiry to be decided at the snapshot’s own instant, never the sharing module’s clock.
- One case changes a principal fact from
nulltoNaNwhile a page is open. Identity evidence is compared exactly, so the old page is not returned; the engine refuses the new value as a subject attribute, and the listing must answeridentity_evidence_missing, never an empty page. - One case keeps changing the principal on every attempt and must answer
ACCESS_LISTING_UNAVAILABLEwith reasonchangedafter three attempts, each with its own snapshot.
The adapter must implement runConsistentPage. The cases’ identity adapters supply bracketed evidence, so
the fixture configures no identity of its own.
SharingListAccessScopeFactory
interface SharingListAccessScopeFactory {
create(options: {
readonly clock: SharingClock;
}): Awaitable<SharingListAccessScopeFixture>;
} SharingListAccessScopeFixture
interface SharingListAccessScopeFixture {
readonly adapter: SharingAdapter;
seed(input: {
readonly tenantId: string;
readonly id: string;
readonly owner: ResourceRef;
readonly memberships?: readonly {
readonly subject: ResourceRef;
readonly role: string;
readonly expiresAt?: Date;
}[];
}): Awaitable<void>;
archive(input: { readonly tenantId: string; readonly id: string }): Awaitable<void>;
} archive sets the resource’s archived attribute (seeded false) to true and changes its version. The
adapter must read the clock given to create wherever it reads the time itself, such as to leave out
expired memberships; the contract keeps that clock fixed and drives the module’s own clock.
Storage whose seeded resources carry their tenant’s workspace as their only ancestor, so a tenant-wide grant
applies. Its fences must admit every subject in tenant_a.
SharingAdapterContractFactory
interface SharingAdapterContractFactory {
create(): Awaitable<SharingAdapterContractFixture>;
} SharingAdapterContractFixture
interface SharingAdapterContractFixture {
readonly sharing: ResourceSharing<SharingResourceConfigurations>;
readonly adapter: SharingAdapter;
readAudits(): Awaitable<readonly Pick<SharingAuditEvent, "action" | "idempotencyKey" | "invitationId">[]>;
now(): Date;
setNow(value: Date): void;
seed(id?: string, memberships?: readonly SharingAdapterContractMembership[]): Awaitable<void>;
seedInTenant?(tenantId: string, id: string): Awaitable<void>;
revokeTenantEligibility(subject: SharingAdapterContractSubject): Awaitable<void>;
useNonBooleanFences(): Awaitable<void>;
useNonBooleanFactRevalidation(): Awaitable<void>;
deleteApplicationResource?(resourceId: string, transaction: unknown): Awaitable<void>;
storeSnapshot?(): Awaitable<string>;
grantTenantEligibility?(tenantId: string, subject: SharingAdapterContractSubject): Awaitable<void>;
moveApplicationResource?(input: {
readonly resourceId: string;
readonly toTenantId: string;
readonly resultingResourceVersion: string;
readonly transaction: unknown;
}): Awaitable<"applied" | "conflict">;
} What create() returns: the sharing instance, adapter, seeding, clock, fence switches, and audit reads.
Three optional members serve the lookup cases: storeSnapshot() (every row of every table, so each
lookup is checked to write nothing at all; without it the cases compare the resource’s revision,
memberships and audit), and moveApplicationResource() with grantTenantEligibility() (so a real
lifecycle move clears a source key on an adapter whose standalone resourceMoved is unsupported).
The first-party SQLite and PostgreSQL fixtures supply all three.
SharingAdapterContractCase
interface SharingAdapterContractCase {
readonly name: string;
run(): Promise<void>;
} A named case: register run with your runner.
SharingAdapterContractMembership
interface SharingAdapterContractMembership {
readonly subject: SharingAdapterContractSubject;
readonly role: "editor" | "viewer";
readonly expiresAt?: Date;
} SharingAdapterContractSubject
interface SharingAdapterContractSubject {
readonly type: string;
readonly id: string;
readonly attributes?: Readonly<Record<string, unknown>>;
} sharingAdapterContractSubjects
const sharingAdapterContractSubjects: Readonly<{
owner: Readonly<{
type: "user";
id: "owner";
attributes: Readonly<{
email: "owner@example.test";
}>;
}>;
editor: Readonly<{
type: "user";
id: "editor";
attributes: Readonly<{
email: "editor@example.test";
}>;
}>;
viewer: Readonly<{
type: "user";
id: "viewer";
attributes: Readonly<{
email: "viewer@example.test";
}>;
}>;
invitee: Readonly<{
type: "user";
id: "invitee";
attributes: Readonly<{
email: "invitee@example.test";
}>;
}>;
outsider: Readonly<{
type: "user";
id: "outsider";
attributes: Readonly<{
email: "outsider@example.test";
}>;
}>;
projectionUser: Readonly<{
type: "user";
id: "shared_projection_id";
attributes: Readonly<{
email: "projection-user@example.test";
}>;
}>;
projectionService: Readonly<{
type: "service";
id: "shared_projection_id";
attributes: Readonly<{
email: "projection-service@example.test";
}>;
}>;
projectionUnrelated: Readonly<{
type: "user";
id: "unrelated_projection_id";
attributes: Readonly<{
email: "projection-unrelated@example.test";
}>;
}>;
}>; The contract’s subjects with their emails.
sharingAdapterContractTenants
const sharingAdapterContractTenants: Readonly<{
primary: "tenant_a";
secondary: "tenant_b";
}>; sharingAdapterContractProject
const sharingAdapterContractProject: Readonly<{
type: "project";
id: "project_1";
}>; Teams contract
sharingTeamsContract
function sharingTeamsContract(factory: SharingTeamsContractFactory): readonly {
readonly name: string;
run(): Promise<void>;
}[]; The team-rule cases.
SharingTeamsContractFactory
interface SharingTeamsContractFactory {
create(): Awaitable<SharingTeamsContractFixture>;
} SharingTeamsContractFixture
interface SharingTeamsContractFixture {
readonly sharing: ResourceSharing<SharingResourceConfigurations>;
readonly adapter: SharingAdapter;
seed(
id: string,
memberships?: readonly {
readonly subject: ResourceRef;
readonly role: string;
}[],
): Awaitable<void>;
addTeamMember(team: ResourceRef, user: ResourceRef, tenantId?: string): Awaitable<void>;
removeTeamMember(team: ResourceRef, user: ResourceRef): Awaitable<void>;
deleteTeam(team: ResourceRef): Awaitable<void>;
} SharingTeamsContractRole
type SharingTeamsContractRole = (typeof sharingTeamsContractRoles)[number]; sharingTeamsContractRoles
const sharingTeamsContractRoles: readonly ["viewer", "editor", "manager", "blocked"]; The canonical teams policy roles the fixture must use.
sharingTeamsContractSubjects
const sharingTeamsContractSubjects: Readonly<{
owner: Readonly<{
type: "user";
id: "team_owner";
}>;
alice: Readonly<{
type: "user";
id: "alice";
}>;
bob: Readonly<{
type: "user";
id: "bob";
}>;
carol: Readonly<{
type: "user";
id: "carol";
}>;
}>; sharingTeamsContractTeams
const sharingTeamsContractTeams: Readonly<{
design: Readonly<{
type: "team";
id: "design";
}>;
marketing: Readonly<{
type: "team";
id: "marketing";
}>;
research: Readonly<{
type: "team";
id: "research";
}>;
}>; sharingTeamsContractTenants
const sharingTeamsContractTenants: Readonly<{
primary: "tenant_a";
secondary: "tenant_b";
}>; Inherited-access contract
See inherited access. The PostgreSQL and SQLite adapters run sharingInheritanceContract; the memory adapter runs sharingInheritanceRefusalContract.
sharingInheritanceContract
function sharingInheritanceContract(factory: SharingInheritanceContractFactory): readonly SharingInheritanceContractCase[]; The inherited-access contract cases, each over fresh storage from factory: inherit from a parent and from a deeper ancestor, revoke on the parent, an explicit deny on the child, a move (document and subtree), parent membership expiry, a cross-tenant ancestor, cyclic and over-deep chains, listAccessible/listAccess parity with authorize, ownership never inheriting, a deny on an ancestor, owner recovery keeping an ancestor’s deny, a mismatched definition refused, enrollment refusing unplaced resources, control actions refused to unauthorized actors, delete, an ancestor whose resource is gone, an impossible subtree height, and describeAccess deciding inspection before reading other members. The cases use only public Sharing APIs.
sharingInheritanceRefusalContract
function sharingInheritanceRefusalContract(createAdapter: () => unknown): readonly SharingInheritanceContractCase[]; For an adapter without an inherited read path, such as the memory adapter: defineSharing must refuse inheritance: "ancestors" on it, and refuse the recursive contract policy without the opt-in.
SharingInheritanceContractFactory
interface SharingInheritanceContractFactory {
create(): Promise<SharingInheritanceContractFixture>;
} Creates fresh storage with tenant_a and tenant_b enrolled and activated through the public hierarchy control facade, and tenant_c prepared but not enrolled.
SharingInheritanceContractFixture
interface SharingInheritanceContractFixture {
readonly sharing: VersionedResourceSharing<SharingResourceConfigurations>;
create(tenantId: string, resource: Ref, parent: Ref | null): Promise<void>;
move(tenantId: string, resource: Ref, parent: Ref): Promise<void>;
corruptParent(tenantId: string, resource: Ref, parent: Ref): Promise<void>;
corruptHeight(tenantId: string, resource: Ref, height: number): Promise<void>;
removeOwnerRow(tenantId: string, resource: Ref): Promise<void>;
insertRawMembership(tenantId: string, scope: Ref, subject: Ref, role: string): Promise<void>;
insertUnplacedResource(tenantId: string, resource: Ref): Promise<void>;
delete(tenantId: string, resource: Ref): Promise<void>;
createAs(actor: Ref, tenantId: string, resource: Ref, parent: Ref | null): Promise<unknown>;
control(tenantId: string, actor: Ref): {
enroll(input: {
readonly idempotencyKey: string;
}): Promise<{
readonly status: string;
}>;
activate(input: {
readonly idempotencyKey: string;
}): Promise<{
readonly status: string;
}>;
releaseQuarantine(input: {
readonly idempotencyKey: string;
}): Promise<{
readonly status: string;
}>;
repairHeights(): Promise<{
readonly status: string;
}>;
};
inventory(tenantId: string): Promise<{
readonly status: string;
}>;
sharingWith(change: (resources: typeof sharingInheritanceContractResources) => Record<string, unknown>): Promise<VersionedResourceSharing<SharingResourceConfigurations>>;
close(): Promise<void>;
} create, createAs, move and delete go through the control facade’s structure commands; control and inventory drive enrollment. corruptParent, corruptHeight, removeOwnerRow, insertRawMembership and insertUnplacedResource are raw-storage seams, bypassing the store’s own constraints, for the fail-closed cases. sharingWith builds a second versioned instance over the same adapters.
SharingInheritanceContractCase
interface SharingInheritanceContractCase {
readonly name: string;
run(): Promise<void>;
} One named case.
sharingInheritanceContractPolicy
const sharingInheritanceContractPolicy: unknown; The contract policy: the bootstrap type tenant_admin, a recursive folder type and document below it, with folder viewer/editor roles that reach documents and a document role that denies document:read.
sharingInheritanceContractResources
const sharingInheritanceContractResources: unknown; The Sharing configuration of folder and document, both with inheritance: "ancestors", without the adapter the factory supplies.
sharingInheritanceContractCommands
const sharingInheritanceContractCommands: unknown; The hierarchy command map for the contract policy.
sharingInheritanceContractIdentityAssignments
function sharingInheritanceContractIdentityAssignments(subject: Ref): readonly {
readonly subject: Ref;
readonly role: string;
readonly scope: {
readonly resource: Ref;
readonly appliesTo: "self" | "descendants";
};
}[]; The identity assignments the factory’s local identity projection gives a subject in every contract tenant: operator holds the bootstrap role and structure rights on the roots r1, r2 and r3; carol holds structure rights on r2’s subtree; everyone else holds none.
sharingInheritanceContractSubjects
const sharingInheritanceContractSubjects: unknown; operator, alice, bob and carol, all eligible in both tenants; only operator has identity assignments.
sharingInheritanceContractRoots
const sharingInheritanceContractRoots: unknown; The root folder IDs r1, r2 and r3 the operator’s structure rights cover.
sharingInheritanceContractTenants
const sharingInheritanceContractTenants: unknown; tenant_a and tenant_b (enrolled; tenant_b reuses tenant_a’s resource IDs so a tenant leak is visible) and tenant_c (never enrolled by the factory).
Policy contracts
policyVersionsContract
function policyVersionsContract(
factory: PolicyVersionsContractFactory,
): readonly PolicyContractCase[]; The 13 policy-version cases.
customRolesContract
function customRolesContract(
factory: PolicyVersionsContractFactory,
): readonly PolicyContractCase[]; The 23 custom-role cases.
policyStoreContract
function policyStoreContract(
factory: PolicyStoreContractFactory,
): readonly PolicyContractCase[]; The 21 PolicyStore cases.
PolicyContractCase
interface PolicyContractCase {
readonly name: string;
run(): Promise<void>;
} PolicyVersionsContractFactory
interface PolicyVersionsContractFactory {
create(): Awaitable<PolicyVersionsContractFixture>;
} PolicyVersionsContractFixture
interface PolicyVersionsContractFixture {
readonly sharing: VersionedResourceSharing<SharingResourceConfigurations>;
readonly store: PolicyStore;
readonly adapter: SharingAdapter;
now(): Date;
setNow(value: Date): void;
seed(
id?: string,
memberships?: readonly {
readonly subject: SharingAdapterContractSubject;
readonly role: "editor" | "viewer" | CustomRoleLabel;
}[],
tenantId?: "tenant_a" | "tenant_c",
): Awaitable<void>;
beforeNextApply(hook: () => Promise<void>): void;
createPeer(): Promise<VersionedResourceSharing<SharingResourceConfigurations>>;
setStoreUnavailable(unavailable: boolean): Awaitable<void>;
throwFromNextFence(): Awaitable<void>;
readAudits(): Awaitable<readonly Pick<SharingAuditEvent, "action" | "idempotencyKey">[]>;
} PolicyStoreContractFactory
interface PolicyStoreContractFactory {
create(): Awaitable<PolicyStoreContractFixture>;
} PolicyStoreContractFixture
interface PolicyStoreContractFixture {
readonly store: PolicyStore;
storeSnapshot?(): Awaitable<string>;
setCounters(input: {
readonly generation?: string;
readonly tenantRevisions?: Readonly<Record<string, string>>;
}): Awaitable<void>;
failNextAudit(): Awaitable<void>;
} policyContractPolicies
const policyContractPolicies: Readonly<{
v1: Readonly<
import("rolebook").RolebookPolicy<
string,
import("rolebook").PolicyPermissionFromResources<import("rolebook").ResourceDefinitions>,
import("rolebook").ResourceDefinitions
>
>;
v2: Readonly<
import("rolebook").RolebookPolicy<
string,
import("rolebook").PolicyPermissionFromResources<import("rolebook").ResourceDefinitions>,
import("rolebook").ResourceDefinitions
>
>;
}>; The seed (v1) and draft (v2) policies the policy contracts expect.
Protected-write correctness fixtures
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.
protectedWritePolicy
const protectedWritePolicy: Readonly<import("rolebook").RolebookPolicy<"blocked" | "editor" | "title_editor", import("rolebook").PolicyPermissionFromResources<{
readonly document: {
readonly actions: readonly ["update"];
};
}>, {
readonly document: {
readonly actions: readonly ["update"];
};
}>>; Canonical document-update policy for the initial correctness corpus, with resource-wide editor, explicit deny and title-only roles. It is a test fixture, not a production protected-write wrapper.
protectedWriteDecisionFixtures
const protectedWriteDecisionFixtures: readonly [{
readonly id: "PW-ALLOW";
readonly roles: readonly ["editor"];
readonly scopeId: "document-a";
readonly allowed: true;
}, {
readonly id: "PW-NO-GRANT";
readonly roles: readonly [];
readonly scopeId: "document-a";
readonly allowed: false;
}, {
readonly id: "PW-DENY-WINS";
readonly roles: readonly ["editor", "blocked"];
readonly scopeId: "document-a";
readonly allowed: false;
}, {
readonly id: "PW-WRONG-RESOURCE";
readonly roles: readonly ["editor"];
readonly scopeId: "document-b";
readonly allowed: false;
}, {
readonly id: "PW-FIELD-ONLY";
readonly roles: readonly ["title_editor"];
readonly scopeId: "document-a";
readonly allowed: false;
}]; Expected allow/deny cases for grants, explicit denies, wrong resources and field-only access. Field-only grants must never admit arbitrary resource-wide SQL.
protectedWriteHistoryRequirements
const protectedWriteHistoryRequirements: readonly ["completed revoke before new snapshot denies", "completed grant before new snapshot allows", "write before revoke may commit in a valid serial order", "concurrent sharing-path revision bump conflicts with seal", "expiry at or before advancing seal clock aborts", "failed seal rolls business, receipt, audit and outbox back together", "same intent key and different payload conflicts", "lost commit acknowledgement requires receipt reconciliation", "resource delete and recreate cannot reuse prior-incarnation authority", "policy and custom-role changes conflict with declared authority fences"]; The required concurrency and recovery histories for protected-write adapters. The PostgreSQL resource/action wrapper has integration coverage for these histories; this exported checklist is not evidence that another adapter or a broader field-mediated contract passes them.
Managed update correctness fixtures
These shared cases exercise field allows, deny precedence, declared no-ops and before/after conditions across the SQL adapters.
managedWritePolicy
const managedWritePolicy: Readonly<import("rolebook").RolebookPolicy<"blocked" | "editor" | "private_editor" | "title_blocked" | "title_editor", import("rolebook").PolicyPermissionFromResources<{
readonly document: {
readonly actions: readonly [
"update"
];
};
}>, {
readonly document: {
readonly actions: readonly [
"update"
];
};
}>>; managedWriteDecisionFixtures
const managedWriteDecisionFixtures: readonly [
{
readonly id: "MW-FIELD-ALLOW";
readonly roles: readonly [
"title_editor"
];
readonly before: {
readonly title: "before";
readonly visibility: "private";
};
readonly patch: {
readonly title: "after";
};
readonly allowed: true;
},
{
readonly id: "MW-FIELD-DENY";
readonly roles: readonly [
"editor",
"title_blocked"
];
readonly before: {
readonly title: "before";
readonly visibility: "private";
};
readonly patch: {
readonly title: "after";
};
readonly allowed: false;
},
{
readonly id: "MW-MIXED-PATCH";
readonly roles: readonly [
"title_editor"
];
readonly before: {
readonly title: "before";
readonly visibility: "private";
};
readonly patch: {
readonly title: "after";
readonly visibility: "public";
};
readonly allowed: false;
},
{
readonly id: "MW-POST-STATE-DENY";
readonly roles: readonly [
"private_editor"
];
readonly before: {
readonly title: "before";
readonly visibility: "private";
};
readonly patch: {
readonly visibility: "public";
};
readonly allowed: false;
},
{
readonly id: "MW-PRE-STATE-DENY";
readonly roles: readonly [
"private_editor"
];
readonly before: {
readonly title: "before";
readonly visibility: "public";
};
readonly patch: {
readonly visibility: "private";
};
readonly allowed: false;
},
{
readonly id: "MW-STABLE-STATE-ALLOW";
readonly roles: readonly [
"private_editor"
];
readonly before: {
readonly title: "before";
readonly visibility: "private";
};
readonly patch: {
readonly title: "after";
};
readonly allowed: true;
},
{
readonly id: "MW-NOOP-DENY";
readonly roles: readonly [
"editor",
"title_blocked"
];
readonly before: {
readonly title: "before";
readonly visibility: "private";
};
readonly patch: {
readonly title: "before";
};
readonly allowed: false;
},
{
readonly id: "MW-UNDECLARED-DENY-IRRELEVANT";
readonly roles: readonly [
"editor",
"title_blocked"
];
readonly before: {
readonly title: "before";
readonly visibility: "private";
};
readonly patch: {
readonly visibility: "public";
};
readonly allowed: true;
},
{
readonly id: "MW-RESOURCE-DENY-WINS";
readonly roles: readonly [
"title_editor",
"blocked"
];
readonly before: {
readonly title: "before";
readonly visibility: "private";
};
readonly patch: {
readonly title: "after";
};
readonly allowed: false;
}
]; Document workload conformance
These exports describe the bounded rolebook-66-local-sql-v1 correctness profile.
They do not run a database or certify an adapter. The repository’s file-backed Bun
SQLite runner collects observations; auditDocumentWorkload compares them with
expectations derived from protectedWriteDecisionFixtures and
managedWriteDecisionFixtures, independently of the implementation’s decisions.
The profile includes five raw-write and nine managed-write cases, persisted row and receipt checks, callback counts, replay, conflicting intent, callback rollback, and stable-dataset listing at page sizes 1, 2, and 100. Listing must exhaust and match both the declared allowed IDs and individual authorization checks. A negative control deliberately injects a false allow and must fail admission.
This is a local SQL correctness profile, not a benchmark or a competitive ranking.
It assumes a complete local identity projection and no concurrent changes during
listing. Local libSQL, PostgreSQL, HTTP, concurrent revocation, expiry races, lost
acknowledgements, and outbox delivery are unmodeled by this profile; that does
not mean the products lack those capabilities. Remote libSQL and libSQL in-memory
protected writes are recorded separately as unsupported by the SQLite protected-write
adapter. The full protectedWriteHistoryRequirements gate is not satisfied merely
by passing this bounded profile.
documentWorkload
const documentWorkload: {
readonly id: "rolebook-66-local-sql-v1";
// Additional manifest fields described below.
}; The signature above is abbreviated. The manifest contains baseline (the original
fixture/profile source commit), cases (IDs, expected allowance, raw/managed kind,
and before/after rows), listing (page sizes and expected IDs),
productUnsupported, and harnessUnmodeled. The baseline identifies the profile’s
origin; it is not an attestation of the implementation revision currently tested.
Record the actual source revision and report hashes with each run. Treat the
manifest and its nested fixture-derived values as inputs; do not mutate them.
auditDocumentWorkload
function auditDocumentWorkload(evidence: DocumentEvidence): readonly string[]; Returns an empty array only when every registered observation and listing is
present exactly once and its checked outcomes and effects match the profile.
Otherwise it returns diagnostic strings such as FALSE_ALLOW:PW-NO-GRANT,
CARDINALITY:<id>:<count>, ROW:<id>, RECEIPT:<id>, LIST_COMPLETENESS:<size>,
REPLAY, CONFLICT, or ROLLBACK. Unknown observations and unexpected listing
sizes also fail admission. Treat any returned diagnostic as a failed gate; the
array is not a score. This function accepts typed evidence, not unvalidated JSON,
and does not independently observe or authenticate database effects.
import { auditDocumentWorkload, type DocumentEvidence } from "@rolebook/sharing-testkit";
declare const evidence: DocumentEvidence; // Collected by your workload driver.
const violations = auditDocumentWorkload(evidence);
if (violations.length > 0) {
throw new Error(`Conformance failed: ${violations.join(", ")}`);
} DocumentObservation
interface DocumentObservation {
readonly id: string;
readonly status: string;
readonly errorCode?: string;
readonly row: Readonly<Record<string, unknown>>;
readonly receipt: boolean;
readonly callbackCalls: number;
} One write case’s measured result. id identifies a registered fixture. The
expected status is committed for allowed cases and denied for denied cases;
a denied result also requires errorCode: "PROTECTED_WRITE_DENIED". Other status
or error values fail the oracle. row contains exactly the observed title,
visibility, and version; receipt records whether lookup found a persisted
receipt. callbackCalls counts actual raw-write callback invocations and is zero
for managed writes. Do not substitute expected values for observed effects.
ListingObservation
interface ListingObservation {
readonly pageSize: number;
readonly ids: readonly string[];
readonly individuallyAllowed: readonly string[];
readonly exhausted: boolean;
} One complete traversal at pageSize. ids contains all listed resource IDs;
individuallyAllowed contains IDs allowed by individual checks across every
seeded document in the same stable dataset. Both must equal the manifest’s
expected set without duplicates. exhausted must be true; stopping at a page
limit or losing a continuation cursor is not a complete result.
HistoryObservation
interface HistoryObservation {
readonly replayStatus: string;
readonly callbackCalls: number;
readonly conflictCode: string;
readonly rollbackCode: string;
readonly rollbackRow: Readonly<Record<string, unknown>>;
readonly rollbackReceipt: boolean;
} Records the bounded history checks: identical intent returns replayed, the raw
callback runs once across the initial write, replay, and conflicting attempt,
and conflicting payload reports IDEMPOTENCY_CONFLICT. The rollback case reports
INJECTED_CALLBACK_FAILURE, preserves the original row, and has no receipt.
These fields do not attest to lost-acknowledgement recovery or concurrent histories.
DocumentEvidence
interface DocumentEvidence {
readonly observations: readonly DocumentObservation[];
readonly listings: readonly ListingObservation[];
readonly history: HistoryObservation;
} The complete typed input to auditDocumentWorkload: all write observations,
one listing observation for each registered page size, and the bounded history
observations. Keep failed cases in the evidence; omitting them cannot produce a
passing result. Runtime metadata and source hashes belong in the surrounding
report and are not verified by this interface or the oracle.
Additive document lifecycle profile v2
The rolebook-66-document-v2 profile adds managed deletion and outbox recovery to
all v1 expectations. It does not expand the underlying product contract. Its baseline
is a2650b656ebf2c0a86304968d6244ba237a91ae9; keep actual source/patch hashes and
runtime metadata in the report. It models five deletion outcomes: allow, no grant,
deny precedence, field-only grant, and rollback after a rejected final fence.
The collector runs one scenario across PostgreSQL, Bun SQLite and file-backed libSQL. Each driver must return actual persisted rows and counts; an adapter-authored boolean is not a substitute. Fixtures include owner, membership, invitation and command idempotency rows, a business row at version 1, and sharing revision 7 over floor 0. Deletion must clear live data while retaining exactly one protected receipt, event and deletion audit. Recreation uses the same resource key with a new incarnation; original intent replay must preserve the replacement and a fresh key with the old incarnation must fail closed. Retained revision floors must be valid canonical decimal strings.
Recovery quarantines and requeues the same event, verifies newer delivery generations,
and rejects nine obsolete/duplicate token operations. staleEffects contains full
persisted outbox/dead-letter snapshots before and after each attempt, in addition to
its returned result in staleAccepted. False returns with changed state fail admission.
recoveryState() must return independent JSON-compatible snapshots, not mutable
references shared with subsequent operations. Missing prerequisite commits, claims,
quarantine tokens or records throw; an incomplete run never becomes admission.
The auditor returns diagnostics and does not execute SQL or validate arbitrary untyped JSON. Its input is the complete typed evidence from a trusted harness. It requires the unchanged v1 oracle to pass as well. Neither profile establishes external sink exactly-once delivery, performance, concurrent revocation, expiry races, same-tenant moves or operator history. Invitation rows are cleanup fixtures; invitation workflows are not exercised. The SQL CLI profiles now report v2 IDs; historical v1 reports retain their original IDs.
documentLifecycleWorkload
const documentLifecycleWorkload: unknown; collectDocumentLifecycleEvidence
function collectDocumentLifecycleEvidence(driver: DocumentLifecycleDriver, prior: DocumentEvidence): Promise<DocumentLifecycleEvidence>; auditDocumentLifecycleWorkload
function auditDocumentLifecycleWorkload(e: DocumentLifecycleEvidence): readonly string[]; DocumentLifecycleState
interface DocumentLifecycleState {
readonly row: Readonly<Record<string, unknown>> | null;
readonly liveRows: number;
readonly receipts: number;
readonly events: number;
readonly deletionAudits: number;
readonly revisionFloor: string | null;
} DocumentLifecycleEvidence
interface DocumentLifecycleEvidence {
readonly prior: DocumentEvidence;
readonly deletions: readonly {
readonly id: string;
readonly status: string;
readonly code: string;
readonly before: DocumentLifecycleState;
readonly after: DocumentLifecycleState;
}[];
readonly recovery: {
readonly receiptId: string;
readonly receiptSame: boolean;
readonly firstIds: readonly string[];
readonly recoveredIds: readonly string[];
readonly kind: string;
readonly payloadSame: boolean;
readonly firstGeneration: string;
readonly recoveredGeneration: string;
readonly deadEventIds: readonly string[];
readonly deadReason: string;
readonly deadTokenSame: boolean;
readonly pendingWhileDead: number;
readonly claimsWhileDead: number;
readonly requeued: boolean;
readonly deadAfterRequeue: number;
readonly staleEffects: Readonly<Record<string, {
readonly before: unknown;
readonly after: unknown;
}>>;
readonly staleAccepted: Readonly<Record<string, boolean>>;
readonly acknowledged: boolean;
readonly claimsAfterAck: number;
readonly replayStatus: string;
readonly replayReceiptSame: boolean;
readonly incarnationChanged: boolean;
readonly oldIncarnationCode: string;
readonly replacement: DocumentLifecycleState;
};
} DocumentLifecycleDriver
interface DocumentLifecycleDriver {
prepare(id: string, roles: readonly string[]): Promise<DeleteInput>;
remove(input: DeleteInput): Promise<{
readonly status: string;
readonly receipt: Receipt;
}>;
rollback(input: DeleteInput): Promise<{
readonly status: string;
readonly receipt: Receipt;
}>;
lookup(input: DeleteInput): Promise<Receipt | undefined>;
state(input: DeleteInput): Promise<DocumentLifecycleState>;
recreate(input: DeleteInput): Promise<string>;
recoveryState(): Promise<unknown>;
worker: {
claim(input: {
limit: number;
leaseMs: number;
}): Promise<readonly Claim[]>;
inspectPending(input: {
limit: number;
}): Promise<readonly unknown[]>;
quarantine(token: Token, input: {
reason: string;
}): Promise<Token | undefined>;
inspectDeadLetters(input: {
limit: number;
}): Promise<readonly {
eventId: string;
reason: string;
quarantineToken: Token;
}[]>;
requeue(token: Token): Promise<boolean>;
acknowledge(token: Token): Promise<boolean>;
retry(token: Token, input: {
delayMs: number;
}): Promise<boolean>;
};
} DocumentLifecycleDriver is the structural driver seam used by the collector.
DeleteInput in these signatures denotes resource type/id, action, incarnation ID,
idempotency key and expected version (all strings). Receipt requires receiptId;
drivers retain their full receipts so replay equality checks all fields. Token
contains environment ID, event ID and generation strings. Claim contains event ID,
kind, payload and delivery token. These supporting aliases are internal; implement
the exported interface against the public authority/outbox APIs.
Additive document move and operator-history profile v3
rolebook-66-document-v3 is tied to baseline
c25bd402fd7743d90b11c851960b075aba4768b1. Its eight declared move cases cover
child/source/destination permissions, destination deny, field-only child permission,
post-state deny and a final-fence rollback. Expected outcomes are fixed by the corpus,
not generated from the policy under test. Admission also requires every unchanged
v1/v2 expectation through nested prior evidence. Versioned v1/v2 runners remain
available; this profile uses a separate move/history entry point.
The shared collector consumes actual persisted state from PostgreSQL, Bun SQLite or file-backed libSQL. State includes the child’s parent/version/revision/title, original owner/direct grants and parent rows, unique receipt/event, move audit and lifecycle record. Failed moves preserve the full observed state. Replay returns the original receipt, a changed postVersion conflicts, and recovery preserves the same move event.
Operator history uses two quarantine/requeue cycles: captured service attribution,
then no attribution. The original run starts generation at 9007199254740992; the mandatory second
run starts at 9999999999999995 and crosses decimal digit length. Both use the same
move/history corpus, with the second run in boundary. Drivers
must keep persisted counters exact using SQL decimal-string projections rather than
JavaScript Number conversion. Page sizes 1, 2 and 3 must exhaust the same four actions
with exclusive string cursors. Stale attempts capture independent JSON-compatible
snapshots of outbox, dead-letter and history rows before and after. Failed history
append must roll back the complete quarantine transition. Operator identity is trusted
caller attribution, not authentication. Returned timestamps are transition times,
not an exact COMMIT-time guarantee.
The oracle rejects missing/extra/mutated move and history observations, incorrect attribution/generation, changed retained payload, replay effects and stale mutations hidden behind false returns. It returns diagnostics for complete typed evidence; it is not a general JSON validator or an independent database observer. Missing collector prerequisites throw instead of producing an admitted partial result.
The bounded profile excludes new worker pumps, consistency-token runtime, concurrent revocation/expiry races, cross-tenant or recursive moves and external sink exactly-once semantics. It measures no performance. Local evidence and unpublished artifacts do not close broader conformance requirements or establish a production rollout.
collectDocumentMoveRunEvidence collects one driver-backed run. The outer
collectDocumentMoveEvidence invokes the supplied run function for both declared
ranges and adds prior v1/v2 evidence. auditDocumentMoveWorkload requires both exact
ranges; a missing boundary run cannot pass. Boundary diagnostics use a BOUNDARY:
prefix. Baseline c25bd40 had text-alias history ordering at the digit boundary;
admission requires the separately recorded SDK correction, and original red evidence
must remain distinguishable from combined verification.
Evidence revision 2 supersedes the earlier v3 physical-history admission gap.
DocumentRecoverySnapshot contains direct SQL observations, normalized independently
from the history API. Every successful quarantine/requeue records its immediate
physical prefix (1/2/3/4 rows), and final acknowledgement requires exactly four.
Failed append requires zero rows; each stale phase requires its known prefix even
when before and after are identical. Each physical row independently matches the
expected identity, exact generation, action ID, action, attribution, reason and
valid timestamp; a separate equality check ties those rows to API observations.
Missing/extra/corrupt physical history therefore cannot pass merely because the API
returns correct records. transitionSnapshots and finalSnapshot are mandatory.
The SQL read orders by the qualified integer column and preserves decimal strings.
documentMoveWorkload
const documentMoveWorkload: unknown; collectDocumentMoveEvidence
function collectDocumentMoveEvidence(run: (initialGeneration: string) => Promise<DocumentMoveRunEvidence>, prior: DocumentLifecycleEvidence): Promise<DocumentMoveEvidence>; collectDocumentMoveRunEvidence
function collectDocumentMoveRunEvidence(driver: DocumentMoveDriver, initialGeneration: string): Promise<DocumentMoveRunEvidence>; auditDocumentMoveWorkload
function auditDocumentMoveWorkload(e: DocumentMoveEvidence): readonly string[]; DocumentMoveInput
interface DocumentMoveInput {
readonly resource: {
readonly type: string;
readonly id: string;
};
readonly action: string;
readonly incarnationId: string;
readonly idempotencyKey: string;
readonly expectedVersion: string;
readonly postVersion: string;
readonly sourceParent: {
readonly id: string;
readonly incarnationId: string;
readonly version: string;
};
readonly destinationParent: {
readonly id: string;
readonly incarnationId: string;
readonly version: string;
};
} DocumentMoveState
interface DocumentMoveState {
readonly row: {
readonly parentId: string;
readonly version: string;
readonly revision: string;
readonly title: string;
} | null;
readonly owners: readonly unknown[];
readonly members: readonly unknown[];
readonly parents: readonly unknown[];
readonly receipts: readonly {
readonly receiptId: string;
readonly result: unknown;
}[];
readonly events: readonly {
readonly eventId: string;
readonly receiptId: string;
readonly kind: string;
readonly payload: Readonly<Record<string, unknown>>;
}[];
readonly audits: number;
readonly lifecycle: number;
} DocumentOperatorAction
interface DocumentOperatorAction {
readonly environmentId: string;
readonly eventId: string;
readonly actionId: string;
readonly generation: string;
readonly action: string;
readonly operator: {
readonly type: string;
readonly id: string;
} | null;
readonly reason: string | null;
readonly recordedAt: string;
} DocumentMoveDriver
interface DocumentMoveDriver {
prepare(id: string, roles: readonly string[]): Promise<DocumentMoveInput>;
move(input: DocumentMoveInput): Promise<MoveResult>;
rollback(input: DocumentMoveInput): Promise<MoveResult>;
state(input: DocumentMoveInput): Promise<DocumentMoveState>;
lookup(input: DocumentMoveInput): Promise<MoveResult["receipt"] | undefined>;
setGeneration(eventId: string, generation: string): Promise<void>;
recoveryState(): Promise<DocumentRecoverySnapshot>;
failTransition(token: Token): Promise<unknown>;
readonly attributed: Worker;
readonly unattributed: Worker;
} DocumentMoveEvidence
interface DocumentMoveEvidence extends DocumentMoveRunEvidence {
readonly prior: DocumentLifecycleEvidence;
readonly boundary: DocumentMoveRunEvidence;
} DocumentMoveRunEvidence
interface DocumentMoveRunEvidence {
readonly initialGeneration: string;
readonly moves: readonly {
readonly id: string;
readonly input: DocumentMoveInput;
readonly status: string;
readonly code: string;
readonly before: DocumentMoveState;
readonly after: DocumentMoveState;
}[];
readonly replay: {
readonly status: string;
readonly sameReceipt: boolean;
readonly lookupSame: boolean;
readonly conflictCode: string;
readonly state: DocumentMoveState;
};
readonly history: {
readonly eventId: string;
readonly transitionSnapshots: readonly DocumentRecoverySnapshot[];
readonly finalSnapshot: DocumentRecoverySnapshot;
readonly actions: readonly DocumentOperatorAction[];
readonly pages: readonly {
readonly pageSize: number;
readonly actions: readonly DocumentOperatorAction[];
readonly exhausted: boolean;
}[];
readonly stale: Readonly<Record<string, {
readonly accepted: boolean;
readonly before: DocumentRecoverySnapshot;
readonly after: DocumentRecoverySnapshot;
}>>;
readonly failedTransition: {
readonly code: string;
readonly before: DocumentRecoverySnapshot;
readonly after: DocumentRecoverySnapshot;
};
readonly requeued: readonly boolean[];
readonly acknowledged: boolean;
readonly claimsAfterAck: number;
readonly finalState: DocumentMoveState;
readonly finalActions: readonly DocumentOperatorAction[];
};
} DocumentRecoverySnapshot
interface DocumentRecoverySnapshot {
readonly outbox: readonly unknown[];
readonly dead: readonly unknown[];
readonly history: readonly DocumentOperatorAction[];
} DocumentMoveDriver is the structural scenario seam. Its internal MoveResult
requires status and the full receipt (including receiptId/result). Token is an
environment/event/generation triple. Worker combines the existing lifecycle worker
operations with bounded inspectOperatorActions. Drivers use public authority/outbox
APIs for operations and direct reads for persisted evidence. setGeneration and
failTransition are fixture-only hooks for exact-counter and rollback cases; they
must never become production worker behavior.