Skip to content

Commit 8de810a

Browse files
committed
feat(cli): carry a form withdrawal onto a read-only package's view into its .custom pair (wip)
Claude-Session: https://claude.ai/code/session_01ADHkmQTt48dSV5oqZ5jUhK Co-authored-by: Claude <noreply@anthropic.com>
1 parent aca58cd commit 8de810a

4 files changed

Lines changed: 496 additions & 4 deletions

File tree

‎packages/cli/src/commands/migrate/organization-ownership.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ import {
4141
import {
4242
applyOrganizationOwnership,
4343
checkpointFromDetails,
44+
protocolCustomizationPairs,
4445
MetadataChoiceRefusal,
4546
ORGANIZATION_OWNERSHIP_MIGRATION_ID,
4647
judgeDeclaredSharingRules,
@@ -751,7 +752,7 @@ export default class OrganizationOwnershipCeremony extends Command {
751752
// The dialect, once, before the first statement: an unresolved one is
752753
// refused here, naming the driver, and never read as SQLite.
753754
const dialect = ceremonyDialectOf(stack.driver);
754-
const { normalizeRows } = await import('@objectstack/metadata-protocol');
755+
const { isWritablePackage, normalizeRows } = await import('@objectstack/metadata-protocol');
755756
// [#23816] A boot that skipped schema sync measured no table absent, so
756757
// the ledger's presence is read from the catalog instead.
757758
const ledgerAbsent = stack.schemaSync === 'skipped'
@@ -774,6 +775,7 @@ export default class OrganizationOwnershipCeremony extends Command {
774775
getMetaItems?: (request: { type: string }) => Promise<{ items?: unknown[] } | unknown[]>;
775776
getMetaItemsForExecution?: (request: { type: string }) => Promise<{ items?: unknown[] }>;
776777
getMetaItem?: (request: { type: string; name: string; packageId?: string }) => Promise<unknown>;
778+
ensureCustomizationPackage?: (request: { basePackageId: string }) => Promise<{ packageId: string }>;
777779
} | undefined;
778780
const catalog = createSecurityCatalogReader({
779781
registry: engine.registry as never,
@@ -926,6 +928,21 @@ export default class OrganizationOwnershipCeremony extends Command {
926928
};
927929
},
928930
},
931+
// [ADR-0146 D1, D3] A withdrawal onto a read-only package's view goes
932+
// into its `.custom` pair: the save door's own writability predicate,
933+
// and the ensure door, in process.
934+
pairs: protocolCustomizationPairs({
935+
ensureCustomizationPackage: async (request) => {
936+
if (typeof protocol?.ensureCustomizationPackage !== 'function') {
937+
throw new Error('no metadata protocol is composed on this stack');
938+
}
939+
return protocol.ensureCustomizationPackage(request);
940+
},
941+
isWritablePackage: (packageId) => isWritablePackage(engine, packageId),
942+
baseVersion: (packageId) =>
943+
(engine.registry as { getPackage?(id: string): { manifest?: { version?: unknown } } | undefined } | undefined)
944+
?.getPackage?.(packageId)?.manifest?.version,
945+
}),
929946
views: {
930947
// The env-wide view list, exactly as the anonymous form doors read it.
931948
list: async () => {
Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* `os migrate organization-ownership --apply`, the form-withdrawal carry onto
5+
* a view a READ-ONLY package ships (ADR-0146 D1, D2, D3).
6+
*
7+
* The read-only base itself takes no customization: the metadata door refuses
8+
* a save naming it where its `.custom` pair can take the write (the named-base
9+
* close). So the carry ensures the pair through the ensure door and saves the
10+
* withdrawal into it, declaring `overrides: { package: <base>, basedOn }`.
11+
*
12+
* ## The fixture
13+
*
14+
* A project whose config is a booted code package (read-only: its manifest is
15+
* registered at boot) shipping an object and a public form view, over a
16+
* database a served boot of this tree left behind, shaped like v17:
17+
* `sys_metadata` carries `organization_id`, and an organization's row of the
18+
* form view withdraws it (`sharing.enabled: false`).
19+
*
20+
* ## What each case measures
21+
*
22+
* The real command, in process through oclif (plan, then `--apply`): the step
23+
* carries the withdrawal into the pair, the pair is in `sys_packages`, its row
24+
* declares the override at the base's version, and the env-wide view list the
25+
* anonymous doors judge by serves the form withdrawn. A second `--apply` over
26+
* the same database carries nothing more.
27+
*/
28+
29+
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
30+
import Database from 'better-sqlite3';
31+
import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
32+
import { randomBytes } from 'node:crypto';
33+
import { tmpdir } from 'node:os';
34+
import { dirname, join, resolve } from 'node:path';
35+
import { fileURLToPath } from 'node:url';
36+
import { anonymousFormIntakeCandidates, anonymousFormIntakeWithdrawnIn } from '@objectstack/metadata-core';
37+
import { isExitSignal } from '../../utils/format.js';
38+
import { bootSchemaStack } from '../../utils/schema-migrate.js';
39+
import MigrateOrganizationOwnership from './organization-ownership.js';
40+
41+
// [#10126] Pay the first load of what the command reaches through dynamic
42+
// `import()`s at MODULE LOAD, outside the clocked case.
43+
import '@objectstack/runtime';
44+
import '@objectstack/objectql';
45+
import '@objectstack/metadata-protocol';
46+
import { PackageServicePlugin } from '@objectstack/service-package';
47+
48+
const HERE = dirname(fileURLToPath(import.meta.url));
49+
const CLI_ROOT = resolve(HERE, '..', '..', '..');
50+
const CASE_TIMEOUT_MS = 240_000;
51+
52+
const OVERRIDING_ENV = [
53+
'OS_DATABASE_URL', 'DATABASE_URL', 'TURSO_DATABASE_URL', 'OS_DATABASE_DRIVER', 'OS_HOME', 'OS_ARTIFACT_PATH',
54+
'OS_TELEMETRY_DB', 'OS_AUTH_SECRET', 'OS_MULTI_ORG_ENABLED',
55+
] as const;
56+
57+
const BASE = 'com.example.wdpair';
58+
const PAIR = `${BASE}.custom`;
59+
const VERSION = '1.4.0';
60+
const VIEW = 'wdp_lead.intake';
61+
const SLUG = 'wdp-intake';
62+
const DATA = { provider: 'object', object: 'wdp_lead' };
63+
const FORM = {
64+
type: 'simple',
65+
data: DATA,
66+
sections: [{ name: 'main', label: 'Main', columns: 1, fields: [{ field: 'name' }] }],
67+
sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` },
68+
};
69+
const CONFIG = {
70+
manifest: { id: BASE, name: 'Withdrawal Pair', version: VERSION, type: 'app', namespace: 'wdp' },
71+
objects: [{ name: 'wdp_lead', label: 'Lead', fields: { name: { type: 'text', label: 'Name' } } }],
72+
views: [{ list: { label: 'Leads', type: 'grid', data: DATA, columns: [{ field: 'name' }] }, formViews: { intake: FORM } }],
73+
};
74+
/** The organization's 17.x row of the form view: the served body, the form withdrawn. */
75+
const WITHDRAWN = {
76+
name: VIEW,
77+
object: 'wdp_lead',
78+
viewKind: 'form',
79+
label: 'Intake',
80+
config: { ...FORM, sharing: { ...FORM.sharing, enabled: false } },
81+
};
82+
83+
let dir: string;
84+
let projectDir: string;
85+
let templateDb: string;
86+
const savedEnv: Record<string, string | undefined> = {};
87+
const savedCwd = process.cwd();
88+
89+
/** The real command over `dbFile`: the plan run first (its file is the reviewed plan), then `--apply`. */
90+
async function applyOver(dbFile: string, tag: string): Promise<{ report: any; exitCode: number }> {
91+
const savedExit = process.exitCode;
92+
const swallow = ((_chunk: unknown, ...rest: unknown[]) => {
93+
const cb = rest.find((a) => typeof a === 'function') as (() => void) | undefined;
94+
if (cb) cb();
95+
return true;
96+
}) as typeof process.stdout.write;
97+
const stdout = vi.spyOn(process.stdout, 'write').mockImplementation(swallow);
98+
vi.spyOn(process.stderr, 'write').mockImplementation(swallow);
99+
vi.spyOn(console, 'log').mockImplementation(() => {});
100+
vi.spyOn(console, 'warn').mockImplementation(() => {});
101+
vi.spyOn(console, 'error').mockImplementation(() => {});
102+
process.chdir(projectDir);
103+
let exitCode: number | undefined;
104+
try {
105+
const planFile = join(projectDir, `plan-${tag}.json`);
106+
await MigrateOrganizationOwnership.run(['--out', planFile, '--database-url', `file:${dbFile}`, '--json'], { root: CLI_ROOT });
107+
stdout.mockClear();
108+
try {
109+
await MigrateOrganizationOwnership.run(
110+
[
111+
'--apply', '--backup-taken', '--plan-file', planFile,
112+
'--out', join(projectDir, `apply-${tag}.json`), '--database-url', `file:${dbFile}`, '--json',
113+
],
114+
{ root: CLI_ROOT },
115+
);
116+
} catch (error) {
117+
if (!isExitSignal(error)) throw error;
118+
exitCode = (error as { oclif?: { exit?: number } }).oclif?.exit;
119+
}
120+
const payload = JSON.parse(stdout.mock.calls.map((c) => String(c[0])).join('').trim());
121+
expect(payload.error, JSON.stringify(payload).slice(0, 600)).toBeUndefined();
122+
return { report: payload.report, exitCode: exitCode ?? (process.exitCode as number | undefined) ?? 0 };
123+
} finally {
124+
process.chdir(savedCwd);
125+
process.exitCode = savedExit;
126+
vi.restoreAllMocks();
127+
}
128+
}
129+
130+
const promotion = (report: any): { status: string; summary: Record<string, number>; blockers: string[] } =>
131+
report.steps.find((s: { step: string }) => s.step === 'metadata-promotion');
132+
133+
/** The stored `view` rows of the form, `package/state`, with the declaration each body carries. */
134+
function storedForm(dbFile: string): Array<{ pkg: string; enabled: unknown; overrides: unknown }> {
135+
const db = new Database(dbFile, { readonly: true });
136+
try {
137+
return (db.prepare(`SELECT package_id, metadata FROM sys_metadata WHERE type = 'view' AND name = ? ORDER BY package_id`)
138+
.all(VIEW) as Array<{ package_id: string | null; metadata: string }>)
139+
.map((row) => {
140+
const body = JSON.parse(row.metadata) as { config?: { sharing?: { enabled?: unknown } }; overrides?: unknown };
141+
return { pkg: row.package_id ?? '-', enabled: body.config?.sharing?.enabled, overrides: body.overrides };
142+
});
143+
} finally {
144+
db.close();
145+
}
146+
}
147+
148+
/** On a fresh boot of `dbFile`: the base's served form, and the views the anonymous doors serve the slug from. */
149+
async function served(dbFile: string): Promise<{ base: unknown; open: string[] }> {
150+
process.chdir(projectDir);
151+
const stack = await bootSchemaStack({
152+
jsonOutput: false, databaseUrl: `file:${dbFile}`, projectRoot: projectDir, composeHostStack: true,
153+
// The package registry `os serve` composes, so the pair installs from `sys_packages` as it does there.
154+
extraPlugins: [new PackageServicePlugin()],
155+
});
156+
try {
157+
const protocol = stack.kernel.getService('protocol') as any;
158+
const base = (await protocol.getMetaItem({ type: 'view', name: VIEW, packageId: BASE }))?.item;
159+
const listed = await protocol.getMetaItems({ type: 'view' });
160+
const list = ((Array.isArray(listed) ? listed : listed?.items) ?? []) as Array<Record<string, unknown>>;
161+
const open = list
162+
.filter((v) => anonymousFormIntakeCandidates(v).some((c) => c.slug === SLUG && !anonymousFormIntakeWithdrawnIn(list, v, c)))
163+
.map((v) => `${String(v.name)}|${String(v._packageId ?? '')}`);
164+
return { base: (base as { config?: { sharing?: unknown } } | undefined)?.config?.sharing, open };
165+
} finally {
166+
await stack.shutdown();
167+
process.chdir(savedCwd);
168+
}
169+
}
170+
171+
beforeAll(async () => {
172+
for (const key of [...OVERRIDING_ENV, 'NODE_ENV', 'OS_SECRET_KEY'] as const) savedEnv[key] = process.env[key];
173+
for (const key of OVERRIDING_ENV) delete process.env[key];
174+
process.env.NODE_ENV = 'production';
175+
process.env.OS_SECRET_KEY = randomBytes(32).toString('hex');
176+
177+
dir = mkdtempSync(join(tmpdir(), 'os-ceremony-withdrawal-pair-'));
178+
projectDir = join(dir, 'project');
179+
mkdirSync(projectDir, { recursive: true });
180+
writeFileSync(join(projectDir, 'objectstack.config.mjs'), `export default ${JSON.stringify(CONFIG, null, 2)};\n`);
181+
182+
// A served boot of this tree provisions the tables; then the v17 shape.
183+
templateDb = join(dir, 'template.db');
184+
process.chdir(projectDir);
185+
try {
186+
const seed = await bootSchemaStack({
187+
jsonOutput: false, databaseUrl: `file:${templateDb}`, projectRoot: projectDir, composeHostStack: true,
188+
extraPlugins: [new PackageServicePlugin()],
189+
});
190+
await seed.shutdown();
191+
} finally {
192+
process.chdir(savedCwd);
193+
}
194+
const db = new Database(templateDb);
195+
try {
196+
db.exec(`ALTER TABLE "sys_metadata" ADD COLUMN "organization_id" varchar(255)`);
197+
const now = new Date().toISOString();
198+
db.prepare(
199+
`INSERT INTO sys_metadata (id, organization_id, type, name, package_id, state, version, created_at, updated_at, metadata) ` +
200+
`VALUES ('md_org', 'org_x', 'view', ?, NULL, 'active', 1, ?, ?, ?)`,
201+
).run(VIEW, now, now, JSON.stringify(WITHDRAWN));
202+
} finally {
203+
db.close();
204+
}
205+
}, CASE_TIMEOUT_MS);
206+
207+
afterAll(() => {
208+
process.chdir(savedCwd);
209+
for (const [key, value] of Object.entries(savedEnv)) {
210+
if (value === undefined) delete process.env[key];
211+
else process.env[key] = value;
212+
}
213+
rmSync(dir, { recursive: true, force: true });
214+
});
215+
216+
describe('organization-ownership --apply: a withdrawal onto a read-only package\'s view goes into its .custom pair', () => {
217+
it('⭐ carried into the pair, declared as the override of the base; the served form is withdrawn; a re-run carries nothing', async () => {
218+
const dbFile = join(dir, 'case.db');
219+
copyFileSync(templateDb, dbFile);
220+
expect((await served(dbFile)).open, 'PRECONDITION: the shipped form is served open').toEqual([`${VIEW}|${BASE}`]);
221+
222+
const { report } = await applyOver(dbFile, 'first');
223+
const step = promotion(report);
224+
expect(step.blockers.filter((b) => b.includes(VIEW))).toEqual([]);
225+
expect(step.summary.withdrawalsCarried).toBe(1);
226+
expect(storedForm(dbFile).filter((r) => r.pkg === PAIR)).toEqual([
227+
{ pkg: PAIR, enabled: false, overrides: { package: BASE, basedOn: VERSION } },
228+
]);
229+
// ⛔ Nothing bound to the read-only base itself.
230+
expect(storedForm(dbFile).filter((r) => r.pkg === BASE)).toEqual([]);
231+
232+
const after = await served(dbFile);
233+
expect(after.base).toMatchObject({ enabled: false });
234+
expect(after.open).toEqual([]);
235+
236+
const again = await applyOver(dbFile, 'again');
237+
expect(promotion(again.report).summary.withdrawalsCarried ?? 0).toBe(0);
238+
expect(storedForm(dbFile).filter((r) => r.pkg === PAIR)).toHaveLength(1);
239+
}, CASE_TIMEOUT_MS);
240+
});

0 commit comments

Comments
 (0)