diff --git a/.changeset/36647-artifact-unmounted-plugins.md b/.changeset/36647-artifact-unmounted-plugins.md new file mode 100644 index 00000000000..771aaaeb10d --- /dev/null +++ b/.changeset/36647-artifact-unmounted-plugins.md @@ -0,0 +1,14 @@ +--- +'@objectstack/runtime': patch +--- + +fix(runtime): an artifact boot names every code plugin of the app that it does not run + +Clause-②: no +Metadata-protocol: none + +A compiled artifact carries an app's metadata and hook handlers, not its code plugins: `os build` writes each entry of the stack's `plugins` as a plain descriptor (`{ name, version, dependencies, options }`), and the runtime module beside the JSON exports `functions` only. So a boot from the artifact (`OS_ARTIFACT_URL`, the composed hosted boot, `os start` on a built app) runs none of them. That is the envelope-key rule: an artifact carries metadata, a host assembles plugins. It used to happen in silence, and every service those plugins register was simply absent, so whatever depended on them failed later and somewhere else. + +The artifact boot now says so once, at `warn`, when the app's `AppPlugin` starts: `[AppPlugin] app 'APP_ID' lists N plugin(s) that are not running on this kernel: 'PLUGIN_NAME', …`, with the remedy (boot the app from its `objectstack.config.ts`, or from a host config that loads the artifact and lists the plugins in its own `plugins`, or package them with `os plugin build` and `os plugin install`). The structured fields are `{ appId, plugins }`. Each listed plugin is judged by name against the kernel's own plugin table, so a host that assembles the app's plugins itself hears nothing about the ones it runs. A package-specifier string entry is not judged: the name its plugin registers under is not in the specifier. + +Only the artifact door judges: the `AppPlugin` that `createStandaloneStack` builds over the artifact it loaded (the one composed with `securityMetadataRegistrar: 'artifact-door'`). A config boot's `AppPlugin` does not, because its host materializes the stack's `plugins` itself. No option, export or artifact field is added, and nothing else changes: no plugin is mounted, refused or reordered, and the boot does not fail. diff --git a/content/docs/deployment/self-hosting.mdx b/content/docs/deployment/self-hosting.mdx index 2b6bc4d9372..1425fe2717c 100644 --- a/content/docs/deployment/self-hosting.mdx +++ b/content/docs/deployment/self-hosting.mdx @@ -150,6 +150,7 @@ rotate. Two variables would make "URL updated, hash not" a state you can reach. | `#sha256=` present, artifact host unreachable | Falls back to the cached copy **only** if it still hashes to the pin, with a loud warning that the instance is running on cached content. | | Artifact's `engines.protocol` excludes this runtime | **Refuses to boot** — the safety belt of the two-axis split. Repoint the reference, or run a matching image version. | | The artifact needs a destructive schema change | Safe migrations run at boot; a destructive one **refuses to boot** and names each change. Run `os migrate apply --allow-destructive` deliberately, then restart. Never skipped in silence. | +| The app's stack lists code plugins (`plugins: [new XPlugin()]`) | Boots **without them**: an artifact carries the app's metadata and hook handlers, not its code plugins, so nothing those plugins register exists. The boot warns once, naming each listed plugin the kernel does not run. To run them, boot a host config that loads the artifact and lists the plugins in its own `plugins`, or package them as a plugin (`os plugin build`, then `os plugin install`). | **Recommended production discipline** (convention, not enforced by the runtime): publish immutable, version-named objects; give only CI write access to the diff --git a/packages/cli/test/build-artifact-code-plugins-boot.test.ts b/packages/cli/test/build-artifact-code-plugins-boot.test.ts new file mode 100644 index 00000000000..0826bfab174 --- /dev/null +++ b/packages/cli/test/build-artifact-code-plugins-boot.test.ts @@ -0,0 +1,134 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #36647, end to end: a real `os build` of a stack that lists a code plugin, + * then a real boot of the artifact it wrote. The boot runs none of the app's + * code plugins, and says so, naming each one, once. + * + * The build half is the measured premise. `os build` writes the stack's + * `plugins` into `objectstack.json` as plain JSON (the instance's own data, no + * `init`), and nothing on the artifact path turns that back into a plugin: + * `plugins` are artifact ENVELOPE keys, runtime assembly instructions a host + * hands to `kernel.use()`, never metadata the artifact carries. The boot half + * is the fix: the artifact door's `AppPlugin` names every listed plugin the + * kernel's own table does not hold (`@objectstack/runtime`, + * `artifact-declared-plugins.ts`), so the drop is no longer silent. + * + * The boot reaches `@objectstack/runtime` through its `exports` map, so it + * measures `dist/`: rebuild the runtime before reading a result here. + */ + +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { createStandaloneStack, Runtime } from '@objectstack/runtime'; +import Compile from '../src/commands/compile'; +import { defineStackSourceFromLiteral, linkSpec } from './helpers/define-stack-fixture.js'; + +// Pay the first transform of these dist-resolved workspace deps at MODULE LOAD: +// the build and the boot below import them lazily, inside a clocked hook +// (`scripts/check-test-source-alias.mjs`, the clocked-window rule). +import '@objectstack/objectql/core'; +import '@objectstack/plugin-security'; + +const CLI_ROOT = resolve(fileURLToPath(import.meta.url), '..', '..'); +const APP_ID = 'com.test.issue-36647-build'; +const VECTOR = 'com.test.issue-36647-build.vector'; +const INDEXER = 'com.test.issue-36647-build.indexer'; +const BOOT_TIMEOUT = 120_000; + +/** + * The stack as an author writes it: two code plugins, live instances with an + * `init`, the shape `plugins: [new XPlugin()]` evaluates to. + */ +const CONFIG_LITERAL = `{ + manifest: { id: '${APP_ID}', name: 'Plugin Build Probe', version: '1.0.0', type: 'app', namespace: 'probeb' }, + objects: [{ name: 'probeb_clause', label: 'Clause', sharingModel: 'private', fields: { title: { type: 'text', label: 'Title' } } }], + plugins: [ + { name: '${VECTOR}', version: '1.0.0', dependencies: [], options: { dimensions: 1536 }, init: async () => {} }, + { name: '${INDEXER}', version: '1.0.0', dependencies: ['${VECTOR}'], init: async () => {} }, + ], +}`; + +let root = ''; +let artifactPath = ''; + +/** Runs `os build` in-process; answers the exit code (0 when the command returned) and what it printed. */ +async function build(configPath: string, output: string): Promise<{ code: number; stdout: string }> { + const chunks: string[] = []; + const spy = vi.spyOn(process.stdout, 'write').mockImplementation(((chunk: unknown, ...rest: unknown[]) => { + chunks.push(String(chunk)); + const done = rest.find((a) => typeof a === 'function') as ((e?: Error | null) => void) | undefined; + done?.(null); + return true; + }) as never); + const exitCodeBefore = process.exitCode; + try { + await Compile.run([configPath, '--output', output], { root: CLI_ROOT }); + return { code: 0, stdout: chunks.join('') }; + } catch (error) { + const exit = (error as { oclif?: { exit?: unknown } }).oclif?.exit; + if (typeof exit !== 'number') throw error; + return { code: exit, stdout: chunks.join('') }; + } finally { + spy.mockRestore(); + process.exitCode = exitCodeBefore; + } +} + +beforeAll(async () => { + root = mkdtempSync(join(tmpdir(), 'os-36647-build-')); + const dir = join(root, 'app'); + mkdirSync(dir, { recursive: true }); + const configPath = join(dir, 'objectstack.config.ts'); + writeFileSync(configPath, defineStackSourceFromLiteral(CONFIG_LITERAL)); + linkSpec(dir); + mkdirSync(join(root, 'host'), { recursive: true }); + artifactPath = join(dir, 'dist', 'objectstack.json'); + const built = await build(configPath, artifactPath); + expect(built.code, built.stdout).toBe(0); +}, 60_000); + +afterAll(() => { + if (root) rmSync(root, { recursive: true, force: true }); +}); + +describe('#36647 — os build, then an artifact boot of what it wrote', () => { + it('PREMISE: the artifact holds the plugins as inert descriptors, nothing that can start', () => { + const artifact = JSON.parse(readFileSync(artifactPath, 'utf8')) as { plugins?: Array> }; + expect(artifact.plugins?.map((p) => p.name)).toEqual([VECTOR, INDEXER]); + for (const p of artifact.plugins ?? []) expect(p).not.toHaveProperty('init'); + }); + + it('the boot runs neither plugin, and warns once naming both', async () => { + let kernel: any; + try { + const standalone = await createStandaloneStack({ + artifactPath, + // A directory of its own: the boot's root, apart from the source tree the build read. + projectRoot: join(root, 'host'), + databaseUrl: ':memory:', + skipSeedData: true, + runPlatformMigrations: false, + }); + kernel = new Runtime({ cluster: false }).getKernel(); + const warn = vi.spyOn(kernel.logger, 'warn'); + for (const p of standalone.plugins) await kernel.use(p as never); + await kernel.bootstrap(); + // CONTROL: the drop is real. + expect(kernel.hasPlugin(VECTOR)).toBe(false); + expect(kernel.hasPlugin(INDEXER)).toBe(false); + const named = warn.mock.calls + .map(([message, meta]) => ({ message: String(message), meta: meta as any })) + .filter(({ meta }) => meta?.appId === APP_ID && Array.isArray(meta?.plugins)); + expect(named).toHaveLength(1); + expect(named[0]!.meta).toEqual({ appId: APP_ID, plugins: [VECTOR, INDEXER] }); + expect(named[0]!.message).toContain(VECTOR); + expect(named[0]!.message).toContain(INDEXER); + } finally { + try { await kernel?.shutdown(); } catch { /* noop */ } + } + }, BOOT_TIMEOUT); +}); diff --git a/packages/runtime/src/app-plugin.ts b/packages/runtime/src/app-plugin.ts index 46a1172fbd3..aada1f591ce 100644 --- a/packages/runtime/src/app-plugin.ts +++ b/packages/runtime/src/app-plugin.ts @@ -42,6 +42,7 @@ import { QuickJSScriptRunner } from './sandbox/quickjs-runner.js'; import { hookBodyRunnerFactory, actionBodyRunnerFactory } from './sandbox/body-runner.js'; import { hookRefusalI18nReader } from './sandbox/hook-refusal-catalogue.js'; import { bindAppArtifactHandlers, scheduleAppArtifactJobs } from './app-artifact-handlers.js'; +import { warnUnmountedDeclaredPlugins } from './artifact-declared-plugins.js'; import { countServerTiming } from '@objectstack/observability'; /** @@ -1439,7 +1440,21 @@ export class AppPlugin implements Plugin { } const sys = this.bundle.manifest || this.bundle; const appId = sys.id || sys.name; - + + // The artifact's `plugins` (an envelope key: top level only) that this + // kernel does not run, named once. An artifact carries descriptors for + // them and nothing that can start, so a boot from the artifact alone + // mounts none of them; before this it said nothing. Keyed on the + // `'artifact-door'` registrar: it is the declaration, made by + // `createStandaloneStack` alone, that this bundle IS the artifact that + // door reads. A config bundle's `plugins` are materialized by its host + // under names a descriptor cannot predict, so they are not judged here. + // Read in `start()`: the kernel's plugin table is closed once bootstrap + // begins. See `./artifact-declared-plugins.ts`. + if (this.securityMetadataRegistrar === 'artifact-door') { + warnUnmountedDeclaredPlugins(ctx, (this.bundle as { plugins?: unknown }).plugins, String(appId)); + } + // Execute Runtime Step // Retrieve ObjectQL engine from services // ctx.getService throws when a service is not registered, so we diff --git a/packages/runtime/src/artifact-declared-plugins.test.ts b/packages/runtime/src/artifact-declared-plugins.test.ts new file mode 100644 index 00000000000..a6789f8dd92 --- /dev/null +++ b/packages/runtime/src/artifact-declared-plugins.test.ts @@ -0,0 +1,182 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #36647: an artifact boot runs none of the app's code plugins, and now says + * so, naming each one, once. + * + * `os build` writes a stack's `plugins` into the artifact as plain descriptors + * (`{ name, version, dependencies, options }`); the runtime module beside it + * exports `functions` only. So `createStandaloneStack` over that artifact (the + * artifact door every artifact boot goes through: `OS_ARTIFACT_URL`, the + * composed hosted boot, `os start` on a built app) mounts none of them, which + * is correct under the envelope-key ruling (an artifact carries metadata, a + * host assembles plugins). Before this it said nothing: the knowledge service, + * the vector adapter and the app's own indexer were simply absent. + * + * The boots below are real: `createStandaloneStack`'s plugins over an artifact + * file on disk, on a fresh kernel. The warning is identified by its structured + * fields (the app id and the list of names), never by its prose. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { Runtime } from './runtime.js'; +import { AppPlugin } from './app-plugin.js'; +import { createStandaloneStack } from './standalone-stack.js'; +import { findUnmountedDeclaredPlugins } from './artifact-declared-plugins.js'; + +// [#10126] Pay the first transform of these dist-resolved workspace deps at +// MODULE LOAD: the factory and the kernel boot below import them lazily, inside +// a clocked hook (`scripts/check-test-source-alias.mjs`, the clocked-window rule). +import '@objectstack/objectql'; +import '@objectstack/service-datasource'; +import '@objectstack/metadata'; + +const APP_ID = 'com.test.issue-36647'; +const VECTOR = 'com.test.issue-36647.vector'; +const INDEXER = 'com.test.issue-36647.indexer'; +const BOOT_TIMEOUT = 120_000; + +/** A descriptor exactly as `os build` serializes a plugin instance into the artifact. */ +const descriptor = (name: string) => ({ name, version: '1.0.0', dependencies: [], options: {} }); + +const artifact = (plugins: unknown[] | undefined) => ({ + manifest: { id: APP_ID, name: 'Plugin Drop Probe', version: '1.0.0', type: 'app', namespace: 'probep' }, + objects: [{ name: 'probep_clause', label: 'Clause', fields: { title: { type: 'text', label: 'Title' } } }], + ...(plugins ? { plugins } : {}), +}); + +/** A host-mounted plugin under `name`: what a host config that assembles the app's plugins registers. */ +const hostPlugin = (name: string) => ({ name, version: '1.0.0', init: async () => {}, start: async () => {} }); + +interface Booted { + /** Every `warn` the kernel logger took about this app's listed plugins. */ + warnings: Array<{ message: string; meta: any }>; + /** Whether the kernel's table holds each probe name. */ + registered: Record; +} + +async function bootArtifact( + tag: string, + plugins: unknown[] | undefined, + extra: unknown[] = [], +): Promise { + const dir = mkdtempSync(join(tmpdir(), `os-36647-${tag}-`)); + let kernel: any; + try { + const artifactPath = join(dir, 'objectstack.json'); + writeFileSync(artifactPath, JSON.stringify(artifact(plugins)), 'utf-8'); + const standalone = await createStandaloneStack({ + artifactPath, + projectRoot: dir, + databaseUrl: ':memory:', + skipSeedData: true, + runPlatformMigrations: false, + }); + // CONTROL on the composition: the artifact loaded, so the door pushed its AppPlugin. + expect(standalone.plugins.some((p: any) => p instanceof AppPlugin)).toBe(true); + kernel = new Runtime({ cluster: false }).getKernel(); + const warn = vi.spyOn(kernel.logger, 'warn'); + for (const p of [...extra, ...standalone.plugins]) await kernel.use(p as any); + await kernel.bootstrap(); + const warnings = warn.mock.calls + .map(([message, meta]) => ({ message: String(message), meta: meta as any })) + .filter(({ meta }) => meta?.appId === APP_ID && Array.isArray(meta?.plugins)); + const registered = Object.fromEntries([VECTOR, INDEXER].map((n) => [n, kernel.hasPlugin(n)])); + return { warnings, registered }; + } finally { + try { await kernel?.shutdown(); } catch { /* noop */ } + rmSync(dir, { recursive: true, force: true }); + } +} + +describe('#36647 — an artifact boot names every listed plugin it does not run', () => { + it('two descriptors, neither mounted: exactly one warning naming both', async () => { + const booted = await bootArtifact('none', [descriptor(VECTOR), descriptor(INDEXER)]); + // CONTROL: the drop is real — neither plugin is in the kernel's table. + expect(booted.registered).toEqual({ [VECTOR]: false, [INDEXER]: false }); + expect(booted.warnings).toHaveLength(1); + expect(booted.warnings[0]!.meta).toEqual({ appId: APP_ID, plugins: [VECTOR, INDEXER] }); + // The subject names are in the line an operator reads, beside the remedy. + expect(booted.warnings[0]!.message).toContain(VECTOR); + expect(booted.warnings[0]!.message).toContain(INDEXER); + expect(booted.warnings[0]!.message).toContain('os plugin build'); + }, BOOT_TIMEOUT); + + it('CONTROL: a host that mounts one of them is told only about the other', async () => { + const booted = await bootArtifact('host-one', [descriptor(VECTOR), descriptor(INDEXER)], [hostPlugin(VECTOR)]); + expect(booted.registered).toEqual({ [VECTOR]: true, [INDEXER]: false }); + expect(booted.warnings).toHaveLength(1); + expect(booted.warnings[0]!.meta).toEqual({ appId: APP_ID, plugins: [INDEXER] }); + }, BOOT_TIMEOUT); + + it('CONTROL: a host that mounts both says nothing', async () => { + const booted = await bootArtifact( + 'host-both', + [descriptor(VECTOR), descriptor(INDEXER)], + [hostPlugin(VECTOR), hostPlugin(INDEXER)], + ); + expect(booted.registered).toEqual({ [VECTOR]: true, [INDEXER]: true }); + expect(booted.warnings).toEqual([]); + }, BOOT_TIMEOUT); + + it('CONTROL: an artifact that lists no plugins says nothing', async () => { + const booted = await bootArtifact('no-plugins', undefined); + expect(booted.warnings).toEqual([]); + }, BOOT_TIMEOUT); + + it('CONTROL: a config boot (the default registrar) never judges its plugins — the host materializes them', async () => { + // `os serve objectstack.config.ts` with no compiled artifact: the door + // finds none and pushes no AppPlugin, and the CLI wraps the config. + const dir = mkdtempSync(join(tmpdir(), 'os-36647-config-')); + let kernel: any; + try { + const standalone = await createStandaloneStack({ + artifactPath: join(dir, 'dist', 'objectstack.json'), + projectRoot: dir, + databaseUrl: ':memory:', + skipSeedData: true, + runPlatformMigrations: false, + }); + expect(standalone.plugins.some((p: any) => p instanceof AppPlugin)).toBe(false); + kernel = new Runtime({ cluster: false }).getKernel(); + const warn = vi.spyOn(kernel.logger, 'warn'); + for (const p of [...standalone.plugins, new AppPlugin(artifact([descriptor(VECTOR)]))]) await kernel.use(p as any); + await kernel.bootstrap(); + // CONTROL: the plugin really is absent, so only the gate keeps this silent. + expect(kernel.hasPlugin(VECTOR)).toBe(false); + const warnings = warn.mock.calls.filter(([, meta]) => (meta as any)?.appId === APP_ID && Array.isArray((meta as any)?.plugins)); + expect(warnings).toEqual([]); + } finally { + try { await kernel?.shutdown(); } catch { /* noop */ } + rmSync(dir, { recursive: true, force: true }); + } + }, BOOT_TIMEOUT); +}); + +describe('findUnmountedDeclaredPlugins — which entries can be judged by name', () => { + const none = () => false; + + it('names each unregistered descriptor once, in listed order', () => { + expect(findUnmountedDeclaredPlugins([descriptor('b'), descriptor('a'), descriptor('b')], none)).toEqual(['b', 'a']); + }); + + it('a bundle entry (no init) counts as mounted when the host wrapped it into its AppPlugin', () => { + const bundle = { name: 'crm', manifest: { id: 'com.example.crm' }, objects: [] }; + expect(findUnmountedDeclaredPlugins([bundle], (n) => n === 'plugin.app.com.example.crm')).toEqual([]); + expect(findUnmountedDeclaredPlugins([bundle], none)).toEqual(['crm']); + }); + + it('a live plugin instance counts only under its own name', () => { + const live = hostPlugin('com.example.live'); + expect(findUnmountedDeclaredPlugins([live], (n) => n === 'plugin.app.com.example.live')).toEqual(['com.example.live']); + }); + + it('a package specifier string, an unnamed entry and a non-array are never named', () => { + expect(findUnmountedDeclaredPlugins(['@acme/plugin-x', {}, null, 7, { name: '' }], none)).toEqual([]); + expect(findUnmountedDeclaredPlugins(undefined, none)).toEqual([]); + expect(findUnmountedDeclaredPlugins({ name: 'x' }, none)).toEqual([]); + }); +}); diff --git a/packages/runtime/src/artifact-declared-plugins.ts b/packages/runtime/src/artifact-declared-plugins.ts new file mode 100644 index 00000000000..586c00c58de --- /dev/null +++ b/packages/runtime/src/artifact-declared-plugins.ts @@ -0,0 +1,128 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The plugins an app's stack lists that this kernel does not run — named, once + * per boot, at `warn`. + * + * A stack's `plugins` are runtime ASSEMBLY instructions (`stack.zod.ts`, the + * artifact envelope keys): what a host hands to `kernel.use()`. A compiled + * artifact is inert JSON, so what `os build` writes there for a code plugin is + * a plain descriptor (`{ name, version, dependencies, options }`), not anything + * a loader could construct, and the runtime module it ships beside the JSON + * exports the hook handlers (`functions`) only. Nothing on the artifact path + * turns a descriptor back into a plugin, and nothing should: code and its + * dependencies are distributed as a signed `.osplugin` (ADR-0025, layer L2), or + * assembled by a host config. So an artifact booted on its own runs none of its + * app's code plugins. + * + * That is correct. Doing it in silence is the defect: the build summary counts + * the plugins, the boot lists the platform's plugins and not the app's, and + * every service the missing plugins would have registered fails later and + * somewhere else (an empty retrieval, a hook that finds no service). This is the + * one place that knows both halves, the app's list and the kernel's table, so + * it is where the absence is said. + * + * The judgment is per name, against the kernel's own plugin table: a host that + * assembles the app's plugins itself (a config boot over the app's own compiled + * output, or a host config that imports the artifact and appends them) has them + * registered under those names, and is told nothing. The table is final by the + * time this is read: the kernel refuses `use()` once bootstrap has begun. + * + * A functional degradation (a capability is absent, and the next caller of it + * finds out), so `warn`, not `error` (AGENTS.md, "Degradation log levels"). + */ + +/** + * The names a stack's `plugins` entry can be running under: a plugin's (or its + * serialized descriptor's) `name`, and, for an entry with no `init`, the name + * of the `AppPlugin` a host wraps such a bundle into (`materializeStackPlugin`, + * `@objectstack/core`). Answers nothing for an entry that names no plugin. + * + * A string entry answers nothing too. It is a package specifier, and a host + * that loads it registers whatever name the module's plugin carries, which the + * specifier does not tell. So such an entry is never named as missing: this + * says only what the kernel's table can confirm. + */ +function candidateNames(entry: unknown): { name: string; aliases: string[] } | undefined { + if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return undefined; + const record = entry as { name?: unknown; init?: unknown; manifest?: { id?: unknown } | null }; + const name = record.name; + if (typeof name !== 'string' || name.length === 0) return undefined; + if (typeof record.init === 'function') return { name, aliases: [] }; + const manifestId = record.manifest && typeof record.manifest.id === 'string' ? record.manifest.id : undefined; + return { name, aliases: [`plugin.app.${manifestId ?? name}`] }; +} + +/** + * The names of the entries of `declared` (a stack's `plugins`) that + * `isRegistered` answers for under none of their names, in listed order, each + * once. `undefined` (or anything not an array) lists nothing. + */ +export function findUnmountedDeclaredPlugins( + declared: unknown, + isRegistered: (name: string) => boolean, +): string[] { + const missing: string[] = []; + if (!Array.isArray(declared)) return missing; + for (const entry of declared) { + const candidate = candidateNames(entry); + if (candidate === undefined) continue; + if (isRegistered(candidate.name) || candidate.aliases.some(isRegistered)) continue; + if (!missing.includes(candidate.name)) missing.push(candidate.name); + } + return missing; +} + +/** The slice of a kernel this reads: its plugin table, by name. */ +interface PluginTable { + hasPlugin?: (name: string) => boolean; + getPlugins?: () => Map; +} + +/** The slice of a plugin context this uses. */ +interface DeclaredPluginsContext { + getKernel?: () => unknown; + logger: { warn: (message: string, meta?: Record) => void }; +} + +/** + * Warn once, naming every plugin the app's stack lists that this kernel does + * not run. Silent when the stack lists none, when every one is registered, or + * when the context exposes no plugin table to judge against (nothing is said + * that the table could contradict). + */ +export function warnUnmountedDeclaredPlugins( + ctx: DeclaredPluginsContext, + declared: unknown, + appId: string, +): string[] | undefined { + if (!Array.isArray(declared) || declared.length === 0) return undefined; + let table: PluginTable | undefined; + try { + table = (typeof ctx.getKernel === 'function' ? ctx.getKernel() : undefined) as PluginTable | undefined; + } catch { + table = undefined; + } + let isRegistered: ((name: string) => boolean) | undefined; + if (typeof table?.hasPlugin === 'function') { + isRegistered = (name) => table!.hasPlugin!(name); + } else if (typeof table?.getPlugins === 'function') { + const registered = table.getPlugins(); + isRegistered = (name) => registered.has(name); + } + if (isRegistered === undefined) return undefined; + + const missing = findUnmountedDeclaredPlugins(declared, isRegistered); + if (missing.length === 0) return missing; + + ctx.logger.warn( + `[AppPlugin] app '${appId}' lists ${missing.length} plugin(s) that are not running on this kernel: ` + + `${missing.map((n) => `'${n}'`).join(', ')}. A compiled artifact carries an app's metadata and hook ` + + 'handlers, not its code plugins, so every service those plugins register is absent here and ' + + 'whatever depends on them fails later. To run them, boot the app from its objectstack.config.ts, ' + + 'or from a host config that loads this artifact and lists the plugins in its own `plugins`, ' + + 'or package them as a plugin (os plugin build, then os plugin install).', + { appId, plugins: missing }, + ); + return missing; +}