Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/38062-migrate-artifact-item-capabilities.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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/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 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) };
const starts = [...out.matchAll(/(^|\n)\{/g)].map((m) => m.index + m[1].length).reverse();
for (const start of starts) {
try {
payload = JSON.parse(out.slice(start));
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<string, string | undefined> = {};
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, unknown>): 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);
});
7 changes: 5 additions & 2 deletions packages/cli/src/utils/schema-migrate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
23 changes: 20 additions & 3 deletions packages/cli/src/utils/schema-migration-plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand All @@ -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<SchemaMigrationComposition> {
const cwd = opts.cwd ?? process.cwd();
const hostConfigPath = findHostConfig(cwd);
Expand Down Expand Up @@ -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 } : {}),
});
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
Loading