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
harness start -f runs the master, and a core on its own hands each update to a master that judges it (#895)
Dee9cdcf3b9077b
diff --git a/cli/AGENTS.md b/cli/AGENTS.mdindex 7ae3b2877..0a76e4bc1 100644--- a/cli/AGENTS.md+++ b/cli/AGENTS.md@@ -16,8 +16,11 @@ SERVICES src/services/ everything else: search, viewers, models, workspaces,````src/core/main.ts` `runForeground()` is the composition root: it creates the modules and wires them-together. It is the core's own entry (`harness __run`); `src/cli.ts` is the CLI, and calls in for-`__run` and `start -f`. `src/backendSocket.ts` is the transport: it receives frames and dispatches them.+together. It is the core's own entry (`harness __run`), which the master starts; `src/cli.ts` is the CLI,+and calls in for `__run`. `harness start -f` runs the master in the foreground, as launchd and systemd do.+A core with no master (`HARNESS_NO_MASTER=1`, or one an older release's handoff started) hands each update+to a master that judges it (`src/core/updateHandoff.ts`). `src/backendSocket.ts` is the transport: it+receives frames and dispatches them.`src/gateway/` is the relay: the backend link, the E2EE sessions and keys, and every rule about what aremote client may send and how what it is sent is sealed. It runs in a process of its own(`src/gateway/gatewayProcess.ts`; the core's side is `src/core/gatewayLink.ts`), or in the core's withdiff --git a/cli/README.md b/cli/README.mdindex 24c99ad66..e5f836a82 100644--- a/cli/README.md+++ b/cli/README.md@@ -78,7 +78,7 @@ harness login # asks how to sign in (Google, Apple, or a QR your phone sharness login --google # or --apple: straight to that account in the browser, without askingharness login --force # stop the daemon and sign in as a different SSO accountharness start # starts the local adapter; uses a saved SSO session if present-harness start -f # foreground mode for a supervisor; logs to stdout+harness start -f # foreground mode for a supervisor (harnessd's master and its core); logs to stdoutharness status # is it running? shows pid + the chat linkharness stop # stop the background adapterharness version # print the installed versiondiff --git a/cli/e2e/harness/daemon.ts b/cli/e2e/harness/daemon.tsindex cad0761d8..af07a87b4 100644--- a/cli/e2e/harness/daemon.ts+++ b/cli/e2e/harness/daemon.ts@@ -55,6 +55,8 @@ export interface DaemonOptions {codexModel?: string/** Boot the core on its own (`__run`) instead of under harnessd's master (`__harnessd`). */noMaster?: boolean+ /** Start as a supervisor does, `harness start -f`: the master in the foreground, the core its child. */+ foreground?: boolean/** Run this bundle (an installed `cli.js`) instead of the checkout's source. */scriptPath?: string/** Keep the daemon's data folder here instead of under the throwaway root (a test volume). The fake@@ -300,19 +302,19 @@ export class IsolatedDaemon {// Checked at every start: a test writes a shell profile, or the data folder remembers a home, between them.assertHooksContained(this.root, this.env)const heap = this.options.heapMiB ? [`--max-old-space-size=${this.options.heapMiB}`] : []- const entry = this.options.noMaster ? '__run' : '__harnessd'+ const entry = this.options.noMaster ? ['__run'] : this.options.foreground ? ['start', '-f'] : ['__harnessd']// Readiness is judged from what this start prints, never from an earlier boot's lines.const from = this.output.length// A test's own bundle (an old release), the run's bundle (`E2E_BUNDLE`, see bundle.ts), or the sources.const bundle = this.options.scriptPath ?? process.env.E2E_BUNDLE_PATHconst script = bundle ? [bundle] : ['--import', 'tsx', 'src/cli.ts']- const child = spawn(process.execPath, [...heap, ...script, entry], {+ const child = spawn(process.execPath, [...heap, ...script, ...entry], {cwd: CLI_ROOT, env: this.env, stdio: ['ignore', 'pipe', 'pipe'],})this.child = child// The whole log, as files, for a failing test's CI artifacts (E2E_ARTIFACTS_DIR, artifacts.ts).const logName = `daemon-${this.port}.log`- artifactLog(logName, `---- ${new Date().toISOString()} start (pid ${child.pid}, ${script.at(-1)} ${entry}, data ${this.dataDir})\n`)+ artifactLog(logName, `---- ${new Date().toISOString()} start (pid ${child.pid}, ${script.at(-1)} ${entry.join(' ')}, data ${this.dataDir})\n`)const take = (chunk: Buffer) => {const text = chunk.toString('utf8')this.output += textdiff --git a/cli/e2e/master.e2e.ts b/cli/e2e/master.e2e.tsindex 892aab626..3f90d1ed2 100644--- a/cli/e2e/master.e2e.ts+++ b/cli/e2e/master.e2e.ts@@ -3,6 +3,7 @@* own, the agents keep running in tmux, and a client picks up where it was. Whatever happens to the* master, nothing is left behind holding the port.*/+import { execFileSync } from 'node:child_process'import { existsSync, mkdirSync, readFileSync } from 'node:fs'import { join } from 'node:path'import { afterEach, describe, expect, it, onTestFailed } from 'vitest'@@ -115,6 +116,31 @@ describe('harnessd', () => {expect(existsSync(join(d.dataDir, 'adapter.pid'))).toBe(false)})+ it('`harness start -f` runs the master in the foreground, as launchd does: the core its child, a stop ends both', async () => {+ // It ran the core alone, with no master: every update then had to be handed over by the core itself.+ daemon = await IsolatedDaemon.create({ foreground: true, env: { HARNESSD_INITIAL_BACKOFF_MS: '100' } })+ const d = daemon+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-80).join('\n')}`) })+ await d.start()+ const master = d.pid!+ const core = d.corePid()!+ expect(core).not.toBe(master)+ expect(Number(execFileSync('ps', ['-o', 'ppid=', '-p', String(core)], { encoding: 'utf8' }).trim())).toBe(master)+ const status = await (await fetch(`http://127.0.0.1:${d.port}/api/status`)).json() as Record<string, any>+ expect(status.harnessd.masterPid).toBe(master)+ expect(readFileSync(join(d.dataDir, 'adapter.pid'), 'utf8').trim()).toBe(String(master))+ // A crashed core is restarted under it, and the agent goes on.+ const { agentId } = await withAgent(d)+ const wired = wiredCount(d)+ process.kill(core, 'SIGKILL')+ await until('a new core to finish starting', () => wiredCount(d) > wired, 60_000)+ await turnWorks(d, agentId)+ const second = d.corePid()!+ process.kill(master, 'SIGTERM')+ await until('both to exit', () => !IsolatedDaemon.alive(master) && !IsolatedDaemon.alive(second), 10_000, 25)+ expect(existsSync(join(d.dataDir, 'adapter.pid'))).toBe(false)+ })+it('restarts a core that outgrows its memory budget, backing off while it keeps doing so', async () => {daemon = await IsolatedDaemon.create({ env: { HARNESSD_INITIAL_BACKOFF_MS: '200', HARNESSD_RSS_LIMIT_MIB: '1' } })const d = daemondiff --git a/cli/e2e/updateOnItsOwn.e2e.ts b/cli/e2e/updateOnItsOwn.e2e.tsnew file mode 100644index 000000000..6eab3b76a--- /dev/null+++ b/cli/e2e/updateOnItsOwn.e2e.ts@@ -0,0 +1,252 @@+/**+ * A self-update of a core that runs with no master, on real release bundles: what this build's core does+ * when an older release's own handoff started it (it spawned `cli.js __run`, e2e/migration.e2e.ts), or+ * `HARNESS_NO_MASTER=1` asked for it. It hands the machine to harnessd's master on the staged bundle,+ * which judges the update as it judges every one: a build whose core crashes is rolled back, remembered+ * and the master re-executed onto the build before; a good one is kept. A build whose master cannot+ * start is refused before anything is let go, and this build goes on under a master of its own. Before,+ * the core spawned a core like itself and judged it, and the successor had no master either. The same+ * holds for an update staged while such a core is still starting, or is in safe mode, as the boot+ * handoff hands it over (core/main.ts `bootHandoff`).+ *+ * The bundles are built from this checkout at made-up versions and served from a local manifest, as in+ * e2e/update.e2e.ts, so nothing here reaches beyond the machine.+ */+import { execFileSync } from 'node:child_process'+import { createHash } from 'node:crypto'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { createServer, type Server } from 'node:http'+import { tmpdir } from 'node:os'+import { 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'++const FIRST = '44.0.1'+const sha = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex')+type Row = Record<string, any>++describe('a self-update of a core with no master', () => {+ let scratch = ''+ let server: Server | undefined+ let daemon: IsolatedDaemon | undefined+ const releases = new Map<string, Buffer>()+ let notify = Buffer.alloc(0)+ let offered = FIRST+ const cliDir = () => join(scratch, 'cli')+ const installed = () => readFileSync(join(cliDir(), 'cli.js'))+ const rejected = () => JSON.parse(readFileSync(join(cliDir(), 'update-rejected.json'), 'utf8')) as string[]+ const status = async (): Promise<Row | null> =>+ fetch(`http://127.0.0.1:${daemon!.port}/api/status`).then((response) => response.json() as Promise<Row>).catch(() => null)+ /** What the master this test never started writes: the daemon's log file. */+ const masterLog = (): string => { try { return readFileSync(join(daemon!.dataDir, 'harness.log'), 'utf8') } catch { return '' } }+ /** The pids answering on the daemon's port: whatever runs it now. */+ const listeners = (): number[] => {+ try {+ return execFileSync('lsof', ['-n', '-P', '-t', `-iTCP:${daemon!.port}`, '-sTCP:LISTEN']).toString().trim().split('\n').filter(Boolean).map(Number)+ } catch { return [] }+ }+ const parentOf = (pid: number): number => Number(execFileSync('ps', ['-o', 'ppid=', '-p', String(pid)], { encoding: 'utf8' }).trim())+ const rows = async (client: LocalClient): Promise<Row[]> =>+ (await client.request<{ agents: Row[] }>('agents_list', { includeStopped: true }, 30_000)).agents+ const turn = async (client: LocalClient, agentId: string, content: string) => {+ const ended = client.next((frame: Frame) => frame.type === 'turn_ended' && frame.agentId === agentId, 60_000, `turn_ended (${content})`)+ client.send('message', { agentId, content })+ await ended+ }+ /** The master the core handed the machine to, once its core on `version` answers. */+ const underMaster = (version: string) => until(`the machine to run ${version} under a master`, async () => {+ const now = await status()+ return now?.version === version && now.harnessd?.masterPid && IsolatedDaemon.alive(now.harnessd.masterPid) ? now : null+ }, 120_000, 250)+ let master: number | null = null++ beforeAll(async () => {+ scratch = mkdtempSync(join(tmpdir(), 'harnessd-update-alone-'))+ const out = join(scratch, 'build')+ execFileSync(process.execPath, ['build-bundle.mjs'], {+ cwd: CLI_ROOT, env: { ...process.env, ADAPTER_VERSION: FIRST, BUNDLE_OUT_DIR: out }, stdio: 'pipe',+ })+ const first = readFileSync(join(out, 'cli.js'), 'utf8')+ notify = readFileSync(join(out, 'notify.mjs'))+ /** 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`)+ releases.set(version, Buffer.from(source))+ }+ release(FIRST)+ // Starts a master, whose core dies on every start.+ release('44.0.2', ['__run'])+ // Whose master cannot start at all: it does not answer its probe.+ release('44.0.3', ['__harnessd', '__harnessd-probe'])+ release('44.0.4')+ release('44.0.5', ['__harnessd', '__harnessd-probe'])+ release('44.0.6')++ server = createServer((request, response) => {+ const url = request.url ?? ''+ const origin = `http://127.0.0.1:${(server!.address() as { port: number }).port}`+ if (url === '/metadata.json') {+ const cli = releases.get(offered)!+ response.end(JSON.stringify({ cli: {+ version: offered,+ cli: { url: `${origin}/cli-${offered}.js`, sha256: sha(cli), size: cli.length },+ notify: { url: `${origin}/notify.mjs`, sha256: sha(notify), size: notify.length },+ } }))+ return+ }+ const asked = /^\/cli-(.+)\.js$/.exec(url)?.[1]+ if (asked && releases.has(asked)) { response.end(releases.get(asked)); return }+ if (url === '/notify.mjs') { response.end(notify); return }+ response.statusCode = 404+ response.end()+ })+ await new Promise<void>((done) => server!.listen(0, '127.0.0.1', done))+ const local = `http://127.0.0.1:${(server.address() as { port: number }).port}`++ mkdirSync(cliDir())+ writeFileSync(join(cliDir(), 'cli.js'), releases.get(FIRST)!)+ writeFileSync(join(cliDir(), 'notify.mjs'), notify)+ writeFileSync(join(cliDir(), 'package.json'), '{"type":"module"}\n')+ daemon = await IsolatedDaemon.create({+ scriptPath: join(cliDir(), 'cli.js'),+ // A core on its own, as an older release's handoff, or HARNESS_NO_MASTER=1, starts it.+ noMaster: true,+ env: {+ ADAPTER_CLI_DIR: cliDir(),+ ADAPTER_UPDATE_DISABLE: 'false',+ ADAPTER_UPDATE_URL: `${local}/metadata.json`,+ ADAPTER_UPDATE_CHECK_MS: '1000',+ ADAPTER_UPDATE_SLOT_SEC: '-1',+ HARNESSD_UPDATE_PROBATION_MS: '3000',+ HARNESSD_INITIAL_BACKOFF_MS: '100',+ HARNESS_TUI_MANIFEST_URL: `${local}/tui/metadata.json`,+ ADAPTER_RUNTIME_METADATA_URL: `${local}/runtime/metadata.json`,+ ADAPTER_GRID_RUNTIME_METADATA_URL: `${local}/grid/metadata.json`,+ },+ })+ await daemon.start()+ expect((await status())?.version).toBe(FIRST)+ expect((await status())?.harnessd).toBeFalsy()+ }, 300_000)++ afterAll(async () => {+ // The master this core handed the machine to is no child of the test's: it goes first, with its core.+ if (master && IsolatedDaemon.alive(master)) {+ process.kill(master, 'SIGTERM')+ await until('the master to stop', () => !IsolatedDaemon.alive(master) || null, 15_000, 100).catch(() => { try { process.kill(master!, 'SIGKILL') } catch { /* gone */ } })+ }+ for (const pid of listeners()) { try { process.kill(pid, 'SIGTERM') } catch { /* gone */ } }+ await daemon?.close()+ await new Promise<void>((done) => server ? server.close(() => done()) : done())+ if (scratch) rmSync(scratch, { recursive: true, force: true })+ })++ /** The agent, on its conversation, taking a turn: proof it came through. */+ const goesOn = async (agent: Row, content: string) => {+ const client = await LocalClient.connect(daemon!)+ await until('the agent back on its conversation', async () => {+ const row = (await rows(client)).find((one) => one.id === agent.id)+ return row?.status === 'active' && row.sessionId === agent.sessionId ? row : null+ }, 60_000, 500)+ await turn(client, agent.id, content)+ client.close()+ }+ /** One daemon: the core this test started has left, and the one on the port is the master's child. */+ const oneDaemon = async (under: number) => {+ await until('the core this test started to have left', () => !IsolatedDaemon.alive(daemon!.pid) || null, 30_000, 250)+ const cores = await until('one core on the port', () => { const now = listeners(); return now.length === 1 ? now : null }, 30_000, 250)+ expect(parentOf(cores[0])).toBe(under)+ }++ it('hands each update to a master, which judges it; refuses one whose master cannot start; agents go on', async () => {+ const d = daemon!+ onTestFailed(() => { console.log(`---- the core's log\n${d.log().split('\n').slice(-60).join('\n')}\n---- the daemon's log file\n${masterLog().split('\n').slice(-120).join('\n')}`) })+ const client = await LocalClient.connect(d)+ const cwd = join(d.projectsDir, 'alone')+ mkdirSync(cwd, { recursive: true })+ const created = await client.request('agent_create', { engine: 'claude', cwd, bypassPermission: true }, 90_000)+ expect(created.error, JSON.stringify(created)).toBeUndefined()+ const agent = await until('the agent to bind', async () => {+ const row = (await rows(client)).find((one) => one.id === created.agent.id)+ return row?.sessionId && row.status === 'active' ? row : null+ }, 60_000, 500)+ await turn(client, agent.id, `on ${FIRST}, on its own`)+ client.close()++ // A build whose core crashes: the core on its own stages it and hands the machine to a master on it,+ // which finds the update unjudged, puts its first core on probation, rolls it back when it crashes and+ // re-executes onto the build before.+ offered = '44.0.2'+ await until('the core to hand 44.0.2 to a master', () => d.log().includes('handing 44.0.2 to a harnessd master, which judges it') || null, 90_000, 250)+ await until('the master to roll it back', () => masterLog().includes('the updated core failed (code 3) — rolled back') || null, 90_000, 250)+ master = (await underMaster(FIRST)).harnessd.masterPid+ expect(master).not.toBe(d.pid)+ expect(installed()).toEqual(releases.get(FIRST))+ expect(rejected()).toEqual(['44.0.2'])+ expect(existsSync(join(cliDir(), 'update-pending.json'))).toBe(false)+ await oneDaemon(master!)+ await goesOn(agent, `back on ${FIRST}, under the master`)++ // On its own again (an older release's handoff, HARNESS_NO_MASTER=1), and a build whose master cannot+ // start: refused before anything is let go, and this build goes on under a master of its own.+ process.kill(master!, 'SIGTERM')+ await until('the master to stop', () => (!IsolatedDaemon.alive(master) && listeners().length === 0) || null, 30_000, 250)+ await d.start()+ expect((await status())?.harnessd).toBeFalsy()+ const from = d.log().length+ const masterFrom = masterLog().length+ offered = '44.0.3'+ await until('the core to refuse 44.0.3', () => d.log().slice(from).includes('44.0.3\'s master did not answer its probe') || null, 90_000, 250)+ master = (await underMaster(FIRST)).harnessd.masterPid+ expect(rejected()).toEqual(['44.0.2', '44.0.3'])+ expect(installed()).toEqual(releases.get(FIRST))+ await oneDaemon(master!)+ // Its master started on this build, with nothing to judge: 44.0.3 never ran.+ expect(masterLog().slice(masterFrom)).not.toContain('on probation')+ await goesOn(agent, `on ${FIRST}, under a master of its own`)++ // A good build: now the master's to apply, re-executing on it in its own process, and to keep.+ offered = '44.0.4'+ await underMaster('44.0.4')+ await until('the master to keep it', () => masterLog().includes('the update stayed up — keeping it') || null, 60_000, 250)+ expect((await status())?.harnessd.masterPid).toBe(master)+ expect(installed()).toEqual(releases.get('44.0.4'))+ expect(rejected()).toEqual(['44.0.2', '44.0.3'])+ await goesOn(agent, 'on 44.0.4, kept')++ // The boot handoff: a core on its own in safe mode (its start-up threw; only its updater runs) hands an+ // update over without finishing start-up. A build whose master cannot start is rolled back first, and+ // this build's master starts, out of safe mode: the safe mode was the core's, not the master's to keep.+ const inSafeMode = async () => {+ process.kill(master!, 'SIGTERM')+ await until('the master to stop', () => (!IsolatedDaemon.alive(master) && listeners().length === 0) || null, 30_000, 250)+ d.env.HARNESSD_SAFE_MODE = 'an e2e start-up that failed'+ await d.start({ ready: 'none' })+ await until('the core to be in safe mode', async () => (await status())?.safeMode === true || null, 60_000, 250)+ delete d.env.HARNESSD_SAFE_MODE+ }+ await inSafeMode()+ offered = '44.0.5'+ await until('the boot handoff to refuse 44.0.5', () => d.log().includes('44.0.5\'s master did not answer its probe') || null, 90_000, 250)+ master = (await underMaster('44.0.4')).harnessd.masterPid+ expect(rejected()).toEqual(['44.0.2', '44.0.3', '44.0.5'])+ expect(installed()).toEqual(releases.get('44.0.4'))+ await oneDaemon(master!)+ expect((await status())?.safeMode).toBeFalsy()+ await goesOn(agent, 'on 44.0.4, out of safe mode under a master')++ // …and a good build, which the master judges on its first core and keeps.+ await inSafeMode()+ const keptBefore = masterLog().split('the update stayed up — keeping it').length+ offered = '44.0.6'+ await until('the boot handoff to hand 44.0.6 over', () => d.log().includes('44.0.6 staged during start-up — handing off to harnessd\'s master') || null, 90_000, 250)+ master = (await underMaster('44.0.6')).harnessd.masterPid+ await until('the master to keep it', () => masterLog().split('the update stayed up — keeping it').length > keptBefore || null, 60_000, 250)+ expect(installed()).toEqual(releases.get('44.0.6'))+ await oneDaemon(master!)+ await goesOn(agent, 'on 44.0.6, kept')+ }, 900_000)+})diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex 6b6499746..c5a233aa0 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -141,9 +141,10 @@ const WALK_TIMEOUT_MS = 60_000** RUN_FOREGROUND_BUDGET went up from 2,572 on 5 October, when the socket's request cases moved into core* modules: binding each of them is the wiring this function is for. backendSocket.ts lost 615 lines in- * those moves, and runForeground gained 28.+ * those moves, and runForeground gained 28. Down to 2,380 on 6 October (step 11), at 2,346: a core on its+ * own hands an update to a master, which judges it, and no longer spawns, judges and rolls back a core.*/-const RUN_FOREGROUND_BUDGET = 2_600+const RUN_FOREGROUND_BUDGET = 2_380/** Lowered from 2,180 when the relay and its E2EE left the socket for the gateway (step 10, R1: 1,440).* The Wi-Fi device's relay came back to it in R2, beside the device service it answers for, over the* gateway's sessions (lib/autonomous-device/overGateway.ts): 1,460. */@@ -211,7 +212,11 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {// the session crypto it ran in the core's process (lib/e2ee/relayClient.ts and what it loads) is the// gateway's alone, and the Share relay (sharing/relay.ts) runs in the gateway with the relay's other sockets.// What a service in its own process may ask of the account (core/accountQueries.ts) is the 41 lines added.-const CORE_CLOSURE_BUDGET = 95_440+//+// Then at 95,374 in 417 (step 11), from 95,380: a core on its own hands an update to a master on the new+// build, which judges it, instead of spawning a core and judging it itself. Not the 180 lines the plan+// counted on: a core still runs without a master when an older release's own handoff started it.+const CORE_CLOSURE_BUDGET = 95_420/** What is not the core's, by path: each goes to a service or its own process, in the plan's order. */const EDGE: RegExp[] = [diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex d1faa4b1e..a5212f2c4 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -64,9 +64,9 @@ import { gridSetupCommand } from './lib/gridSetupCommand.js'import { WebSocket as NewCommandSocket } from 'ws'import { describeMasterStatus, readStatusFile } from './harnessd/master.js'import { namedNode } from './harnessd/processName.js'-import { probeThisMaster, startMaster } from './masterProcess.js'+import { probeThisMaster, startMaster, startMasterInForeground } from './masterProcess.js'import { startServiceProcess } from './serviceProcess.js'-import { isLocalSocketName } from './lib/localSocket.js'+import { isLocalSocketName, localSocketPath, refuseServedDataFolder } from './lib/localSocket.js'import { legacyDaemonStatus, localDaemonStatus } from './lib/daemonEndpoint.js'import { runAutonomousDeviceCommand } from './lib/autonomous-device/command.js'import { E2eeStore, identitySpent, peekIdentityPub } from './lib/e2ee/store.js'@@ -109,7 +109,8 @@ Machine:harness login --entry-point=desktop record which surface started the sign-in (GUI clients; default cli)harness auth status --json print {loggedIn,...} for this computer's saved sessionharness start start the adapter using the saved SSO session- harness start -f run the adapter in the FOREGROUND (for a supervisor; logs to stdout)+ harness start -f run the daemon in the FOREGROUND (for a supervisor; logs to stdout): harnessd's+ master, as launchd and systemd run it, its core and services its childrenharness start --device-dump[=<file>]record every frame to/from the paired Autonomous device, decrypted, asJSON lines (default ~/.harness/logs/device-dump-<time>.jsonl). Contains@@ -1291,7 +1292,19 @@ async function launch(foreground: boolean, repair: boolean = false): Promise<voiconst repaired = await repairManagedRuntimes(foreground)if (repaired) runtimeNode = repaired}- // Foreground mode (supervisor) OR dev/tsx (can't cleanly spawn a .ts detached) → run inline.+ // Foreground mode (a supervisor: launchd, systemd, a terminal) → harnessd's master in this process, as+ // launchd and systemd run it, the core its child. The core ran here on its own before, and a core with no+ // master must hand each update over itself (core/updateHandoff.ts). HARNESS_NO_MASTER=1 still runs the+ // core here alone, as `harness start` then spawns it.+ if (foreground && process.env.HARNESS_NO_MASTER !== '1') {+ // Beside a daemon that serves this data folder, leave at once and say so, as its core would have:+ // the master would start its services and a core only to see the core refused, and end with 0.+ await refuseServedDataFolder(localSocketPath(env.ADAPTER_DATA_DIR, env.PORT))+ startMasterInForeground(SCRIPT_PATH)+ return+ }+ // …and a dev/tsx run (a .ts is not spawned detached): the core inline, on its own. A repo run never updates+ // itself (runForeground), so it has no update to hand over.if (foreground || SCRIPT_PATH.endsWith('.ts')) {if (!foreground) console.log('[cli] dev mode — running in the foreground (Ctrl-C to stop)')await runCoreInForeground(session, SCRIPT_PATH)diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex e7d36bd6c..c7700e9ae 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -5,8 +5,9 @@* is measured from its own entry rather than from the CLI's (docs/design/2026-10-06-core-boundary-next.md,* step 1); `src/architecture.spec.ts` walks the imports from this file and holds them to a budget.*- * cli.ts stays the process's entry and the CLI: it parses the command and, for `__run` and- * `start -f`, calls in here.+ * cli.ts stays the process's entry and the CLI: it parses the command and, for `__run` (and a start under tsx,+ * or `start -f` with `HARNESS_NO_MASTER=1`), calls in here. `start -f` runs harnessd's master, which starts+ * the core with `__run`.*/import { ensureBundledCoreHarnesses } from '../dsh/builtins.js'import { createDeviceStore, deviceStoreAgents } from '../lib/autonomous-device/storeRuntime.js'@@ -17,7 +18,7 @@ import { SharedViewerPool } from '../sharing/viewer.js'import { runningDevicePart, startDevicePart } from '../lib/autonomous-device/parts.js'import { readFileSync, writeFileSync, openSync, existsSync, rmSync, statSync } from 'fs'import { join } from 'path'-import { spawn } from 'child_process'+import { execFile, spawn, spawnSync } from 'child_process'import { createServer, type Server } from 'http'import { homedir, hostname } from 'os'import { env } from '../config/env.js'@@ -38,7 +39,7 @@ import { installCodexHooks } from '../lib/hooks.js'import { DAEMON_LOG_FILE, PID_FILE, daemonPort, isAlive, readPid, LEGACY_LOG_FILE, MACHINE_NAME_FILE, tildify, computerId, thisDeviceLabel } from '../lib/daemonState.js'import { clearSafeModeMarker, runBootHandoff, safeModeDisposition, safeModeStatusBody, SafeModeRequest, writeSafeModeMarker } from '../lib/daemonSafeMode.js'import { awakeTimeout } from '../lib/sleepAware.js'-import { BIND_WAIT_MS, defaultLaunchDeps, removePidFileIf, waitForBind, waitForReady, onError } from '../lib/daemonLaunch.js'+import { removePidFileIf, onError } from '../lib/daemonLaunch.js'import { describeSpawnLockOwner, withSpawnLock } from '../lib/daemonSpawnLock.js'import { ensureTmuxOnPath } from '../lib/tmuxOnPath.js'import { AUTH_DIR, AuthSessionError, AuthSessionManager, clearAuthSession, ensureSignInEpoch, readAuthSession, signInOf, type AuthSession } from '../lib/authSession.js'@@ -98,7 +99,7 @@ import { createQuestions } from './questions.js'import { createTurnActivity } from './turns/activity.js'import { createLastTurnReader } from './transcripts/lastTurn.js'import { createRecaps } from './turns/recaps.js'-import { createUpdateHandoff, type HandoffChild } from './updateHandoff.js'+import { createUpdateHandoff, probeStagedMaster, probeVerdict } from './updateHandoff.js'import { createHeartbeats } from './turns/heartbeats.js'import { createEventFunnel, outsideConsumers } from './turns/funnel.js'import { createAgyBackstop } from './turns/agyBackstop.js'@@ -141,7 +142,7 @@ import { KNOWN_SERVICES, servicesTheMasterRuns } from '../harnessd/services.js'import { createTeamsLink } from './teamsLink.js'import { startModels } from '../services/models.js'import { startFleet } from '../services/fleet.js'-import { CORE_EXIT_STOP, CORE_EXIT_UPDATE } from '../harnessd/protocol.js'+import { CORE_EXIT_STOP, CORE_EXIT_UPDATE, PROBE_COMMAND, PROBE_TIMEOUT_MS } from '../harnessd/protocol.js'import { localSocketPath, refuseServedDataFolder, type LocalSocketServer } from '../lib/localSocket.js'import { saveDaemonPort } from '../lib/daemonEndpoint.js'import { publishHookRoute } from '../lib/hookRoutes.js'@@ -160,7 +161,7 @@ import { TeamError } from '../teams/model.js'import { setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter } from '../lib/voiceRouter.js'import { E2eeStore } from '../lib/e2ee/store.js'import { isLoopbackRequest, loopbackHosts } from '../lib/loopbackRequest.js'-import { startSelfUpdater, restore as restoreUpdate, confirm as confirmUpdate, DOWNLOAD_LIMITS, type Poller } from '../lib/selfUpdate.js'+import { startSelfUpdater, restore as restoreUpdate, DOWNLOAD_LIMITS, type Poller } from '../lib/selfUpdate.js'import { managedNodePath } from '../lib/nodeRuntime.js'import { startTuiUpdater } from '../tui/update.js'import { ensureManagedGrid, startGridPinRecheck } from '../lib/runtimeInstall.js'@@ -248,26 +249,32 @@ const ATTACH_CONCURRENCY = 4let SCRIPT_PATH = ''/**- * Start the daemon that succeeds this one, on whatever bytes are in `~/.harness/cli` right now.- *- * Extracted from `restartForUpdate`'s own closure so the update handoff, the rollback respawn and the- * BOOT handoff below all spawn the same way. Not to be confused with the module's `spawnDaemon`: that- * one serves `harness start`, reads the pid file, finds THIS daemon in it and exits — called from- * inside the daemon it would quietly do nothing and lose the update.- *- * `managedNodePath()` is re-read here rather than captured at boot, so a runtime provisioned during- * this process's lifetime is the one the next daemon runs on.+ * Start harnessd's master, detached, on the bundle on disk, and name it in the pid file: how a core on its+ * own hands the machine to a newer build (core/updateHandoff.ts); the master judges it. Named at once, so a+ * `harness start` in the seconds after this core leaves finds a live daemon and starts no second master,+ * whose core would lose to this one's and roll the update back. Not `harness start`'s `spawnDaemon`, which+ * finds THIS daemon in the pid file and exits. The managed Node is re-read, so a runtime provisioned while+ * this ran is the master's. `ADAPTER_UPDATED_TO` (an older build's handoff) and `HARNESSD_SAFE_MODE` (a+ * master's word to its own core) are not for the master to pass to every core it starts.*/-function spawnDaemonChild(extraEnv: Record<string, string>): ReturnType<typeof spawn> {- prepareLogFile(LOG_FILE, LEGACY_LOG_FILE) // before the fd, so the caller's sinceOffset sees one size- const fd = openSync(LOG_FILE, 'a')- const child = spawn(managedNodePath(), [SCRIPT_PATH, '__run'], {- detached: true, env: { ...process.env, ...extraEnv }, stdio: ['ignore', fd, fd],- })+function startMasterHere(): void {+ // A log that cannot be opened (a full disk) costs the master's lines, never the handoff.+ let log: number | 'ignore' = 'ignore'+ try {+ prepareLogFile(LOG_FILE, LEGACY_LOG_FILE)+ log = openSync(LOG_FILE, 'a')+ } catch (e) { console.error('[update] the master starts without the log:', e instanceof Error ? e.message : e) }+ const { ADAPTER_UPDATED_TO: _handedOver, HARNESSD_SAFE_MODE: _safeMode, ...inherited } = process.env+ const master = spawn(managedNodePath(), [SCRIPT_PATH, '__harnessd'], { detached: true, env: inherited, stdio: ['ignore', log, log] })// A spawn failure (e.g. EMFILE) emits 'error' on the child; with no listener that is an- // uncaughtException. Catch it so a failed restart can't take the daemon that asked for it down.- child.on('error', (e) => console.error('[update] daemon spawn error:', e instanceof Error ? e.message : e))- return child+ // uncaughtException. This core is leaving either way, and the next `harness start` starts the daemon.+ master.on('error', (e) => console.error('[update] master spawn error:', e instanceof Error ? e.message : e))+ master.unref()+ try {+ if (master.pid) writeFileSync(PID_FILE, `${master.pid}\n`)+ else removePidFileIf(process.pid)+ } catch { /* the master claims it itself once its core has bound */ }+ console.log(`[update] harnessd's master started (pid ${master.pid ?? '?'})`)}/**@@ -308,12 +315,14 @@ const daemonBoot: {* SYNCHRONOUS END TO END, and that is the whole safety argument: never awaiting means the half-built* `runForeground` body cannot interleave between the port closing and the exit, so it can never* reach the code that would bind the port the successor is about to take, and two daemons are- * impossible by construction. That is also why it does not supervise the child the way- * `restartForUpdate` does — waiting would leave this process running alongside the new one for up to- * a minute, both reconciling tmux and writing the registry.+ * impossible by construction. That is also why it does not wait for the master to claim the pid file the+ * way `restartForUpdate` does — waiting would leave this process running alongside the new core, both+ * reconciling tmux and writing the registry.*- * It spawns rather than merely exiting because on a machine with no desktop app nothing else would- * ever start the successor, and even with one the next spawn window is up to ~70s away.+ * Without a master it spawns one rather than merely exiting, because on a machine with no desktop app+ * nothing else would ever start the successor, and even with one the next spawn window is up to ~70s+ * away. The master judges the update it starts on (core/updateHandoff.ts); the core this once spawned+ * instead ran it unjudged.*/function bootHandoff(version: string): void {if (daemonBoot.handingOff) return@@ -334,76 +343,18 @@ function bootHandoff(version: string): void {try { daemonBoot.hookServer?.close() } catch { /* already gone */ }try { daemonBoot.localSocket?.closeSync() } catch { /* already gone */ }},- // Only if it still names us — a no-op when start-up never got as far as claiming it.- removePidFile: () => { removePidFileIf(process.pid) },- spawn: (extraEnv) => spawnDaemonChild(extraEnv),+ // Synchronous, as all of this is: start-up has not finished, and has nothing to serve meanwhile.+ probeMaster: () => {+ const probe = spawnSync(managedNodePath(), [SCRIPT_PATH, PROBE_COMMAND], { encoding: 'utf8', timeout: PROBE_TIMEOUT_MS })+ return probeVerdict(probe.error ?? (probe.status === 0 ? null : new Error(probe.signal ? `signal ${probe.signal}` : `exit ${probe.status}`)), probe.stdout ?? '')+ },+ rollBack: () => restoreUpdate(env.ADAPTER_CLI_DIR),+ startMaster: startMasterHere,exit: (code) => process.exit(code),log: (message) => console.log(message),})}-/**- * The update handoff of a core run on its own (core/updateHandoff.ts, once the teardown is done): hand- * off to a freshly spawned daemon running the just-swapped cli.js, then SUPERVISE it and roll back to the- * .prev bytes if it fails to come up. NOT launch() — that refuses while a daemon is alive.- *- * Runs under the spawn lock for its whole length (the updater's `withLock` wraps the staging and this- * together), so no `harness start` can spawn into the seconds where the port is free and the pid file- * names nothing. `track` names the child a signal mid-handoff must take down with us, rather than leave- * two daemons — see shutdown(); null the moment the handoff is CONFIRMED, when that child is the daemon.- */-async function handOffWithoutMaster(newVersion: string, track: (child: HandoffChild | null) => void): Promise<void> {- const sinceOffset = existsSync(LOG_FILE) ? statSync(LOG_FILE).size : 0- const child = spawnDaemonChild({ ADAPTER_UPDATED_TO: newVersion })- track(child)- let childExited = false- child.on('exit', () => { childExited = true })-- // Two phases. First the child has to BIND the port — it claims the pid file itself at that- // moment, and nothing else writes that file any more. A child that exits or stalls before then- // is a bad build (or a port it could not take): roll back at once instead of burning the whole- // connect window on it. Then, bound, wait for the backend: KEEP on connected/unreachable/busy- // (the new build RAN), ROLL BACK only on `fatal`. unreachable = backend transient, not a bad build.- const bind = await waitForBind(child.pid ?? -1, () => childExited, BIND_WAIT_MS, launchDeps)- const ready = bind === 'bound' ? await waitForReady(sinceOffset, 30_000, launchDeps) : null- if (bind === 'bound' && !childExited && ready?.state !== 'fatal') {- // Confirmed: it is the daemon now. Let go of it BEFORE anything else — a SIGTERM landing between- // here and the exit below must not take it down with us (see shutdown()).- track(null)- child.unref()- confirmUpdate(env.ADAPTER_CLI_DIR) // drop the .prev backups- console.log(`[update] now running ${newVersion} (pid ${child.pid})`)- process.exit(0)- }- console.error(`[update] new build failed to start (${bind !== 'bound' ? bind : childExited ? 'exited' : ready?.state}) — rolling back`)- try { if (child.pid) process.kill(child.pid, 'SIGKILL') } catch { /* ignore */ }- // A killed child cannot remove its own pid file; do it for it — but only once it is actually- // dead (SIGKILL is asynchronous, and a child mid-bind could still write the file after our- // removal) and only if it is still ITS file.- if (child.pid) {- const gone = Date.now() + 2_000- while (Date.now() < gone && isAlive(child.pid)) await new Promise((r) => setTimeout(r, 50))- }- removePidFileIf(child.pid)- restoreUpdate(env.ADAPTER_CLI_DIR) // restore .prev → cli.js/notify.mjs- const good = spawnDaemonChild({})- track(good)- let goodExited = false- good.on('exit', () => { goodExited = true })- // Hold the lock — and this process — until the rollback child has bound too. Exiting the moment it- // is spawned would free the lock while the port is still unclaimed, which is the window this whole- // arrangement exists to close. Nothing to do if it fails: the .prev bytes were the build that was- // running a minute ago, and `harness start` can be tried by hand.- const goodBind = await waitForBind(good.pid ?? -1, () => goodExited, BIND_WAIT_MS, launchDeps)- if (goodBind !== 'bound') console.error(`[update] rollback build did not come up either (${goodBind}) — run harness start`)- good.unref()- process.exit(0)-}--/** The log-tail readiness classifier and the two-phase wait live in lib/daemonLaunch.ts — see there.- * `launchDeps` binds them to this process's log file and port. */-const launchDeps = defaultLaunchDeps(LOG_FILE, daemonPort())-/** Set by runForeground once the DSH companions exist; a frame projected before that carries none. */let activityFrameContextRef: ((s: RegisteredSession) => ActivityFrame | null) | null = null@@ -506,7 +457,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {// a successor it is judging down with us.const updateHandoff = createUpdateHandoff({version: VERSION, supervised: coreLink.supervised, exitForUpdate: () => process.exit(CORE_EXIT_UPDATE),- handOff: handOffWithoutMaster, log: (line) => console.log(line), error: (line) => console.error(line),+ // A core on its own: the staged bundle's master must answer its probe, as a master asks before it+ // re-executes on one; then a master takes the machine, and judges the update.+ probeMaster: () => probeStagedMaster((done) => execFile(managedNodePath(), [SCRIPT_PATH, PROBE_COMMAND], { encoding: 'utf8' }, (error, stdout) => done(error, stdout))),+ rollBack: () => restoreUpdate(env.ADAPTER_CLI_DIR),+ handOff: () => { startMasterHere(); process.exit(0) },+ log: (line) => console.log(line), error: (line) => console.error(line),})// Another daemon serves this data folder: leave before reading or writing anything of its — its@@ -2435,7 +2391,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {}// ── self-update: a staged bundle restarts the daemon IMMEDIATELY (core/updateHandoff.ts, and- // handOffWithoutMaster for a core run on its own). The handler stops being `bootHandoff` HERE, and not a+ // handOffToMaster for a core run on its own). The handler stops being `bootHandoff` HERE, and not a// line earlier: everything the teardown releases exists by now. A straight-line assignment, never a// wait: if the body never reaches this line the handler stays `bootHandoff`, and the fix still lands.daemonBoot.applyStagedUpdate = (v) => updateHandoff.restartForUpdate(v, [@@ -2457,27 +2413,16 @@ async function runForeground(session: AuthSession | null): Promise<void> {['the viewers', () => ports.viewers?.stop()], ['the gateway', () => gateway.stop()],// A graceful close releases the backend's one-machine claim, given a moment before the reclaim.['the backend', () => backend.stop()], ['a grace', () => new Promise((r) => setTimeout(r, 1000))],- ]).catch((err) => {- // Only without a master: a step or the successor failed before anything was handed over.- console.error('[update] restart failed — staying on current build:', err instanceof Error ? err.message : err)- updateHandoff.abandon()- })+ ])/** Stopping for good — removed from the account, or connected from elsewhere: tell harnessd's master,* which restarts any other exit (harnessd/protocol.ts). */const forGood = (reason: string): boolean => reason === 'revoked' || reason === 'busy'const shutdown = async (signal: string): Promise<void> => {console.log(`\n[cli] ${signal} — shutting down`)- // Mid-handoff everything below has already been torn down once, and the daemon that matters is- // the child being supervised. Take it down with us and leave — a second teardown of closed servers- // is noise, and a child left running would be a daemon nothing manages.+ // Mid-handoff everything below is already being torn down, and nothing has been started yet: leave+ // — a second teardown of closed servers is noise.if (updateHandoff.restarting()) {- const child = updateHandoff.child() // null once the handoff was confirmed — that daemon stays up- if (child?.pid) {- console.log(`[cli] ${signal} during an update handoff — stopping the new daemon (pid ${child.pid}) too`)- try { process.kill(child.pid, 'SIGTERM') } catch { /* ignore */ }- removePidFileIf(child.pid)- }try { if (readPid() === process.pid) rmSync(PID_FILE, { force: true }) } catch { /* ignore */ }process.exit(0)}@@ -2872,7 +2817,7 @@ export function runCore(scriptPath: string): void {runForeground(readAuthSession()).catch(enterSafeMode)}-/** `harness start -f`, and a start under tsx: the core in the process of the command that asked for it. */+/** `harness start -f` with `HARNESS_NO_MASTER=1`, and a start under tsx: the core alone, in the process of the command that asked for it. */export function runCoreInForeground(session: AuthSession | null, scriptPath: string): Promise<void> {SCRIPT_PATH = scriptPathreturn runForeground(session)diff --git a/cli/src/core/updateHandoff.spec.ts b/cli/src/core/updateHandoff.spec.tsindex 2319d1b19..547a4aa2d 100644--- a/cli/src/core/updateHandoff.spec.ts+++ b/cli/src/core/updateHandoff.spec.ts@@ -1,27 +1,23 @@import { afterEach, describe, expect, it, vi } from 'vitest'-import { TEARDOWN_DEADLINE_MS, createUpdateHandoff, type HandoffChild, type TeardownStep, type UpdateHandoffDeps } from './updateHandoff.js'+import { PROBE_ANSWER } from '../harnessd/protocol.js'+import { TEARDOWN_DEADLINE_MS, createUpdateHandoff, probeStagedMaster, probeVerdict, type TeardownStep, type UpdateHandoffDeps } from './updateHandoff.js'describe('the update handoff', () => {afterEach(() => { vi.useRealTimers() })const make = (over: Partial<UpdateHandoffDeps> = {}) => {const calls: string[] = []- const tracked: Array<HandoffChild | null> = []const handoff = createUpdateHandoff({version: '1.0.0', supervised: true,exitForUpdate: () => calls.push('exit 75'),- handOff: async (version, track) => {- calls.push(`hand off ${version}`)- track({ pid: 42 })- tracked.push(handoff.child())- track(null)- tracked.push(handoff.child())- },+ probeMaster: async () => { calls.push('probe the master'); return null },+ rollBack: () => calls.push('roll back'),+ handOff: () => calls.push('start a master, exit'),log: (line) => calls.push(line),error: (line) => calls.push(line),...over,})- return { handoff, calls, tracked }+ return { handoff, calls }}const step = (calls: string[], name: string, release: () => unknown = () => {}): TeardownStep => [name, () => { calls.push(`release ${name}`); return release() }]@@ -72,21 +68,69 @@ describe('the update handoff', () => {expect(plain.calls.at(-1)).toBe('exit 75')})- it('without a master, releases in order, hands off, and tracks the successor until it is the daemon', async () => {- const { handoff, calls, tracked } = make({ supervised: false })- expect(handoff.child()).toBeNull()- await handoff.restartForUpdate('2.0.0', [step(calls, 'the registry'), step(calls, 'the backend')])- expect(calls).toEqual(['[update] applying 1.0.0 → 2.0.0 — restarting daemon', 'release the registry', 'release the backend', 'hand off 2.0.0'])- expect(tracked).toEqual([{ pid: 42 }, null])- })-- it('without a master, stops at a step that fails, hands nothing over, and lets this core carry on once abandoned', async () => {+ it('without a master, gives the machine to a master on the staged build once its master answers, after the same teardown', async () => {const { handoff, calls } = make({ supervised: false })- await expect(handoff.restartForUpdate('2.0.0', [step(calls, 'the timers', () => { throw new Error('no') }), step(calls, 'the backend')])).rejects.toThrow('no')- expect(calls).toEqual(['[update] applying 1.0.0 → 2.0.0 — restarting daemon', 'release the timers'])- expect(handoff.restarting()).toBe(true)- handoff.abandon()+ const done = handoff.restartForUpdate('2.0.0', [step(calls, 'the registry'), step(calls, 'the backend', () => { throw new Error('no') })])+ // Asked before anything is let go: the core serves on meanwhile.expect(handoff.restarting()).toBe(false)- expect(handoff.child()).toBeNull()+ await handoff.restartForUpdate('2.0.0', [])+ await done+ expect(handoff.restarting()).toBe(true)+ expect(calls).toEqual([+ '[update] applying 1.0.0 → 2.0.0 — restarting daemon', 'probe the master', 'release the registry', 'release the backend',+ '[update] the backend did not let go (no) — handing over all the same',+ '[update] handing 2.0.0 to a harnessd master, which judges it — this core is leaving', 'start a master, exit',+ ])+ })++ it('without a master, rolls a build whose master does not answer back, and hands this build to a master of its own', async () => {+ const { handoff, calls } = make({ supervised: false, probeMaster: async () => 'harnessd-probe failed: a bad build' })+ await handoff.restartForUpdate('2.0.0', [step(calls, 'the registry')])+ expect(calls).toEqual([+ '[update] applying 1.0.0 → 2.0.0 — restarting daemon',+ '[update] 2.0.0\'s master did not answer its probe (harnessd-probe failed: a bad build) — rolled back; this build goes on under a master of its own',+ 'roll back', 'release the registry',+ '[update] handing 1.0.0 to a harnessd master, which judges it — this core is leaving', 'start a master, exit',+ ])+ })++ it('under harnessd, asks no probe: the master asks its own before it re-executes', async () => {+ const { handoff, calls } = make()+ await handoff.restartForUpdate('2.0.0', [])+ expect(calls).not.toContain('probe the master')+ })+})++describe('the probe of a staged bundle\'s master', () => {+ /** A probe that ends as told, and the deadline it is given. */+ const run = (error: Error | null, stdout: string) => {+ const killed: string[] = []+ return { killed, probe: (done: (error: Error | null, stdout: string) => void) => { queueMicrotask(() => done(error, stdout)); return { kill: () => killed.push('kill') } } }+ }++ it('passes a master that answers, and says why one did not', async () => {+ expect(await probeStagedMaster(run(null, `starting\n${PROBE_ANSWER} · protocol 2 · v2.0.0\n`).probe)).toBeNull()+ expect(await probeStagedMaster(run(new Error('exit 1'), 'harnessd-probe failed: no supervisor\n').probe)).toBe('harnessd-probe failed: no supervisor')+ expect(await probeStagedMaster(run(new Error('Command failed: exit 1'), '').probe)).toBe('Command failed: exit 1')+ // An exit 0 that never says it is a master is no answer: a bundle from before probes prints its usage.+ expect(await probeStagedMaster(run(null, '').probe)).toBe('no answer')+ })++ it('judges a probe\'s end alike, however it was run', () => {+ expect(probeVerdict(null, `${PROBE_ANSWER} · protocol 2`)).toBeNull()+ expect(probeVerdict(undefined, `${PROBE_ANSWER}`)).toBeNull()+ expect(probeVerdict(new Error('exit 1'), `${PROBE_ANSWER}`)).toBe(PROBE_ANSWER)+ expect(probeVerdict(new Error('signal SIGKILL'), '')).toBe('signal SIGKILL')+ })++ it('kills a probe that does not answer within its deadline, counted in running time', async () => {+ let expire = (): void => {}+ const deadline = vi.fn((_ms: number, fire: () => void) => { expire = fire; return () => {} })+ const killed: string[] = []+ const answer = probeStagedMaster(() => ({ kill: () => killed.push('kill') }), 1_000, deadline)+ expect(deadline.mock.calls[0][0]).toBe(1_000)+ expire()+ expect(await answer).toBe('no answer within 1000 ms')+ expect(killed).toEqual(['kill'])})})diff --git a/cli/src/core/updateHandoff.ts b/cli/src/core/updateHandoff.tsindex 1a8075ac9..b91815608 100644--- a/cli/src/core/updateHandoff.ts+++ b/cli/src/core/updateHandoff.ts@@ -9,8 +9,12 @@* (e2e/updateHostile.e2e.ts, round 40). Now every step is tried, one that fails is said and passed, and* the core exits 75 whatever happened; one that hangs is given up on after `TEARDOWN_DEADLINE_MS`.*- * Without a master (a core run on its own) the old way stands: the first step that fails ends the- * handoff, and `handOff` spawns the successor and judges it itself.+ * Without a master (a core an older release's own handoff started, e2e/migration.e2e.ts, or+ * `HARNESS_NO_MASTER=1`) the core gives the machine to one, which judges the build as every update: the+ * staged bundle's master must answer its probe first, as before a re-execution (harnessd/reexec.ts), or the+ * build before goes back, rejected; then the same teardown, and `handOff` starts `__harnessd` and exits.+ * The master finds the pending note and puts its first core on probation (harnessd/supervisor.ts,+ * `unjudgedUpdate`). The core once spawned a core like itself and judged it, which then had no master.** Staged means restart now. The restart once waited for the computer to go idle, and "idle" is a set of* latches (an open turn, a settling composer, an awaited submit, the control lock, a recap in flight):@@ -21,12 +25,12 @@* Moved out of `runForeground` (src/architecture.spec.ts).*/+import { patientDeadline } from '../lib/patientExec.js'+import { PROBE_ANSWER, PROBE_TIMEOUT_MS } from '../harnessd/protocol.js'+/** One thing the next core needs released, named for the log. */export type TeardownStep = readonly [name: string, release: () => unknown]-/** The successor a handoff without a master spawned, which a signal must take down with this core. */-export interface HandoffChild { pid?: number }-/** How long the teardown may take before the core hands over all the same: it takes about a second. */export const TEARDOWN_DEADLINE_MS = 15_000@@ -37,19 +41,21 @@ export interface UpdateHandoffDeps {supervised: boolean/** Exit for the update (`CORE_EXIT_UPDATE`), to the master that starts the new bundle. */exitForUpdate(): void- /**- * The handoff without a master: spawn the successor on the staged bundle, keep it or roll back.- * `track` names the successor a signal must take down with this core, and null once it is the daemon.- */- handOff(newVersion: string, track: (child: HandoffChild | null) => void): Promise<void>+ /** Without a master: whether the staged bundle's master answers its probe (`probeStagedMaster`); null when+ * it does, why not otherwise. */+ probeMaster(): Promise<string | null>+ /** Without a master: put the build before back (`selfUpdate.restore`), remembering this one as rejected. */+ rollBack(): void+ /** Without a master: start harnessd's master on the bundle now on disk, name it in the pid file, exit. */+ handOff(): voidlog(line: string): voiderror(line: string): voidteardownDeadlineMs?: number}export function createUpdateHandoff(deps: UpdateHandoffDeps) {+ let started = falselet restarting = false- let child: HandoffChild | null = nullconst deadlineMs = deps.teardownDeadlineMs ?? TEARDOWN_DEADLINE_MSconst message = (error: unknown): string => error instanceof Error ? error.message : String(error)@@ -75,36 +81,61 @@ export function createUpdateHandoff(deps: UpdateHandoffDeps) {}return {- /** Between an update being staged and this core leaving (`/api/status`, and a signal mid-handoff). */+ /** Between the teardown starting and this core leaving (`/api/status`, and a signal mid-handoff). */restarting: (): boolean => restarting,- /** The successor a handoff without a master is judging, until it is the daemon. */- child: (): HandoffChild | null => child,- /**- * Hand over to `newVersion`, releasing `teardown` first. Once: a second call while one is under way- * does nothing. Rejects only without a master, when a step failed or the successor could not be- * started; then `abandon` lets this core carry on.- */+ /** Hand over to `newVersion`, releasing `teardown` first. Once: a second call while one is under way does nothing. */async restartForUpdate(newVersion: string, teardown: readonly TeardownStep[]): Promise<void> {- if (restarting) return- restarting = true+ if (started) return+ started = truedeps.log(`[update] applying ${deps.version} → ${newVersion} — restarting daemon`)+ // Asked before anything is let go: the core serves on while it answers.+ const refused = deps.supervised ? null : await deps.probeMaster()+ if (refused !== null) {+ deps.error(`[update] ${newVersion}'s master did not answer its probe (${refused}) — rolled back; this build goes on under a master of its own`)+ deps.rollBack()+ }+ restarting = true+ await releaseAll(teardown)if (deps.supervised) {- await releaseAll(teardown)// Everything above is released, or said not to be; the master starts the new bundle as soon as// this exits and rolls back to the .prev bytes if it does not come up and stay up.deps.log(`[update] handing ${newVersion} to harnessd`)deps.exitForUpdate()return}- for (const [, release] of teardown) await release()- await deps.handOff(newVersion, (successor) => { child = successor })- },- /** A handoff without a master that failed before it handed anything over: this core stays. */- abandon(): void {- restarting = false- child = null+ deps.log(`[update] handing ${refused === null ? newVersion : deps.version} to a harnessd master, which judges it — this core is leaving`)+ deps.handOff()},}}export type UpdateHandoff = ReturnType<typeof createUpdateHandoff>++/** Run the staged bundle's master probe (`node cli.js __harnessd-probe`); `done` gets how it ended. */+export type ProbeRun = (done: (error: Error | null, stdout: string) => void) => { kill(): void }++/**+ * Whether the staged bundle's master answers its probe: null when it does, why not otherwise. Its deadline+ * counts only time this process ran (`patientDeadline`), as the canary's does: a lid closed mid-probe must+ * not reject a good build.+ */+export function probeStagedMaster(run: ProbeRun, timeoutMs = PROBE_TIMEOUT_MS, deadline = patientDeadline): Promise<string | null> {+ return new Promise((resolve) => {+ let probe: { kill(): void } | null = null+ const cancel = deadline(timeoutMs, () => {+ probe?.kill()+ resolve(`no answer within ${timeoutMs} ms`)+ })+ probe = run((error, stdout) => {+ cancel()+ resolve(probeVerdict(error, stdout))+ })+ })+}++/** What a master probe's end says: null when it answered as a master, why not otherwise. Shared by the+ * boot handoff's synchronous probe (lib/daemonSafeMode.ts `runBootHandoff`). */+export function probeVerdict(error: Error | null | undefined, stdout: string): string | null {+ if (!error && stdout.includes(PROBE_ANSWER)) return null+ return stdout.trim().split('\n').pop()?.trim() || error?.message || 'no answer'+}diff --git a/cli/src/harnessd/protocol.ts b/cli/src/harnessd/protocol.tsindex d0756f1c4..82ea3cb1c 100644--- a/cli/src/harnessd/protocol.ts+++ b/cli/src/harnessd/protocol.ts@@ -15,6 +15,12 @@ import type { SupervisorStatus } from './supervisor.js'/** 2: `ready`, the event-loop delay on the heartbeat, and the exit-code contract below. */export const HARNESSD_PROTOCOL = 2+/** The command a bundle's master answers its probe on, and what it answers. */+export const PROBE_COMMAND = '__harnessd-probe'+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+/** 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.ts b/cli/src/harnessd/reexec.tsindex 0ce264298..06ef5c126 100644--- a/cli/src/harnessd/reexec.ts+++ b/cli/src/harnessd/reexec.ts@@ -27,15 +27,14 @@import { spawn, type ChildProcess } from 'node:child_process'import { createHash } from 'node:crypto'import { readFileSync, 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'/** The environment variable that hands a master's state to the one it re-executes as. */export const RESUME_ENV = 'HARNESSD_RESUME'-/** The command a bundle's master answers its probe on, and what it answers. */-export const PROBE_COMMAND = '__harnessd-probe'-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+/** Asked by a core on its own too, before it hands an update to a master (core/updateHandoff.ts): in+ * ./protocol.ts, which the core's process loads anyway, where this module it does not need is not. */+export { PROBE_ANSWER, PROBE_COMMAND, PROBE_TIMEOUT_MS } from './protocol.js'/*** This many re-executions in a row without a core coming up, and the master keeps its code: each new* master found yet another bundle before it could start one, and following them would be a loop. Andiff --git a/cli/src/lib/daemonSafeMode.spec.ts b/cli/src/lib/daemonSafeMode.spec.tsindex 665d34896..d08f0f2fe 100644--- a/cli/src/lib/daemonSafeMode.spec.ts+++ b/cli/src/lib/daemonSafeMode.spec.ts@@ -84,24 +84,31 @@ describe('the safe-mode marker', () => {describe('runBootHandoff', () => {function harness(over: Partial<BootHandoffDeps> = {}) {const calls: string[] = []- let env: Record<string, string> = {}let exited: number | null = nullconst deps: BootHandoffDeps = {closeServer: () => calls.push('close'),- removePidFile: () => calls.push('removePid'),- spawn: (extra) => { calls.push('spawn'); env = extra; return { pid: 999, unref: () => calls.push('unref') } },+ probeMaster: () => { calls.push('probe'); return null },+ rollBack: () => calls.push('roll back'),+ startMaster: () => calls.push('start the master'),exit: ((code: number) => { calls.push(`exit:${code}`); exited = code; return undefined as never }),log: () => {},...over,}- return { deps, calls, env: () => env, exited: () => exited }+ return { deps, calls, exited: () => exited }}- it('releases the port, then the pid file, then spawns the successor and leaves', () => {+ it('probes the new build\'s master, releases the port, then starts the master on the new build, and leaves', () => {const h = harness()runBootHandoff('0.3.5', '0.3.6', h.deps)- expect(h.calls).toEqual(['close', 'removePid', 'spawn', 'unref', 'exit:0'])- expect(h.env()).toEqual({ ADAPTER_UPDATED_TO: '0.3.6' })+ expect(h.calls).toEqual(['probe', 'close', 'start the master', 'exit:0'])+ })++ it('rolls a build whose master does not answer back, and starts this build\'s master instead', () => {+ const lines: string[] = []+ const h = harness({ probeMaster: () => 'harnessd-probe failed: a bad build', log: (m) => lines.push(m) })+ runBootHandoff('0.3.5', '0.3.6', h.deps)+ expect(h.calls).toEqual(['roll back', 'close', 'start the master', 'exit:0'])+ expect(lines[1]).toBe('[update] 0.3.6\'s master did not answer its probe (harnessd-probe failed: a bad build) — rolled back; 0.3.5 goes on under a master of its own')})it('has already exited by the time it returns — the property that makes two daemons impossible', () => {@@ -112,17 +119,11 @@ describe('runBootHandoff', () => {expect(h.exited()).toBe(0) // no await, no tick: true immediately after the call returns})- it('a start-up that never bound or claimed anything still hands off', () => {- const h = harness({ closeServer: () => {}, removePidFile: () => {} })- runBootHandoff('0.3.5', '0.3.6', h.deps)- expect(h.calls).toEqual(['spawn', 'unref', 'exit:0'])- })-- it('says which pid took over, so the log names the successor', () => {+ it('says what it hands over, and to whom', () => {const lines: string[] = []const h = harness({ log: (m) => lines.push(m) })runBootHandoff('0.3.5', '0.3.6', h.deps)expect(lines[0]).toContain('0.3.5 → 0.3.6')- expect(lines[1]).toContain('pid 999')+ expect(lines[0]).toContain('harnessd\'s master')})})diff --git a/cli/src/lib/daemonSafeMode.ts b/cli/src/lib/daemonSafeMode.tsindex cfaa65706..3962be854 100644--- a/cli/src/lib/daemonSafeMode.ts+++ b/cli/src/lib/daemonSafeMode.ts@@ -114,8 +114,13 @@ export function clearSafeModeMarker(dataDir: string): void {export interface BootHandoffDeps {/** The bound control port, if start-up ever got that far. */closeServer: () => void- removePidFile: () => void- spawn: (extraEnv: Record<string, string>) => { pid?: number; unref: () => void }+ /** Whether the staged bundle's master answers its probe, synchronously: null when it does, why not otherwise. */+ probeMaster: () => string | null+ /** Put the build before back (`selfUpdate.restore`), remembering this one as rejected. */+ rollBack: () => void+ /** Start harnessd's master on the bundle now on disk, named in the pid file: it starts the core, and+ * judges the update. */+ startMaster: () => voidexit: (code: number) => neverlog: (message: string) => void}@@ -130,16 +135,23 @@ export interface BootHandoffDeps {* would leave this process running alongside the new one for up to a minute, both reconciling tmux* and writing the registry.*- * It spawns rather than merely exiting because nothing supervises a daemon: on a machine with no- * desktop app nothing else would ever start the successor.+ * It spawns rather than merely exiting because nothing supervises this core: on a machine with no+ * desktop app nothing else would ever start the successor. What it spawns is harnessd's master, which+ * judges the update its core starts on; the core it once spawned ran the update unjudged. The staged+ * bundle's master is probed first, as a master asks before it re-executes on a new bundle, and+ * synchronously like the rest: one that cannot start would leave nothing running and nothing to judge, so+ * the build before goes back and its master is started instead.*/export function runBootHandoff(from: string, to: string, deps: BootHandoffDeps): void {- deps.log(`[update] ${from} → ${to} staged during start-up — handing off without finishing boot`)+ deps.log(`[update] ${from} → ${to} staged during start-up — handing off to harnessd's master without finishing boot`)+ const refused = deps.probeMaster()+ if (refused !== null) {+ deps.log(`[update] ${to}'s master did not answer its probe (${refused}) — rolled back; ${from} goes on under a master of its own`)+ deps.rollBack()+ }deps.closeServer()- deps.removePidFile()- const child = deps.spawn({ ADAPTER_UPDATED_TO: to })- child.unref()- deps.log(`[update] boot handoff → pid ${child.pid ?? '?'} · this process is leaving`)+ deps.startMaster()+ deps.log('[update] boot handoff · this process is leaving')deps.exit(0)}diff --git a/cli/src/masterProcess.spec.ts b/cli/src/masterProcess.spec.tsindex 944671581..65c6dd379 100644--- a/cli/src/masterProcess.spec.ts+++ b/cli/src/masterProcess.spec.ts@@ -11,7 +11,7 @@ const leanBundle = vi.hoisted(() => ({ read: vi.fn((_bundle: Buffer): LeanBundlevi.mock('./harnessd/leanBundle.js', async (real) => ({ ...await real<object>(), readLeanBundle: (bundle: Buffer) => leanBundle.read(bundle) }))const {- BUNDLE_ENV, BUNDLE_SHA256_ENV, LEAN_DIR, LEAN_FINGERPRINT_ENV, LEAN_OFF_FILE, probeLean, probeThisMaster, processBundleDeps, startMaster, startMasterFromBundle,+ BUNDLE_ENV, BUNDLE_SHA256_ENV, LEAN_DIR, LEAN_FINGERPRINT_ENV, LEAN_OFF_FILE, probeLean, probeThisMaster, processBundleDeps, startMaster, startMasterFromBundle, startMasterInForeground,} = await import('./masterProcess.js')type Deps = Parameters<typeof startMasterFromBundle>[1] & object@@ -197,6 +197,18 @@ describe('starting the master', () => {} finally { rmSync(folder, { recursive: true, force: true }) }})+ it('runs in the foreground as launchd runs it: a bundle as one, the sources as cli.ts runs them', () => {+ const calls: unknown[] = []+ const start = { fromBundle: (bundle: string) => { calls.push(['bundle', bundle]) }, fromSources: (given: unknown) => { calls.push(['sources', given]) } }+ startMasterInForeground('/cli/cli.js', start)+ startMasterInForeground('/checkout/cli/src/cli.ts', start)+ expect(calls).toEqual([['bundle', '/cli/cli.js'], ['sources', { scriptPath: '/checkout/cli/src/cli.ts' }]])+ // By default, the two ways a master starts: from the bundle (entry.ts's `__harnessd`), or as cli.ts runs it.+ runMaster.mockClear()+ startMasterInForeground('/checkout/cli/src/cli.ts')+ expect(runMaster.mock.calls[0][0]).toMatchObject({ scriptPath: '/checkout/cli/src/cli.ts' })+ })+it('answers the probe a re-executing master asks', () => {const log = vi.spyOn(console, 'log').mockImplementation(() => {})expect(probeThisMaster()).toBe(0)diff --git a/cli/src/masterProcess.ts b/cli/src/masterProcess.tsindex cbc32c786..e75b84ff0 100644--- a/cli/src/masterProcess.ts+++ b/cli/src/masterProcess.ts@@ -78,6 +78,22 @@ export function startMaster(start: MasterStart, exit: (code: number) => void = (})}+/**+ * `harness start -f`, for a supervisor (launchd, systemd, a terminal): the master in this process, as+ * launchd and systemd run it (`__harnessd`, entry.ts), the core and the services its children, their lines+ * on this process's output. The core used to run here on its own, and a core with no master has to hand+ * each update over itself (docs/design/2026-10-06-core-boundary-next.md, "Updaters"). A bundle+ * re-executes on the lean bundle it carries, same pid, as a master launchd starts does; the sources have+ * none, and run as cli.ts's `__harnessd` runs them.+ */+export function startMasterInForeground(+ scriptPath: string,+ start: { fromBundle: (bundlePath: string) => void; fromSources: (start: MasterStart) => unknown } = { fromBundle: startMasterFromBundle, fromSources: startMaster },+): void {+ if (scriptPath.endsWith('.ts')) start.fromSources({ scriptPath })+ else start.fromBundle(scriptPath)+}+/** Whether this bundle can run a master that takes over from the running one; the exit code. */export function probeThisMaster(): number {return probeMaster({ env: process.env, execArgv: process.execArgv, version: VERSION })diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.mdindex 1ad8d53cf..b0df4bdbf 100644--- a/docs/design/2026-10-03-harnessd.md+++ b/docs/design/2026-10-03-harnessd.md@@ -331,7 +331,10 @@ Built for the core ([`harnessd/`](../../cli/src/harnessd/), spawn protocol 2): rbinding, with a start-up deadline; the heartbeat watch; the exit-code contract; exit reasons;crash-loop safe mode; the heap and resident budgets; the status file; log trimming in the master; andupdates with probation from ready and rollback — a broken update that falls into safe mode rolls back-too. `HARNESS_NO_MASTER=1` runs the core on its own. What follows is the design the master is held to;+too. `HARNESS_NO_MASTER=1` runs the core on its own; `harness start -f` runs the master in the foreground,+as launchd and systemd do. A core on its own (that switch, or a core an older release's own handoff+started) hands an update to a master on the new build, which judges it (`core/updateHandoff.ts`); it no+longer spawns and judges a core like itself. What follows is the design the master is held to;the parts still to build say so.- **Ready is not bound.** The core says `bound` when its port is listening and `ready` when start-updiff --git a/os/root/usr/lib/systemd/user/harness-daemon.service b/os/root/usr/lib/systemd/user/harness-daemon.serviceindex bac03be9c..59e7e1f6f 100644--- a/os/root/usr/lib/systemd/user/harness-daemon.service+++ b/os/root/usr/lib/systemd/user/harness-daemon.service@@ -6,6 +6,10 @@ ConditionPathExists=!/etc/harness-liveType=execEnvironment=ADAPTER_UPDATE_DISABLE=trueEnvironment=HARNESS_OS=1+# `start --foreground` runs harnessd's master, as launchd does; here it keeps running the core alone, one+# process, as the memory and zram checks in os/tests measure it (self-update is off, so no update needs+# the master to judge it).+Environment=HARNESS_NO_MASTER=1Environment=HARNESS_TUI_BIN=/usr/lib/harness/hnEnvironment=PATH=%h/.local/bin:/usr/local/bin:/usr/binEnvironment=npm_config_prefix=%h/.local