import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { childPluginId, definePlugin, createToken, rootPluginId, type ConfigDocumentPort, type ConfigDocumentSnapshot, type ConfigPatch, type PreparedConfigDocument, type RuntimeConfigDocument, } from '@zhin.js/plugin-runtime'; import { RootRuntime, createEnvStore, envStoreToken, primaryConfigToken, type PrimaryConfig, type EnvironmentLayers, type EnvironmentLayersPort, type ModuleRuntime, type ProcessInvalidationPlan, } from '../src/index.js'; const temporary: string[] = []; afterEach(async () => { await Promise.all(temporary.splice(0).map((path) => rm(path, { recursive: true }))); }); describe('RootRuntime watched inputs', () => { it('validates against the desired environment without publishing it', async () => { const declaration = { configVersion: 2, plugins: { child: '@test/child', sibling: '@test/sibling' }, log_level: 'debug' }; const fixture = await createFixture(declaration); fixture.modules.installSetups({ resources: 0, root: 0, child: 0, sibling: 0 }); const environment = new FakeEnvironmentSource(join(fixture.root, '.env'), { base: {} }); const runtime = new RootRuntime({ projectRoot: fixture.root, modules: fixture.modules, config: fixture.config, environment: testEnvironment, environmentSource: environment, installResources() {}, configUpdates: [{ id: 'model-like', paths: [['log_level']], validate(input) { if (input.next.log_level === 'warn' && !input.hasEnvironmentValue('NEW_VALUE')) throw new Error('Missing desired environment'); }, prepare: async () => undefined, }] }); try { await runtime.start(); const before = runtime.configurationApplication; environment.write({ base: { NEW_VALUE: 'synthetic-new-value' } }); await expect(runtime.validateConfiguration({ ...declaration, log_level: 'warn' })).resolves.toBeUndefined(); expect(runtime.configurationApplication).toBe(before); const effectiveEnv = runtime.snapshot.resources.get(rootPluginId())?.get(envStoreToken.id) as ReturnType; expect(effectiveEnv.has('NEW_VALUE')).toBe(false); } finally { await runtime.stop(); } }); it('keeps direct env consumers and process Host captures on the same effective environment', async () => { const declaration = { configVersion: 2, plugins: { child: '@test/child', sibling: '@test/sibling' }, ai: { apiKey: 'env://AI_KEY' } }; const fixture = await createFixture(declaration); const environment = new FakeEnvironmentSource(join(fixture.root, '.env'), { base: { AI_KEY: 'key-before' } }); const hostToken = createToken<{ key: string | undefined }>('test.captured-environment'); const installs = { resources: 0, root: 0, child: 0, sibling: 0 }; fixture.modules.installSetups(installs); const runtime = new RootRuntime({ projectRoot: fixture.root, modules: fixture.modules, config: fixture.config, environment: testEnvironment, environmentSource: environment, installResources({ resources }) { installs.resources++; // A real installed consumer captures the Root-provided startup EnvStore. resources.provide(hostToken, { key: resources.use(envStoreToken).get('AI_KEY') }); } }); const initial = await runtime.start(); const processHost = initial.resources.get(rootPluginId())?.get(hostToken.id) as { key: string | undefined }; const hmr = runtime.createHmrCoordinator({ onRestartRequired() { throw new Error('unexpected process restart'); }, onError(error) { throw error; } }); const effectiveKey = () => (runtime.snapshot.resources.get(rootPluginId())?.get(envStoreToken.id) as ReturnType).get('AI_KEY'); try { environment.write({ base: { AI_KEY: 'key-after' } }); await hmr.enqueue(environment.sources[0]); expect(runtime.snapshot).toBe(initial); expect(effectiveKey()).toBe(processHost.key); expect(installs.resources).toBe(1); expect(runtime.snapshot.resources.get(rootPluginId())?.get(hostToken.id)).toBe(processHost); expect(runtime.configurationApplication.groups).toEqual([expect.objectContaining({ id: 'environment', status: 'restart-pending' })]); expect(JSON.stringify(runtime.configurationApplication)).not.toContain('key-after'); fixture.config.writeExternal({ ...declaration, child: { label: 'updated' } }); await hmr.enqueue(fixture.configSource); await hmr.enqueue(join(fixture.root, 'plugins/child/plugin.ts')); expect(effectiveKey()).toBe(processHost.key); expect(installs.resources).toBe(1); expect(runtime.configurationApplication.groups).toEqual(expect.arrayContaining([expect.objectContaining({ id: 'environment', status: 'restart-pending' })])); environment.write({ base: { AI_KEY: 'key-before' } }); await hmr.enqueue(environment.sources[0]); expect(runtime.configurationApplication.groups.some(group => group.id === 'environment')).toBe(false); } finally { await hmr.stop(); await runtime.stop(); } }); it('applies independent plugin changes while retaining pending Host settings across later source reloads', async () => { const declaration = { configVersion: 2, plugins: { child: '@test/child', sibling: '@test/sibling' } }; const fixture = await createFixture({ ...declaration, http: { port: 8080 }, child: { label: 'one' } }); const installs = { resources: 0, root: 0, child: 0, sibling: 0 }; fixture.modules.installSetups(installs); const runtime = new RootRuntime({ projectRoot: fixture.root, modules: fixture.modules, config: fixture.config, environment: testEnvironment, installResources() { installs.resources += 1; } }); await runtime.start(); const restarts: ProcessInvalidationPlan[] = []; const coordinator = runtime.createHmrCoordinator({ onRestartRequired(plan) { restarts.push(plan); }, onError(error) { throw error; } }); try { fixture.config.writeExternal({ ...declaration, http: { port: 9090 }, child: { label: 'two' } }); await coordinator.enqueue(fixture.configSource); expect(runtime.snapshot.config.get(childPluginId(rootPluginId(), 'child'))).toEqual({ label: 'two' }); expect(restarts).toEqual([]); expect(installs.resources).toBe(1); await coordinator.enqueue(join(fixture.root, 'plugins/child/plugin.ts')); expect(installs.resources).toBe(1); expect(runtime.configurationApplication.groups).toEqual(expect.arrayContaining([ expect.objectContaining({ effect: 'restart-process', status: 'restart-pending' }), ])); } finally { await coordinator.stop(); await runtime.stop(); } }); it('pauses instances before source config preflight can evaluate inline plugin schema modules', async () => { const fixture = await createFixture({ configVersion: 2, plugins: { child: '@test/child', sibling: '@test/sibling' }, child: { label: 'one' } }); fixture.modules.installSetups({ root: 0, child: 0, sibling: 0 }); let paused = false, changing = false, inspected = false; const original = fixture.modules.load.bind(fixture.modules); fixture.modules.load = async (source: string): Promise => { if (changing) { inspected = true; expect(paused).toBe(true); } if (changing && source === join(fixture.root, 'plugins/child/plugin.ts')) return { default: definePlugin({ name: 'child', config: { toJsonSchema: () => ({ type: 'object', additionalProperties: false, properties: { label: { type: 'string' } } }) }, }) } as T; return original(source); }; const notices: import('@zhin.js/plugin-runtime').HmrResumeDetails[] = []; const runtime = new RootRuntime({ projectRoot: fixture.root, modules: fixture.modules, config: fixture.config, environment: testEnvironment, installResources({ events }) { events.on('hmr.pause', () => { paused = true; }); events.on('hmr.resume', event => { notices.push(event.details); }); } }); await runtime.start(); // The schema reader falls back to the inline module after this sidecar disappears. await rm(join(fixture.root, 'plugins/child/schema.json')); changing = true; const hmr = runtime.createHmrCoordinator({ onRestartRequired() { throw new Error('unexpected restart'); }, onError(error) { throw error; } }); fixture.config.writeExternal({ configVersion: 2, plugins: { child: '@test/child', sibling: '@test/sibling' }, child: { label: 'two' } }); try { await hmr.enqueue(fixture.configSource); expect(inspected).toBe(true); expect(notices).toHaveLength(1); expect(notices[0]).toMatchObject({ trigger: 'source', changed: [fixture.configSource], outcome: 'committed' }); paused = false; await hmr.enqueue(fixture.configSource); expect(notices).toHaveLength(2); expect(notices[1]).toMatchObject({ outcome: 'unchanged', replaced: [] }); } finally { await hmr.stop(); await runtime.stop(); } }); it('reloads only the Plugin subtree changed by an external config edit', async () => { const fixture = await createFixture({ configVersion: 2, plugins: {"child":"@test/child","sibling":"@test/sibling"}, child: { label: 'one' } }); const installs = { resources: 0, root: 0, child: 0, sibling: 0 }; fixture.modules.installSetups(installs); const runtime = new RootRuntime({ projectRoot: fixture.root, modules: fixture.modules, config: fixture.config, environment: testEnvironment, installResources() { installs.resources += 1; }, }); await runtime.start(); const coordinator = runtime.createHmrCoordinator({ onRestartRequired() { throw new Error('unexpected process restart'); }, onError(error) { throw error; }, }); fixture.config.writeExternal({ configVersion: 2, plugins: {"child":"@test/child","sibling":"@test/sibling"}, child: { label: 'two' } }); await coordinator.enqueue(fixture.configSource); expect(runtime.snapshot.config.get(childPluginId(rootPluginId(), 'child'))) .toEqual({ label: 'two' }); expect(installs).toEqual({ resources: 1, root: 1, child: 2, sibling: 1 }); await coordinator.stop(); await runtime.stop(); }); it('retains unsupported Host edits as pending without locking the HMR coordinator', async () => { const fixture = await createFixture({ configVersion: 2, plugins: {"child":"@test/child","sibling":"@test/sibling"}, http: { port: 8080 } }); fixture.modules.installSetups({ resources: 0, root: 0, child: 0, sibling: 0 }); const outcomes: string[] = []; const runtime = new RootRuntime({ projectRoot: fixture.root, modules: fixture.modules, config: fixture.config, installResources({ events }) { events.on('hmr.resume', event => { outcomes.push(event.details.outcome); }); }, environment: testEnvironment, }); await runtime.start(); const restarts: ProcessInvalidationPlan[] = []; const coordinator = runtime.createHmrCoordinator({ onRestartRequired(plan) { restarts.push(plan); }, onError(error) { throw error; }, }); fixture.config.writeExternal({ configVersion: 2, plugins: {"child":"@test/child","sibling":"@test/sibling"}, http: { port: 9090 } }); await coordinator.enqueue(fixture.configSource); expect(restarts).toEqual([]); expect(runtime.configurationApplication.groups).toEqual([expect.objectContaining({ status: 'restart-pending', paths: [['http', 'port']] })]); expect(runtime.snapshot.generation).toBe(1); expect(outcomes).toEqual(['unchanged']); await coordinator.stop(); await runtime.stop(); }); it('reloads dotenv layers and re-expands Plugin config references', async () => { const fixture = await createFixture({ configVersion: 2, plugins: {"child":"@test/child","sibling":"@test/sibling"}, child: { label: '${LABEL}' } }); const environment = new FakeEnvironmentSource( join(fixture.root, '.env'), { base: { LABEL: 'one' } }, ); fixture.modules.installSetups({ resources: 0, root: 0, child: 0, sibling: 0 }); const runtime = new RootRuntime({ projectRoot: fixture.root, modules: fixture.modules, config: fixture.config, environment: testEnvironment, environmentSource: environment, }); await runtime.start(); const child = childPluginId(rootPluginId(), 'child'); expect(runtime.snapshot.config.get(child)).toEqual({ label: 'one' }); const coordinator = runtime.createHmrCoordinator({ onRestartRequired() { throw new Error('unexpected process restart'); }, onError(error) { throw error; }, }); environment.write({ base: { LABEL: 'two' } }); await coordinator.enqueue(environment.sources[0]!); expect(runtime.snapshot.config.get(child)).toEqual({ label: 'two' }); await coordinator.stop(); await runtime.stop(); }); it('keeps the previous environment snapshot when shadow setup rejects a reload', async () => { const fixture = await createFixture({ configVersion: 2, plugins: {"child":"@test/child","sibling":"@test/sibling"}, child: { label: '${LABEL}' } }); const environment = new FakeEnvironmentSource( join(fixture.root, '.env'), { base: { LABEL: 'one' } }, ); fixture.modules.installSetups({ resources: 0, root: 0, child: 0, sibling: 0 }); const runtime = new RootRuntime({ projectRoot: fixture.root, modules: fixture.modules, config: fixture.config, environment: testEnvironment, environmentSource: environment, }); await runtime.start(); const child = childPluginId(rootPluginId(), 'child'); const coordinator = runtime.createHmrCoordinator({ onRestartRequired() { throw new Error('unexpected process restart'); }, onError() {}, }); environment.write({ base: { LABEL: 'broken' } }); await expect(coordinator.enqueue(environment.sources[0]!)) .rejects.toThrow('child environment setup failed'); expect(runtime.snapshot.config.get(child)).toEqual({ label: 'one' }); environment.write({ base: { LABEL: 'two' } }); await coordinator.enqueue(environment.sources[0]!); expect(runtime.snapshot.config.get(child)).toEqual({ label: 'two' }); await coordinator.stop(); await runtime.stop(); }); it('retains an unapplied Host environment layer through subsequent config and source edits', async () => { const fixture = await createFixture({ configVersion: 2, plugins: {"child":"@test/child","sibling":"@test/sibling"}, http: { token: '${HTTP_TOKEN}' } }); const environment = new FakeEnvironmentSource( join(fixture.root, '.env'), { base: { HTTP_TOKEN: 'one' } }, ); fixture.modules.installSetups({ resources: 0, root: 0, child: 0, sibling: 0 }); const runtime = new RootRuntime({ projectRoot: fixture.root, modules: fixture.modules, config: fixture.config, environment: testEnvironment, environmentSource: environment, installResources() {}, }); await runtime.start(); const restarts: ProcessInvalidationPlan[] = []; const coordinator = runtime.createHmrCoordinator({ onRestartRequired(plan) { restarts.push(plan); }, onError(error) { throw error; }, }); environment.write({ base: { HTTP_TOKEN: 'two' } }); await coordinator.enqueue(environment.sources[0]!); expect(restarts).toEqual([]); expect(runtime.configurationApplication.groups).toEqual([expect.objectContaining({ id: 'environment', status: 'restart-pending' })]); fixture.config.writeExternal({ ...(await fixture.config.read()).document, child: { label: 'new' } }); await coordinator.enqueue(fixture.configSource); expect(runtime.configurationApplication.groups).toEqual(expect.arrayContaining([expect.objectContaining({ id: 'environment', status: 'restart-pending' })])); await coordinator.enqueue(join(fixture.root, 'plugins/child/plugin.ts')); const primary = runtime.snapshot.resources.get(rootPluginId())?.get(primaryConfigToken.id) as PrimaryConfig; expect(primary.expanded.http).toEqual({ token: 'one' }); await coordinator.stop(); await runtime.stop(); }); }); const testEnvironment = Object.freeze({ name: 'test', mode: 'test', platform: 'node' } as const); class FakeConfigDocument implements ConfigDocumentPort { readonly sources: readonly string[]; #document: RuntimeConfigDocument; #revision = 0; constructor(source: string, document: RuntimeConfigDocument) { this.sources = Object.freeze([source]); this.#document = structuredClone(document); } writeExternal(document: RuntimeConfigDocument): void { this.#document = structuredClone(document); this.#revision += 1; } async read(): Promise { return Object.freeze({ document: structuredClone(this.#document), revision: `r${this.#revision}`, }); } async prepare( _current: ConfigDocumentSnapshot, _patches: readonly ConfigPatch[], ): Promise { throw new Error('not used by watched-input tests'); } } class FakeEnvironmentSource implements EnvironmentLayersPort { readonly sources: readonly string[]; #layers: EnvironmentLayers; constructor(source: string, layers: EnvironmentLayers) { this.sources = Object.freeze([source]); this.#layers = structuredClone(layers); } write(layers: EnvironmentLayers): void { this.#layers = structuredClone(layers); } async read(): Promise { return structuredClone(this.#layers); } } class FakeModules implements ModuleRuntime { readonly #modules = new Map(); constructor(private readonly root: string) {} installSetups(counts: { root: number; child: number; sibling: number }): void { this.#modules.set(join(this.root, 'plugin.ts'), { default: definePlugin({ name: 'root', setup() { counts.root += 1; } }), }); for (const name of ['child', 'sibling'] as const) { this.#modules.set(join(this.root, `plugins/${name}/plugin.ts`), { default: definePlugin({ name, setup({ config }) { if (name === 'child' && (config.get() as { label?: string }).label === 'broken') { throw new Error('child environment setup failed'); } counts[name] += 1; }, }), }); } } async load(source: string): Promise { if (!this.#modules.has(source)) throw new Error(`Missing fake module: ${source}`); return this.#modules.get(source) as T; } requiresProcessRestart(source: string): boolean { return source.endsWith('.env'); } invalidate(): void {} async close(): Promise {} } async function createFixture(document: RuntimeConfigDocument): Promise<{ readonly root: string; readonly configSource: string; readonly config: FakeConfigDocument; readonly modules: FakeModules; }> { const root = await mkdtemp(join(tmpdir(), 'zhin-runtime-input-')); temporary.push(root); await writeJson(join(root, 'package.json'), { name: '@test/root', dependencies: { '@test/child': 'workspace:*', '@test/sibling': 'workspace:*' }, zhin: { protocol: 1, type: 'plugin', entry: './plugin.ts', plugins: [], }, }); await writeSchema(join(root, 'schema.json'), 'mode', 'development'); await pluginPackage(root, 'child', '@test/child', 'child'); await pluginPackage(root, 'sibling', '@test/sibling', 'sibling'); for (const file of ['plugin.ts', 'plugins/child/plugin.ts', 'plugins/sibling/plugin.ts']) { await touch(join(root, file)); } const canonicalRoot = await realpath(root); const configSource = join(canonicalRoot, 'zhin.config.yml'); return { root: canonicalRoot, configSource, config: new FakeConfigDocument(configSource, document), modules: new FakeModules(canonicalRoot), }; } async function pluginPackage( root: string, directory: string, name: string, defaultLabel: string, ): Promise { await writeJson(join(root, `plugins/${directory}/package.json`), { name, zhin: { protocol: 1, type: 'plugin', entry: './plugin.ts' }, }); await writeSchema(join(root, `plugins/${directory}/schema.json`), 'label', defaultLabel); } async function writeSchema( path: string, property: string, defaultValue: string, ): Promise { await writeJson(path, { type: 'object', additionalProperties: false, properties: { [property]: { type: 'string', default: defaultValue } }, }); } async function writeJson(path: string, value: unknown): Promise { await mkdir(dirname(path), { recursive: true }); await writeFile(path, `${JSON.stringify(value, null, 2)}\n`); } async function touch(path: string): Promise { await mkdir(dirname(path), { recursive: true }); await writeFile(path, ''); }