The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
The core runs from its own entry in the lean bundle (#955)
Dee08548179c21c
diff --git a/cli/build-bundle.mjs b/cli/build-bundle.mjsindex 7c507d9b5..8af495155 100644--- a/cli/build-bundle.mjs+++ b/cli/build-bundle.mjs@@ -81,12 +81,32 @@ const lean = await esbuild.build({write: false,logLevel: 'warning',})+// The core, bundled apart from them (src/leanCoreEntry.ts): built as one more entry of the same build, it+// shared their files, and each file a build splits out holds what any entry that loads it uses, so the+// master and every service loaded what only the core uses. Its files are named `core-*`, so the two never+// meet in the folder they are written to.+const leanCore = await esbuild.build({+ ...options,+ entryPoints: { 'harnessd-core': 'src/leanCoreEntry.ts' },+ outdir: 'lean',+ splitting: true,+ chunkNames: 'core-[name]-[hash]',+ outExtension: { '.js': '.mjs' },+ write: false,+ logLevel: 'warning',+})const leanFiles = Object.fromEntries(lean.outputFiles.map((file) => [basename(file.path), file.contents]))+for (const file of leanCore.outputFiles) {+ const name = basename(file.path)+ if (name in leanFiles) throw new Error(`the core's lean file ${name} has the name of one of the master's and the services'`)+ leanFiles[name] = file.contents+}await esbuild.build({...options,// Still one file, which the self-updater downloads, verifies and swaps whole. Its entry decides what a- // process loads (src/entry.ts), and the master starts itself and the services from the lean bundle.+ // process loads (src/entry.ts), and the master starts itself, the core and the services from the lean+ // bundle.entryPoints: ['src/entry.ts'],outfile: `${outDir}/cli.js`,})diff --git a/cli/e2e/cli.e2e.ts b/cli/e2e/cli.e2e.tsindex 0fcb01164..c33486647 100644--- a/cli/e2e/cli.e2e.ts+++ b/cli/e2e/cli.e2e.ts@@ -103,6 +103,9 @@ const panes = (m: Machine) => m.daemon.tmux.run('list-panes', '-a', '-F', '#{pan/** A process's command line, as ps prints it. */const commandOf = (pid: number): string => execFileSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8' }).trim()const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')+/** The core a master starts on an installed bundle: from the core's entry in the lean bundle it carries,+ * written out into the data folder. */+const leanCore = (m: Machine) => new RegExp(` ${escape(join(m.daemon.dataDir, 'lean'))}/[0-9a-f]{16}/harnessd-core\\.mjs __run$`)const statusOf = async (m: Machine) => await (await fetch(`http://127.0.0.1:${m.daemon.port}/api/status`)).json() as Record<string, any>describe('harness start, stop and status from the installed bundle', () => {@@ -188,9 +191,10 @@ describe('harness start, stop and status from the installed bundle', () => {const core = status.corePid as numberexpect(core).not.toBe(master)seen.add(master).add(core)- // harnessd's master (it retitles itself), running the installed bundle's core.+ // harnessd's master (it retitles itself), running the installed bundle's core: from the lean bundle that+ // bundle carries, written out into the data folder (src/harnessd/leanBundle.ts).expect(commandOf(master)).toBe('harnessd')- expect(commandOf(core)).toMatch(new RegExp(` ${escape(m.cli)} __run$`))+ expect(commandOf(core)).toMatch(leanCore(m))const running = await harness(m, 'status')expect(running.stdout).toMatch(/status +● running · this computer only \(not signed in\)/)@@ -233,7 +237,7 @@ describe('harness start, stop and status from the installed bundle', () => {expect(commandOf(first)).toBe('harnessd')const firstCore = (await statusOf(m)).corePid as numberseen.add(firstCore)- expect(commandOf(firstCore)).toMatch(new RegExp(` ${escape(m.cli)} __run$`))+ expect(commandOf(firstCore)).toMatch(leanCore(m))const definition = readFileSync(m.definition, 'utf8')expect(definition).toContain(m.node)expect(definition).toContain(m.cli)diff --git a/cli/e2e/harness/release.ts b/cli/e2e/harness/release.tsindex 42630f814..6f5b87d69 100644--- a/cli/e2e/harness/release.ts+++ b/cli/e2e/harness/release.ts@@ -1,10 +1,10 @@/*** A release of this checkout at a made-up version, as the update and re-execution tests serve them: the* bundle built once, with its version swapped. The version is baked in at build time, in cli.js and in- * the lean bundle cli.js carries for harnessd's master and its services (src/harnessd/leanBundle.ts), so- * it is swapped in both: a master reporting the build before is not the build it was handed.+ * the lean bundle cli.js carries for harnessd's master, its services and its core (src/harnessd/leanBundle.ts),+ * so it is swapped in both: a master reporting the build before is not the build it was handed.*/-import { readLeanBundle } from '../../src/harnessd/leanBundle.js'+import { LEAN_CORE_ENTRY, LEAN_ENTRY, readLeanBundle } from '../../src/harnessd/leanBundle.js'const { LEAN_MARKER, leanBlock } = await import('../../scripts/lib/leanBlock.mjs' as string) as {LEAN_MARKER: string@@ -26,3 +26,20 @@ export function withLean(bundle: string, files: Record<string, string>): stringconst head = at < 0 ? bundle : bundle.slice(0, at).replace(/\n$/, '')return head + leanBlock(files)}++/**+ * [bundle] with [code] run first wherever a daemon process starts on it: after cli.js's first line, and+ * at the top of the lean bundle's two entries: the one the master re-executes on and starts the services+ * from (src/leanEntry.ts), and the core's (src/leanCoreEntry.ts). A fault aimed at the core+ * (`process.argv[2]==="__run"`) must reach a core started from either file, as a build whose core+ * crashes does.+ */+export function withFault(bundle: string, code: string): string {+ if (!code) return bundle+ const inCli = bundle.replace('\n', `\n${code}\n`)+ const lean = readLeanBundle(Buffer.from(inCli))+ if (!lean) return inCli+ const files = Object.fromEntries([...lean.files].map(([name, text]) => [name, text.toString('utf8')]))+ for (const entry of [LEAN_ENTRY, LEAN_CORE_ENTRY]) if (files[entry]) files[entry] = files[entry]!.replace('\n', `\n${code}\n`)+ return withLean(inCli, files)+}diff --git a/cli/e2e/lean.e2e.ts b/cli/e2e/lean.e2e.tsindex 4c36e9c86..06bb90682 100644--- a/cli/e2e/lean.e2e.ts+++ b/cli/e2e/lean.e2e.ts@@ -1,10 +1,11 @@/*** harnessd's master and its services lean, on a real release bundle: Node parses all of the file a* process starts on, and started on the whole 4.4 MB cli.js each paid about 45 MiB for that alone. So- * the master re-executes, same pid, on the lean bundle cli.js carries, and starts every service from it- * (src/harnessd/leanBundle.ts); the core runs from cli.js as always. Every service still runs in its own- * process and does its work, for Claude Code and Codex agents alike. A lean bundle that cannot start a- * master is never handed the daemon, and `HARNESSD_LEAN=off` runs everything from cli.js as before.+ * the master re-executes, same pid, on the lean bundle cli.js carries, and starts every service and the core+ * from it (src/harnessd/leanBundle.ts), the core on its own code: what it hands on still names cli.js. Every+ * service still runs in its own process and does its work, for Claude Code and Codex agents alike. A lean+ * bundle that cannot start a master is never handed the daemon, a core that cannot start from it starts+ * from cli.js, and `HARNESSD_LEAN=off` runs everything from cli.js as before.** The bundle is built from this checkout (the run's own with `E2E_BUNDLE=1`).*/@@ -16,7 +17,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, it, onTestFailed } frimport { LocalClient, type Frame } from './harness/client.js'import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'import { withLean } from './harness/release.js'-import { readLeanBundle } from '../src/harnessd/leanBundle.js'+import { LEAN_CORE_ENTRY, readLeanBundle } from '../src/harnessd/leanBundle.js'type Engine = 'claude' | 'codex'/** The processes the master runs the services in, and the services, each on its own link to the core. The@@ -31,6 +32,14 @@ const servicePids = (d: IsolatedDaemon): Map<string, number> => new Map(PROCESSEreturn [name, Number(started.at(-1)?.[1] ?? 0)]}))const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId+/** The command the daemon's hooks run, as it installed them for Claude Code in the test's home. */+const claudeHookCommand = (d: IsolatedDaemon): string => {+ const settings = JSON.parse(readFileSync(join(d.root, 'home', '.claude', 'settings.json'), 'utf8')) as { hooks: Record<string, Array<{ hooks: Array<{ command: string }> }>> }+ return settings.hooks.UserPromptSubmit![0]!.hooks[0]!.command+}+const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')+/** This daemon's core, by the pid it reports, and what started it. */+const coreCommand = (d: IsolatedDaemon): string => commandOf(d.corePid()!)describe('harnessd\'s master and services lean', () => {let scratch = ''@@ -75,7 +84,7 @@ describe('harnessd\'s master and services lean', () => {} finally { client.close() }}- it('re-executes the master, same pid, on the lean bundle, and runs every service from it; the core from cli.js', async () => {+ it('re-executes the master, same pid, on the lean bundle, and runs every service and the core from it', async () => {const d = await fresh()// The master titles itself `harnessd`, so its log says what it runs on: the lean bundle, written// into the data folder, which only a master running on it says it shares with the services.@@ -86,13 +95,18 @@ describe('harnessd\'s master and services lean', () => {// The same process `harness start` started: re-executed in place.const master = d.pid!expect(commandOf(master)).toBe('harnessd')- expect(commandOf(d.corePid()!)).toContain(`${bundle} __run`)+ // The core from the lean bundle too, on its own entry; to everything it hands on, its script is cli.js:+ // the hooks it installed run the notify.mjs beside it, not one beside the lean bundle.+ expect(coreCommand(d)).toMatch(new RegExp(` ${escape(join(d.dataDir, 'lean'))}/[0-9a-f]{16}/${escape(LEAN_CORE_ENTRY)} __run$`))+ expect(claudeHookCommand(d)).toContain(join(dirname(bundle), 'notify.mjs'))for (const [name, pid] of servicePids(d)) expect(commandOf(pid), name).toBe(`harnessd-${name}`)// Lean: under the cost of parsing the whole CLI, which every one of them paid before (at idle,// 115 to 160 MiB each), and a long way under it at that (55 to 80).for (const [name, pid] of [['master', master], ...servicePids(d)] as Array<[string, number]>) {expect(rssMiB(pid), `${name} resident MiB`).toBeLessThan(100)}+ // The core in it, beside its own processes, and nothing it starts runs from its folder: the panes' CLI is cli.js.+ expect(d.log()).not.toMatch(/the lean bundle runs a core only for the cli\.js/)// A service's lines are stamped, as the core's and the master's are in the log they share.for (const name of SERVICES) {await until(`${name} to say it is connected`, () => new RegExp(`\\d{4}-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d\\.\\d{3} \\[service ${name}\\] connected to the core`).test(d.log()) || null, 30_000, 200)@@ -120,12 +134,36 @@ describe('harnessd\'s master and services lean', () => {const before = restarts()process.kill(search, 'SIGKILL')await until('search started again', () => restarts() > before || null, 60_000, 200)- // From cli.js, as the core: its path as the master resolved it.- expect(d.log()).toMatch(new RegExp(`\\[harnessd\\] the lean bundle \\S+ cannot be used \\(it is gone\\): services start from \\S+cli\\.js`))+ // From cli.js: its path as the master resolved it.+ expect(d.log()).toMatch(new RegExp(`\\[harnessd\\] the lean bundle \\S+ cannot be used \\(it is gone\\): the core and the services start from \\S+cli\\.js`))expect(d.log()).toContain(`the lean bundle ${ours} cannot be used`)await agentWorks(d, 'codex')+ // The core too, the next time it starts: killed, it comes back from cli.js and its agents go on.+ process.kill(d.corePid()!, 'SIGKILL')+ await until('the core started again', () => d.coresStarted() >= 2 || null, 60_000, 200)+ await until('the core bound again', async () => (await fetch(`http://127.0.0.1:${d.port}/api/health`).then((r) => r.ok, () => false)) || null, 60_000, 250)+ expect(coreCommand(d).endsWith(`${bundle} __run`)).toBe(true)+ await agentWorks(d, 'claude')expect(d.log()).not.toMatch(/MODULE_NOT_FOUND|Cannot find module/)- expect(d.coresStarted()).toBe(1)+ })++ it('starts the core from cli.js once it has died twice from the lean bundle before it beat, and the daemon works', async () => {+ // A lean core that cannot start costs two quick restarts, never the daemon: the master, the services+ // and every later core run on. Here its own module throws as it loads; the master's and the services' are whole.+ const lean = readLeanBundle(readFileSync(bundle))!+ const files = Object.fromEntries([...lean.files].map(([name, code]) => [name, code.toString('utf8')]))+ const core = Object.keys(files).find((name) => name.startsWith('core-coreProcess-'))!+ files[core] = 'throw new Error("a lean core that cannot load")\n'+ const brokenCore = join(scratch, 'broken-core', 'cli.js')+ mkdirSync(join(scratch, 'broken-core'), { recursive: true })+ writeFileSync(brokenCore, withLean(readFileSync(bundle, 'utf8'), files), { mode: 0o755 })+ const d = await fresh({ HARNESSD_INITIAL_BACKOFF_MS: '200' }, brokenCore)+ expect(d.log()).toMatch(/\[harnessd\] the core died 2 times from the lean bundle before it beat: it starts from \S+cli\.js from now on/)+ expect(d.coresStarted()).toBe(3)+ expect(coreCommand(d).endsWith(`${brokenCore} __run`)).toBe(true)+ // Still lean: the master and the services.+ expect(d.log()).toMatch(/\[harnessd\] services run from \S+, as this master does/)+ await agentWorks(d, 'codex')})it('keeps a master\'s lean bundle while it lives: another build\'s master on the same data folder leaves it, and its services still restart', async () => {@@ -157,11 +195,23 @@ describe('harnessd\'s master and services lean', () => {expect(d.coresStarted()).toBe(1)})- it('runs everything from cli.js, as before, with HARNESSD_LEAN=off', async () => {+ it('runs everything from cli.js, as before, with HARNESSD_LEAN=off, and with the lean-off file the core too', async () => {const d = await fresh({ HARNESSD_LEAN: 'off' })expect(existsSync(join(d.dataDir, 'lean'))).toBe(false)expect(d.log()).not.toMatch(/\[harnessd\] services run from/)+ expect(coreCommand(d).endsWith(`${bundle} __run`)).toBe(true)await agentWorks(d, 'codex')+ await d.close()+ daemon = undefined+ // The switch for a master launchd or systemd starts, whose environment is the unit's.+ const off = await IsolatedDaemon.create({ scriptPath: bundle })+ daemon = off+ mkdirSync(off.dataDir, { recursive: true })+ writeFileSync(join(off.dataDir, 'lean-off'), '')+ await off.start()+ expect(off.log()).toContain('lean-off is there: the master, the core and the services run from')+ expect(coreCommand(off).endsWith(`${bundle} __run`)).toBe(true)+ await agentWorks(off, 'claude')})it('never hands the daemon a lean bundle that cannot start a master: everything runs from cli.js', async () => {@@ -169,8 +219,9 @@ describe('harnessd\'s master and services lean', () => {mkdirSync(join(scratch, 'broken'), { recursive: true })writeFileSync(broken, withLean(readFileSync(bundle, 'utf8'), { 'harnessd.mjs': 'process.exit(5)\n' }), { mode: 0o755 })const d = await fresh({}, broken)- expect(d.log()).toMatch(/\[harnessd\] the lean bundle \S+ did not answer its probe \(exit 5\): the master and the services run from /)+ expect(d.log()).toMatch(/\[harnessd\] the lean bundle \S+ did not answer its probe \(exit 5\): the master, the core and the services run from /)expect(d.log()).not.toMatch(/\[harnessd\] services run from/)+ expect(coreCommand(d).endsWith(`${broken} __run`)).toBe(true)await agentWorks(d, 'claude')expect(d.coresStarted()).toBe(1)})diff --git a/cli/e2e/reexec.e2e.ts b/cli/e2e/reexec.e2e.tsindex 488a641c0..96f1bf2bd 100644--- a/cli/e2e/reexec.e2e.ts+++ b/cli/e2e/reexec.e2e.ts@@ -21,7 +21,7 @@ import { dirname, join } from 'node:path'import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'import { LocalClient, type Frame } from './harness/client.js'import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'-import { atVersion } from './harness/release.js'+import { atVersion, withFault } from './harness/release.js'import { PROBE_COMMAND, runProbe } from '../src/harnessd/reexec.js'const FIRST = '42.0.1'@@ -78,7 +78,8 @@ describe('the master re-executing itself on an update', () => {const daemonProcesses = (): Array<{ pid: number; ppid: number; command: string }> =>execFileSync('ps', ['-axo', 'pid=,ppid=,command='], { encoding: 'utf8' }).split('\n').map((line) => /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line))- .filter((match): match is RegExpExecArray => !!match && match[3].includes(join(cliDir(), 'cli.js')))+ // The core and the services from the lean bundle in the data folder, or from cli.js.+ .filter((match): match is RegExpExecArray => !!match && (match[3].includes(join(cliDir(), 'cli.js')) || (!!daemon && match[3].includes(join(daemon.dataDir, 'lean'))))).map((match) => ({ pid: Number(match[1]), ppid: Number(match[2]), command: match[3] }))const nothingOrphaned = async (masterPid: number) => {// A probe is over within the update; give one a moment to end.@@ -98,7 +99,7 @@ describe('the master re-executing itself on an update', () => {const release = (version: string, inject = ''): void => {// The version is baked in at build time; the others are the same bytes with it swapped, and a// fault put in at the top where a test needs one.- const source = atVersion(first, FIRST, version).replace('\n', `\n${inject}\n`)+ const source = withFault(atVersion(first, FIRST, version), inject)const file = join(out, `cli-${version}.js`)writeFileSync(file, source)expect(execFileSync(process.execPath, [file, 'version'], { encoding: 'utf8' }).trim()).toBe(version)diff --git a/cli/e2e/releaseRehearsal.e2e.ts b/cli/e2e/releaseRehearsal.e2e.tsindex 2538d0a48..50aa2370d 100644--- a/cli/e2e/releaseRehearsal.e2e.ts+++ b/cli/e2e/releaseRehearsal.e2e.ts@@ -66,7 +66,8 @@ describe.skipIf(!FROM)('a release rehearsal: the update from a published releaseconst daemonProcesses = (): Array<{ pid: number; ppid: number; command: string }> =>execFileSync('ps', ['-axo', 'pid=,ppid=,command='], { encoding: 'utf8' }).split('\n').map((line) => /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line))- .filter((match): match is RegExpExecArray => !!match && match[3].includes(join(cliDir(), 'cli.js')))+ // The core and the services from the lean bundle in the data folder, or from cli.js.+ .filter((match): match is RegExpExecArray => !!match && (match[3].includes(join(cliDir(), 'cli.js')) || (!!daemon && match[3].includes(join(daemon.dataDir, 'lean'))))).map((match) => ({ pid: Number(match[1]), ppid: Number(match[2]), command: match[3] }))/** The pids answering on the daemon's port: whatever runs it now, a successor nothing started for us included. */const listeners = (): number[] => {diff --git a/cli/e2e/update.e2e.ts b/cli/e2e/update.e2e.tsindex d54a216ac..7d7c46da7 100644--- a/cli/e2e/update.e2e.ts+++ b/cli/e2e/update.e2e.ts@@ -16,7 +16,7 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'-import { atVersion } from './harness/release.js'+import { atVersion, withFault } from './harness/release.js'const FIRST = '41.0.1'const sha = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex')@@ -60,7 +60,7 @@ describe('a self-update under harnessd', () => {const release = (version: string, crashesOnStart = false): void => {let source = atVersion(first, FIRST, version)// Passes the updater's canary (`cli.js version`), then dies on every start as a core.- if (crashesOnStart) source = source.replace('\n', '\nif(process.argv[2]==="__run")process.exit(3);\n')+ if (crashesOnStart) source = withFault(source, 'if(process.argv[2]==="__run")process.exit(3);')const file = join(out, `cli-${version}.js`)writeFileSync(file, source)expect(execFileSync(process.execPath, [file, 'version'], { encoding: 'utf8' }).trim()).toBe(version)diff --git a/cli/e2e/updateHostile.e2e.ts b/cli/e2e/updateHostile.e2e.tsindex 4eca6ae42..91e1813f5 100644--- a/cli/e2e/updateHostile.e2e.ts+++ b/cli/e2e/updateHostile.e2e.ts@@ -24,7 +24,7 @@ import { join } from 'node:path'import { afterAll, afterEach, beforeAll, describe, expect, it, onTestFailed } from 'vitest'import { LocalClient, type Frame } from './harness/client.js'import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'-import { atVersion } from './harness/release.js'+import { atVersion, withFault } from './harness/release.js'const FIRST = '43.0.1'const DISKFULL = process.env.DISKFULL === '1' && process.platform === 'darwin'@@ -67,8 +67,8 @@ class Releases {readonly cli = new Map<string, Buffer>()readonly notify = new Map<string, Buffer>()add(version: string, inject = ''): void {- // In the lean bundle cli.js carries for the master and the services too (e2e/harness/release.ts).- const source = atVersion(built, FIRST, version).replace('\n', `\n${inject}\n`)+ // In the lean bundle cli.js carries for the master, the services and the core too (e2e/harness/release.ts).+ const source = withFault(atVersion(built, FIRST, version), inject)const file = join(buildDir, `cli-${version}.js`)writeFileSync(file, source)expect(execFileSync(process.execPath, [file, 'version'], { encoding: 'utf8' }).trim()).toBe(version)@@ -296,7 +296,7 @@ class Installed {daemonProcesses(): Array<{ pid: number; ppid: number; command: string }> {return execFileSync('ps', ['-axo', 'pid=,ppid=,command='], { encoding: 'utf8' }).split('\n').map((line) => /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line))- .filter((match): match is RegExpExecArray => !!match && match[3].includes(join(this.cliDir, 'cli.js')))+ .filter((match): match is RegExpExecArray => !!match && (match[3].includes(join(this.cliDir, 'cli.js')) || (!!this.daemon && match[3].includes(join(this.daemon.dataDir, 'lean'))))).map((match) => ({ pid: Number(match[1]), ppid: Number(match[2]), command: match[3] }))}diff --git a/cli/e2e/updateOnItsOwn.e2e.ts b/cli/e2e/updateOnItsOwn.e2e.tsindex da5a87774..eacea3f3e 100644--- a/cli/e2e/updateOnItsOwn.e2e.ts+++ b/cli/e2e/updateOnItsOwn.e2e.ts@@ -22,7 +22,7 @@ import { join } from 'node:path'import { afterAll, afterEach, beforeAll, describe, expect, it, onTestFailed } from 'vitest'import { LocalClient, type Frame } from './harness/client.js'import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'-import { atVersion } from './harness/release.js'+import { atVersion, withFault } from './harness/release.js'const FIRST = '44.0.1'const sha = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex')@@ -110,7 +110,7 @@ describe('a core with no master', () => {/** A release; `dies` names the commands it dies on (exit 3), after the updater's canary (`cli.js version`). */const release = (version: string, dies: string[] = []): void => {let source = atVersion(first, FIRST, version)- if (dies.length) source = source.replace('\n', `\nif(${JSON.stringify(dies)}.includes(process.argv[2]))process.exit(3);\n`)+ if (dies.length) source = withFault(source, `if(${JSON.stringify(dies)}.includes(process.argv[2]))process.exit(3);`)releases.set(version, Buffer.from(source))}release(FIRST)diff --git a/cli/scripts/check-lean-bundle.mjs b/cli/scripts/check-lean-bundle.mjsindex deec74b13..c96aabc10 100644--- a/cli/scripts/check-lean-bundle.mjs+++ b/cli/scripts/check-lean-bundle.mjs@@ -1,12 +1,15 @@/*** Before a release is uploaded (scripts/upload-cli.sh): the lean bundle cli.js carries for harnessd's- * master and its services (src/harnessd/leanBundle.ts) must start a master and load every service.+ * master, its services and its core (src/harnessd/leanBundle.ts) must start a master and load every+ * service's module and the core's.*- * A master started on cli.js runs only a lean bundle that answers its probe, and a service that cannot- * start from it is started from cli.js, so a broken one costs memory, not the daemon. This keeps a broken- * one from shipping at all: it writes the files out, asks the master's probe (`harnessd.mjs- * __harnessd-probe`), and imports the module each process starts on, each in a Node of its own, in a- * throwaway home and data folder.+ * A master started on cli.js runs only a lean bundle that answers its probe, and a service or a core that+ * cannot start from it is started from cli.js, so a broken one costs memory and two restarts, not the+ * daemon. But the first core of an update is judged as it starts, from the lean bundle: one that cannot+ * load there rolls a good build back. This keeps a broken one from shipping at all: it writes the files+ * out, asks the master's probe (`harnessd.mjs __harnessd-probe`), starts the core's entry as no master+ * would, to see it load and refuse, and imports the module each process starts on, each in a Node of its+ * own, in a throwaway home and data folder.** node scripts/check-lean-bundle.mjs dist/cli.js*/@@ -32,10 +35,18 @@ try {let answertry { answer = run([join(dir, 'harnessd.mjs'), '__harnessd-probe']) } catch (error) { fail(`its master does not answer its probe: ${String(error.stderr || error.message).trim()}`) }if (!answer.includes('harnessd-probe ok')) fail(`its master answered its probe with: ${answer.trim()}`)- // Each process's own module: the master's, and every service's (serviceProcess.ts loads the one it is named).- const modules = Object.keys(files).filter((name) => /^(masterProcess|serviceProcess|\w+Process)-[A-Z0-9]+\.mjs$/.test(name))- if (!modules.some((name) => name.startsWith('masterProcess-')) || !modules.some((name) => name.startsWith('serviceProcess-'))) {- fail(`its lean bundle is missing the master's or the services' module (${modules.join(', ') || 'none'})`)+ // Each process's own module: the master's, every service's (serviceProcess.ts loads the one it is named),+ // and the core's, built apart from them (src/leanCoreEntry.ts).+ const modules = Object.keys(files).filter((name) => /^(core-)?\w+Process-[A-Z0-9]+\.mjs$/.test(name))+ if (!files['harnessd-core.mjs'] || !['masterProcess-', 'serviceProcess-', 'core-coreProcess-'].every((own) => modules.some((name) => name.startsWith(own)))) {+ fail(`its lean bundle is missing the master's, the services' or the core's module (${modules.join(', ') || 'none'})`)+ }+ // Without the cli.js a master names, the core's entry refuses to run: proof it loads, without a core.+ try {+ run([join(dir, 'harnessd-core.mjs'), '__run'])+ fail('its core\'s entry ran a core no master started')+ } catch (error) {+ if (error.status !== 2 || !String(error.stderr).includes('runs a core only for the cli.js')) fail(`its core's entry does not load: ${String(error.stderr || error.message).trim()}`)}for (const name of modules) {try { run(['--input-type=module', '-e', `await import(${JSON.stringify(pathToFileURL(join(dir, name)).href)})`]) } catch (error) {diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 51d6b41af..ba88dcfb4 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -26,7 +26,8 @@ import { createInterface, emitKeypressEvents } from 'readline'import { homedir, hostname } from 'os'import { env } from './config/env.js'import { VERSION } from './version.js'-import { runCore, runCoreInForeground } from './core/main.js'+import { runCoreInForeground } from './core/main.js'+import { startCoreProcess } from './coreProcess.js'import { GRID_MINT_TIMEOUT_MS, backendHttpBase, requestJson, postJson, controlPlaneAuth } from './lib/controlPlane.js'import { LEGACY_LOG_FILE, MACHINE_NAME_FILE, tildify, computerId, thisDeviceLabel, DAEMON_LOG_FILE, HARNESSD_STATUS_FILE, daemonPort, isAlive, isDaemonRunning, readPid } from './lib/daemonState.js'import { onError, BIND_WAIT_MS, connectFailure, defaultLaunchDeps, waitForBind } from './lib/daemonLaunch.js'@@ -2445,7 +2446,8 @@ switch (cmd) {void startServiceProcess(rest[0])breakcase '__run': // internal: the detached daemon child reads the durable SSO session — or runs without one- runCore(SCRIPT_PATH)+ // From the sources: cli.js and the lean bundle start it in coreProcess.ts without loading this file.+ startCoreProcess(SCRIPT_PATH)breakcase 'autonomous-device':runAutonomousDeviceCommand(rest, env.ADAPTER_DATA_DIR, daemonPort()).then(code => { process.exitCode = code }).catch(onError)diff --git a/cli/src/coreProcess.spec.ts b/cli/src/coreProcess.spec.tsnew file mode 100644index 000000000..23c6b077e--- /dev/null+++ b/cli/src/coreProcess.spec.ts@@ -0,0 +1,15 @@+import { describe, expect, it, vi } from 'vitest'++const calls = vi.hoisted(() => [] as string[])+vi.mock('./core/main.js', () => ({ runCore: vi.fn((script: string) => { calls.push(`runCore ${script}`) }) }))+vi.mock('./lib/childLocale.js', () => ({ ensureUtf8Locale: vi.fn(() => { calls.push('ensureUtf8Locale') }) }))+vi.mock('./lib/launchers.js', () => ({ ensureHnLauncher: vi.fn((script: string) => { calls.push(`ensureHnLauncher ${script}`); return false }) }))++const { startCoreProcess } = await import('./coreProcess.js')++describe('the core\'s process, however it is started', () => {+ it('does what cli.ts does first for every command, then runs the core for the CLI it names', () => {+ startCoreProcess('/home/me/.harness/cli/cli.js')+ expect(calls).toEqual(['ensureUtf8Locale', 'ensureHnLauncher /home/me/.harness/cli/cli.js', 'runCore /home/me/.harness/cli/cli.js'])+ })+})diff --git a/cli/src/coreProcess.ts b/cli/src/coreProcess.tsnew file mode 100644index 000000000..bfcddc44a--- /dev/null+++ b/cli/src/coreProcess.ts@@ -0,0 +1,22 @@+/**+ * The core's process (`__run`), however it is started: from cli.js (entry.ts), from the lean bundle cli.js+ * carries (leanCoreEntry.ts) or from the sources (cli.ts). One start for all three, so a core started from the+ * lean bundle, which never loads cli.ts, starts exactly as one started from cli.js does.+ *+ * Its own module so the lean bundle can start the core on the core's own code: started on the whole+ * cli.js, the core parsed every command of the CLI, every service's code and the master's+ * (docs/design/2026-10-06-core-boundary-next.md, "The target, and its test").+ */+import { runCore } from './core/main.js'+import { ensureUtf8Locale } from './lib/childLocale.js'+import { ensureHnLauncher } from './lib/launchers.js'++/** Run the core, [scriptPath] being the CLI's own script (cli.js, or src/cli.ts from the sources). */+export function startCoreProcess(scriptPath: string): void {+ // What cli.ts does first for every command: a `ps` or `git` the core runs must not get mangled output.+ ensureUtf8Locale()+ // On entry to the installed bundle, a daemon handoff's included: machines installed before hn shipped+ // get it from whichever core runs first after the update (lib/launchers.ts).+ ensureHnLauncher(scriptPath)+ runCore(scriptPath)+}diff --git a/cli/src/entry.ts b/cli/src/entry.tsindex 0099d3d14..82702a525 100644--- a/cli/src/entry.ts+++ b/cli/src/entry.ts@@ -8,8 +8,8 @@* to 160, so isolating the services cost more memory than everything else the daemon does. Here the* master and the services load only their own modules: esbuild, bundling without code splitting, turns* each dynamic import below into a module initialised the first time it is imported, so the code a- * process never imports is parsed but never run. Everything else, the core (`__run`) included, is the- * CLI as it always was.+ * process never imports is parsed but never run. The core (`__run`) starts as it does from the lean bundle+ * (coreProcess.ts), and everything else is the CLI as it always was.** Nothing heavy may be imported statically here: it would be evaluated by every process.*/@@ -24,6 +24,9 @@ if (command === '__harnessd') {process.exitCode = (await import('./masterProcess.js')).probeThisMaster()} else if (command === '__service') {await (await import('./serviceProcess.js')).startServiceProcess(name)+} else if (command === '__run') {+ // The core: started the one way it is started from the lean bundle too (coreProcess.ts), on cli.js.+ (await import('./coreProcess.js')).startCoreProcess(fileURLToPath(import.meta.url))} else {await import('./cli.js')}diff --git a/cli/src/harnessd/leanBundle.ts b/cli/src/harnessd/leanBundle.tsindex 9c8ed5a35..2210e57e8 100644--- a/cli/src/harnessd/leanBundle.ts+++ b/cli/src/harnessd/leanBundle.ts@@ -1,17 +1,19 @@/**- * The lean bundle a release's cli.js carries, written out for the master and the services to run from.+ * The lean bundle a release's cli.js carries, written out for the master, the core and the services to+ * run from.** Node parses the whole file a process is started on. Started on the 4.4 MB cli.js, harnessd's master* and each service paid about 45 MiB for that alone, at idle, before running a line of their own code- * (measured 2026-10-05). The build therefore bundles the master and the services a second time on their- * own, split into files so that each process parses only the ones its own code is in, and appends those- * files to cli.js as a comment, which Node only skims (scripts/lib/leanBlock.mjs). This reads them back- * and writes them where the master can start processes from them: `lean/<sha>/` in the data folder.+ * (measured 2026-10-05), and the core parsed the CLI's commands with it. The build therefore bundles the+ * master and the services a second time on their own, and the core apart from them, split into files so+ * that each process parses only the ones its own code is in, and appends those files to cli.js as a+ * comment, which Node only skims (scripts/lib/leanBlock.mjs). This reads them back and writes them where+ * the master can start processes from them: `lean/<sha>/` in the data folder.** Nothing here is needed for the daemon to run. A cli.js without the block (one built from the* sources, or a test's), a block that does not match its checksum, or a folder that cannot be written- * leaves every process running from cli.js, as before; and a service is started from cli.js whenever- * its master's lean files are gone or changed, or cli.js is no longer the bundle they came from+ * leaves every process running from cli.js, as before; and a service or the core is started from cli.js+ * whenever its master's lean files are gone or changed, or cli.js is no longer the bundle they came from* (./leanServices.ts).** Several masters can share one data folder (a second `harness start`, two builds on one computer), and@@ -25,12 +27,16 @@ import { lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, wrimport { uptime } from 'node:os'import { dirname, join } from 'node:path'import { brotliDecompressSync } from 'node:zlib'+import { sha256File } from './reexec.js'/** As scripts/lib/leanBlock.mjs writes it. Built in two pieces, so this file's own text never matches. */const MARKER = Buffer.from('/*@harness-' + 'lean:')const END = Buffer.from('*/')/** The file the master and the services start on (src/leanEntry.ts); the others are what it imports. */export const LEAN_ENTRY = 'harnessd.mjs'+/** The file the core starts on (src/leanCoreEntry.ts). It and the files it imports, named `core-*`, are+ * built apart from the master's and the services', so that neither loads code only the other uses. */+export const LEAN_CORE_ENTRY = 'harnessd-core.mjs'const FILE_NAME = /^[A-Za-z0-9_-][A-Za-z0-9_.-]*\.mjs$/const FOLDER = /^[0-9a-f]{16}$/const CLAIM = /^\.claim-(\d+)$/@@ -96,7 +102,8 @@ export function folderFingerprint(folder: string): string | null {if (!names.includes(LEAN_ENTRY)) return nullconst hash = createHash('sha256')try {- for (const name of names) hash.update(`${name}\0${sha256(readFileSync(join(folder, name)))}\n`)+ // A piece at a time, as cli.js is: before every process a master starts (./reexec.ts `sha256File`).+ for (const name of names) hash.update(`${name}\0${sha256File(join(folder, name))}\n`)} catch {return null}diff --git a/cli/src/harnessd/leanServices.spec.ts b/cli/src/harnessd/leanServices.spec.tsindex 95cc8766c..26d8e75b6 100644--- a/cli/src/harnessd/leanServices.spec.ts+++ b/cli/src/harnessd/leanServices.spec.ts@@ -1,9 +1,10 @@import { describe, expect, it } from 'vitest'-import { LEAN_EARLY_DEATHS, leanServices, type LeanServicesDeps } from './leanServices.js'+import { CORE, LEAN_EARLY_DEATHS, leanServices, type LeanServicesDeps } from './leanServices.js'import type { CoreHandle } from './supervisor.js'const CLI = '/cli/cli.js'const LEAN = '/data/lean/aaaa/harnessd.mjs'+const LEAN_CORE = '/data/lean/aaaa/harnessd-core.mjs'function fakeProcess() {const messages: Array<(message: unknown) => void> = []@@ -35,7 +36,7 @@ function make(over: Partial<LeanServicesDeps> = {}) {return { lean, logs, world }}-describe('the file a service starts from', () => {+describe('the file a service, or the core, starts from', () => {it('is the lean bundle while its files are the ones the master started with, and cli.js is the bundle they came from', () => {const { lean, logs } = make()expect(lean.scriptFor('search')).toBe(LEAN)@@ -56,8 +57,8 @@ describe('the file a service starts from', () => {world.fingerprint = 'changed'expect(lean.scriptFor('search')).toBe(CLI)expect(logs).toEqual([- `[harnessd] the lean bundle ${LEAN} cannot be used (it is gone): services start from ${CLI}`,- `[harnessd] the lean bundle ${LEAN} cannot be used (its files changed): services start from ${CLI}`,+ `[harnessd] the lean bundle ${LEAN} cannot be used (it is gone): the core and the services start from ${CLI}`,+ `[harnessd] the lean bundle ${LEAN} cannot be used (its files changed): the core and the services start from ${CLI}`,])world.fingerprint = 'f'expect(lean.scriptFor('search')).toBe(LEAN)@@ -72,7 +73,7 @@ describe('the file a service starts from', () => {const { lean, logs, world } = make()world.same = falseexpect(lean.scriptFor('search')).toBe(CLI)- expect(logs).toEqual([`[harnessd] the lean bundle ${LEAN} cannot be used (${CLI} is no longer the bundle it came from): services start from ${CLI}`])+ expect(logs).toEqual([`[harnessd] the lean bundle ${LEAN} cannot be used (${CLI} is no longer the bundle it came from): the core and the services start from ${CLI}`])})it('checks only that the entry is there when it has no fingerprint to check against', () => {@@ -97,6 +98,20 @@ describe('the file a service starts from', () => {expect(lean.scriptFor('viewers')).toBe(LEAN)})+ it('is cli.js for the core that died twice running from the lean bundle before it beat, counted apart from any service', () => {+ const { lean, logs } = make()+ for (let death = 1; death <= LEAN_EARLY_DEATHS; death++) {+ // Its own entry, beside the services'.+ expect(lean.scriptFor(CORE)).toBe(LEAN_CORE)+ const child = fakeProcess()+ lean.started(CORE, LEAN_CORE, child.handle)+ child.exit(1)+ }+ expect(logs).toEqual([`[harnessd] the core died ${LEAN_EARLY_DEATHS} times from the lean bundle before it beat: it starts from ${CLI} from now on`])+ expect(lean.scriptFor(CORE)).toBe(CLI)+ expect(lean.scriptFor('search')).toBe(LEAN)+ })+it('counts only deaths in a row before a beat, and never the master\'s own stop', () => {const { lean } = make()const early = fakeProcess()diff --git a/cli/src/harnessd/leanServices.ts b/cli/src/harnessd/leanServices.tsindex 18ca3ec69..248bf44c4 100644--- a/cli/src/harnessd/leanServices.ts+++ b/cli/src/harnessd/leanServices.ts@@ -1,6 +1,6 @@/**- * Which file a service's process is started from: the lean bundle (./leanBundle.ts), only while it is- * purely an optimisation, and cli.js otherwise.+ * Which file a service's process, or the core's, is started from: the lean bundle (./leanBundle.ts), only+ * while it is purely an optimisation, and cli.js otherwise.** The lean bundle is code the master wrote into the data folder as it started, and a master lives for* weeks. Started from it unconditionally, a service failed on every restart once the folder went (a@@ -8,22 +8,36 @@* installed a new cli.js that this master did not re-execute on (a Node without `process.execve`, or a* re-execution it kept back), every service ran the old lean code against the new core for the rest of* the master's life. So before each start: the lean bundle's files must still be the ones this master- * was started with, and cli.js must still be the bundle they came from; and a service that dies twice+ * was started with, and cli.js must still be the bundle they came from; and a process that dies twice* running from it before it ever beats starts from cli.js from then on. cli.js is always there to fall- * back on: it is what the core runs.+ * back on: it is what the CLI runs.+ *+ * The core runs from it by the same rules, under the name `CORE` (./master.ts), from its own entry beside+ * the services' (./leanBundle.ts `LEAN_CORE_ENTRY`): parsing the whole cli.js cost it the CLI's commands,+ * every service's code and the master's. A core started from cli.js after an+ * update its master did not re-execute on runs the new build, never the old lean code. Whether an update+ * is kept is the supervisor's to judge, as before, whichever file the core it judges started from.*/-import { dirname } from 'node:path'+import { dirname, join } from 'node:path'+import { LEAN_CORE_ENTRY } from './leanBundle.js'import { isCoreMessage } from './protocol.js'import type { CoreHandle } from './supervisor.js'-/** This many deaths in a row before a first heartbeat, started from the lean bundle, and a service is- * started from cli.js for the rest of this master's life. */+/** This many deaths in a row before a first heartbeat, started from the lean bundle, and a service (or the+ * core) is started from cli.js for the rest of this master's life. */export const LEAN_EARLY_DEATHS = 2+/** The name the core is chosen for under, beside the services' own. */+export const CORE = 'core'++/** How the log names what is started: the core, or a service. */+const named = (name: string): string => (name === CORE ? 'the core' : `service ${name}`)+export interface LeanServicesDeps {/** cli.js (or the sources): what the core runs. */scriptPath: string- /** The lean bundle's entry, when this master has one. */+ /** The lean bundle's entry, when this master has one: the master's and the services'. The core's is+ * beside it. */leanPath?: string/** What the lean bundle's folder should fingerprint to (./leanBundle.ts `leanFingerprint`); without* it, only that the entry is there is checked. */@@ -37,7 +51,7 @@ export interface LeanServicesDeps {}export interface LeanServices {- /** The file to start service [name] from now. */+ /** The file to start service [name] (or `CORE`) from now. */scriptFor(name: string): string/** Watch a process started from [script] for a death before its first heartbeat. */started(name: string, script: string, handle: CoreHandle): void@@ -59,9 +73,9 @@ export function leanServices(deps: LeanServicesDeps): LeanServices {if (!leanPath || leanPath === scriptPath) return scriptPathif ((earlyDeaths.get(name) ?? 0) >= LEAN_EARLY_DEATHS) return scriptPathconst why = unusable(leanPath)- if (why === null) { said = null; return leanPath }+ if (why === null) { said = null; return name === CORE ? join(dirname(leanPath), LEAN_CORE_ENTRY) : leanPath }// Said once per reason, not on every restart.- if (said !== why) deps.log(`[harnessd] the lean bundle ${leanPath} cannot be used (${why}): services start from ${scriptPath}`)+ if (said !== why) deps.log(`[harnessd] the lean bundle ${leanPath} cannot be used (${why}): the core and the services start from ${scriptPath}`)said = whyreturn scriptPath},@@ -79,7 +93,7 @@ export function leanServices(deps: LeanServicesDeps): LeanServices {const deaths = (earlyDeaths.get(name) ?? 0) + 1earlyDeaths.set(name, deaths)if (deaths === LEAN_EARLY_DEATHS) {- deps.log(`[harnessd] service ${name} died ${deaths} times from the lean bundle before it beat: it starts from ${scriptPath} from now on`)+ deps.log(`[harnessd] ${named(name)} died ${deaths} times from the lean bundle before it beat: it starts from ${scriptPath} from now on`)}})},diff --git a/cli/src/harnessd/master.spec.ts b/cli/src/harnessd/master.spec.tsindex 3771fe89e..2a2e07596 100644--- a/cli/src/harnessd/master.spec.ts+++ b/cli/src/harnessd/master.spec.ts@@ -9,9 +9,9 @@ import {readStatusFile, runMaster, supervisorOptions, trimLogEvery, writeStatusFile, type MasterStatusFile,} from './master.js'import { ignoreLogWriteErrors } from '../lib/log.js'-import { folderFingerprint } from './leanBundle.js'+import { LEAN_CORE_ENTRY, folderFingerprint } from './leanBundle.js'import { PROBE_ANSWER, RESUME_ENV, decodeResume, encodeResume, fingerprint, readMarker, writeMarker } from './reexec.js'-import { HARNESSD_PROTOCOL } from './protocol.js'+import { HARNESSD_PROTOCOL, LEAN_CORE_SCRIPT_ENV } from './protocol.js'import { DEFAULT_SUPERVISOR_OPTIONS, type ResumeState } from './supervisor.js'describe('supervisorOptions', () => {@@ -529,14 +529,15 @@ describe('runMaster', { timeout: 60_000 }, () => {} finally { log.mockRestore() }})- it('starts the services from the lean bundle when given one, and the core from the CLI entry', async () => {- // The lean bundle cli.js carries (./leanBundle.ts): each service parses its own code, not the CLI's.+ it('starts the services and the core from the lean bundle when given one, telling the core which CLI it runs for', async () => {+ // The lean bundle cli.js carries (./leanBundle.ts): each service, and the core, parses its own code, not+ // the CLI's. A core started from it is told the cli.js it came from, its CLI to everything it hands on.const pidFile = join(dir, 'adapter.pid')const seen = join(dir, 'seen')const body = (who: string) => `const { appendFileSync } = require('node:fs')const role = process.argv[2] === '__service' ? 'service:' + process.argv[3] : process.argv[2]- appendFileSync(${JSON.stringify(seen)}, JSON.stringify({ role, from: ${JSON.stringify(who)} }) + '\\n')+ appendFileSync(${JSON.stringify(seen)}, JSON.stringify({ role, from: ${JSON.stringify(who)}, cli: process.env.${LEAN_CORE_SCRIPT_ENV} ?? null }) + '\\n')if (role === '__run') { process.send({ type: 'harnessd:bound', protocol: 2, port: 1 }); process.send({ type: 'harnessd:ready' }) }setInterval(() => process.send({ type: 'harnessd:heartbeat', rssBytes: 1, heapUsedBytes: 1, loopDelayMs: 0 }), 50)process.on('SIGTERM', () => process.exit(0))@@ -545,6 +546,8 @@ describe('runMaster', { timeout: 60_000 }, () => {const lean = join(dir, 'lean.cjs')writeFileSync(cli, body('cli'))writeFileSync(lean, body('lean'))+ // The core's own entry, beside the services'.+ writeFileSync(join(dir, LEAN_CORE_ENTRY), body('lean core').replace("require('node:fs')", "await import('node:fs')"))const lines: string[] = []const log = vi.spyOn(console, 'log').mockImplementation((line: string) => { lines.push(line) })const exits: number[] = []@@ -558,13 +561,49 @@ describe('runMaster', { timeout: 60_000 }, () => {})const roles = (): Array<Record<string, string>> => existsSync(seen) ? readFileSync(seen, 'utf8').trim().split('\n').map((line) => JSON.parse(line)) : []await until('the core and the service', () => roles().length >= 2)- expect(roles().sort((a, b) => a.role.localeCompare(b.role))).toEqual([{ role: '__run', from: 'cli' }, { role: 'service:search', from: 'lean' }])+ expect(roles().sort((a, b) => a.role.localeCompare(b.role))).toEqual([{ role: '__run', from: 'lean core', cli }, { role: 'service:search', from: 'lean', cli: null }])expect(lines.some((line) => line.endsWith(`[harnessd] services run from ${lean}`))).toBe(true)signals.get('SIGTERM')!()await until('the master to finish', () => exits.length > 0)} finally { log.mockRestore() }})+ it('starts the core from cli.js once it has died twice from the lean bundle before it beat, and judges it the same', async () => {+ // A lean core that cannot start costs two quick restarts, never the daemon (./leanServices.ts).+ const pidFile = join(dir, 'adapter.pid')+ const seen = join(dir, 'seen')+ const cli = join(dir, 'cli.cjs')+ const lean = join(dir, 'lean.cjs')+ writeFileSync(cli, `+ require('node:fs').appendFileSync(${JSON.stringify(seen)}, 'cli\\n')+ process.send({ type: 'harnessd:bound', protocol: 2, port: 1 }); process.send({ type: 'harnessd:ready' })+ setInterval(() => process.send({ type: 'harnessd:heartbeat', rssBytes: 1, heapUsedBytes: 1, loopDelayMs: 0 }), 50)+ process.on('SIGTERM', () => process.exit(0))+ `)+ // The services' entry is fine; the core's, beside it, dies as it starts.+ writeFileSync(lean, '')+ writeFileSync(join(dir, LEAN_CORE_ENTRY), `(await import('node:fs')).appendFileSync(${JSON.stringify(seen)}, 'lean\\n'); process.exit(1)`)+ const lines: string[] = []+ const log = vi.spyOn(console, 'log').mockImplementation((line: string) => { lines.push(line) })+ const exits: number[] = []+ const signals = new Map<string, () => void>()+ try {+ const supervisor = runMaster({+ nodePath: process.execPath, execArgv: [], scriptPath: cli, serviceScriptPath: lean, pidFile,+ restoreUpdate: () => {}, confirmUpdate: () => {},+ env: { ...process.env, HARNESSD_SERVICES: 'none', HARNESSD_INITIAL_BACKOFF_MS: '0' },+ exit: (code) => exits.push(code), onSignal: (signal, listener) => signals.set(signal, listener),+ })+ await until('a core from cli.js, running', () => supervisor.status().state === 'running')+ expect(readFileSync(seen, 'utf8').trim().split('\n')).toEqual(['lean', 'lean', 'cli'])+ expect(lines.some((line) => line.endsWith(`[harnessd] the core died 2 times from the lean bundle before it beat: it starts from ${cli} from now on`))).toBe(true)+ // Two crashes, as any two: not yet the three in a row that start it in safe mode.+ expect(supervisor.status().safeMode).toBeNull()+ signals.get('SIGTERM')!()+ await until('the master to finish', () => exits.length > 0)+ } finally { log.mockRestore() }+ })+it('starts a service from cli.js once its lean bundle is gone, or cli.js is no longer the bundle it came from', async () => {// A master lives for weeks: a lean folder gone from under it failed every restart of every service// with MODULE_NOT_FOUND, and after an update it did not re-execute on, the services ran the old lean@@ -614,14 +653,14 @@ describe('runMaster', { timeout: 60_000 }, () => {expect(services()[0]!.from).toBe('lean')rmSync(leanDir, { recursive: true })expect(await restart()).toBe('cli')- expect(lines.some((line) => line.endsWith(`[harnessd] the lean bundle ${lean} cannot be used (it is gone): services start from ${cli}`))).toBe(true)+ expect(lines.some((line) => line.endsWith(`[harnessd] the lean bundle ${lean} cannot be used (it is gone): the core and the services start from ${cli}`))).toBe(true)// Back as it was, and then cli.js replaced by an update this master runs no code of.mkdirSync(leanDir)writeFileSync(lean, body('lean').replace("require('node:fs')", "await import('node:fs')"))expect(await restart()).toBe('lean')writeFileSync(cli, `${body('cli')}\n// the next release\n`)expect(await restart()).toBe('cli')- expect(lines.some((line) => line.endsWith(`[harnessd] the lean bundle ${lean} cannot be used (${cli} is no longer the bundle it came from): services start from ${cli}`))).toBe(true)+ expect(lines.some((line) => line.endsWith(`[harnessd] the lean bundle ${lean} cannot be used (${cli} is no longer the bundle it came from): the core and the services start from ${cli}`))).toBe(true)signals.get('SIGTERM')!()await until('the master to finish', () => exits.length > 0)} finally { log.mockRestore() }diff --git a/cli/src/harnessd/master.ts b/cli/src/harnessd/master.tsindex 65879a574..a44f699eb 100644--- a/cli/src/harnessd/master.ts+++ b/cli/src/harnessd/master.ts@@ -9,10 +9,10 @@ import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from 'nodimport { performance } from 'node:perf_hooks'import { ignoreLogWriteErrors, trimLogFile, ts } from '../lib/log.js'import { folderFingerprint } from './leanBundle.js'-import { leanServices } from './leanServices.js'+import { CORE, leanServices } from './leanServices.js'import { platformFromEnv, type PlatformName } from './platform.js'import { baseNode, namedNode } from './processName.js'-import type { MasterMessage } from './protocol.js'+import { LEAN_CORE_SCRIPT_ENV, type MasterMessage } from './protocol.js'import {PROBE_ANSWER, RESUME_ENV, createReexec, decodeResume, fingerprint, readMarker, recoverFailedReexec, removeMarker, runProbe, writeMarker,} from './reexec.js'@@ -31,15 +31,15 @@ export interface MasterConfig {/** The managed runtime's folder: a node inside it runs each process under its own name* (./processName.ts); any other node runs as `node`. */runtimeDir?: string- /** The CLI entry (`cli.js`, or `src/cli.ts` under tsx): what the core runs, and what an update- * replaces on disk. */+ /** The CLI entry (`cli.js`, or `src/cli.ts` under tsx): what the core and the services fall back on,+ * and what an update replaces on disk. */scriptPath: string- /** What the services run instead, when it is not the CLI entry: the lean bundle the entry carries- * (./leanBundle.ts), so each service parses its own code and not the whole CLI's. Only ever an- * optimisation: a service starts from `scriptPath` whenever it cannot be used (./leanServices.ts). */+ /** What the services and the core run instead, when it is not the CLI entry: the lean bundle the entry+ * carries (./leanBundle.ts), so each parses its own code and not the whole CLI's. Only ever an+ * optimisation: each starts from `scriptPath` whenever it cannot be used (./leanServices.ts). */serviceScriptPath?: string/** What the lean bundle's folder fingerprints to as this master starts (./leanBundle.ts- * `leanFingerprint`): checked before every service is started from it. */+ * `leanFingerprint`): checked before every service and every core is started from it. */leanFingerprint?: string/** The sha256 of the bundle this master's code came from, when the master was not started on* `scriptPath` itself but on the lean bundle read from it: the bundle it runs is the one it was read@@ -332,11 +332,23 @@ export function runMaster(config: MasterConfig): Supervisor {log,}) : nullsupervisor = new Supervisor({- spawnCore: (extra) => coreHandle(spawn(named('harnessd-core'), [...execArgv, config.scriptPath, '__run'], {- // Told which services this master runs, so it routes to exactly those and runs the rest itself.- env: { ...env, ...extra, HARNESSD_SERVICE_TOKEN: token, ...serviceProcessesEnv(specs) },- stdio: ['ignore', 'inherit', 'inherit', 'ipc'],- })),+ spawnCore: (extra) => {+ // From the lean bundle on the core's own code when it can be, as a service is, by the same rules+ // (./leanServices.ts), and from cli.js otherwise. The supervisor judges the core it is given the+ // same either way: an update's first core, lean or not, is on probation as before.+ const script = lean.scriptFor(CORE)+ const handle = coreHandle(spawn(named('harnessd-core'), [...execArgv, script, '__run'], {+ // Told which services this master runs, so it routes to exactly those and runs the rest itself;+ // and, from the lean bundle, which cli.js is its CLI (leanCoreEntry.ts).+ env: {+ ...env, ...extra, HARNESSD_SERVICE_TOKEN: token, ...serviceProcessesEnv(specs),+ ...(script === config.scriptPath ? {} : { [LEAN_CORE_SCRIPT_ENV]: config.scriptPath }),+ },+ stdio: ['ignore', 'inherit', 'inherit', 'ipc'],+ }))+ lean.started(CORE, script, handle)+ return handle+ },now: () => performance.now(),wallClock: () => Date.now(),writeStatus: (status) => { if (config.statusFile) writeStatusFile(config.statusFile, { ...status, masterPid: process.pid, ...(platform ? { platform } : {}) }) },diff --git a/cli/src/harnessd/protocol.ts b/cli/src/harnessd/protocol.tsindex 87ea4e896..133a4d9fc 100644--- a/cli/src/harnessd/protocol.ts+++ b/cli/src/harnessd/protocol.ts@@ -24,6 +24,14 @@ export const PROBE_ANSWER = 'harnessd-probe ok'/** How long a probe may take: the updater gives its canary as long. */export const PROBE_TIMEOUT_MS = 15_000+/**+ * Handed by a master to a core it starts from the lean bundle (./leanBundle.ts): the cli.js that bundle+ * was read from. The core's own file is then the lean bundle's, which runs no command but the daemon's,+ * and everything the core hands on (the hooks it installs, the CLI it writes into agents' panes, a+ * successor it starts on an update) must name the CLI (leanCoreEntry.ts).+ */+export const LEAN_CORE_SCRIPT_ENV = 'HARNESSD_CORE_SCRIPT'+/** The exit code a core uses to be restarted at once on the bundle now on disk (a staged update). */export const CORE_EXIT_UPDATE = 75diff --git a/cli/src/harnessd/reexec.spec.ts b/cli/src/harnessd/reexec.spec.tsindex 9e957f7db..80f9a855a 100644--- a/cli/src/harnessd/reexec.spec.ts+++ b/cli/src/harnessd/reexec.spec.ts@@ -1,3 +1,4 @@+import { createHash, randomBytes } from 'node:crypto'import { EventEmitter } from 'node:events'import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'@@ -6,7 +7,7 @@ import type { ChildProcess } from 'node:child_process'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import {PROBE_ANSWER, PROBE_COMMAND, PROBE_TIMEOUT_MS, REEXEC_LIMIT, RESUME_ENV, createReexec, decodeResume, encodeResume, fingerprint,- readMarker, recoverFailedReexec, removeMarker, runProbe, writeMarker, type ProbeResult, type ReexecDeps,+ readMarker, recoverFailedReexec, removeMarker, runProbe, sha256File, writeMarker, type ProbeResult, type ReexecDeps,} from './reexec.js'import type { ReexecOutcome, ResumeState } from './supervisor.js'@@ -23,11 +24,21 @@ describe('which bundle', () => {const file = join(dir, 'cli.js')writeFileSync(file, 'one')const one = fingerprint(file)- expect(one).toMatch(/^[0-9a-f]{64}$/)+ expect(one).toBe(createHash('sha256').update('one').digest('hex'))writeFileSync(file, 'two')expect(fingerprint(file)).not.toBe(one)expect(fingerprint(join(dir, 'none.js'))).toBeNull()- expect(fingerprint('x', () => Buffer.from('one'))).toBe(one)+ expect(fingerprint(dir)).toBeNull()+ })++ it('reads it a piece at a time, to the same sha256 as all its bytes at once, empty or not', () => {+ // A bundle is megabytes: more than one piece, and a last piece that is not whole.+ const file = join(dir, 'cli.js')+ const bytes = randomBytes(3 * 64 * 1024 + 123)+ writeFileSync(file, bytes)+ expect(sha256File(file)).toBe(createHash('sha256').update(bytes).digest('hex'))+ writeFileSync(file, '')+ expect(sha256File(file)).toBe(createHash('sha256').update('').digest('hex'))})})diff --git a/cli/src/harnessd/reexec.ts b/cli/src/harnessd/reexec.tsindex 06ef5c126..3cbf27417 100644--- a/cli/src/harnessd/reexec.ts+++ b/cli/src/harnessd/reexec.ts@@ -26,7 +26,7 @@*/import { spawn, type ChildProcess } from 'node:child_process'import { createHash } from 'node:crypto'-import { readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { closeSync, openSync, readFileSync, readSync, renameSync, rmSync, writeFileSync } from 'node:fs'import { PROBE_ANSWER, PROBE_COMMAND, PROBE_TIMEOUT_MS } from './protocol.js'import type { ExitReason, ReexecOutcome, ResumeState } from './supervisor.js'@@ -42,9 +42,30 @@ export { PROBE_ANSWER, PROBE_COMMAND, PROBE_TIMEOUT_MS } from './protocol.js'*/export const REEXEC_LIMIT = 3+/** How much of a file `sha256File` holds at a time. */+const HASH_PIECE_BYTES = 64 * 1024++/**+ * The sha256 of the file at [path], read a piece at a time. A master hashes cli.js, 6.5 MB, and every+ * file of its lean bundle before each process it starts (./leanServices.ts), eight of them as it boots:+ * read whole, each read was a buffer the size of the file, and at idle a master still held 35 to 45 MiB+ * of them, which a collection would have freed but none came (measured 2026-10-06).+ */+export function sha256File(path: string): string {+ const hash = createHash('sha256')+ const fd = openSync(path, 'r')+ try {+ const piece = Buffer.allocUnsafe(HASH_PIECE_BYTES)+ for (let read = readSync(fd, piece); read > 0; read = readSync(fd, piece)) hash.update(piece.subarray(0, read))+ } finally {+ closeSync(fd)+ }+ return hash.digest('hex')+}+/** A file's sha256: which bundle a master runs, or which is on disk; null when it cannot be read. */-export function fingerprint(path: string, read: (path: string) => Buffer = readFileSync): string | null {- try { return createHash('sha256').update(read(path)).digest('hex') } catch { return null }+export function fingerprint(path: string): string | null {+ try { return sha256File(path) } catch { return null }}const EXIT_REASONS: readonly ExitReason[] = ['crashed', 'hung', 'did-not-bind', 'not-ready', 'memory', 'update', 'stopped']diff --git a/cli/src/leanCoreEntry.ts b/cli/src/leanCoreEntry.tsnew file mode 100644index 000000000..d583efbdb--- /dev/null+++ b/cli/src/leanCoreEntry.ts@@ -0,0 +1,34 @@+/**+ * The core's entry in the lean bundle (harnessd/leanBundle.ts `LEAN_CORE_ENTRY`): the core's own code,+ * and nothing else.+ *+ * Started on the whole cli.js, the core parsed every command of the CLI, every service's code and the+ * master's. Built apart from leanEntry.ts, and not as one more of its entries, because a build splits+ * the code its entries share into files they all load, each holding what any of them uses: built+ * together, the master and every service loaded the parts of the files they share that only the core+ * uses, Node's http and net among them, and paid about 5 MiB each for it, which the core's own saving+ * did not cover (measured 2026-10-06). Built apart, the master and the services load exactly what they+ * did before, and the core loads only its own files (`core-*`).+ *+ * Started from here only by a master that read this bundle out of cli.js and says which+ * (harnessd/master.ts). To everything the core hands on, its script is that cli.js, never this file: the+ * hooks it installs find notify.mjs beside it, the CLI it writes into agents' panes runs commands this+ * file does not have (lib/daemonCommand.ts reads it as process.argv[1]), and a successor it starts on an+ * update runs it. Without it this core cannot know the CLI, and dies before it beats: its master then+ * starts it from cli.js (harnessd/leanServices.ts).+ */+import { LEAN_CORE_SCRIPT_ENV } from './harnessd/protocol.js'++const [, , command] = process.argv+const cli = process.env[LEAN_CORE_SCRIPT_ENV]+if (command !== '__run') {+ console.error(`[harnessd] the lean bundle's core entry runs the core (__run); ${command ?? 'nothing'} is the CLI's (cli.js)`)+ process.exit(2)+} else if (!cli) {+ console.error('[harnessd] the lean bundle runs a core only for the cli.js its master read it from, which hands over its path')+ process.exit(2)+} else {+ delete process.env[LEAN_CORE_SCRIPT_ENV]+ process.argv[1] = cli+ ;(await import('./coreProcess.js')).startCoreProcess(cli)+}diff --git a/cli/src/leanEntry.spec.ts b/cli/src/leanEntry.spec.tsindex e29e91268..9c3b2d526 100644--- a/cli/src/leanEntry.spec.ts+++ b/cli/src/leanEntry.spec.ts@@ -1,24 +1,24 @@/*** The lean bundle a release carries, as the build writes it: what each process of harnessd loads from* it. A process parses every file it imports, so the memory each costs is the code it imports, and- * that is what this holds: the master none of the services' code, a service none of another's, and the- * master, search and workspaces no zod (`config/env.ts` and `lib/registry.ts` once brought it to every+ * that is what this holds: the master none of the services' code, a service none of another's, the core+ * none of the CLI's commands, and the master, search and workspaces no zod (`config/env.ts` and `lib/registry.ts` once brought it to every* one of them, 8 to 19 MiB each, measured 2026-10-05).*/import { execFileSync, spawnSync } from 'node:child_process'import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'-import { join } from 'node:path'+import { dirname, join } from 'node:path'import { fileURLToPath } from 'node:url'import { afterAll, beforeAll, describe, expect, it } from 'vitest'-import { LEAN_ENTRY, readLeanBundle, writeLeanBundle } from './harnessd/leanBundle.js'+import { LEAN_CORE_ENTRY, LEAN_ENTRY, readLeanBundle, writeLeanBundle } from './harnessd/leanBundle.js'import { PROBE_ANSWER } from './harnessd/reexec.js'import { KNOWN_SERVICES, SERVICE_HOSTS } from './harnessd/services.js'const CLI_ROOT = fileURLToPath(new URL('..', import.meta.url))// The updater, beside the services the core knows: the master runs it (harnessd/services.ts `UPDATER_HOST`).-const ROLES = ['master', ...KNOWN_SERVICES, 'updater']-const RUNNER: Record<string, string> = { master: 'masterProcess' }+const ROLES = ['master', 'core', ...KNOWN_SERVICES, 'updater']+const RUNNER: Record<string, string> = { master: 'masterProcess', core: 'core-coreProcess' }for (const name of [...KNOWN_SERVICES, 'updater']) RUNNER[name] = `${name}Process`describe('the lean bundle a release carries', () => {@@ -39,7 +39,9 @@ describe('the lean bundle a release carries', () => {function loads(role: string): Set<string> {const runner = [...files.keys()].find((name) => name.startsWith(`${RUNNER[role]}-`))expect(runner, `${role}'s own file`).toBeDefined()- const roots = role === 'master' ? [LEAN_ENTRY, runner!] : [LEAN_ENTRY, [...files.keys()].find((name) => name.startsWith('serviceProcess-'))!, runner!]+ const roots = role === 'core' ? [LEAN_CORE_ENTRY, runner!]+ : role === 'master' ? [LEAN_ENTRY, runner!]+ : [LEAN_ENTRY, [...files.keys()].find((name) => name.startsWith('serviceProcess-'))!, runner!]const seen = new Set<string>()const visit = (name: string): void => {if (seen.has(name)) return@@ -52,13 +54,52 @@ describe('the lean bundle a release carries', () => {const runnerOf = (name: string): string | undefined => Object.entries(RUNNER).find(([, runner]) => name.startsWith(`${runner}-`))?.[0]const hasZod = (names: Set<string>): boolean => [...names].some((name) => files.get(name)!.includes('$ZodType'))- it('is files of their own for the master and each service, the code it runs and no other role\'s', () => {+ it('is files of their own for the master, the core and each service, the code it runs and no other role\'s', () => {for (const role of ROLES) {const others = [...loads(role)].map(runnerOf).filter((owner) => owner && owner !== role)expect(others, `${role} loads another's code`).toEqual([])}})+ it('builds the core apart: it loads none of the master\'s and the services\' files, and they none of its', () => {+ // Built together, the files they shared held what the core uses too, and the master and every service+ // loaded it (leanCoreEntry.ts).+ const isCores = (name: string): boolean => name === LEAN_CORE_ENTRY || name.startsWith('core-')+ for (const role of ROLES) {+ const loaded = [...loads(role)]+ expect(loaded.filter((name) => isCores(name) !== (role === 'core')), role).toEqual([])+ }+ })++ it('gives the core its own code and none of the CLI\'s commands, which parsing cli.js cost it', () => {+ const core = loads('core')+ const text = [...core].map((name) => files.get(name)!).join('\n')+ // The core's own (core/main.ts), and not the CLI's: its usage text, written only in cli.ts.+ expect(text).toContain('[fatal-guard] uncaughtException')+ expect(text).not.toContain('sign in with Google in your browser, without asking')+ // Smaller than the whole bundle it used to parse, by the CLI's commands and the other processes' code.+ const whole = [...files.values()].reduce((sum, code) => sum + code.length, 0)+ expect([...core].reduce((sum, name) => sum + files.get(name)!.length, 0)).toBeLessThan(whole)+ })++ it('runs a core only from the core\'s entry, only for the cli.js its master read it from, and says so otherwise', () => {+ const run = (file: string, command: string) => spawnSync(process.execPath, [join(dirname(entry), file), command], {+ env: { PATH: process.env.PATH, HOME: join(scratch, 'home'), ADAPTER_DATA_DIR: join(scratch, 'data') }, encoding: 'utf8', timeout: 30_000,+ })+ const core = run(LEAN_CORE_ENTRY, '__run')+ expect(core.status).toBe(2)+ expect(core.stderr).toContain('the lean bundle runs a core only for the cli.js its master read it from')+ const other = run(LEAN_CORE_ENTRY, '__harnessd')+ expect(other.status).toBe(2)+ expect(other.stderr).toContain('__harnessd is the CLI\'s (cli.js)')+ const nothing = run(LEAN_CORE_ENTRY, '')+ expect(nothing.status).toBe(2)+ // The master's and the services' entry has no core to run.+ const services = run(LEAN_ENTRY, '__run')+ expect(services.status).toBe(2)+ expect(services.stderr).toContain('__run is the CLI\'s (cli.js)')+ })+it('brings no zod to the master, search, the updater or the edge host', () => {expect(hasZod(new Set(files.keys())), 'the bundle still holds zod, for the services whose own code uses it').toBe(true)// The edge host's services share one process: zod in any of them would be in all of them.@@ -79,11 +120,25 @@ describe('the lean bundle a release carries', () => {expect(bad.status).toBe(1)expect(bad.stderr).toContain(`${search} does not load`)expect(bad.stderr).toContain('a broken service')+ const core = [...files.keys()].find((name) => name.startsWith('core-coreProcess-'))!+ writeFileSync(broken, `console.log("cli")\n${leanBlock({ ...Object.fromEntries(files), [core]: 'throw new Error("a broken core")' })}`)+ expect(check(broken).stderr).toContain(`${core} does not load`)+ writeFileSync(broken, `console.log("cli")\n${leanBlock({ ...Object.fromEntries(files), [LEAN_CORE_ENTRY]: 'throw new Error("a broken entry")' })}`)+ expect(check(broken).stderr).toContain('its core\'s entry does not load')+ writeFileSync(broken, `console.log("cli")\n${leanBlock({ ...Object.fromEntries(files), [LEAN_CORE_ENTRY]: 'process.exit(0)' })}`)+ expect(check(broken).stderr).toContain('its core\'s entry ran a core no master started')+ const { [core]: _gone, ...coreless } = Object.fromEntries(files)+ writeFileSync(broken, `console.log("cli")\n${leanBlock(coreless)}`)+ expect(check(broken).stderr).toContain('missing the master\'s, the services\' or the core\'s module')+ const { [LEAN_CORE_ENTRY]: _entry, ...entryless } = Object.fromEntries(files)+ writeFileSync(broken, `console.log("cli")\n${leanBlock(entryless)}`)+ expect(check(broken).stderr).toContain('missing the master\'s, the services\' or the core\'s module')writeFileSync(broken, `console.log("cli")\n${leanBlock({ ...Object.fromEntries(files), [LEAN_ENTRY]: 'process.exit(5)' })}`)expect(check(broken).stderr).toContain('its master does not answer its probe')writeFileSync(broken, 'console.log("no lean bundle")\n')expect(check(broken).stderr).toContain('carries no lean bundle')- }, 120_000)+ // Eight checks, most importing every process's module in a Node of its own, the core's among them.+ }, 300_000)it('starts as written out: its master answers the probe a re-executing master asks', () => {const run = spawnSync(process.execPath, [entry, '__harnessd-probe'], {diff --git a/cli/src/leanEntry.ts b/cli/src/leanEntry.tsindex 20a89c114..d48fc9918 100644--- a/cli/src/leanEntry.ts+++ b/cli/src/leanEntry.ts@@ -7,8 +7,8 @@* a file of its own with what only it uses, so a process loads this file, its own and the shared ones it* imports: the master never the services' code, a service never the master's nor another service's* (leanEntry.spec.ts holds it to that). A master started on cli.js re-executes on this file- * (masterProcess.ts `startMasterFromBundle`) and starts the services from it. The core and the CLI- * always run from cli.js.+ * (masterProcess.ts `startMasterFromBundle`) and starts the services from it. The core has an entry of+ * its own, built apart (leanCoreEntry.ts), and the CLI always runs from cli.js.*/import { fileURLToPath } from 'node:url'diff --git a/cli/src/lib/hooks.spec.ts b/cli/src/lib/hooks.spec.tsindex b1a5b9736..2e2288431 100644--- a/cli/src/lib/hooks.spec.ts+++ b/cli/src/lib/hooks.spec.ts@@ -40,6 +40,23 @@ describe('Codex hook installation', () => {vi.unstubAllEnvs()})+ it('runs the notify.mjs beside the CLI a core started from the lean bundle runs for, never one beside its own file', async () => {+ // A core started from the lean bundle in the data folder: its own file has no notify.mjs beside it,+ // and its script (process.argv[1], leanEntry.ts) is the cli.js it was read from.+ const cliDir = mkdtempSync(join(tmpdir(), 'adapter-cli-dir-'))+ writeFileSync(join(cliDir, 'notify.mjs'), '')+ const script = process.argv[1]+ process.argv[1] = join(cliDir, 'cli.js')+ try {+ const { installCodexHooks } = await loadHooks()+ installCodexHooks(19473)+ expect(readFileSync(join(codexHome, 'hooks.json'), 'utf-8')).toContain(join(cliDir, 'notify.mjs'))+ } finally {+ process.argv[1] = script+ rmSync(cliDir, { recursive: true, force: true })+ }+ })+it('merges foreign hooks and installs the canonical catch hooks idempotently', async () => {const file = join(codexHome, 'hooks.json')writeFileSync(file, JSON.stringify({diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.tsindex c2910f141..f7fc59aba 100644--- a/cli/src/lib/hooks.ts+++ b/cli/src/lib/hooks.ts@@ -29,11 +29,13 @@ const COPILOT_HOOKS_PATH = join(env.COPILOT_HOME, 'hooks', 'harness.json')// notify.mjs location depends on the layout (import.meta.url is the REAL executing file at runtime):// - packaged/bundled: cli.js at ~/.harness/cli/cli.js → notify.mjs is a SIBLING (dist/ bundle too).+// - a core started from the lean bundle (leanEntry.ts): its file is lean/<sha>/ in the data folder, which+// holds no notify.mjs, and its script (process.argv[1]) is the cli.js it was read from: the sibling of that.// - dev/per-file: hooks.js at <appRoot>/{src,dist}/lib/ → notify.mjs at ../../hook/notify.mjs.// Prefer the sibling, fall back to the dev path.const cliDir = dirname(fileURLToPath(import.meta.url))const HOOK_SCRIPT =- [join(cliDir, 'notify.mjs'), join(cliDir, '..', '..', 'hook', 'notify.mjs')].find(existsSync) ??+ [join(cliDir, 'notify.mjs'), ...(process.argv[1] ? [join(dirname(process.argv[1]), 'notify.mjs')] : []), join(cliDir, '..', '..', 'hook', 'notify.mjs')].find(existsSync) ??join(cliDir, '..', '..', 'hook', 'notify.mjs')// SessionStart/UserPromptSubmit bind mutable engine-session metadata to the process agent. SessionEnddiff --git a/cli/src/masterProcess.spec.ts b/cli/src/masterProcess.spec.tsindex abfe207a1..73b2dddd8 100644--- a/cli/src/masterProcess.spec.ts+++ b/cli/src/masterProcess.spec.ts@@ -64,7 +64,7 @@ describe('a master started on cli.js', () => {const { given, calls } = deps({ execve: null })startMasterFromBundle('/cli/cli.js', given)expect(calls.starts).toEqual([{ scriptPath: '/cli/cli.js', serviceScriptPath: '/data/lean/harnessd-aaaa.mjs', leanFingerprint: PRINT }])- expect(calls.logs).toEqual(['[harnessd] this Node cannot re-execute the master: it runs from /cli/cli.js, the services from /data/lean/harnessd-aaaa.mjs'])+ expect(calls.logs).toEqual(['[harnessd] this Node cannot re-execute the master: it runs from /cli/cli.js, the core and the services from /data/lean/harnessd-aaaa.mjs'])const failing = deps({ execve: () => { throw new Error('E2BIG') } })startMasterFromBundle('/cli/cli.js', failing.given)expect(failing.calls.starts).toEqual([{ scriptPath: '/cli/cli.js', serviceScriptPath: '/data/lean/harnessd-aaaa.mjs', leanFingerprint: PRINT }])@@ -82,7 +82,7 @@ describe('a master started on cli.js', () => {startMasterFromBundle('/cli/cli.js', given)expect(calls.execs).toEqual([])expect(calls.starts).toEqual([{ scriptPath: '/cli/cli.js' }])- expect(calls.logs).toEqual([`[harnessd] ${gone} is not there to re-execute on: the master and the services run from /cli/cli.js`])+ expect(calls.logs).toEqual([`[harnessd] ${gone} is not there to re-execute on: the master, the core and the services run from /cli/cli.js`])}})@@ -91,7 +91,7 @@ describe('a master started on cli.js', () => {startMasterFromBundle('/cli/cli.js', given)expect(calls.starts).toEqual([{ scriptPath: '/cli/cli.js' }])expect(calls.probes).toEqual([])- expect(calls.logs).toEqual([`[harnessd] ${LEAN_OFF_FILE} is there: the master and the services run from /cli/cli.js`])+ expect(calls.logs).toEqual([`[harnessd] ${LEAN_OFF_FILE} is there: the master, the core and the services run from /cli/cli.js`])})it('runs everything from cli.js when the lean bundle is not there to use, and says why', () => {@@ -111,7 +111,7 @@ describe('a master started on cli.js', () => {const none = deps()startMasterFromBundle('/cli/cli.js', none.given)expect(none.calls.starts).toEqual([{ scriptPath: '/cli/cli.js' }])- expect(none.calls.logs).toEqual(['[harnessd] no lean bundle in /cli/cli.js: the master and the services run from it'])+ expect(none.calls.logs).toEqual(['[harnessd] no lean bundle in /cli/cli.js: the master, the core and the services run from it'])})it('runs everything from cli.js, quietly, with HARNESSD_LEAN=off', () => {diff --git a/cli/src/masterProcess.ts b/cli/src/masterProcess.tsindex 71481cde9..acb2cf840 100644--- a/cli/src/masterProcess.ts+++ b/cli/src/masterProcess.ts@@ -6,8 +6,8 @@* process evaluated the whole bundle, and Node parses all of the file a process is started on whatever* it runs. Measured from the bundle at idle (2026-10-05): the master 160 MiB resident, each service 115* to 160. So a master started on cli.js re-executes itself, same pid, on the lean bundle cli.js carries- * (harnessd/leanBundle.ts), and starts the services from it too: each then parses its own code and not- * the whole CLI's 4.4 MB.+ * (harnessd/leanBundle.ts), and starts the services and the core from it too: each then parses its own+ * code and not the whole CLI's 4.4 MB.*/import { spawnSync } from 'node:child_process'import { existsSync, readFileSync } from 'node:fs'@@ -162,26 +162,26 @@ export function startMasterFromBundle(bundlePath: string, deps: BundleMasterDepsdeps.start({ scriptPath: bundlePath, ...(lean ? { serviceScriptPath: lean.path, leanFingerprint: lean.fingerprint } : {}) })}if (deps.env.HARNESSD_LEAN === 'off') { fromBundle(null); return }- if (deps.leanOff()) { fromBundle(`${LEAN_OFF_FILE} is there: the master and the services run from ${bundlePath}`); return }+ if (deps.leanOff()) { fromBundle(`${LEAN_OFF_FILE} is there: the master, the core and the services run from ${bundlePath}`); return }let written: { lean: LeanBundle; path: string } | nulltry {const lean = readLeanBundle(deps.read(bundlePath))written = lean ? { lean, path: deps.write(lean) } : null} catch (error) {- fromBundle(`the lean bundle could not be written out (${error instanceof Error ? error.message : String(error)}): the master and the services run from ${bundlePath}`)+ fromBundle(`the lean bundle could not be written out (${error instanceof Error ? error.message : String(error)}): the master, the core and the services run from ${bundlePath}`)return}- if (!written) { fromBundle(`no lean bundle in ${bundlePath}: the master and the services run from it`); return }+ if (!written) { fromBundle(`no lean bundle in ${bundlePath}: the master, the core and the services run from it`); return }const { lean, path: leanPath } = writtenconst fingerprint = leanFingerprint(lean)const leanEnv = { ...deps.env, [BUNDLE_ENV]: bundlePath, [BUNDLE_SHA256_ENV]: lean.bundleSha256, [LEAN_FINGERPRINT_ENV]: fingerprint }const probed = deps.probe(leanPath, leanEnv)if (!probed.ok) {- fromBundle(`the lean bundle ${leanPath} did not answer its probe (${probed.detail}): the master and the services run from ${bundlePath}`)+ fromBundle(`the lean bundle ${leanPath} did not answer its probe (${probed.detail}): the master, the core and the services run from ${bundlePath}`)return}if (!deps.execve) {- fromBundle(`this Node cannot re-execute the master: it runs from ${bundlePath}, the services from ${leanPath}`, { path: leanPath, fingerprint })+ fromBundle(`this Node cannot re-execute the master: it runs from ${bundlePath}, the core and the services from ${leanPath}`, { path: leanPath, fingerprint })return}// An exec that fails cannot be caught once it has begun: on Node 22.23 a node binary that is not there@@ -190,13 +190,13 @@ export function startMasterFromBundle(bundlePath: string, deps: BundleMasterDepsconst node = deps.node?.() ?? process.execPathconst missing = [node, leanPath].find((path) => !deps.exists(path))if (missing) {- fromBundle(`${missing} is not there to re-execute on: the master and the services run from ${bundlePath}`)+ fromBundle(`${missing} is not there to re-execute on: the master, the core and the services run from ${bundlePath}`)return}try {deps.execve(node, [node, ...process.execArgv, leanPath, '__harnessd'], leanEnv)} catch (error) {// Only what `process.execve` refuses before it begins: arguments it cannot take.- fromBundle(`the master could not re-execute on ${leanPath} (${error instanceof Error ? error.message : String(error)}): it runs from ${bundlePath}, the services from ${leanPath}`, { path: leanPath, fingerprint })+ fromBundle(`the master could not re-execute on ${leanPath} (${error instanceof Error ? error.message : String(error)}): it runs from ${bundlePath}, the core and the services from ${leanPath}`, { path: leanPath, fingerprint })}}diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.mdindex 8f7b8bcd4..dfd6a2746 100644--- a/cli/src/services/AGENTS.md+++ b/cli/src/services/AGENTS.md@@ -80,12 +80,13 @@ master too old to run it starts it beside itself, still in its own process (`srca service whose start throws there is left off while the others in its process run. The core'sin-process starts are in `inline.ts`, which the core loads only when a service runs in its process:a service in its own leaves the core's import closure (`src/architecture.spec.ts`). From a release,- it runs on the lean bundle cli.js carries for the master and the services- (`src/harnessd/leanBundle.ts`), split so that a service loads its own code and nothing else: 61 to 77- MiB resident at idle (20 to 35 MiB physical footprint), against 118 to 131 (54 to 90) when each- started on cli.js (2026-10-05). It is only an optimisation: the master starts a service from cli.js- whenever the lean bundle cannot be used (`src/harnessd/leanServices.ts`), and the release script- refuses one that does not load (`scripts/check-lean-bundle.mjs`).+ it runs on the lean bundle cli.js carries for the master and the services, built apart from the+ core's own entry (`src/harnessd/leanBundle.ts`, `src/leanCoreEntry.ts`), split so that a service+ loads its own code and nothing else: 61 to 77 MiB resident at idle (20 to 35 MiB physical+ footprint), against 118 to 131 (54 to 90) when each started on cli.js (2026-10-05). It is only an+ optimisation: the master starts a service from cli.js whenever the lean bundle cannot be used+ (`src/harnessd/leanServices.ts`), and the release script refuses one that does not load+ (`scripts/check-lean-bundle.mjs`).- **What a service imports is what its process costs.** Import from small modules: one schema modulepulled in for a constant brought zod to search and workspaces, 8 MiB each (`src/dsh/id.ts`). Afailing import fails the service's start, loudly, and the master parks it. `src/leanEntry.spec.ts`diff --git a/cli/src/startupOrder.spec.ts b/cli/src/startupOrder.spec.tsindex b4b9d2254..be734f9a9 100644--- a/cli/src/startupOrder.spec.ts+++ b/cli/src/startupOrder.spec.ts@@ -20,8 +20,10 @@ import { join } from 'node:path'* the source, rather than left to whoever next adds a helper below the restore block.*/const SOURCE = readFileSync(join(import.meta.dirname, 'core', 'main.ts'), 'utf-8')-/** The CLI, which starts the core for `harness __run` (core/main.ts `runCore`). */+/** The CLI, which starts the core for `harness __run` (coreProcess.ts, then core/main.ts `runCore`). */const CLI_SOURCE = readFileSync(join(import.meta.dirname, 'cli.ts'), 'utf-8')+/** The one start of the core's process, from cli.ts, cli.js and the lean bundle alike. */+const CORE_PROCESS_SOURCE = readFileSync(join(import.meta.dirname, 'coreProcess.ts'), 'utf-8')/** `runForeground`'s own body. Other functions are indented the same way; their locals are not ours. */function runForegroundBody(source: string): { text: string; from: number } {@@ -163,8 +165,12 @@ describe('the core\'s start-up order (core/main.ts)', () => {const cli = code(CLI_SOURCE)const start = cli.indexOf("case '__run'")const arm = cli.slice(start, cli.indexOf('break', start))- expect(arm, 'cli.ts starts the core through its entry').toContain('runCore(')+ expect(arm, 'cli.ts starts the core through its process\'s start').toContain('startCoreProcess(')expect(arm, 'a daemon that exits here can never be updated').not.toContain('catch(onError)')+ // That start, which entry.ts and the lean bundle's core entry call too, runs the core's entry.+ const processStart = code(CORE_PROCESS_SOURCE)+ expect(processStart, 'coreProcess.ts starts the core through its entry').toContain('runCore(')+ expect(processStart, 'a daemon that exits here can never be updated').not.toContain('catch(onError)')// The entry it calls: what the arm did before the core had one of its own.const source = code(SOURCE)const from = source.indexOf('export function runCore(')diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.mdindex 2c46d093d..c953410d2 100644--- a/docs/design/2026-10-03-harnessd.md+++ b/docs/design/2026-10-03-harnessd.md@@ -572,13 +572,33 @@ Done so far:before beating (`cli/src/harnessd/leanServices.ts`); `lean-off` in the data folder turns it off for amaster launchd or systemd starts; and the release script refuses a lean bundle whose master does notanswer its probe or whose modules do not load (`cli/scripts/check-lean-bundle.mjs`). The environment is read without zod- (`cli/src/config/envFields.ts`), which every process loads and which cost each 15 to 19 MiB. The core- and the CLI run from cli.js. The release is still the one cli.js the updater downloads, verifies and- swaps. Where Node cannot re-execute (before 22.15), the master runs from cli.js and the services still- from the lean bundle; without a lean bundle that answers, everything runs from cli.js, as with- `HARNESSD_LEAN=off`. Measured at idle, the median of three runs: the master 55 MiB resident (16 MiB- physical footprint, from 113), search 77 (35), the viewers 69 (29), workspaces 61 (20), the teams 66- (26); 465 MiB with the core, against 839. `e2e/lean.e2e.ts` proves it on a real release bundle.+ (`cli/src/config/envFields.ts`), which every process loads and which cost each 15 to 19 MiB. The CLI+ runs from cli.js, and the core did until its own entry (below). The release is still the one cli.js+ the updater downloads, verifies and swaps. Where Node cannot re-execute (before 22.15), the master+ runs from cli.js and the services still from the lean bundle; without a lean bundle that answers,+ everything runs from cli.js, as with `HARNESSD_LEAN=off`. Measured at idle, the median of three+ runs: the master 55 MiB resident (16 MiB physical footprint, from 113), search 77 (35), the viewers+ 69 (29), workspaces 61 (20), the teams 66 (26); 465 MiB with the core, against 839.+ `e2e/lean.e2e.ts` proves it on a real release bundle.+- **The core's lean entry** (2026-10-06). The core parsed the whole cli.js too: every command of the+ CLI, the master's code and every service's. It now starts from an entry of its own in the lean bundle+ (`cli/src/leanCoreEntry.ts`, `harnessd-core.mjs`), which loads 3.1 MB of code against cli.js's 4.6.+ It is built apart from the master's and the services' (`cli/build-bundle.mjs`), its files named+ `core-*`: built as one more entry of the same build, the files they shared held the parts only the+ core uses, Node's http and net among them, and the master and every service paid about 5 MiB each+ for that, more than the core saved. The master hands the core the cli.js it read the bundle from+ (`HARNESSD_CORE_SCRIPT`), and to everything the core hands on that is its script: the hooks it+ installs, the CLI in agents' panes, a successor on an update. The core starts from it by the+ services' rules (`cli/src/harnessd/leanServices.ts`): from cli.js when the lean files are gone or+ changed, cli.js is no longer the bundle they came from, it died twice from them before beating,+ `HARNESSD_LEAN=off` or `lean-off`. The supervisor judges an update's first core as before, whichever+ file it started from, so the release script checks that the core's entry loads+ (`cli/scripts/check-lean-bundle.mjs`). A master hashes cli.js and the lean files before every+ process it starts, and now reads each a piece at a time (`cli/src/harnessd/reexec.ts` `sha256File`):+ read whole, the buffers stayed in the master at idle. Measured at idle from the bundle, two+ paired runs of three samples each against the build before, medians: the core 135 MiB resident+ against 159, and 88 MiB physical footprint against 95.5; every other process within 1.5 MiB of+ before; 638.5 MiB resident in all against 663.5, and 286 MiB footprint against 298.5.- **Services in their own processes** (step 4; on by default since 2026-10-05, `HARNESSD_SERVICES=none`to run them inside the core's process). The master runs each service as `harness __service <name>`beside the core