Skip to content

Commit e26e7be

Browse files
fix(organizations): the walled Default Organization's seed resolves its bound owner (#34457)
Fixes #34425 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:隔离(walled)部署首次启动时,系统自动创建的默认组织(Default Organization)的示例数据(seed)回放,从"组织行写入时"推迟到"平台所有者成为该组织成员之后",示例数据里指向所有者的人员字段(指派人、审核人等)现在能正确填上。 - 为什么改:原来回放早于所有者的成员行写入,默认组织里一个成员都没有,示例数据中所有指向所有者的人员字段都存成空值;只有负责人(owner_id)靠后续的归属交接被补上,其它人员字段一直为空。 - 风险与回滚:只改了 `@objectstack/organizations` 一个中间件的触发时机,复用 #34038 已上线的"等待第一个成员再回放"机制;非隔离部署、用户新建组织、导入与迁移等路径不变,每个组织仍只回放一次;启动流程没能绑定所有者时,仍会在启动调用结束时照旧回放。回滚即还原这一个 PR。 - 先看:`packages/plugins/organizations/src/organizations-plugin.ts`(Middleware B 的默认组织等待分支与 runEnsure 的兜底回放)、`default-organization-seed-owner.wall.test.ts`(真实隔离启动的复现测试)。 - 两分钟验证:`pnpm --filter @objectstack/organizations exec vitest run src/default-organization-seed-owner.wall.test.ts`,预期 3 个用例全绿;在 main 上第二个用例是红的(所有者的指派人、审核人字段为空)。 - 需要你做的:无,席位落地。 ## What changes **Landing point: `packages/plugins/organizations/src/organizations-plugin.ts` only.** On a walled posture the default-organization bootstrap is wired by this package alone (`AuthPlugin` skips its own bootstrap under a wall), and the replay trigger is this package's Middleware B. `plugin-auth`'s `ensure-default-organization.ts` is unchanged: it still writes the organization, then the owner's member row, then runs the seed-ownership handoff. Both `ensure-default-organization.ts` files named in the claim's file surface are untouched. The order on main, measured on a walled `bootStack`: the bootstrap inserts the `default` organization as SYSTEM with no person behind it, Middleware B replays the seed inside that insert, every person reference in the seed is refused as "not a member of organization ORG", and only then does the owner's `sys_member` row land. The seed-ownership handoff re-owns NULL `owner_id` rows afterwards, so `owner_id` reads right and every other person column (a `Field.user()` column, a `Field.lookup('sys_user')` column) stays NULL. The change reuses the mechanism #34038 added for the organization-create path (the `awaitingFirstMember` wait, released by the organization's first `sys_member` insert, one replay per organization). It adds a second way in, and no second mechanism: - While this plugin's default-organization bootstrap is running (a counter, because the owner bind re-enters the bootstrap from inside the deciding call), a SYSTEM `sys_organization` insert with slug `default` and no `userId` no longer replays on the insert. It waits for the organization's first member row and replays inside it, after the row is stored. The replay names that member (the bound owner) as the locale user, as the founder is named on the create path. - When the bootstrap binds nobody (the owner bind was decided earlier and only the organization was recreated, or the member write failed), the last bootstrap call to finish replays the still-waiting organization at once, with no person. That is the order it had before, delayed only to the end of the bootstrap call. - Every other organization insert is unchanged: an attributed create waits as before, and any other SYSTEM or `userId` insert replays on the insert. **No signal is borrowed from attribution.** Stamping `attributedUserId` on the bootstrap's organization insert would also have made Middleware B wait, but `attributedUserId` is the audit attribution channel (`sys_audit_log.user_id`), and nobody acted to create the Default Organization. The bootstrap-scoped wait keeps the audit row as it is. ## Tests - New `packages/plugins/organizations/src/default-organization-seed-owner.wall.test.ts`: `bootStack` (`@objectstack/verify`) with the real `AuthPlugin`, `SecurityPlugin`, `AppPlugin` replayer and this package's `OrganizationsPlugin`. The app's seed names the harness's dev admin (the declared platform owner on a walled boot) in a `user` field, a `lookup` to `sys_user` and `owner_id`. - premise: the wall is up, and the Default Organization's only member is the owner, role `owner`; - the Default Organization was seeded once, and all three references store the owner's user id; - control, un-walled boot of the same app: the wall is down, the row is seeded once, and it reads exactly as on main. - `organizations-plugin.test.ts`, new top-level describe on an engine double whose inserts run the plugin's middlewares, driven by the owner's verified `sys_user` insert (the walled bootstrap trigger): - the `default` organization replays once, inside the owner's member write, naming the owner, and the member row is stored when the replay reads membership; - control: with the member write refused, the organization still replays once, with no person. <details><summary>Red on main, green on the fix, ablation</summary> Red: the new wall test on `78cfdf31` / `b7675220` (test only, main's plugin): ```text ERROR [SeedLoader] Deferred reference UNRESOLVED after pass 2 — seedowner_task.assignee is NULL at the end of pass 2 on record 'Owner task'. ... because the sys_user row that answers to it is not a member of organization org_mwjons01f49gucr4, the organization this load seeds ... × the replay seeded the Default Organization once, and every person reference naming the owner resolves to the owner 7ms - "assignee": "jHY1Q8qdwMEN0mVDt0FKd5WCPBrkgp7J", + "assignee": null, - "reviewer": "jHY1Q8qdwMEN0mVDt0FKd5WCPBrkgp7J", + "reviewer": null, Test Files 1 failed (1) Tests 1 failed | 2 passed (3) os-verify-lock: VERDICT command-exit 1 ``` Green, with the fix (now `46d2a91f`), the new wall test beside the #34038 wall test: ```text Test Files 2 passed (2) Tests 6 passed (6) os-verify-lock: VERDICT command-exit 0 ``` Ablation, after committing the fix: `organizations-plugin.ts` restored from the base commit `6a7403ba` (anchor `defaultOrgBootstrapsInFlight` counted 0 on disk, file hash equal to the base blob `56168912`), the wall test and the unit file run, the file restored from `HEAD` (anchor count 5, hash equal to the HEAD blob `2b1eac94`, `git diff HEAD` empty). The tests import the plugin from source, so no build was involved. ```text × replays the default organization once, inside the owner's member write, naming the owner 9ms × the replay seeded the Default Organization once, and every person reference naming the owner resolves to the owner 6ms Test Files 2 failed (2) Tests 2 failed | 25 passed (27) ``` Package suite and typecheck on `46d2a91f`: ```text pnpm --filter @objectstack/organizations test Test Files 20 passed (20) · Tests 262 passed (262) pnpm --filter @objectstack/organizations typecheck tsc --noEmit clean · check:test-typecheck: OK os-verify-lock: VERDICT command-exit 0 ``` </details> ## Acceptance notes - **The card's un-walled baseline does not resolve these references either, for another reason.** Measured on the un-walled control boot: the boot seed loads before the dev admin's `sys_user` row exists, so `assignee` and `reviewer` land NULL with "no such sys_user row exists", and only the first-admin handoff writes `owner_id`. The card reads "exactly as on an un-walled boot"; on this fixture the un-walled boot is not a resolving baseline. The walled replay runs after the owner exists and is the person being bound, so after this change it resolves them. The un-walled reading is the same class of gap reached through another entry point (only `owner_id` is repaired), and this PR does not fix it: it is carried by #34458. The control pins the un-walled reading as it stands on main, so a change to the un-walled path shows up there; #34458's Done-when flips that control (`control: the same seed on an un-walled boot reads as it did before the fix`) to the admin id. - **Residual, not changed here:** if the bootstrap call throws after inserting the organization and before its member write, the waiting entry stays until a later member write releases it (the next bootstrap trigger binds the owner) or the abandoned-create warning drops it. `ensureDefaultOrganization` catches its own write failures, so no such throw is known. - No public contract moves: no spec, export, hook signature, error code or route changes. ## Verification Local gate subset, derived with `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` against `46d2a91f` (68 families): 67 ran with exit 0. One was not measured locally and is left to CI: - `pnpm check:dual-build-cjs-loads`: exit 3, PREREQUISITE NOT MET (packages outside this card's build closure have no `dist/` in this worktree). `--ran` reconciliation on `46d2a91f`: `68 derived, 67 run, 1 NOT-MEASURED, 0 UNRUN`. `origin/main` has not moved since the branch point (`6a7403ba`). ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes (left to CI). - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: not touched. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. Opened for seat `repo:objectstack#1` · os-project-manager · session_01FEkQ5kgF3mo9f7LXuv5hac, area o1-C. --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5kgF3mo9f7LXuv5hac)_ <!-- signed: repo:objectstack#1 · os-project-manager · session_01FEkQ5kgF3mo9f7LXuv5hac --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 152cd1f commit e26e7be

4 files changed

Lines changed: 395 additions & 11 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
'@objectstack/organizations': patch
3+
---
4+
5+
Clause-②: no
6+
Metadata-protocol: none
7+
8+
On a walled boot, the Default Organization's seed now resolves the platform owner it is bound to. The default-organization bootstrap writes the `default` organization as SYSTEM and then the owner's `sys_member` row; the per-organization seed replay ran on the organization write, before that member existed, so a seeded `Field.user()` or `Field.lookup('sys_user')` column naming the owner was stored as NULL (only `owner_id` was repaired later, by the seed-ownership handoff). The replay of the organization that bootstrap creates now waits for the owner's member row and runs inside it, the same way an organization a person creates already does, with the owner as the locale user. When the bootstrap binds nobody (the bind was decided earlier, or the member write failed), the organization still replays once, with no person, as soon as the bootstrap call is over. Un-walled boots and every other organization write are unchanged.
Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,212 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The Default Organization's seed resolves the platform owner it is bound to.
5+
*
6+
* On a walled boot the default-organization bootstrap writes the
7+
* `sys_organization` row as SYSTEM, with no person behind it, and THEN the
8+
* platform owner's `sys_member` row. This package's per-org seed replay is
9+
* the organization insert's middleware, and an organization-scoped seed load
10+
* resolves a person through membership in the load organization. When the
11+
* replay ran on the organization insert, the Default Organization had no
12+
* member at all, so every person reference the app's seed declared landed NULL
13+
* with "not a member of organization ORG", the owner's included. The
14+
* seed-ownership handoff that follows the bind re-owns NULL `owner_id` rows,
15+
* so `owner_id` read right; a `Field.user()` or `Field.lookup('sys_user')`
16+
* column naming the owner stayed NULL.
17+
*
18+
* The control boots the same app un-walled. There the boot seed loads before
19+
* the dev admin exists, so its person columns have nobody to resolve to, and
20+
* only the first-admin handoff writes `owner_id` afterwards. That outcome is
21+
* measured on main and pinned here as it stands: the fix waits only for the
22+
* walled bootstrap's own `default` organization, so the un-walled boot must
23+
* read exactly as before.
24+
*
25+
* ## What is real
26+
*
27+
* `bootStack` (`@objectstack/verify`): an `ObjectKernel` over in-process
28+
* SQLite, the real `AuthPlugin`, `SecurityPlugin`, the real `AppPlugin` seed
29+
* replayer and THIS package's `OrganizationsPlugin`. The walled leg runs under
30+
* `OS_TENANCY_POSTURE=isolated`; the harness declares its dev admin as the
31+
* platform owner, so the bootstrap binds that admin. Nothing is stubbed.
32+
* Stored rows are read back through the engine as SYSTEM.
33+
*/
34+
35+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
36+
import { bootStack, type VerifyStack } from '@objectstack/verify';
37+
import { OrganizationsPlugin } from './organizations-plugin.js';
38+
39+
const WALLED_BOOT_ENV = [
40+
['OS_TENANCY_POSTURE', 'isolated'],
41+
// A walled deployment must declare what a new user joins, or this package's
42+
// own boot gate refuses it.
43+
['OS_AUTH_MEMBERSHIP_POLICY', 'invite-only'],
44+
] as const;
45+
46+
/** The harness's dev admin: the declared platform owner on the walled leg. */
47+
const ADMIN_EMAIL = 'admin@objectos.ai';
48+
const ADMIN_NAME = 'Dev Admin';
49+
50+
const TASK = 'seedowner_task';
51+
52+
const APP = {
53+
manifest: {
54+
id: 'com.example.seedowner',
55+
namespace: 'seedowner',
56+
version: '0.0.1',
57+
type: 'app',
58+
name: 'Seed Owner Fixture',
59+
},
60+
objects: [
61+
{
62+
name: TASK,
63+
label: 'Task',
64+
fields: {
65+
name: { type: 'text', label: 'Name' },
66+
assignee: { type: 'user', label: 'Assignee', reference: 'sys_user' },
67+
reviewer: { type: 'lookup', label: 'Reviewer', reference: 'sys_user' },
68+
},
69+
},
70+
],
71+
data: [
72+
{
73+
object: TASK,
74+
mode: 'upsert',
75+
externalId: 'name',
76+
records: [
77+
// Every person reference the seed can carry names the platform owner.
78+
{ name: 'Owner task', assignee: ADMIN_NAME, reviewer: ADMIN_NAME, owner_id: ADMIN_NAME },
79+
],
80+
},
81+
],
82+
};
83+
84+
const SYS = { context: { isSystem: true } } as const;
85+
86+
/** Boot the walled stack once at module scope and stop it: the first boot's loading is paid here, never in a clocked hook. */
87+
async function warmUp(): Promise<void> {
88+
const before = { ...process.env };
89+
for (const [name, value] of WALLED_BOOT_ENV) process.env[name] = value;
90+
try {
91+
const stack = await bootStack({ manifest: { ...APP.manifest, id: 'com.example.seedowner.warmup' }, objects: [] } as never, {
92+
extraPlugins: [new OrganizationsPlugin()],
93+
});
94+
await stack.stop();
95+
} finally {
96+
for (const key of Object.keys(process.env)) if (!(key in before)) delete process.env[key];
97+
Object.assign(process.env, before);
98+
}
99+
}
100+
await warmUp();
101+
102+
/**
103+
* Hold `env` for one leg: set it before the boot and restore it after the
104+
* stack stops, because the plugins read the posture live. A name mapped to
105+
* `undefined` is removed for the leg.
106+
*/
107+
function legEnv(env: ReadonlyArray<readonly [string, string | undefined]>) {
108+
const saved: Array<[string, string | undefined]> = [];
109+
return {
110+
apply() {
111+
for (const [name, value] of env) {
112+
saved.push([name, process.env[name]]);
113+
if (value === undefined) delete process.env[name];
114+
else process.env[name] = value;
115+
}
116+
},
117+
restore() {
118+
for (const [name, value] of saved.reverse()) {
119+
if (value === undefined) delete process.env[name];
120+
else process.env[name] = value;
121+
}
122+
},
123+
};
124+
}
125+
126+
interface Booted {
127+
stack: VerifyStack;
128+
ql: any;
129+
adminId: string;
130+
}
131+
132+
/** Boot APP, sign the dev admin in, and read the admin's id. */
133+
async function bootApp(): Promise<Booted> {
134+
const stack = await bootStack(APP as never, { extraPlugins: [new OrganizationsPlugin()] });
135+
await stack.signIn();
136+
const ql = await stack.kernel.getServiceAsync<any>('objectql');
137+
const adminId = String((await ql.findOne('sys_user', { where: { email: ADMIN_EMAIL }, ...SYS }))?.id ?? '');
138+
return { stack, ql, adminId };
139+
}
140+
141+
async function ownerTasks(ql: any, where: Record<string, unknown>): Promise<Array<Record<string, unknown>>> {
142+
return ql.find(TASK, { where: { name: 'Owner task', ...where }, ...SYS });
143+
}
144+
145+
describe('the walled Default Organization’s seed resolves the platform owner it is bound to', () => {
146+
const env = legEnv(WALLED_BOOT_ENV);
147+
let booted: Booted;
148+
let defaultOrgId: string;
149+
150+
beforeAll(async () => {
151+
env.apply();
152+
booted = await bootApp();
153+
defaultOrgId = String(
154+
(await booted.ql.findOne('sys_organization', { where: { slug: 'default' }, ...SYS }))?.id ?? '',
155+
);
156+
}, 120_000);
157+
158+
afterAll(async () => {
159+
await booted?.stack.stop();
160+
env.restore();
161+
});
162+
163+
it('PREMISE: the wall is up, and the Default Organization’s only member is the platform owner', async () => {
164+
const tenancy: any = await booted.stack.kernel.getServiceAsync('tenancy');
165+
expect(tenancy.posture).toBe('isolated');
166+
expect(tenancy.isolationActive).toBe(true);
167+
expect(booted.adminId).not.toBe('');
168+
expect(defaultOrgId).not.toBe('');
169+
const members: Array<Record<string, unknown>> = await booted.ql.find('sys_member', {
170+
where: { organization_id: defaultOrgId },
171+
...SYS,
172+
});
173+
expect(members.map((m) => [m.user_id, m.role])).toEqual([[booted.adminId, 'owner']]);
174+
});
175+
176+
it('the replay seeded the Default Organization once, and every person reference naming the owner resolves to the owner', async () => {
177+
const rows = await ownerTasks(booted.ql, { organization_id: defaultOrgId });
178+
expect(rows).toHaveLength(1);
179+
expect(rows[0]).toMatchObject({
180+
assignee: booted.adminId,
181+
reviewer: booted.adminId,
182+
owner_id: booted.adminId,
183+
});
184+
});
185+
});
186+
187+
describe('control: the same seed on an un-walled boot reads as it did before the fix', () => {
188+
const env = legEnv([
189+
['OS_TENANCY_POSTURE', undefined],
190+
['OS_AUTH_MEMBERSHIP_POLICY', undefined],
191+
]);
192+
let booted: Booted;
193+
194+
beforeAll(async () => {
195+
env.apply();
196+
booted = await bootApp();
197+
}, 120_000);
198+
199+
afterAll(async () => {
200+
await booted?.stack.stop();
201+
env.restore();
202+
});
203+
204+
it('the wall is down, the seed landed once before the admin existed, and only the handoff owns the row', async () => {
205+
const tenancy: any = await booted.stack.kernel.getServiceAsync('tenancy');
206+
expect(tenancy.isolationActive).toBe(false);
207+
expect(booted.adminId).not.toBe('');
208+
const rows = await ownerTasks(booted.ql, {});
209+
expect(rows).toHaveLength(1);
210+
expect(rows[0]).toMatchObject({ assignee: null, reviewer: null, owner_id: booted.adminId });
211+
});
212+
});

‎packages/plugins/organizations/src/organizations-plugin.test.ts‎

Lines changed: 122 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
22

3-
import { describe, it, expect, vi } from 'vitest';
3+
import { describe, it, expect, vi, afterEach } from 'vitest';
4+
import { resetPlatformAdminEmailMemo } from '@objectstack/core';
45
import { OrganizationsPlugin } from './organizations-plugin.js';
56

67
// ⛔ Nothing is granted here, and nothing needs to be. In the closed runtime
@@ -471,3 +472,123 @@ describe('per-org seed replay names the founder (#30281)', () => {
471472
expect(seedReplayer.mock.calls[0]).toEqual(['org_sys']);
472473
});
473474
});
475+
476+
// [#34425] The walled default-organization bootstrap writes the `default`
477+
// organization as SYSTEM, with no person behind it, and then the platform
478+
// owner's member row. Its replay waits for that member row, the same way an
479+
// organization a person created does (#34038), and names the owner it binds.
480+
// When the bootstrap binds nobody, the replay still runs, with no person, once
481+
// the bootstrap call is over. The real walled boot is pinned in
482+
// `default-organization-seed-owner.wall.test.ts`; these pin the two branches
483+
// on an engine double whose inserts run the plugin's middlewares.
484+
describe('the walled default-organization bootstrap replays after the owner it binds (#34425)', () => {
485+
const OWNER_EMAIL = 'owner@bootstrap.test';
486+
type Row = Record<string, unknown>;
487+
488+
function makeEngine(store: Record<string, Row[]>, options: { refuseMembers?: boolean } = {}) {
489+
const middlewares: any[] = [];
490+
const matches = (row: Row, where: Row | undefined): boolean =>
491+
!where ||
492+
Object.entries(where).every(([key, value]) => {
493+
// ⛔ Refuse a combinator rather than reading it as a field name
494+
// (`pnpm check:where-matcher`): exact-match keys only.
495+
if (key.startsWith('$')) throw new Error(`fake engine: WHERE combinator \`${key}\` is not implemented`);
496+
return value === null ? row[key] == null : row[key] === value;
497+
});
498+
const ql: any = {
499+
registerMiddleware: (mw: any) => middlewares.push(mw),
500+
getSchema: () => null,
501+
find: vi.fn(async (object: string, query: any) => {
502+
const rows = (store[object] ?? []).filter((r) => matches(r, query?.where));
503+
return rows.slice(0, query?.limit ?? rows.length);
504+
}),
505+
insert: vi.fn(async (object: string, data: Row, opts?: { context?: Row }) => {
506+
if (object === 'sys_member' && options.refuseMembers) throw new Error('member write refused');
507+
(store[object] ??= []).push({ ...data });
508+
// Each middleware awaits `next()` first, so running them after the
509+
// store is the order the engine gives them.
510+
const opCtx = { object, operation: 'insert', data, result: { ...data }, context: opts?.context };
511+
for (const mw of middlewares) await mw(opCtx, async () => {});
512+
return { ...data };
513+
}),
514+
};
515+
return { ql, middlewares };
516+
}
517+
518+
async function bootWalled(options: { refuseMembers?: boolean } = {}) {
519+
process.env.OS_TENANCY_POSTURE = 'isolated';
520+
process.env.OS_PLATFORM_OWNER_EMAIL = OWNER_EMAIL;
521+
resetPlatformAdminEmailMemo();
522+
const store: Record<string, Row[]> = {};
523+
const { ql } = makeEngine(store, options);
524+
const replays: Array<{ args: unknown[]; membersAtReplay: Row[] }> = [];
525+
const seedReplayer = vi.fn(async (...args: unknown[]) => {
526+
replays.push({ args, membersAtReplay: [...(store.sys_member ?? [])] });
527+
return { inserted: 1, updated: 0, skipped: 0, errors: [] };
528+
});
529+
const services: Record<string, unknown> = {
530+
manifest: { register: vi.fn() },
531+
objectql: ql,
532+
settings: {
533+
getNamespace: vi.fn(async () => ({ values: { membership_policy: { value: 'invite-only', source: 'env' } } })),
534+
},
535+
auth: { getMembershipPolicy: () => 'invite-only' },
536+
'seed-datasets': [{ object: 'crm_account', records: [{ id: 'a1' }] }],
537+
'seed-replayer': seedReplayer,
538+
};
539+
const ctx: any = {
540+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
541+
registerService: (name: string, svc: unknown) => {
542+
services[name] = svc;
543+
},
544+
getService: (name: string) => {
545+
if (!(name in services)) throw new Error(`service not registered: ${name}`);
546+
return services[name];
547+
},
548+
// No `kernel:ready` is fired: the owner's verified `sys_user` insert is
549+
// the trigger, as on a walled boot.
550+
hook: vi.fn(),
551+
};
552+
const plugin = new OrganizationsPlugin();
553+
await plugin.init(ctx);
554+
await plugin.start(ctx);
555+
// The declared owner's verified account lands: a bootstrap trigger.
556+
await ql.insert(
557+
'sys_user',
558+
{ id: 'usr_owner', email: OWNER_EMAIL, email_verified: true, name: 'Owner', created_at: '2026-01-01' },
559+
{ context: { isSystem: true } },
560+
);
561+
return { store, replays };
562+
}
563+
564+
const savedPosture = process.env.OS_TENANCY_POSTURE;
565+
const savedOwner = process.env.OS_PLATFORM_OWNER_EMAIL;
566+
afterEach(() => {
567+
if (savedPosture === undefined) delete process.env.OS_TENANCY_POSTURE;
568+
else process.env.OS_TENANCY_POSTURE = savedPosture;
569+
if (savedOwner === undefined) delete process.env.OS_PLATFORM_OWNER_EMAIL;
570+
else process.env.OS_PLATFORM_OWNER_EMAIL = savedOwner;
571+
resetPlatformAdminEmailMemo();
572+
});
573+
574+
it('replays the default organization once, inside the owner\'s member write, naming the owner', async () => {
575+
const { store, replays } = await bootWalled();
576+
577+
const orgId = store.sys_organization?.[0]?.id;
578+
expect(store.sys_organization?.map((o) => o.slug)).toEqual(['default']);
579+
expect(replays.map((r) => r.args)).toEqual([[orgId, { userId: 'usr_owner' }]]);
580+
// The owner's member row was stored before the replay read membership.
581+
expect(replays[0]!.membersAtReplay.map((m) => [m.organization_id, m.user_id, m.role])).toEqual([
582+
[orgId, 'usr_owner', 'owner'],
583+
]);
584+
});
585+
586+
it('control: when the bootstrap binds nobody, the default organization still replays once, with no person', async () => {
587+
const { store, replays } = await bootWalled({ refuseMembers: true });
588+
589+
const orgId = store.sys_organization?.[0]?.id;
590+
expect(orgId).toBeTruthy();
591+
expect(store.sys_member ?? []).toEqual([]);
592+
expect(replays.map((r) => r.args)).toEqual([[orgId]]);
593+
});
594+
});

0 commit comments

Comments
 (0)