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.
This commit is contained in:
Turtle
2026-08-07 11:58:03 +08:00
parent f749e04881
commit 1f0a0440f3
23 changed files with 720 additions and 593 deletions

View File

@@ -26,9 +26,10 @@
- id: headless-startup
name: '@deepseek-ai/dsh-headless/startup'
# Shipped off, not merely waiting: the runner's schema requires the task.
# The startup row enables it with the task after parsing this app's argv.
# Reads its task from the headlessStartup service after the startup row
# resolves this app's command line.
- id: headless-runner
name: '@deepseek-ai/dsh-headless'
inject: [headlessStartup]
disabled: true
config:
task: !!js ctx.get('headlessStartup')?.task

View File

@@ -33,7 +33,8 @@
"license": "BSD-3-Clause",
"dsh": {
"bundle": {
"patch": "./cordis.patch.yml"
"patch": "./cordis.patch.yml",
"entrypoint": "headless-startup"
}
},
"dependencies": {

View File

@@ -15,7 +15,7 @@
import { Command } from 'commander'
import type { Context } from 'cordis'
import type { EntryOptions } from '@cordisjs/plugin-loader'
import { overrideConfig, runStartup, type RowChange } from '@deepseek-ai/dsh-cmdline'
import { runStartup } from '@deepseek-ai/dsh-cmdline'
import { WEB_STARTUP_SERVICE } from '@deepseek-ai/dsh-web-app/startup'
/** Stable Cordis plugin name. */
@@ -24,12 +24,18 @@ export const name = 'headless-startup'
/** Services required before the task can be resolved. */
export const inject = ['cmdlineArgs']
/** The startup service the one-shot runner row injects. */
/** The service this row provides and the one-shot runner row reads. */
export const HEADLESS_STARTUP_SERVICE = 'headlessStartup'
/** The runner row this app configures. */
/** The row that runs the task, and the only reason this app has a command line. */
const RUNNER_ROW_ID = 'headless-runner'
/** What the runner row reads from {@link HEADLESS_STARTUP_SERVICE}. */
export interface HeadlessStartupValues {
/** The task text this invocation asked for. */
task: string
}
/**
* This app's command: the task positional, its description, and its help text.
* @returns a fresh program, so one process can parse more than once (tests).
@@ -49,22 +55,25 @@ Examples:
/**
* Turn the parsed command line into the runner row's task.
* @param program - the parsed headless command.
* @param rows - the waiting rows' composed options, in tree order.
* @returns row id → changes.
* @param rows - the rows waiting on this app's service, in tree order.
* @returns the runner row's service value.
* @throws when the composition has no runner row, which would otherwise accept
* a task and silently run nothing.
*/
function planHeadlessStartup(program: Command, rows: readonly EntryOptions[]): Map<string, RowChange> {
function planHeadlessStartup(program: Command, rows: readonly EntryOptions[]): HeadlessStartupValues {
const task = program.args.join(' ')
if (task === '') program.error('error: a task is required, for example: dsh --profile headless "run the tests"')
const runner = rows.find(row => row.id === RUNNER_ROW_ID)
if (runner === undefined) throw new Error(`headless-startup: the composition has no waiting "${RUNNER_ROW_ID}" row to run the task`)
return new Map([[RUNNER_ROW_ID, overrideConfig(runner, { task })]])
if (!rows.some(row => row.id === RUNNER_ROW_ID)) {
throw new Error(`headless-startup: the composition has no waiting "${RUNNER_ROW_ID}" row to run the task`)
}
return { task }
}
/**
* Resolve the task and start the rows waiting for it.
* Resolve the task and start the runner that reads it.
* @param ctx - plugin context carrying the command line and the Loader.
* @returns nothing once the runner is released, or once `--help` or a missing task requested exit.
* @returns nothing once the runner is started, or once `--help` or a missing task requested exit.
*/
export function apply(ctx: Context): Promise<void> {
return runStartup(ctx, [HEADLESS_STARTUP_SERVICE, WEB_STARTUP_SERVICE], headlessCommand(), planHeadlessStartup)
export function apply(ctx: Context): void {
runStartup(ctx, [HEADLESS_STARTUP_SERVICE, WEB_STARTUP_SERVICE], headlessCommand(), planHeadlessStartup)
}

View File

@@ -1,7 +1,8 @@
/**
* The one-shot app's startup row over a REAL Loader tree: the task
* positional reaches the runner row, a missing task is a usage error, and the
* web startup service this app absorbs releases its rows on the composed values.
* The one-shot app's entrypoint row over a REAL Loader tree: the task
* positional becomes the value the runner row reads, a missing task is a usage
* error, and the web service this app absorbs is provided too, so the web rows
* it rides over resolve on their own fallbacks.
*/
import { mkdtempSync, writeFileSync } from 'node:fs'
@@ -9,21 +10,17 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { Context } from 'cordis'
import z from 'schemastery'
import Loader from '@cordisjs/plugin-loader'
import Include from '@cordisjs/plugin-include'
import { internals, provideCmdline } from '@deepseek-ai/dsh-cmdline'
import { WEB_STARTUP_SERVICE } from '@deepseek-ai/dsh-web-app/startup'
import { afterEach, describe, expect, it } from 'vitest'
import { apply, HEADLESS_STARTUP_SERVICE } from '../src/startup.ts'
import { apply, HEADLESS_STARTUP_SERVICE, type HeadlessStartupValues } from '../src/startup.ts'
/** What one boot of the fixture tree observed. */
interface Observed {
started: Record<string, Record<string, unknown>>
exits: number[]
out: string
/** Patches the startup row handed the launcher for later compositions. */
contributed: unknown[]
}
const disposers: (() => Promise<void>)[] = []
@@ -35,112 +32,90 @@ afterEach(async () => {
})
/**
* Boot the real headless startup row over stand-ins for the runner row and one
* web row it absorbs.
* Mount the real entrypoint row over stand-ins for the runner row and one web
* row this app absorbs, the way a profile mounts phase one.
* @param args - the invocation's inner arguments.
* @returns what the boot observed.
* @param options - fixture knobs for the shapes a composition can take.
* @returns the resolved service values (absent when the app requested exit) and what the boot observed.
*/
async function bootStartup(args: string[], options: { withoutRunner?: boolean } = {}): Promise<Observed> {
async function bootStartup(
args: string[],
options: { withoutRunner?: boolean } = {},
): Promise<{ task: HeadlessStartupValues | undefined; web: unknown; observed: Observed }> {
const dir = mkdtempSync(join(tmpdir(), 'dsh-headless-startup-'))
const observed: Observed = { started: {}, exits: [], out: '', contributed: [] }
// The runner's real schema requires the task, which is exactly what makes a
// waiting-but-enabled row fail at fiber creation; the stand-in keeps that.
writeFileSync(join(dir, 'row.mjs'), `
export const Config = globalThis.__headlessRunnerConfigSchema
export function apply(ctx, config) { globalThis.__headlessStartupObserved.started[ctx.fiber.entry.options.id] = config ?? {} }
`)
writeFileSync(join(dir, 'plain-row.mjs'), `
export function apply(ctx, config) { globalThis.__headlessStartupObserved.started[ctx.fiber.entry.options.id] = config ?? {} }
`)
const observed: Observed = { exits: [], out: '' }
writeFileSync(join(dir, 'row.mjs'), 'export function apply() {}\n')
// The Loader imports a row through Node's own resolver, which cannot resolve
// this workspace's sources; the row delegates to the real plugin the test
// imported through the source-plane path mapping.
writeFileSync(join(dir, 'startup-row.mjs'), `
writeFileSync(join(dir, 'entrypoint.mjs'), `
export const name = 'headless-startup'
export const inject = ['cmdlineArgs']
export const apply = ctx => globalThis.__headlessStartupApply(ctx)
`)
const rowUrl = pathToFileURL(join(dir, 'row.mjs')).href
const plainRowUrl = pathToFileURL(join(dir, 'plain-row.mjs')).href
writeFileSync(join(dir, 'cordis.yml'), [
// A composition that lost the runner still injects the startup service, so
// the startup row reaches its own row check rather than the generic one.
// A composition that lost the runner still injects the service, so the
// entrypoint reaches its own row check rather than the generic one.
options.withoutRunner === true ? '- id: displaced-runner' : '- id: headless-runner',
` name: ${rowUrl}`,
` inject: [${HEADLESS_STARTUP_SERVICE}]`,
// Shipped off, like the bundle patch: the schema below requires the task,
// which only the startup row can supply.
' disabled: true',
'- id: webserver',
` name: ${plainRowUrl}`,
` name: ${rowUrl}`,
` inject: [${WEB_STARTUP_SERVICE}]`,
' config:',
' port: 0',
' disabled: true',
'- id: headless-startup',
` name: ${pathToFileURL(join(dir, 'startup-row.mjs')).href}`,
` name: ${pathToFileURL(join(dir, 'entrypoint.mjs')).href}`,
'',
].join('\n'))
const observing = { write: (chunk: string) => { observed.out += chunk; return true } }
internals.stdout = observing
internals.stderr = observing
const globals = globalThis as unknown as {
__headlessStartupObserved: Observed
__headlessStartupApply: typeof apply
__headlessRunnerConfigSchema: unknown
}
globals.__headlessStartupObserved = observed
globals.__headlessStartupApply = apply
globals.__headlessRunnerConfigSchema = z.object({ task: z.string().required() })
;(globalThis as unknown as { __headlessStartupApply: typeof apply }).__headlessStartupApply = apply
const ctx = new Context()
await ctx.plugin(Loader)
ctx.loader.builtins.include = Include
provideCmdline(ctx, {
args,
exit: code => void observed.exits.push(code),
contribute: patches => void observed.contributed.push(...patches),
})
provideCmdline(ctx, { args, exit: code => void observed.exits.push(code) })
await ctx.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(join(dir, 'cordis.yml')).href } })
await ctx.loader.await()
disposers.push(async () => { await ctx.fiber.dispose() })
return observed
return {
task: ctx.get(HEADLESS_STARTUP_SERVICE) as HeadlessStartupValues | undefined,
web: ctx.get(WEB_STARTUP_SERVICE),
observed,
}
}
describe('headless startup', () => {
it('joins the task positional and starts the runner with it', async () => {
const observed = await bootStartup(['run', 'the', 'tests'])
expect(observed.started['headless-runner']).toEqual({ task: 'run the tests' })
it('joins the task positional into the value the runner reads', async () => {
const { task, observed } = await bootStartup(['run', 'the', 'tests'])
expect(task).toEqual({ task: 'run the tests' })
expect(observed.exits).toEqual([])
})
it('hands the task to the launcher as a patch, so a recomposition keeps it', async () => {
const observed = await bootStartup(['run', 'the', 'tests'])
expect(observed.contributed).toEqual([
{ id: 'headless-runner', disabled: false, config: { task: 'run the tests' } },
])
})
it('starts the web rows it absorbed on the composed one-shot values', async () => {
const observed = await bootStartup(['task'])
expect(observed.started.webserver).toEqual({ port: 0 })
it('provides the web service it absorbed, so those rows resolve on their own fallbacks', async () => {
const { web } = await bootStartup(['task'])
expect(web).toEqual({ task: 'task' })
})
it('rejects an invocation with no task instead of failing inside the runner schema', async () => {
const observed = await bootStartup([])
const { task, observed } = await bootStartup([])
expect(observed.out).toContain('a task is required')
expect(observed.started).toEqual({})
expect(task).toBeUndefined()
expect(observed.exits).toEqual([1])
})
it('prints its own help and resolves nothing', async () => {
const { task, observed } = await bootStartup(['--help'])
expect(observed.out).toContain('dsh --profile headless')
expect(task).toBeUndefined()
expect(observed.exits).toEqual([0])
})
it('fails the boot when the composition has no runner row to give the task to', async () => {
await expect(bootStartup(['task'], { withoutRunner: true }))
.rejects.toThrow('the composition has no waiting "headless-runner" row')
})
it('prints its own help and starts nothing', async () => {
const observed = await bootStartup(['--help'])
expect(observed.out).toContain('dsh --profile headless')
expect(observed.started).toEqual({})
expect(observed.exits).toEqual([0])
})
})