From 10db248b5b2a21f59097c2594b6d988b8dd3fdc3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 04:11:47 +0000 Subject: [PATCH 1/4] fix(cli): os migrate plan composes what an artifact-only stack's shipped items mount, as os serve does Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP Co-authored-by: Claude --- .../plan.artifact-item-capabilities.test.ts | 175 ++++++++++++++++++ packages/cli/src/utils/schema-migrate.ts | 7 +- .../cli/src/utils/schema-migration-plugins.ts | 23 ++- 3 files changed, 200 insertions(+), 5 deletions(-) create mode 100644 packages/cli/src/commands/migrate/plan.artifact-item-capabilities.test.ts diff --git a/packages/cli/src/commands/migrate/plan.artifact-item-capabilities.test.ts b/packages/cli/src/commands/migrate/plan.artifact-item-capabilities.test.ts new file mode 100644 index 00000000000..6ebd0e431a4 --- /dev/null +++ b/packages/cli/src/commands/migrate/plan.artifact-item-capabilities.test.ts @@ -0,0 +1,175 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { isExitSignal } from '../../utils/format.js'; +import MigratePlan from './plan.js'; + +// Pay the first transform of the dist-resolved workspace deps the command +// reaches through dynamic `import()`s at MODULE LOAD, not inside a case. +import '@objectstack/runtime'; +import '@objectstack/objectql'; +import '@objectstack/plugin-auth'; +import '@objectstack/plugin-security'; +import '@objectstack/metadata-protocol'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/platform-objects/system'; +import '@objectstack/rest'; +import '@objectstack/service-datasource'; +import '@objectstack/service-knowledge'; +import '@objectstack/driver-sql'; +import '@objectstack/driver-turso'; + +/** + * [ADR-0161 K8 item 12] An artifact-only stack (`dist/objectstack.json`, no + * `objectstack.config.ts`) that ships a `knowledge_source` and lists no + * `requires: ['knowledge']`: `os serve` lays the standalone stack's result over + * the (empty) config and mounts KnowledgeServicePlugin for the item. `os + * migrate plan` boots the same artifact and must compose the same set — the + * knowledge service among "what `os serve` mounts" — or it plans a different + * platform and its own boot warns that the source is unserved. + * + * Control: the same artifact with no source composes no knowledge service. + */ + +const HERE = dirname(fileURLToPath(import.meta.url)); +const CLI_ROOT = resolve(HERE, '..', '..', '..'); +const CASE_TIMEOUT_MS = 240_000; +const UNSERVED = /knowledge_source item.*no 'knowledge' service is registered/; + +const ENV_KEYS = [ + 'OS_DATABASE_URL', 'DATABASE_URL', 'TURSO_DATABASE_URL', 'OS_DATABASE_DRIVER', 'OS_HOME', + 'OS_TELEMETRY_DB', 'OS_AUTH_SECRET', 'AUTH_SECRET', 'BETTER_AUTH_SECRET', 'OS_ARTIFACT_PATH', 'NODE_ENV', +] as const; + +/** Run `os migrate plan --json` with every output channel captured, and its JSON document parsed. */ +async function plan(): Promise<{ payload: any; exitCode: number; said: string }> { + const savedExit = process.exitCode; + const heard: string[] = []; + const capture = ((chunk: unknown, ...rest: unknown[]) => { + heard.push(String(chunk)); + const cb = rest.find((a) => typeof a === 'function') as (() => void) | undefined; + if (cb) cb(); + return true; + }) as typeof process.stdout.write; + const stdout = vi.spyOn(process.stdout, 'write').mockImplementation(capture); + vi.spyOn(process.stderr, 'write').mockImplementation(capture); + for (const level of ['error', 'log', 'warn', 'info'] as const) { + vi.spyOn(console, level).mockImplementation((...args: unknown[]) => { heard.push(args.map(String).join(' ')); }); + } + let processExit: number | undefined; + vi.spyOn(process, 'exit').mockImplementation(((code?: number) => { + processExit = code ?? 0; + throw new Error(`__PROCESS_EXIT__:${processExit}`); + }) as never); + let thrownExit: number | undefined; + try { + try { + await MigratePlan.run(['--json'], { root: CLI_ROOT }); + } catch (error) { + const trapped = error instanceof Error && error.message.startsWith('__PROCESS_EXIT__'); + if (!trapped && !isExitSignal(error)) throw error; + if (!trapped) thrownExit = (error as { oclif?: { exit?: number } }).oclif?.exit; + } + const out = stdout.mock.calls.map((c) => String(c[0])).join('').trim(); + // The document is the last whole line that parses as a JSON object. + let payload: any = { unparsed: out.slice(-400) }; + for (const line of out.split('\n').reverse()) { + if (!line.startsWith('{')) continue; + try { + payload = JSON.parse(line); + break; + } catch { /* a log fragment */ } + } + return { + payload, + exitCode: processExit ?? thrownExit ?? (process.exitCode as number | undefined) ?? 0, + said: heard.join('\n'), + }; + } finally { + process.exitCode = savedExit; + vi.restoreAllMocks(); + } +} + +const dirs: string[] = []; +const savedEnv: Record = {}; +let savedCwd: string; + +const SOURCE = { name: 'notes', label: 'Notes', source: { kind: 'object', object: 'os38062_note', content: ['title'] } }; + +/** An artifact-only project: `dist/objectstack.json` and no config. */ +function artifactProject(extra: Record): string { + const dir = mkdtempSync(join(tmpdir(), 'os-38062-artifact-')); + dirs.push(dir); + mkdirSync(join(dir, 'dist'), { recursive: true }); + writeFileSync(join(dir, 'dist', 'objectstack.json'), JSON.stringify({ + manifest: { id: 'com.example.os38062', name: 'artifact item mount', version: '0.0.0', type: 'app' }, + objects: [{ name: 'os38062_note', label: 'Note', fields: { title: { type: 'text' } } }], + ...extra, + })); + writeFileSync(join(dir, 'package.json'), `${JSON.stringify({ name: 'os38062-host', version: '0.0.0', private: true }, null, 2)}\n`); + return dir; +} + +/** Enter the fixture as the operator's shell would. */ +function enter(dir: string): void { + process.env.NODE_ENV = 'production'; + process.env.OS_TELEMETRY_DB = '0'; + process.env.OS_ARTIFACT_PATH = join(dir, 'dist', 'objectstack.json'); + process.env.OS_DATABASE_URL = `file:${join(dir, 'app.db')}`; + process.chdir(dir); +} + +/** The "Composed what `os serve` mounts" note, or undefined. */ +function servedNote(payload: any): string | undefined { + return (payload.composition?.notes as string[] | undefined)?.find((n) => n.startsWith('Composed what `os serve` mounts')); +} + +beforeAll(() => { + savedCwd = process.cwd(); + for (const key of ENV_KEYS) savedEnv[key] = process.env[key]; +}); + +beforeEach(() => { + for (const key of ENV_KEYS) delete process.env[key]; +}); + +afterEach(() => { + process.chdir(savedCwd); + for (const key of ENV_KEYS) { + const value = savedEnv[key]; + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } +}); + +afterAll(() => { + for (const d of dirs) { + try { rmSync(d, { recursive: true, force: true }); } catch { /* best-effort */ } + } +}); + +describe('os migrate plan on an artifact-only stack composes what its shipped items mount, as os serve does', () => { + it('⭐ one knowledge_source and no `requires`: the knowledge service is composed and named, and nothing warns it is unserved', async () => { + enter(artifactProject({ knowledgeSources: [SOURCE] })); + + const out = await plan(); + expect(out.exitCode, JSON.stringify(out.payload).slice(0, 400)).toBe(0); + expect(out.payload.composition?.hostConfig, 'precondition: no config, the artifact alone').toBeNull(); + expect(servedNote(out.payload), JSON.stringify(out.payload.composition?.notes)).toContain('KnowledgeServicePlugin'); + expect(out.said).not.toMatch(UNSERVED); + }, CASE_TIMEOUT_MS); + + it('control: the same artifact with no source composes no knowledge service', async () => { + enter(artifactProject({})); + + const out = await plan(); + expect(out.exitCode, JSON.stringify(out.payload).slice(0, 400)).toBe(0); + expect(servedNote(out.payload), 'precondition: the served platform was composed').toBeDefined(); + expect(servedNote(out.payload)).not.toContain('KnowledgeServicePlugin'); + }, CASE_TIMEOUT_MS); +}); diff --git a/packages/cli/src/utils/schema-migrate.ts b/packages/cli/src/utils/schema-migrate.ts index 4a7a238ffc0..a8ef1b0ec73 100644 --- a/packages/cli/src/utils/schema-migrate.ts +++ b/packages/cli/src/utils/schema-migrate.ts @@ -1430,9 +1430,12 @@ export async function bootSchemaStack( : {}), ...(opts.serveFlags ? { serveFlags: opts.serveFlags } : {}), // [#22506] The compiled artifact's `requires`, as `serve`'s merge lays - // them over the config's, for the auth gate and the provider tokens. + // them over the config's, for the auth gate and the provider tokens — + // and the standalone result itself, whose shipped items (an + // artifact-only stack's `knowledgeSources`) `serve` reads the tokens + // they mount off (ADR-0161 K8 item 12). ...(opts.composeServedPlatform === true - ? { servedPlatform: { artifactRequires: stack.requires } } + ? { servedPlatform: { artifactRequires: stack.requires, artifactStack: stack } } : {}), }).catch((error: unknown) => { releaseStdout(); diff --git a/packages/cli/src/utils/schema-migration-plugins.ts b/packages/cli/src/utils/schema-migration-plugins.ts index bd65292c0c8..e2bb115bedb 100644 --- a/packages/cli/src/utils/schema-migration-plugins.ts +++ b/packages/cli/src/utils/schema-migration-plugins.ts @@ -15,6 +15,7 @@ import { stampSearchPinyinEnabled } from '@objectstack/types'; import { isDeclaredByHost } from '@objectstack/types/node'; import { describeAiAutoInjectRefusal, mountsAiServicePlugin, resolveAiServiceLoad } from './ai-service-auto-inject.js'; import { isAppPluginLike } from './graft-runtime-hooks.js'; +import { mergeBootConfig } from './merge-boot-config.js'; import { isHostConfig } from './plugin-detection.js'; import { resolveStackCollection, @@ -1563,7 +1564,11 @@ export async function buildSchemaMigrationPlugins(opts: { * mounts (the stack's `requires` and the always-on slate), and the REST API * plugin — each for its declarations only. See {@link composeServedPlatform}. * `artifactRequires` is the compiled artifact's `requires` as the standalone - * stack surfaced it. + * stack surfaced it. `artifactStack` is the standalone stack's result itself, + * which `serve` lays over the config (`mergeBootConfig`) before it reads the + * tokens the stack's items mount (`stackItemCapabilities`): on an + * artifact-only stack the config is empty, and the shipped items + * (`knowledgeSources`) are on this result alone. * * Set by `os migrate plan` and `os migrate apply`, whose subject is the * deployment's whole object set, and by `os migrate unmapped-columns`, which @@ -1572,7 +1577,7 @@ export async function buildSchemaMigrationPlugins(opts: { * a provider is composed only when a composed plugin hard-depends on it * (#21732), as before. */ - servedPlatform?: { artifactRequires?: readonly string[] }; + servedPlatform?: { artifactRequires?: readonly string[]; artifactStack?: object }; }): Promise { const cwd = opts.cwd ?? process.cwd(); const hostConfigPath = findHostConfig(cwd); @@ -1747,6 +1752,9 @@ export async function buildSchemaMigrationPlugins(opts: { basePlugins: opts.basePlugins, composed: [...opts.basePlugins, ...plugins], artifactRequires: opts.servedPlatform.artifactRequires, + ...(opts.servedPlatform.artifactStack !== undefined + ? { artifactStack: opts.servedPlatform.artifactStack } + : {}), packageRoot: hostConfigPath ? path.dirname(hostConfigPath) : cwd, ...(opts.serveFlags ? { serveFlags: opts.serveFlags } : {}), }); @@ -1955,6 +1963,8 @@ async function composeServedPlatform(input: { /** Everything composed so far — what a provider counts as already held against. */ composed: readonly unknown[]; artifactRequires?: readonly string[]; + /** The standalone stack's result, which `serve` lays over a non-host config before it reads the items. */ + artifactStack?: object; packageRoot: string; /** * `serve`'s flags as the command was given them: `--dev` is a development @@ -2041,7 +2051,14 @@ async function composeServedPlatform(input: { // [ADR-0161 K8 item 12] The tokens the stack's items mount (a shipped // `knowledge_source` mounts `knowledge`), read off the same config `serve` // reads them from (`stackItemCapabilities`), so both boots compose one set. - for (const token of resolveServedCapabilities(requires, { itemTokens: stackItemCapabilities(config) }).tokens) { + // That config is `serve`'s merge: on the standalone path the stack's result + // laid over the authored config (`mergeBootConfig`), the rule `requires` + // follows above — so an artifact-only stack, whose loaded config is empty, + // mounts what its shipped items mount here as it does when served. + const servedConfig = !isHostConfig(config) && input.artifactStack !== undefined + ? mergeBootConfig(config as object, input.artifactStack) + : config; + for (const token of resolveServedCapabilities(requires, { itemTokens: stackItemCapabilities(servedConfig) }).tokens) { const spec = CAPABILITY_PROVIDERS[token]; // A tier token (`auth`, `ui`, `i18n`, `ai`) or one no open package // provides mounts nothing in `serve`'s resolver either. From 3dfa029137ad419374713f364d6859bf8fb364d1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 04:21:30 +0000 Subject: [PATCH 2/4] chore(changeset): cli patch for the artifact-only migrate composition Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP Co-authored-by: Claude --- .changeset/38062-migrate-artifact-item-capabilities.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .changeset/38062-migrate-artifact-item-capabilities.md diff --git a/.changeset/38062-migrate-artifact-item-capabilities.md b/.changeset/38062-migrate-artifact-item-capabilities.md new file mode 100644 index 00000000000..85f16140894 --- /dev/null +++ b/.changeset/38062-migrate-artifact-item-capabilities.md @@ -0,0 +1,10 @@ +--- +'@objectstack/cli': patch +--- + +fix(cli): `os migrate plan` / `apply` on an artifact-only stack compose the capability its shipped items mount, as `os serve` of the same artifact does + +Clause-②: no +Metadata-protocol: none + +A stack served from its compiled artifact alone (`dist/objectstack.json`, no `objectstack.config.ts`) that ships a `knowledge_source` and lists no `requires: ['knowledge']` is served KnowledgeServicePlugin by `os serve`, which lays the standalone stack's result over the empty config before it reads the tokens the stack's items mount. `os migrate plan` and `apply` read those tokens off the loaded config only, which is empty on that stack, so they composed no knowledge service, their "Composed what `os serve` mounts" note named none, and the boot warned that the source was unserved. They now hand the standalone result to the served-platform composition and read the items off `serve`'s own merge (`mergeBootConfig`), so both boots compose one set. A stack with no such item composes what it did before. From 01765b14cf5beeedd83ae5bb57e7130182f9f0be Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 04:43:29 +0000 Subject: [PATCH 3/4] test(cli): read the pretty-printed plan document in the artifact item-mount pin Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP Co-authored-by: Claude --- .../migrate/plan.artifact-item-capabilities.test.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/cli/src/commands/migrate/plan.artifact-item-capabilities.test.ts b/packages/cli/src/commands/migrate/plan.artifact-item-capabilities.test.ts index 6ebd0e431a4..318b3de5f8e 100644 --- a/packages/cli/src/commands/migrate/plan.artifact-item-capabilities.test.ts +++ b/packages/cli/src/commands/migrate/plan.artifact-item-capabilities.test.ts @@ -75,12 +75,13 @@ async function plan(): Promise<{ payload: any; exitCode: number; said: string }> if (!trapped) thrownExit = (error as { oclif?: { exit?: number } }).oclif?.exit; } const out = stdout.mock.calls.map((c) => String(c[0])).join('').trim(); - // The document is the last whole line that parses as a JSON object. + // The document is the last top-level JSON object on stdout, pretty-printed: + // try each line-initial `{` from the end until the rest parses. let payload: any = { unparsed: out.slice(-400) }; - for (const line of out.split('\n').reverse()) { - if (!line.startsWith('{')) continue; + const starts = [...out.matchAll(/(^|\n)\{/g)].map((m) => m.index + m[1].length).reverse(); + for (const start of starts) { try { - payload = JSON.parse(line); + payload = JSON.parse(out.slice(start)); break; } catch { /* a log fragment */ } } From 21be65c7a7eba65f23afbd8fdbb85466139802ab Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 05:17:26 +0000 Subject: [PATCH 4/4] test(cli): drop the unaliased knowledge-service preload from the artifact item-mount pin Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP Co-authored-by: Claude --- .../src/commands/migrate/plan.artifact-item-capabilities.test.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/cli/src/commands/migrate/plan.artifact-item-capabilities.test.ts b/packages/cli/src/commands/migrate/plan.artifact-item-capabilities.test.ts index 318b3de5f8e..14fd6cb3666 100644 --- a/packages/cli/src/commands/migrate/plan.artifact-item-capabilities.test.ts +++ b/packages/cli/src/commands/migrate/plan.artifact-item-capabilities.test.ts @@ -19,7 +19,6 @@ import '@objectstack/platform-objects/plugin'; import '@objectstack/platform-objects/system'; import '@objectstack/rest'; import '@objectstack/service-datasource'; -import '@objectstack/service-knowledge'; import '@objectstack/driver-sql'; import '@objectstack/driver-turso';