Files
deepseek-harness/packages/boot/cmdline/tests/cmdline.spec.ts
T
Turtle 1f0a0440f3 refactor(cmdline)!: an app's entrypoint provides values its rows read
Replaces the patch round trip. An app's entrypoint resolves the command
line into a service, and the rows it configures read that service from
their own config — port: !!js ctx.get('webStartup')?.port ?? 3080 — so the
resolved value beats the value written beside it and nothing is written
back into a row or handed to the launcher.

A bundle names the entrypoint row in its manifest (dsh.bundle.entrypoint),
which is what lets the boot mount in two passes: entrypoints alone, then
the whole composition. That ordering is required, not cosmetic — a row's
config expressions are evaluated when the include applies the row, and a
strict ctx.get only answers for a service whose providing fiber is already
active.

What this removes: ctx.appPatches and the launcher-owned patch layer, the
disable/re-enable recycle and its in-flight-mount barrier, overrideConfig,
and the reload hazard they existed for. A live config edit now re-applies
the second pass against services that are still up, so a served port
survives by construction.

What it adds: ctx.appReady, because Loader settlement no longer means the
app is up — a row mounted in the second pass can observe a settled tree
while that pass is still running, or already rolling back. The web URL line
waits for it, so a boot that fails in the second pass announces nothing.
2026-08-10 23:45:04 +08:00

209 lines
8.4 KiB
TypeScript

/**
* The launcher-to-app command line over a REAL Loader tree, mounted the way a
* profile boot mounts it: the entrypoint row first, then the rest of the
* composition, whose rows read the entrypoint's values from their own config
* expressions. `--help` never reaches that second phase.
*/
import { mkdtempSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { Command } from 'commander'
import { Context } from 'cordis'
import Loader from '@cordisjs/plugin-loader'
import Include from '@cordisjs/plugin-include'
import type { PatchOptions } from '@cordisjs/plugin-include'
import { afterEach, describe, expect, it } from 'vitest'
import { internals, provideCmdline, runStartup, type StartupPlan } from '../src/index.ts'
/** Every value one boot of the fixture tree observed. */
interface Observed {
/** Config the reading row started with; absent means it never started. */
started?: Record<string, unknown>
exits: number[]
out: string
}
/** A booted fixture tree: what it observed, and its root for direct startup calls. */
interface Fixture {
observed: Observed
ctx: Context
}
const disposers: (() => Promise<void>)[] = []
afterEach(async () => {
for (const dispose of disposers.splice(0)) await dispose()
internals.stdout = process.stdout
internals.stderr = process.stderr
})
/** The fixture app's flag family: one `--port` its rows read from the service. */
function demoCommand(): Command {
return new Command().name('demo').exitOverride().option('--port <port>', 'listen port')
}
/** The fixture app's plan: the resolved values its rows read. */
const demoPlan: StartupPlan<{ port?: number }> = (program) => {
const port = program.opts<{ port?: string }>().port
if (port === undefined) return {}
if (!/^\d+$/.test(port)) program.error(`error: --port must be a number, got ${JSON.stringify(port)}`)
return { port: Number(port) }
}
/** A YAML `!!js` expression node, as the include parses one out of a patch file. */
const expression = (source: string): unknown => ({ __jsExpr: source })
/**
* Mount a two-row composition the way a profile boot does: the entrypoint row
* alone first, then everything.
* @param args - the invocation's inner arguments.
* @param plan - the app's plan; defaults to the fixture's own.
* @returns the booted fixture.
*/
async function bootFixture(
args: string[],
plan: StartupPlan = demoPlan,
options: { withoutEntrypoint?: boolean } = {},
): Promise<Fixture> {
const dir = mkdtempSync(join(tmpdir(), 'dsh-cmdline-'))
const observed: Observed = { exits: [], out: '' }
writeFileSync(join(dir, 'reader.mjs'), `
export const name = 'reader'
export const inject = ['demoStartup']
export function apply(ctx, config) { globalThis.__observed.started = config }
`)
// The Loader imports a row through Node's own resolver, which cannot resolve
// this workspace's sources; the row delegates to the real function the test
// imported through the source-plane path mapping.
writeFileSync(join(dir, 'entrypoint.mjs'), `
export const name = 'demo-startup'
export const inject = ['cmdlineArgs']
export function apply(ctx) { return globalThis.__runStartup(ctx) }
`)
writeFileSync(join(dir, 'cordis.yml'), '[]\n')
const observing = { write: (chunk: string) => { observed.out += chunk; return true } }
internals.stdout = observing
internals.stderr = observing
const globals = globalThis as unknown as { __observed: Observed; __runStartup: (ctx: Context) => void }
globals.__observed = observed
globals.__runStartup = (ctx: Context) => { runStartup(ctx, 'demoStartup', demoCommand(), plan) }
// The composition, exactly as a profile delivers one: include patches whose
// config carries `!!js` expressions.
const composition: PatchOptions[] = [{
insert: [
...options.withoutEntrypoint === true
? []
: [{ id: 'demo-startup', name: pathToFileURL(join(dir, 'entrypoint.mjs')).href }],
{
id: 'reader',
name: pathToFileURL(join(dir, 'reader.mjs')).href,
inject: ['demoStartup'],
config: { port: expression("ctx.get('demoStartup')?.port ?? 3080") },
},
],
}]
const ctx = new Context()
await ctx.plugin(Loader)
ctx.loader.builtins.include = Include
provideCmdline(ctx, { args, exit: code => void observed.exits.push(code) })
const rootConfig = { path: pathToFileURL(join(dir, 'cordis.yml')).href }
// Phase one: the entrypoint alone.
const includeId = await ctx.loader.create({
name: 'cordis:include',
config: { ...rootConfig, patches: [...structuredClone(composition), { id: 'reader', disabled: true }] },
})
await ctx.loader.await()
disposers.push(async () => { await ctx.fiber.dispose() })
if (observed.exits.length === 0) {
// Phase two: the whole composition, now that the entrypoint's values answer.
await ctx.loader.resolve(includeId).update({ config: { ...rootConfig, patches: structuredClone(composition) } })
await ctx.loader.await()
}
return { observed, ctx }
}
describe('runStartup', () => {
it('lets a row read the flag value the app resolved', async () => {
const { observed } = await bootFixture(['--port', '8080'])
expect(observed.started).toEqual({ port: 8080 })
expect(observed.exits).toEqual([])
})
it('leaves a row on the value written beside the expression when no flag names one', async () => {
const { observed } = await bootFixture([])
expect(observed.started).toEqual({ port: 3080 })
})
it('prints the app help, starts no reading row, and requests exit 0', async () => {
const { observed } = await bootFixture(['--help'])
expect(observed.out).toContain('Usage: demo')
expect(observed.started).toBeUndefined()
expect(observed.exits).toEqual([0])
})
it('rejects the invocation from the plan without starting the app', async () => {
const { observed } = await bootFixture(['--port', 'abc'])
expect(observed.out).toContain('--port must be a number')
expect(observed.started).toBeUndefined()
expect(observed.exits).toEqual([1])
})
it('rethrows a plan failure that is not commander asking to exit', async () => {
const { ctx } = await bootFixture([], demoPlan, { withoutEntrypoint: true })
const plan: StartupPlan = () => { throw new Error('plan exploded') }
expect(() => { runStartup(ctx, 'demoStartup', demoCommand(), plan) }).toThrow('plan exploded')
})
it('rethrows a thrown value that is not an object at all', async () => {
const { ctx } = await bootFixture([], demoPlan, { withoutEntrypoint: true })
const plan: StartupPlan = () => {
const thrown: unknown = 'plan threw a string'
throw thrown
}
expect(() => { runStartup(ctx, 'demoStartup', demoCommand(), plan) }).toThrow('plan threw a string')
})
it('fails loud when no row injects the service the app provides', async () => {
// The bundle patch and its entrypoint disagree; a silent no-op would leave
// every row of the app on its fallbacks with no explanation.
const { ctx } = await bootFixture([], demoPlan, { withoutEntrypoint: true })
expect(() => { runStartup(ctx, 'absentStartup', demoCommand()) })
.toThrow('absentStartup: no row injects this startup service')
})
it('provides an empty value when the app declares no plan', async () => {
const { ctx } = await bootFixture([], demoPlan, { withoutEntrypoint: true })
runStartup(ctx, 'demoStartup', demoCommand())
expect(ctx.get('demoStartup')).toEqual({})
})
})
describe('provideCmdline', () => {
it('hands the app a snapshot the caller cannot mutate afterwards', () => {
const ctx = new Context()
const args = ['--resume', 'abc']
provideCmdline(ctx, { args, exit: () => {} })
args.push('--tampered')
expect(ctx.cmdlineArgs?.get()).toEqual(['--resume', 'abc'])
})
it('fails loud when an entrypoint runs without the launcher values', () => {
const ctx = new Context()
expect(() => { runStartup(ctx, 'demoStartup', demoCommand()) })
.toThrow('the launcher must provide ctx.cmdlineArgs and ctx.appExit')
})
it('resolves nothing when the tree was disposed while the entrypoint parsed', () => {
// An early SIGTERM takes the Loader with it; there is nothing left to
// configure, and the bundle did nothing wrong.
const exits: number[] = []
const ctx = new Context()
provideCmdline(ctx, { args: [], exit: code => void exits.push(code) })
expect(() => { runStartup(ctx, 'demoStartup', demoCommand()) }).not.toThrow()
expect(exits).toEqual([])
})
})