Skip to content

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.

cli: `start --repair` provisions the managed runtimes beside a daemon that is already up

Kelvin681efb8bcaab
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 84a45125d..6c4ddf5e2 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -888,6 +888,10 @@ async function startCommand(foreground: boolean, repair: boolean = false): Promi
// lock, for the daemon that comes up while we are waiting our turn.
const running = readPid()
if (running && isAlive(running)) {
+ // `--repair` still does its provisioning here: it touches the managed runtimes, never the
+ // bundle, and the live daemon picks a grid laid down now up on its next resolve (see
+ // repairManagedRuntimes). Without this, a new pin could only be followed by a restart.
+ if (repair) await repairManagedRuntimes(false)
console.log(`machine already running (pid ${running}) — it auto-reconnects.`)
console.log(' check: harness status · stop: harness stop · update now: harness update')
process.exit(0)
@@ -5008,6 +5012,24 @@ const launchDeps = defaultLaunchDeps(LOG_FILE, daemonPort())
// ── daemon start / stop / status ───────────────────────────────────────────────────────────────
+/**
+ * `--repair`'s provisioning, in the open: the managed Node runtime (and the launcher that names it),
+ * then the managed grid. Returns the repaired Node, or null when there was nothing to repair.
+ *
+ * Called for the daemon a `start` is about to spawn — and for one that is ALREADY UP. The runtimes
+ * live beside the bundle, not in it, and the daemon reads `current-grid` on every resolve, so a grid
+ * laid down here is the one its next spawn runs, with no restart; the daemon's own call follows the
+ * pin quietly on every start (runForeground), and this is where a person watches it happen. A
+ * FOREGROUND start becomes the daemon itself and runForeground's own call prints to this same
+ * terminal — once is enough, so the grid step is skipped there.
+ */
+async function repairManagedRuntimes(foreground: boolean): Promise<string | null> {
+ const repaired = await ensureManagedRuntime((m) => console.log(m))
+ if (repaired) ensureLauncher(repaired, (m) => console.log(m))
+ if (!foreground) await ensureManagedGrid((m) => console.log(m))
+ return repaired
+}
+
/** Daemonize (or run inline) with the saved SSO session. */
async function launch(foreground: boolean, repair: boolean = false): Promise<void> {
const session = readAuthSession()
@@ -5017,16 +5039,8 @@ async function launch(foreground: boolean, repair: boolean = false): Promise<voi
// provisioning explicitly, for the rare machine whose launcher predates the managed runtime.
let runtimeNode: string | null = managedNodePath()
if (repair) {
- const repaired = await ensureManagedRuntime((m) => console.log(m))
- if (repaired) {
- runtimeNode = repaired
- ensureLauncher(repaired, (m) => console.log(m))
- }
- // The managed grid too, in the open, for the daemon this command is about to spawn: it follows
- // its pin quietly on every start (runForeground), and `--repair` is where a person watches it
- // happen. A FOREGROUND start becomes the daemon itself and runForeground's own call prints to
- // this same terminal — once is enough.
- if (!foreground) await ensureManagedGrid((m) => console.log(m))
+ const repaired = await repairManagedRuntimes(foreground)
+ if (repaired) runtimeNode = repaired
}
// Foreground mode (supervisor) OR dev/tsx (can't cleanly spawn a .ts detached) → run inline.
if (foreground || SCRIPT_PATH.endsWith('.ts')) {
diff --git a/cli/src/cliCommand.spec.ts b/cli/src/cliCommand.spec.ts
index 268bfdd4c..8ae53423a 100644
--- a/cli/src/cliCommand.spec.ts
+++ b/cli/src/cliCommand.spec.ts
@@ -1,5 +1,7 @@
-import { spawnSync } from 'child_process'
-import { mkdtempSync, rmSync } from 'fs'
+import { spawn, spawnSync } from 'child_process'
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
+import { createServer } from 'node:http'
+import type { AddressInfo } from 'node:net'
import { tmpdir } from 'os'
import { join } from 'path'
import { fileURLToPath } from 'url'
@@ -12,24 +14,58 @@ const dirs: string[] = []
afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })
-function run(...args: string[]) {
+/** A throwaway HOME for one CLI run; every path the CLI writes is under it. */
+function freshRoot(): string {
const root = mkdtempSync(join(tmpdir(), 'harness-cli-command-'))
dirs.push(root)
- return spawnSync(process.execPath, [TSX, CLI_SOURCE, ...args], {
- cwd: CLI_ROOT,
- encoding: 'utf8',
- env: {
- ...process.env,
- HOME: root,
- HARNESS_AUTH_DIR: join(root, 'auth'),
- ADAPTER_DATA_DIR: join(root, 'data'),
- ADAPTER_CLI_DIR: join(root, 'cli'),
- ADAPTER_COMPUTER_ID_FILE: join(root, 'computer-id'),
- ADAPTER_UPDATE_DISABLE: 'true',
- },
+ return root
+}
+
+function envFor(root: string, extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv {
+ return {
+ ...process.env,
+ HOME: root,
+ HARNESS_AUTH_DIR: join(root, 'auth'),
+ ADAPTER_DATA_DIR: join(root, 'data'),
+ ADAPTER_CLI_DIR: join(root, 'cli'),
+ ADAPTER_COMPUTER_ID_FILE: join(root, 'computer-id'),
+ ADAPTER_UPDATE_DISABLE: 'true',
+ ...extra,
+ }
+}
+
+function run(...args: string[]) {
+ return spawnSync(process.execPath, [TSX, CLI_SOURCE, ...args], { cwd: CLI_ROOT, encoding: 'utf8', env: envFor(freshRoot()) })
+}
+
+/** The same run, without blocking this process: a test that also SERVES the CLI something (a manifest on
+ * the loopback) has to keep its own event loop free while the child asks for it. */
+function runAsync(root: string, args: string[], extra: NodeJS.ProcessEnv): Promise<{ status: number | null; stdout: string; stderr: string }> {
+ return new Promise((resolve) => {
+ const child = spawn(process.execPath, [TSX, CLI_SOURCE, ...args], { cwd: CLI_ROOT, env: envFor(root, extra), stdio: ['ignore', 'pipe', 'pipe'] })
+ let stdout = ''
+ let stderr = ''
+ child.stdout.on('data', (chunk: Buffer) => { stdout += chunk.toString() })
+ child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString() })
+ child.on('close', (status) => resolve({ status, stdout, stderr }))
})
}
+/** A signed-in computer: `start` refuses without one, before it looks at anything else. */
+function seedSession(root: string): void {
+ mkdirSync(join(root, 'auth'), { recursive: true })
+ writeFileSync(join(root, 'auth', 'session.json'), JSON.stringify({
+ version: 1, accessToken: 'tok', refreshToken: 'refresh', expiresAt: Date.now() + 3_600_000,
+ autonomousEnv: 'prod', computerId: 'a'.repeat(32), machineId: 'm_seeded', updatedAt: Date.now(),
+ }))
+}
+
+/** A daemon that is up, as `start` sees one: a pid file naming a live process — this one. */
+function seedRunningDaemon(root: string): void {
+ mkdirSync(join(root, 'data'), { recursive: true })
+ writeFileSync(join(root, 'data', 'adapter.pid'), `${process.pid}\n`)
+}
+
describe('CLI login/start command contract', () => {
it('does not start or open SSO when start has no saved session', () => {
const result = run('start')
@@ -61,3 +97,58 @@ describe('CLI login/start command contract', () => {
expect(result.stderr).toContain('Unknown command: not-a-command')
})
})
+
+describe('start --repair beside a running daemon', () => {
+ // The managed runtimes live beside the bundle, not in it, and the daemon reads `current-grid` on every
+ // resolve — so a grid laid down here is the one its next spawn runs, with no restart. `--repair` is the
+ // one place a person WATCHES that provisioning; beside a live daemon it used to exit at "already
+ // running" before reaching it, and the only way to follow a new pin was a restart.
+ const key = `${process.platform}-${process.arch}`
+
+ /** Serves a grid manifest that pins 9.9.9 to an archive nobody can fetch: the download is refused at
+ * once, which is a best-effort skip inside ensureManagedGrid — and the "installing" line has already
+ * said the step was reached, which is the whole of what this contract is about. */
+ async function withManifest<T>(body: (url: string) => Promise<T>): Promise<T> {
+ const server = createServer((_req, res) => {
+ res.setHeader('content-type', 'application/json')
+ res.end(JSON.stringify({ grid: { [key]: {
+ version: '9.9.9', url: 'https://127.0.0.1:1/grid.tar.gz', sha256: '0'.repeat(64), archiveRoot: `grid-9.9.9-${key}`,
+ } } }))
+ })
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ try {
+ return await body(`http://127.0.0.1:${(server.address() as AddressInfo).port}/metadata.json`)
+ } finally {
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ }
+ }
+
+ const noNode = 'http://127.0.0.1:9/metadata.json' // refused at once: the Node runtime is not what is under test
+
+ it('provisions the managed grid for the daemon that is up, and still leaves the daemon itself alone', async () => {
+ const root = freshRoot()
+ seedSession(root)
+ seedRunningDaemon(root)
+ const result = await withManifest((manifest) => runAsync(root, ['start', '--repair'], {
+ ADAPTER_RUNTIME_DIR: join(root, 'runtime'), ADAPTER_RUNTIME_METADATA_URL: noNode, ADAPTER_GRID_RUNTIME_METADATA_URL: manifest,
+ }))
+
+ expect(result.status).toBe(0)
+ expect(result.stdout).toContain(`installing the Harness grid runtime (9.9.9, ${key})`)
+ expect(result.stdout).toContain('already running')
+ expect(result.stdout).not.toContain('updated to v') // no bundle staging beside a live daemon
+ }, 20_000)
+
+ it('a plain start beside a running daemon touches nothing', async () => {
+ const root = freshRoot()
+ seedSession(root)
+ seedRunningDaemon(root)
+ const result = await withManifest((manifest) => runAsync(root, ['start'], {
+ ADAPTER_RUNTIME_DIR: join(root, 'runtime'), ADAPTER_RUNTIME_METADATA_URL: noNode, ADAPTER_GRID_RUNTIME_METADATA_URL: manifest,
+ }))
+
+ expect(result.status).toBe(0)
+ expect(result.stdout).toContain('already running')
+ expect(result.stdout).not.toContain('installing the Harness grid runtime')
+ }, 20_000)
+})