Skip to content
14 changes: 14 additions & 0 deletions .changeset/36647-artifact-unmounted-plugins.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions content/docs/deployment/self-hosting.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
134 changes: 134 additions & 0 deletions packages/cli/test/build-artifact-code-plugins-boot.test.ts
Original file line number Diff line number Diff line change
@@ -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<Record<string, unknown>> };
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);
});
17 changes: 16 additions & 1 deletion packages/runtime/src/app-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

/**
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading