Skip to content

Commit 2d94860

Browse files
fix(organizations): a new organization's seed resolves its founder (#34415)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XRT27U1unc64yMdYqqPWFjw)_ Fixes #34038 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:隔离(walled)部署下用户新建组织时,示例数据(seed)的回放从"组织行写入时"推迟到"创建者成为该组织成员之后",示例数据里指向创建者的负责人、指派人等字段现在能正确填上。 - 为什么改:原来回放早于创建者的成员行写入,新组织里一个成员都没有,示例数据里所有人员字段都是空的(连创建者本人也匹配不上),这是新托管组织看到的第一批数据。 - 风险与回滚:只改了 `@objectstack/organizations` 一个中间件的触发时机;默认组织、系统写入等其它建组织路径不变,每个组织仍只回放一次。回滚即还原这一个 PR。 - 先看:`packages/plugins/organizations/src/organizations-plugin.ts`(Middleware B 的等待与回放逻辑)、`organization-create-seed-founder.wall.test.ts`(真实启动的复现测试)。 - 两分钟验证:`pnpm --filter @objectstack/organizations exec vitest run src/organization-create-seed-founder.wall.test.ts`,预期 3 个用例全绿;在 main 上同一测试的第二个用例是红的(创建者的三个人员字段为空)。 - 需要你做的:无,席位落地。 ## What changes **Landing point: `packages/plugins/organizations/src/organizations-plugin.ts`, not the packages the claim's file surface named.** Measurement put the replay trigger in `@objectstack/organizations` (Middleware B, the `sys_organization` insert middleware that calls the `seed-replayer` service). `packages/runtime` only registers the replayer and `plugin-auth` only writes the rows, so the producer of the wrong order is this middleware, and the fix is there. No file under `packages/runtime`, `packages/plugins/plugin-auth` or `packages/plugins/plugin-security` changes. The order on main, measured: better-auth's `createOrganization` (1.7.12) writes the organization (`adapter.createOrganization`), then the founder's member row (`adapter.createMember`), then calls `afterCreateOrganization`. No database transaction wraps the core flow on this adapter (`objectql-adapter.ts`: native transactions are scoped to SCIM requests). Middleware B replayed inside the organization insert, so the replay's membership probe found no member. The change: - An organization insert that carries `attributedUserId` (the better-auth adapter's own write: `withSystemContext` stamps it with the signed-in creator) no longer replays on the insert. It waits for that organization's first `sys_member` insert and replays inside it, after the row is stored, with the founder still passed as the locale user (the existing founder-locale behaviour). - The waiting entry is removed before the replay runs, so later members never replay again: one replay per organization. - Every other organization insert replays on the insert, exactly as before: a SYSTEM insert with no person behind it (the Default Organization bootstrap, whose seed-ownership handoff reads the rows that replay landed; imports; migrations), and a `userId` context. - An entry that waits more than ten minutes (a create that failed between its two writes) is dropped at the next create, with one `warn` naming the organization and the remedy (the `seed-replayer` service). - `onOrganizationCreated` (a public host hook) sees no change: it runs from `afterCreateOrganization`, after the member write, so the seed rows were there before it on main and still are. No hook signature or payload changes. ## Tests - New `packages/plugins/organizations/src/organization-create-seed-founder.wall.test.ts`: `bootStack` (`@objectstack/verify`), the real `AuthPlugin`, `SecurityPlugin`, `AppPlugin` replayer and this package's `OrganizationsPlugin` under `OS_TENANCY_POSTURE=isolated`. A signed-up user creates an organization through `POST /auth/organization/create`. The app's seed names the founder in a `user` field, a `lookup` to `sys_user` and the injected `owner_id`, and names a second real user who is not a member. - the founder's three references store the founder's user id; - control: the non-member's reference stays NULL, with its "not a member of organization" error; - premise: the wall is up, and the new organization's only member is the founder. - `organizations-plugin.test.ts`: the founder-locale pin now drives the organization insert and then the member insert (it pinned the replay on the insert, which is the defect); two new pins: an attributed create waits for ITS organization's first member and replays once (a member of another organization does not release it, a second member does not replay again); a member row of an organization nothing waits on replays nothing. <details><summary>Red on main, green on the fix, ablation</summary> Red, on the unmodified tree (`cfcba539`): ```text 2026-11-16T14:05:52.691Z ERROR [SeedLoader] Deferred reference UNRESOLVED after pass 2 — seedfounder_task.assignee is NULL at the end of pass 2 on record 'Welcome task'. ... the sys_user row that answers to it is not a member of organization 1AfCsr9ICM3TNNIhAdElR0VHtT3zyyn9, the organization this load seeds ... × the replay seeded the new organization, and every person reference naming the founder resolves to the founder 7ms Test Files 1 failed (1) Tests 1 failed | 2 passed (3) os-verify-lock: VERDICT command-exit 1 ``` Green, on `1ab5ceac` (the fix; `803cc501` adds only the changeset): ```text Test Files 2 passed (2) Tests 25 passed (25) os-verify-lock: VERDICT command-exit 0 ``` Ablation, after committing the fix: `organizations-plugin.ts` restored from the base commit (anchor `awaitingFirstMember` counted 0 on disk), the wall test run, the file restored with `git checkout HEAD --` (anchor count 7, `git hash-object` equal to the HEAD blob `8b6ea276`, `git diff HEAD` empty). The test imports the plugin from source, so no build was involved. ```text × the replay seeded the new organization, and every person reference naming the founder resolves to the founder 7ms Tests 1 failed | 2 passed (3) os-verify-lock: VERDICT command-exit 1 ``` Package suite and typecheck on `1ab5ceac`: ```text pnpm --filter @objectstack/organizations test Test Files 19 passed (19) · Tests 257 passed (257) pnpm --filter @objectstack/organizations typecheck tsc --noEmit clean · check:test-typecheck: OK os-verify-lock: VERDICT command-exit 0 ``` </details> ## Acceptance notes - **Residual, same failure on another door, not changed here:** a server-side `auth.api.createOrganization({ body: { userId } })` call made with no auth request in scope carries no `attributedUserId`, so it still replays on the insert, before the member row. No caller of that form exists in this repository (searched `packages/plugins/plugin-auth`, `organizations`, `runtime`, `cloud-connection`); a host calling it gets the old order. - **Out of scope, filed as #34425:** on a walled boot the Default Organization bootstrap (`ensure-default-organization.ts`) inserts its organization as SYSTEM, with no attributed person, so the per-organization replay still runs on that insert, before the platform owner's `sys_member` row is written. Measured on a walled `bootStack` at `e2f88e49` (dev report 6923080865 on #34038): a seed record naming the owner in a `Field.user()` column and in `owner_id` stored the user column as NULL ("not a member of organization ORG" at pass 2); `owner_id` reads the owner only because the seed-ownership handoff claims NULL `owner_id` rows after the bind. This PR leaves that path unchanged. - No public contract moves: no spec, export, hook signature or payload change, and `onOrganizationCreated` observes the same state as before. ## Verification Local gate subset, derived with `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` against `803cc501` (68 families): 64 ran with exit 0. Four were not measured locally and are left to CI: - `node scripts/check-plugin-teardown-shape.mjs --self-test`: exit 3, PREREQUISITE NOT MET (its positive control is pinned to a commit outside this shallow clone). - `pnpm check:dual-build-cjs-loads`: exit 3, PREREQUISITE NOT MET (other packages unbuilt in this worktree). - `pnpm check:query-options-erasure` and `pnpm check:type-check-debt`: stopped by my 300 s local cap (exit 124), repository-wide scans. The organizations package's own `typecheck` ran green above. `--ran` reconciliation: `68 derived, 64 run, 0 NOT-MEASURED, 4 UNRUN`, the four above. Open PRs touching `organizations-plugin.ts` or its test: none of 51 open PRs. `git merge-tree` against `origin/main`: clean. --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5pNoRjsgMJKr5utN33)_ <!-- signed: repo:objectstack#1 · os-project-manager · session_01FEkQ5pNoRjsgMJKr5utN33 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 20bf222 commit 2d94860

4 files changed

Lines changed: 280 additions & 7 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/organizations': patch
3+
---
4+
5+
fix(organizations): a new organization's seed resolves its founder
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
On a walled (`isolated`) deployment, `POST /api/v1/auth/organization/create` replayed the app's seed into the new organization before better-auth wrote the founder's `sys_member` row. A seed loaded into an organization resolves a person only through membership in that organization, so every person reference the seed declared (`Field.user()`, `Field.lookup('sys_user')`, the injected `owner_id`) was stored empty with "not a member of organization ORG", the founder's included.
11+
12+
The per-organization replay now waits, for an organization a signed-in person creates (`POST /api/v1/auth/organization/create`, whose `sys_organization` insert carries that person as `attributedUserId`), until that organization's first `sys_member` row is stored, and replays then. A seed record naming the founder now stores the founder's user id. A person who is not a member of the new organization still resolves to nothing, with the same warning. The replay still runs once per organization, still seeds in the founder's language, and still finishes before a host's `onOrganizationCreated` callback runs. Organizations created any other way (the Default Organization bootstrap, a system insert, or a server-side `auth.api.createOrganization({ body: { userId } })` call made with no auth request in scope, whose insert carries no `attributedUserId`) replay on the insert, as before.
Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* A new organization's own seed resolves its founder (#34038).
5+
*
6+
* On a walled boot, better-auth's `POST /auth/organization/create` writes the
7+
* `sys_organization` row and THEN the founder's `sys_member` row, as two
8+
* separate adapter writes (better-auth's `createOrganization`: `createOrganization`,
9+
* then `createMember`, then `afterCreateOrganization`). This package's per-org
10+
* seed replay is the organization insert's middleware. When it ran on that
11+
* insert, the new organization had no member at all, and an organization-scoped
12+
* seed load resolves a person through membership in the load organization
13+
* (`seed-org-scoped-references.integration.test.ts` in `@objectstack/runtime`
14+
* pins that rule). So every person reference the app's seed declared landed
15+
* NULL with "not a member of organization ORG", the founder's included.
16+
*
17+
* ## What is real
18+
*
19+
* `bootStack` (`@objectstack/verify`): an `ObjectKernel` over in-process
20+
* SQLite, the real `AuthPlugin` (better-auth organizations), `SecurityPlugin`,
21+
* the real `AppPlugin` seed replayer, and THIS package's `OrganizationsPlugin`,
22+
* under `OS_TENANCY_POSTURE=isolated`. The organization is created through the
23+
* product's own door by a signed-up user. Nothing is stubbed. Stored rows are
24+
* read back through the engine as SYSTEM.
25+
*/
26+
27+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
28+
import { bootStack, type VerifyStack } from '@objectstack/verify';
29+
import { OrganizationsPlugin } from './organizations-plugin.js';
30+
31+
const WALLED_BOOT_ENV = [
32+
['OS_TENANCY_POSTURE', 'isolated'],
33+
// A walled deployment must declare what a new user joins, or this package's
34+
// own boot gate refuses it.
35+
['OS_AUTH_MEMBERSHIP_POLICY', 'invite-only'],
36+
] as const;
37+
38+
const FOUNDER_EMAIL = 'seed-founder@verify.test';
39+
const FOUNDER_NAME = 'Founder Fiona';
40+
const STRANGER_EMAIL = 'seed-stranger@verify.test';
41+
const STRANGER_NAME = 'Stranger Sam';
42+
43+
const TASK = 'seedfounder_task';
44+
45+
const APP = {
46+
manifest: {
47+
id: 'com.example.seedfounder',
48+
namespace: 'seedfounder',
49+
version: '0.0.1',
50+
type: 'app',
51+
name: 'Seed Founder Fixture',
52+
},
53+
objects: [
54+
{
55+
name: TASK,
56+
label: 'Task',
57+
fields: {
58+
name: { type: 'text', label: 'Name' },
59+
assignee: { type: 'user', label: 'Assignee', reference: 'sys_user' },
60+
reviewer: { type: 'lookup', label: 'Reviewer', reference: 'sys_user' },
61+
},
62+
},
63+
],
64+
data: [
65+
{
66+
object: TASK,
67+
mode: 'upsert',
68+
externalId: 'name',
69+
records: [
70+
// Every person reference the seed can carry names the founder.
71+
{ name: 'Welcome task', assignee: FOUNDER_NAME, reviewer: FOUNDER_NAME, owner_id: FOUNDER_NAME },
72+
// A real person who is not a member of the new organization.
73+
{ name: 'Outside task', assignee: STRANGER_NAME },
74+
],
75+
},
76+
],
77+
};
78+
79+
const SYS = { context: { isSystem: true } } as const;
80+
81+
/** Boot the walled stack once at module scope and stop it: the first boot's loading is paid here, never in a clocked hook. */
82+
async function warmUp(): Promise<void> {
83+
const before = { ...process.env };
84+
for (const [name, value] of WALLED_BOOT_ENV) process.env[name] = value;
85+
try {
86+
const stack = await bootStack({ manifest: { ...APP.manifest, id: 'com.example.seedfounder.warmup' }, objects: [] } as never, {
87+
extraPlugins: [new OrganizationsPlugin()],
88+
});
89+
await stack.stop();
90+
} finally {
91+
for (const key of Object.keys(process.env)) if (!(key in before)) delete process.env[key];
92+
Object.assign(process.env, before);
93+
}
94+
}
95+
await warmUp();
96+
97+
describe('a new organization’s own seed resolves its founder (#34038)', () => {
98+
const restoreEnv: Array<[string, string | undefined]> = [];
99+
let stack: VerifyStack;
100+
let ql: any;
101+
let founderId: string;
102+
let strangerId: string;
103+
let organizationId: string;
104+
105+
const tasksOf = async (orgId: string): Promise<Record<string, Record<string, unknown>>> => {
106+
const rows: Array<Record<string, unknown>> = await ql.find(TASK, { where: { organization_id: orgId }, ...SYS });
107+
return Object.fromEntries(rows.map((r) => [String(r.name), r]));
108+
};
109+
110+
beforeAll(async () => {
111+
for (const [name, value] of WALLED_BOOT_ENV) {
112+
restoreEnv.push([name, process.env[name]]);
113+
process.env[name] = value;
114+
}
115+
stack = await bootStack(APP as never, { extraPlugins: [new OrganizationsPlugin()] });
116+
ql = await stack.kernel.getServiceAsync('objectql');
117+
118+
const founder = await stack.signUp(FOUNDER_EMAIL, undefined, FOUNDER_NAME);
119+
await stack.signUp(STRANGER_EMAIL, undefined, STRANGER_NAME);
120+
founderId = (await ql.findOne('sys_user', { where: { email: FOUNDER_EMAIL }, ...SYS }))?.id;
121+
strangerId = (await ql.findOne('sys_user', { where: { email: STRANGER_EMAIL }, ...SYS }))?.id;
122+
123+
const created = await stack.apiAs(founder, 'POST', '/auth/organization/create', {
124+
name: 'Seed Founder Co',
125+
slug: 'seed-founder-co',
126+
});
127+
expect(created.status, `organization/create: ${await created.clone().text()}`).toBe(200);
128+
organizationId = ((await created.json()) as { id: string }).id;
129+
}, 120_000);
130+
131+
afterAll(async () => {
132+
await stack?.stop();
133+
for (const [name, value] of restoreEnv.reverse()) {
134+
if (value === undefined) delete process.env[name];
135+
else process.env[name] = value;
136+
}
137+
});
138+
139+
it('PREMISE: the wall is up, the founder is a member of the new organization and the stranger is not', async () => {
140+
const tenancy: any = await stack.kernel.getServiceAsync('tenancy');
141+
expect(tenancy.posture).toBe('isolated');
142+
expect(tenancy.isolationActive).toBe(true);
143+
expect(founderId).toBeTruthy();
144+
expect(strangerId).toBeTruthy();
145+
const members: Array<Record<string, unknown>> = await ql.find('sys_member', { where: { organization_id: organizationId }, ...SYS });
146+
expect(members.map((m) => m.user_id)).toEqual([founderId]);
147+
});
148+
149+
it('the replay seeded the new organization, and every person reference naming the founder resolves to the founder', async () => {
150+
const tasks = await tasksOf(organizationId);
151+
expect(Object.keys(tasks).sort()).toEqual(['Outside task', 'Welcome task']);
152+
expect(tasks['Welcome task']).toMatchObject({ assignee: founderId, reviewer: founderId, owner_id: founderId });
153+
});
154+
155+
it('control: a real person who is not a member of the new organization still resolves to nothing', async () => {
156+
const tasks = await tasksOf(organizationId);
157+
expect(tasks['Outside task']?.assignee ?? null).toBeNull();
158+
});
159+
});

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

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,14 @@ describe('per-org seed replay names the founder (#30281)', () => {
407407
result: { id },
408408
context,
409409
});
410+
/** better-auth's member write, as the adapter hands it to the engine. */
411+
const memberInsert = (organizationId: string, userId: string) => ({
412+
object: 'sys_member',
413+
operation: 'insert' as const,
414+
data: { organization_id: organizationId, user_id: userId, role: 'owner' },
415+
result: { id: `mem_${organizationId}_${userId}`, organization_id: organizationId, user_id: userId, role: 'owner' },
416+
context: { isSystem: true, attributedUserId: userId },
417+
});
410418

411419
async function startWithReplayer() {
412420
const plugin = new OrganizationsPlugin();
@@ -424,11 +432,36 @@ describe('per-org seed replay names the founder (#30281)', () => {
424432
const { seedReplayer, middlewares } = await startWithReplayer();
425433

426434
await middlewares[1](insertBy('org_zh', { isSystem: true, attributedUserId: 'usr_founder' }), async () => {});
435+
// [#34038] better-auth writes the founder's member row next; the replay runs on it.
436+
await middlewares[1](memberInsert('org_zh', 'usr_founder'), async () => {});
427437

428438
expect(seedReplayer).toHaveBeenCalledTimes(1);
429439
expect(seedReplayer.mock.calls[0]).toEqual(['org_zh', { userId: 'usr_founder' }]);
430440
});
431441

442+
it('[#34038] an organization a person created waits for its first member row, and replays once', async () => {
443+
const { seedReplayer, middlewares } = await startWithReplayer();
444+
445+
await middlewares[1](insertBy('org_wait', { isSystem: true, attributedUserId: 'usr_founder' }), async () => {});
446+
expect(seedReplayer).not.toHaveBeenCalled();
447+
448+
// A member of ANOTHER organization does not release it.
449+
await middlewares[1](memberInsert('org_other', 'usr_founder'), async () => {});
450+
expect(seedReplayer).not.toHaveBeenCalled();
451+
452+
await middlewares[1](memberInsert('org_wait', 'usr_founder'), async () => {});
453+
await middlewares[1](memberInsert('org_wait', 'usr_colleague'), async () => {});
454+
expect(seedReplayer.mock.calls).toEqual([['org_wait', { userId: 'usr_founder' }]]);
455+
});
456+
457+
it('[#34038] a member row of an organization nobody is waiting on replays nothing', async () => {
458+
const { seedReplayer, middlewares } = await startWithReplayer();
459+
460+
await middlewares[1](memberInsert('org_existing', 'usr_someone'), async () => {});
461+
462+
expect(seedReplayer).not.toHaveBeenCalled();
463+
});
464+
432465
it('keeps the one-argument call when no person founded the organization', async () => {
433466
const { seedReplayer, middlewares } = await startWithReplayer();
434467

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

Lines changed: 76 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,14 @@ function readSeededRecordIds(
4242
}
4343
}
4444

45+
/**
46+
* [#34038] How long an organization better-auth created may wait for its first
47+
* `sys_member` row before Middleware B stops waiting and says so. better-auth
48+
* writes that row in the same request, milliseconds later; an entry this old
49+
* belongs to a create that failed between the two writes.
50+
*/
51+
const FIRST_MEMBER_WAIT_MS = 10 * 60_000;
52+
4553
async function resolveKernelService(kernel: any, name: string): Promise<any> {
4654
if (typeof kernel?.getServiceAsync === 'function') {
4755
try {
@@ -136,7 +144,9 @@ interface OrgScopingMetadataSlot {
136144
* `tenant_isolation` RLS policy hides them from the very user
137145
* who just created them.
138146
*
139-
* 2. **per-org seed replay** — after `sys_organization` insert, load
147+
* 2. **per-org seed replay** — after `sys_organization` insert (for an
148+
* organization better-auth creates, after its founder's `sys_member`
149+
* row, so the seed's person references resolve them), load
140150
* the APP's own demo seed data into the new org, by replaying the
141151
* registered `seed-datasets` through the kernel-level
142152
* `seed-replayer` callable (set by AppPlugin). It reads no other
@@ -386,17 +396,77 @@ export class OrganizationsPlugin implements Plugin {
386396
});
387397

388398
// ── Middleware B: per-org seed pipeline on sys_organization insert ─
399+
//
400+
// [#34038] WHEN the replay runs depends on who created the organization.
401+
//
402+
// better-auth's `organization/create` writes the `sys_organization` row and
403+
// THEN the founder's `sys_member` row, as two separate adapter writes. An
404+
// organization-scoped seed load resolves a person through membership in the
405+
// load organization (`Field.user()`, `Field.lookup('sys_user')`, the injected
406+
// `owner_id`), so a replay run on the organization insert finds no member at
407+
// all: every person reference the seed declared, the founder's included,
408+
// landed NULL with "not a member of organization ORG". better-auth's create
409+
// is the only `sys_organization` insert that carries `attributedUserId` (the
410+
// adapter's `withSystemContext` stamps the signed-in creator), and it always
411+
// writes the creator's member row next. So an organization insert attributed to a person waits for the
412+
// organization's FIRST `sys_member` insert and replays inside it, after that
413+
// row is stored. better-auth's create runs no database transaction here, so
414+
// the stored row is what the replay's membership probe reads. Everything a
415+
// host's `onOrganizationCreated` observes is unchanged: it runs from
416+
// `afterCreateOrganization`, after the member write, so the seed rows are
417+
// there before it either way.
418+
//
419+
// Every other organization insert replays on the insert, exactly as before:
420+
// a SYSTEM insert with no person behind it (the default-organization
421+
// bootstrap, whose seed-ownership handoff below reads the rows this replay
422+
// landed; imports; migrations) gets no member write it could wait for.
423+
//
424+
// ⛔ One replay per organization: the entry is removed before the replay
425+
// runs, so a second member never replays again.
426+
const awaitingFirstMember = new Map<string, { founderId: string; since: number }>();
427+
const forgetAbandonedCreates = (now: number) => {
428+
for (const [organizationId, entry] of awaitingFirstMember) {
429+
if (now - entry.since < FIRST_MEMBER_WAIT_MS) continue;
430+
awaitingFirstMember.delete(organizationId);
431+
ctx.logger.warn(
432+
`[org-scoping] organization ${organizationId} was created by ${entry.founderId}, but no member row ` +
433+
`followed within ${FIRST_MEMBER_WAIT_MS / 60_000} minutes, so its seed was not replayed. ` +
434+
'The create did not finish; an organization with no member has nobody to see the data. ' +
435+
'Once it has a member, the seed-replayer service called with its id loads the seed.',
436+
{ organizationId, founderId: entry.founderId },
437+
);
438+
}
439+
};
389440
ql.registerMiddleware(async (opCtx: any, next: () => Promise<void>) => {
390441
await next();
391-
if (
392-
opCtx?.object !== 'sys_organization' ||
393-
(opCtx?.operation !== 'create' && opCtx?.operation !== 'insert')
394-
) {
442+
if (opCtx?.operation !== 'create' && opCtx?.operation !== 'insert') return;
443+
444+
if (opCtx?.object === 'sys_member') {
445+
if (awaitingFirstMember.size === 0) return;
446+
const organizationId = opCtx?.result?.organization_id ?? opCtx?.data?.organization_id;
447+
const waiting = typeof organizationId === 'string' ? awaitingFirstMember.get(organizationId) : undefined;
448+
if (!waiting) return;
449+
awaitingFirstMember.delete(organizationId);
450+
await replayOrganizationSeed(organizationId, waiting.founderId);
395451
return;
396452
}
453+
454+
if (opCtx?.object !== 'sys_organization') return;
397455
const newOrgId = opCtx?.result?.id ?? opCtx?.data?.id;
398456
if (!newOrgId) return;
399457

458+
const attributedFounder = opCtx?.context?.attributedUserId;
459+
if (typeof attributedFounder === 'string' && attributedFounder !== '') {
460+
const now = Date.now();
461+
forgetAbandonedCreates(now);
462+
awaitingFirstMember.set(String(newOrgId), { founderId: attributedFounder, since: now });
463+
return;
464+
}
465+
const userId = opCtx?.context?.userId;
466+
await replayOrganizationSeed(newOrgId, typeof userId === 'string' && userId !== '' ? userId : undefined);
467+
});
468+
469+
const replayOrganizationSeed = async (newOrgId: string, founderId: string | undefined): Promise<void> => {
400470
const kernel: any = (ctx as any).kernel ?? ctx;
401471
const datasetsRaw = await resolveKernelService(kernel, 'seed-datasets');
402472
const datasets: any[] | undefined =
@@ -413,7 +483,6 @@ export class OrganizationsPlugin implements Plugin {
413483
// SYSTEM with the signed-in creator as `attributedUserId`; a
414484
// system insert with no person behind it names nobody, and the
415485
// replay falls back to the app's declared default locale.
416-
const founderId = opCtx?.context?.attributedUserId ?? opCtx?.context?.userId;
417486
const summary =
418487
typeof founderId === 'string' && founderId !== ''
419488
? await replayer(newOrgId, { userId: founderId })
@@ -478,7 +547,7 @@ export class OrganizationsPlugin implements Plugin {
478547
'Demo data on signup comes from the app\'s own seed definitions — never from another organization\'s rows.',
479548
{ organizationId: newOrgId },
480549
);
481-
});
550+
};
482551

483552
// ── Default-org bootstrap on kernel:ready + on admin grant ────────
484553
if (this.opts.ensureDefaultOrganization) {

0 commit comments

Comments
 (0)