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.

feat(cli): name harnessd's processes in Activity Monitor (#881)

0xken15e441b3d35ccc
diff --git a/cli/e2e/lean.e2e.ts b/cli/e2e/lean.e2e.ts
index d270d7d2b..4631f37b1 100644
--- a/cli/e2e/lean.e2e.ts
+++ b/cli/e2e/lean.e2e.ts
@@ -84,7 +84,7 @@ describe('harnessd\'s master and services lean', () => {
const master = d.pid!
expect(commandOf(master)).toBe('harnessd')
expect(commandOf(d.corePid()!)).toContain(`${bundle} __run`)
- for (const [name, pid] of servicePids(d)) expect(commandOf(pid), name).toBe(`harnessd ${name}`)
+ 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]>) {
diff --git a/cli/e2e/serviceProcesses.e2e.ts b/cli/e2e/serviceProcesses.e2e.ts
index b37e5dbb3..e63752cde 100644
--- a/cli/e2e/serviceProcesses.e2e.ts
+++ b/cli/e2e/serviceProcesses.e2e.ts
@@ -42,7 +42,7 @@ function searchPids(d: IsolatedDaemon): number[] {
const ours = new Set([...d.log().matchAll(/\[harnessd\] service search started \(pid (\d+)\)/g)].map((match) => Number(match[1])))
const table = execFileSync('ps', ['-A', '-o', 'pid=,command=']).toString().trim().split('\n')
return table.map((line) => line.trim().match(/^(\d+)\s+(.*)$/)).filter((match): match is RegExpMatchArray => !!match)
- .filter(([, pid, command]) => command.trim() === 'harnessd search' && ours.has(Number(pid))).map(([, pid]) => Number(pid))
+ .filter(([, pid, command]) => command.trim() === 'harnessd-search' && ours.has(Number(pid))).map(([, pid]) => Number(pid))
}
const finds = async (client: LocalClient, word: string, sessionId: string): Promise<boolean> =>
JSON.stringify(await client.request('session_search', { query: word }, 30_000)).includes(sessionId)
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 923419f8f..ad01b2d0d 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -1,4 +1,5 @@
import type { PurgeAgentService } from './lib/purgeAgentService.js'
+import { baseNode } from './harnessd/baseNode.js'
import type { Asker, PromptScopes } from './core/api.js'
import { ServiceUnavailableError } from './core/serviceHost.js'
import type { ActivityFrame } from './lib/turnActivity.js'
@@ -386,7 +387,7 @@ export class BackendSocket {
'team_delivery', { action: 'prompt_replied', agentId: address.agentId, teamId, questionId })
},
command: address => address.machineId === this.machineId
- ? this.teamCommand ?? `${[process.execPath, ...process.execArgv, process.argv[1]].map(shellQuote).join(' ')} team --port ${env.PORT}`
+ ? this.teamCommand ?? `${[baseNode(process.execPath), ...process.execArgv, process.argv[1]].map(shellQuote).join(' ')} team --port ${env.PORT}`
: 'harness team',
runtime: async address => {
Address.parse(address)
@@ -424,7 +425,7 @@ export class BackendSocket {
return this.orchestratorService ??= new OrchestratorService({
stateDir: join(env.ADAPTER_DATA_DIR, 'orchestrator'),
workspaceDir: join(homedir(), 'harnesses', 'orchestrated'),
- command: this.orchestratorCommand ?? `${[process.execPath, ...process.execArgv, process.argv[1]].map(shellQuote).join(' ')} orchestrator --port ${env.PORT} --machine ${shellQuote(this.machineId)}`,
+ command: this.orchestratorCommand ?? `${[baseNode(process.execPath), ...process.execArgv, process.argv[1]].map(shellQuote).join(' ')} orchestrator --port ${env.PORT} --machine ${shellQuote(this.machineId)}`,
catalog: () => listInstalledDsh().filter(d => d.manifest.kind !== 'viewer' && !isHiddenBuiltin(d) && !!d.manifest.engine && supportsFirstPrompt(d.manifest.engine)).map(d => ({
id: d.id, name: d.manifest.name, description: d.manifest.description ?? '', engine: d.manifest.engine!, viewer: !!d.manifest.viewer,
})),
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 6012a5e43..2be00e80a 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -63,6 +63,7 @@ import { newCommand } from './lib/newCommand.js'
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 { startServiceProcess } from './serviceProcess.js'
import { isLocalSocketName } from './lib/localSocket.js'
@@ -1336,7 +1337,8 @@ async function spawnDaemon(session: AuthSession | null, runtimeNode: string | nu
// harnessd: a master that keeps the daemon's core running (harnessd/supervisor.ts). HARNESS_NO_MASTER=1
// starts the core on its own, as before, for a machine where the master itself is in question.
const entry = process.env.HARNESS_NO_MASTER === '1' ? '__run' : '__harnessd'
- const child = spawn(runtimeNode ?? process.execPath, [SCRIPT_PATH, entry], {
+ // Under its own name in Activity Monitor (harnessd/processName.ts) rather than `node`.
+ const child = spawn(namedNode(runtimeNode ?? process.execPath, entry === '__run' ? 'harnessd-core' : 'harnessd', env.ADAPTER_RUNTIME_DIR), [SCRIPT_PATH, entry], {
detached: true,
env: { ...process.env },
stdio: ['ignore', logFd, logFd],
diff --git a/cli/src/harnessd/AGENTS.md b/cli/src/harnessd/AGENTS.md
index a7fc83b52..a33808ad3 100644
--- a/cli/src/harnessd/AGENTS.md
+++ b/cli/src/harnessd/AGENTS.md
@@ -32,3 +32,9 @@ It keeps the core and the services running, and nothing else.
it runs from, and one is removed only once no live master claims it. `lean-off` in the data folder
turns it off for masters launchd or systemd start. Never exec onto a file without checking it is
there: a failed exec cannot be caught (`reexec.ts`).
+8. **Each process runs under its own name** (`processName.ts`): Activity Monitor and `top` name a process
+ after the file exec'd, and the master, core and each service are started through a hard link of the
+ managed node (`harnessd`, `harnessd-core`, `harnessd-<service>`), titled the same. The links live in
+ `<runtime>/node-…/libexec/harnessd/` — never `bin/`, which agent panes get on PATH — are made only for
+ the managed runtime's node, never a bare `harness` (the dial's `pgrep -x harness` means the app), and
+ any failure runs the process as `node`. Children a process starts use `baseNode(process.execPath)`.
diff --git a/cli/src/harnessd/baseNode.ts b/cli/src/harnessd/baseNode.ts
new file mode 100644
index 000000000..538aa19d0
--- /dev/null
+++ b/cli/src/harnessd/baseNode.ts
@@ -0,0 +1,5 @@
+import { dirname, join, sep } from 'node:path'
+/** The managed node behind a name link (./processName.ts): `<runtime>/node-…/libexec/harnessd/<name>` → its `bin/node`; any other path is itself. Its own file: the core loads only this. */
+export function baseNode(path: string): string {
+ return dirname(path).endsWith(`${sep}libexec${sep}harnessd`) ? join(dirname(dirname(dirname(path))), 'bin', 'node') : path
+}
diff --git a/cli/src/harnessd/master.spec.ts b/cli/src/harnessd/master.spec.ts
index 9e9e3a6b0..a0c576286 100644
--- a/cli/src/harnessd/master.spec.ts
+++ b/cli/src/harnessd/master.spec.ts
@@ -1,5 +1,5 @@
import { EventEmitter } from 'node:events'
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { spawn, type ChildProcess } from 'node:child_process'
@@ -275,8 +275,10 @@ describe('a log that cannot grow', () => {
describe('runMaster', () => {
let dir: string
+ // runMaster titles the process it runs in: here, the test worker.
+ const title = process.title
beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'harnessd-master-')) })
- afterEach(() => rmSync(dir, { recursive: true, force: true }))
+ afterEach(() => { rmSync(dir, { recursive: true, force: true }); process.title = title })
const until = async (what: string, test: () => boolean, ms = 10_000) => {
const deadline = Date.now() + ms
@@ -286,6 +288,37 @@ describe('runMaster', () => {
}
}
+ it('starts the core through a link named after it, so Activity Monitor tells it from node', async () => {
+ const runtime = join(dir, 'runtime')
+ const bin = join(runtime, 'node-v1', 'bin')
+ mkdirSync(bin, { recursive: true })
+ const node = join(bin, 'node')
+ linkSync(process.execPath, node)
+ const ran = join(dir, 'ran')
+ const core = join(dir, 'core.cjs')
+ writeFileSync(core, `
+ // The services run this script too (as \`__service <name>\`); each records its own.
+ require('node:fs').writeFileSync(${JSON.stringify(ran)} + (process.argv[3] ?? ''), process.execPath)
+ 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))
+ `)
+ const exits: number[] = []
+ const signals = new Map<string, () => void>()
+ const supervisor = runMaster({
+ nodePath: node, runtimeDir: runtime, execArgv: [], scriptPath: core, pidFile: join(dir, 'adapter.pid'),
+ restoreUpdate: () => {}, confirmUpdate: () => {},
+ exit: (code) => exits.push(code), onSignal: (signal, listener) => signals.set(signal, listener),
+ })
+ await until('the core and a service to be running', () => supervisor.status().state === 'running' && existsSync(ran) && existsSync(`${ran}search`))
+ const libexec = join(realpathSync(runtime), 'node-v1', 'libexec', 'harnessd')
+ expect(readFileSync(ran, 'utf8')).toBe(join(libexec, 'harnessd-core'))
+ expect(readFileSync(`${ran}search`, 'utf8')).toBe(join(libexec, 'harnessd-search'))
+ signals.get('SIGTERM')!()
+ await until('the master to finish', () => exits.length > 0)
+ })
+
it('starts the core, claims the pid file when it binds, restarts it after a crash, and stops it on a signal', async () => {
const pidFile = join(dir, 'adapter.pid')
const runs = join(dir, 'runs')
diff --git a/cli/src/harnessd/master.ts b/cli/src/harnessd/master.ts
index d1475527b..226bec34b 100644
--- a/cli/src/harnessd/master.ts
+++ b/cli/src/harnessd/master.ts
@@ -11,6 +11,7 @@ import { ignoreLogWriteErrors, trimLogFile, ts } from '../lib/log.js'
import { folderFingerprint } from './leanBundle.js'
import { leanServices } from './leanServices.js'
import { platformFromEnv, type PlatformName } from './platform.js'
+import { baseNode, namedNode } from './processName.js'
import type { MasterMessage } from './protocol.js'
import {
PROBE_ANSWER, RESUME_ENV, createReexec, decodeResume, fingerprint, readMarker, recoverFailedReexec, removeMarker, runProbe, writeMarker,
@@ -27,6 +28,9 @@ export interface MasterConfig {
/** The node binary and flags the core runs with. */
nodePath: string
execArgv: string[]
+ /** 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. */
scriptPath: string
@@ -250,6 +254,9 @@ export function runMaster(config: MasterConfig): Supervisor {
// The core's stamp, local time (lib/log.ts): in UTC, the master's lines sat hours away from the core's
// lines around them in the one log they share.
const log = (line: string) => console.log(`${ts()} ${line}`)
+ // Each process exec'd through a link named after it, so Activity Monitor and `top` tell them apart.
+ const node = baseNode(config.nodePath)
+ const named = (name: string): string => namedNode(node, name, config.runtimeDir, { log })
// Set by the launchd agent or systemd unit `harness service install` writes (./platform.ts).
const platform = platformFromEnv(env)
if (platform) log(`[harnessd] run by ${platform}, which starts this master again if it dies`)
@@ -291,7 +298,7 @@ export function runMaster(config: MasterConfig): Supervisor {
const services = new ServiceSupervisor(specs, {
spawnService: (spec, extra) => {
const script = lean.scriptFor(spec.name)
- const handle = coreHandle(spawn(config.nodePath, [...coreExecArgv(config.execArgv, spec.heapLimitMiB), script, '__service', spec.name], {
+ const handle = coreHandle(spawn(named(`harnessd-${spec.name}`), [...coreExecArgv(config.execArgv, spec.heapLimitMiB), script, '__service', spec.name], {
env: { ...env, ...extra },
stdio: ['ignore', 'inherit', 'inherit', 'ipc'],
}))
@@ -305,9 +312,9 @@ export function runMaster(config: MasterConfig): Supervisor {
log,
}, serviceOptions(env), { HARNESSD_SERVICE_TOKEN: token })
const reexec = markerFile ? createReexec({
- own, current: bundle, nodePath: config.nodePath, execArgv: config.execArgv, scriptPath: config.scriptPath, env, pid: process.pid,
+ own, current: bundle, nodePath: named('harnessd'), execArgv: config.execArgv, scriptPath: config.scriptPath, env, pid: process.pid,
execve, exists: existsSync,
- probe: (args, probeEnv) => runProbe(config.nodePath, args, probeEnv),
+ probe: (args, probeEnv) => runProbe(node, args, probeEnv),
stopChildren: (done) => services.stop(done),
startChildren: () => services.start(),
writeMarker: (marker) => writeMarker(markerFile, marker),
@@ -317,7 +324,7 @@ export function runMaster(config: MasterConfig): Supervisor {
log,
}) : null
const supervisor = new Supervisor({
- spawnCore: (extra) => coreHandle(spawn(config.nodePath, [...execArgv, config.scriptPath, '__run'], {
+ 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'],
diff --git a/cli/src/harnessd/processName.spec.ts b/cli/src/harnessd/processName.spec.ts
new file mode 100644
index 000000000..f61070207
--- /dev/null
+++ b/cli/src/harnessd/processName.spec.ts
@@ -0,0 +1,94 @@
+import { linkSync, mkdirSync, mkdtempSync, rmSync, statSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { baseNode, namedNode, nodeFs, resetNamedNodeReports, type NamedNodeFs } from './processName.js'
+
+const runtime = '/home/u/.harness/runtime'
+const node = `${runtime}/node-v22/bin/node`
+const libexec = `${runtime}/node-v22/libexec/harnessd`
+
+/** An in-memory folder: path → identity. */
+function memFs(files: Record<string, { dev: number; ino: number }>, fail: Partial<Record<keyof NamedNodeFs, Error>> = {}) {
+ const calls: string[] = []
+ const fs: NamedNodeFs = {
+ identity: (path) => files[path] ?? null,
+ mkdir: (path) => { calls.push(`mkdir ${path}`); if (fail.mkdir) throw fail.mkdir },
+ link: (from, to) => { calls.push(`link ${to}`); if (fail.link) throw fail.link; files[to] = files[from] },
+ rename: (from, to) => { calls.push(`rename ${to}`); if (fail.rename) throw fail.rename; files[to] = files[from]; delete files[from] },
+ unlink: (path) => { if (!files[path]) throw new Error('ENOENT'); delete files[path] },
+ }
+ return { fs, calls, files }
+}
+
+afterEach(() => resetNamedNodeReports())
+
+describe('namedNode', () => {
+ it('links the managed node under the name, beside bin/ and never in it', () => {
+ const { fs, calls } = memFs({ [node]: { dev: 1, ino: 7 } })
+ expect(namedNode(node, 'harnessd-core', runtime, { fs, pid: 9, platform: 'darwin' })).toBe(`${libexec}/harnessd-core`)
+ expect(calls).toEqual([`mkdir ${libexec}`, `link ${libexec}/harnessd-core.9.tmp`, `rename ${libexec}/harnessd-core`])
+ })
+
+ it('reuses a link that is still this node, and replaces one left to another binary', () => {
+ const same = memFs({ [node]: { dev: 1, ino: 7 }, [`${libexec}/harnessd`]: { dev: 1, ino: 7 } })
+ expect(namedNode(node, 'harnessd', runtime, { fs: same.fs, platform: 'linux' })).toBe(`${libexec}/harnessd`)
+ expect(same.calls).toEqual([])
+ const stale = memFs({ [node]: { dev: 1, ino: 7 }, [`${libexec}/harnessd`]: { dev: 1, ino: 3 }, [`${libexec}/harnessd.5.tmp`]: { dev: 1, ino: 3 } })
+ expect(namedNode(node, 'harnessd', runtime, { fs: stale.fs, pid: 5, platform: 'linux' })).toBe(`${libexec}/harnessd`)
+ expect(stale.files[`${libexec}/harnessd`]).toEqual({ dev: 1, ino: 7 })
+ })
+
+ it('leaves any node outside the managed runtime alone, and Windows too', () => {
+ const { fs, calls } = memFs({})
+ expect(namedNode('/opt/homebrew/bin/node', 'harnessd', runtime, { fs, platform: 'darwin' })).toBe('/opt/homebrew/bin/node')
+ expect(namedNode(node, 'harnessd', undefined, { fs, platform: 'darwin' })).toBe(node)
+ expect(namedNode(node, 'harnessd', `${runtime}/node-v22/bin/node`, { fs, platform: 'darwin' })).toBe(node)
+ expect(namedNode(node, 'harnessd', runtime, { fs, platform: 'win32' })).toBe(node)
+ expect(calls).toEqual([])
+ })
+
+ it('runs as node when the link cannot be made, and says why once per name', () => {
+ const log = vi.fn()
+ const missing = memFs({})
+ expect(namedNode(node, 'harnessd', runtime, { fs: missing.fs, platform: 'darwin', log })).toBe(node)
+ const crossDevice = memFs({ [node]: { dev: 1, ino: 7 } }, { link: new Error('EXDEV') })
+ expect(namedNode(node, 'harnessd-core', runtime, { fs: crossDevice.fs, platform: 'darwin', log })).toBe(node)
+ expect(namedNode(node, 'harnessd-core', runtime, { fs: crossDevice.fs, platform: 'darwin', log })).toBe(node)
+ const readOnly = memFs({ [node]: { dev: 1, ino: 7 } }, { mkdir: 'EROFS' as unknown as Error })
+ expect(namedNode(node, 'harnessd-teams', runtime, { fs: readOnly.fs, platform: 'darwin' })).toBe(node)
+ expect(log.mock.calls.map(([line]) => line)).toEqual([
+ '[harnessd] harnessd runs as node (no node binary)',
+ '[harnessd] harnessd-core runs as node (EXDEV)',
+ ])
+ })
+
+ it('cleans up a link it made but could not rename into place', () => {
+ const { fs, files } = memFs({ [node]: { dev: 1, ino: 7 } }, { rename: new Error('EPERM') })
+ expect(namedNode(node, 'harnessd-viewers', runtime, { fs, pid: 4, platform: 'darwin' })).toBe(node)
+ expect(Object.keys(files)).toEqual([node])
+ })
+
+ it('makes a real hard link the kernel names the process by', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'harnessd-name-'))
+ try {
+ const bin = join(dir, 'node-v1', 'bin')
+ mkdirSync(bin, { recursive: true })
+ const fakeNode = join(bin, 'node')
+ linkSync(process.execPath, fakeNode)
+ const link = namedNode(fakeNode, 'harnessd-search', dir)
+ expect(link).toBe(join(dir, 'node-v1', 'libexec', 'harnessd', 'harnessd-search'))
+ expect(statSync(link).ino).toBe(statSync(process.execPath).ino)
+ expect(namedNode(fakeNode, 'harnessd-search', dir, { fs: nodeFs })).toBe(link)
+ expect(baseNode(link)).toBe(fakeNode)
+ } finally { rmSync(dir, { recursive: true, force: true }) }
+ })
+})
+
+describe('baseNode', () => {
+ it('maps a name link back to the node beside its folder, and leaves anything else', () => {
+ expect(baseNode(`${libexec}/harnessd-core`)).toBe(node)
+ expect(baseNode(node)).toBe(node)
+ expect(baseNode('/usr/bin/node')).toBe('/usr/bin/node')
+ })
+})
diff --git a/cli/src/harnessd/processName.ts b/cli/src/harnessd/processName.ts
new file mode 100644
index 000000000..2e137845d
--- /dev/null
+++ b/cli/src/harnessd/processName.ts
@@ -0,0 +1,90 @@
+/**
+ * What the daemon's processes are called in Activity Monitor, `top` and `ps -c`.
+ *
+ * Those name a process after the FILE that was exec'd, not its `process.title`: every one of ours was
+ * `node`. A symlink does not help either — the kernel takes the name of the file it resolves to (Claude
+ * Code shows as `2.1.291`, its binary's file name). A hard link does: same inode, no extra disk, the same
+ * code signature, and the name it was exec'd under. So each process is started through a hard link of
+ * the managed node named after it (`harnessd`, `harnessd-core`, `harnessd-search`…).
+ *
+ * The links live in `<runtime>/node-…/libexec/harnessd/`, never in `bin/`: that folder is put on agent
+ * panes' PATH (lib/engineLaunch.ts `npmRuntimePrelude`), where `harnessd-core` would be a command. Only a
+ * node inside the managed runtime is linked — never a system, Homebrew or developer one, whose folder is
+ * not ours to write in. Anything that goes wrong leaves the process running as `node`, as before: a name
+ * is never worth a process that does not start.
+ */
+import { linkSync, mkdirSync, renameSync, statSync, unlinkSync } from 'node:fs'
+import { basename, dirname, isAbsolute, join, relative } from 'node:path'
+
+export { baseNode } from './baseNode.js'
+
+const LINK_DIR = join('libexec', 'harnessd')
+
+export interface NamedNodeFs {
+ /** The file's identity, or null when it is not there. */
+ identity(path: string): { dev: number; ino: number } | null
+ mkdir(path: string): void
+ link(existing: string, created: string): void
+ rename(from: string, to: string): void
+ unlink(path: string): void
+}
+
+export const nodeFs: NamedNodeFs = {
+ identity: (path) => {
+ const stat = statSync(path, { throwIfNoEntry: false })
+ return stat ? { dev: stat.dev, ino: stat.ino } : null
+ },
+ mkdir: (path) => { mkdirSync(path, { recursive: true }) },
+ link: linkSync,
+ rename: renameSync,
+ unlink: unlinkSync,
+}
+
+export interface NamedNodeOptions {
+ fs?: NamedNodeFs
+ platform?: NodeJS.Platform
+ pid?: number
+ /** Told once per name when the process has to run as plain `node`, and why. */
+ log?: (line: string) => void
+}
+
+const reported = new Set<string>()
+
+/** Tests only. */
+export function resetNamedNodeReports(): void { reported.clear() }
+
+/** [node] under the name [name] — a hard link of it, made or refreshed here — or [node] itself when it
+ * is not the managed runtime's, or the link cannot be made. */
+export function namedNode(node: string, name: string, runtimeDir: string | undefined, options: NamedNodeOptions = {}): string {
+ const fs = options.fs ?? nodeFs
+ const fallBack = (why: string): string => {
+ if (!reported.has(name)) {
+ reported.add(name)
+ options.log?.(`[harnessd] ${name} runs as ${basename(node)} (${why})`)
+ }
+ return node
+ }
+ if ((options.platform ?? process.platform) === 'win32') return node
+ const inside = runtimeDir ? relative(runtimeDir, node) : ''
+ if (!inside || inside.startsWith('..') || isAbsolute(inside)) return node
+ const dir = join(dirname(dirname(node)), LINK_DIR)
+ const link = join(dir, name)
+ const temp = `${link}.${options.pid ?? process.pid}.tmp`
+ try {
+ const target = fs.identity(node)
+ if (!target) return fallBack('no node binary')
+ const current = fs.identity(link)
+ if (current && current.dev === target.dev && current.ino === target.ino) return link
+ // A fresh name, renamed over the old one: two masters at once, or a link to a node since replaced,
+ // never leave the name missing or pointing at the wrong binary.
+ fs.mkdir(dir)
+ try { fs.unlink(temp) } catch { /* not there */ }
+ fs.link(node, temp)
+ fs.rename(temp, link)
+ return link
+ } catch (error) {
+ // A link made but not renamed would otherwise stay behind, one per failed start.
+ try { fs.unlink(temp) } catch { /* never made */ }
+ return fallBack(error instanceof Error ? error.message : String(error))
+ }
+}
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
index 35a7dafa8..3abbd5a76 100644
--- a/cli/src/lib/engineLaunch.ts
+++ b/cli/src/lib/engineLaunch.ts
@@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto'
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { homedir, userInfo } from 'node:os'
import { isAbsolute, basename, dirname, join } from 'node:path'
+import { baseNode } from '../harnessd/baseNode.js'
import { env } from '../config/env.js'
import { isTerminalEngine, type AgentEngine } from '../engines/types.js'
import { isOpencodeV2 } from '../engines/opencode/version.js'
@@ -855,7 +856,7 @@ function codexStartupRetryScript(tmuxBinary: string): string {
const probe = 'harness_codex_check'
const tmux = shellSingleQuote(tmuxBinary)
return 'harness_codex_check() {\n'
- + ` ${shellSingleQuote(process.execPath)} -e ${shellSingleQuote(CODEX_STARTUP_RETRY_PROBE)} "$@"\n`
+ + ` ${shellSingleQuote(baseNode(process.execPath))} -e ${shellSingleQuote(CODEX_STARTUP_RETRY_PROBE)} "$@"\n`
+ '}\n'
+ 'harness_codex_start() {\n'
+ ' [ "$harness_codex_go" = 1 ] || return 0\n'
@@ -902,7 +903,7 @@ function codexOwnedLaunchPrelude(): string {
const probe = `const {execFileSync}=require('node:child_process');try { const h=execFileSync(process.argv[1],['--help'],{timeout:5000,maxBuffer:1048576,encoding:'utf8',stdio:['ignore','pipe','pipe']});process.exit(/--no-daemon(?:[^A-Za-z0-9-]|$)/.test(h)?0:64); } catch { process.exit(2); }`
return 'harness_codex_probe() {\n'
+ ' harness_codex_mode=0\n'
- + ` harness_codex_seen=$(${shellSingleQuote(process.execPath)} -e ${shellSingleQuote(probe)} "$1") || harness_codex_mode=$?\n`
+ + ` harness_codex_seen=$(${shellSingleQuote(baseNode(process.execPath))} -e ${shellSingleQuote(probe)} "$1") || harness_codex_mode=$?\n`
+ ' case "$harness_codex_mode" in\n'
+ ' 0) harness_codex_no_daemon=1 ;;\n'
+ ' 64) harness_codex_no_daemon= ;;\n'
@@ -1077,7 +1078,7 @@ export function shellSingleQuote(value: string): string {
*/
function npmRuntimePrelude(recipe: EngineInstallRecipe, runtimeNode: string): string {
if (!recipe.executable.npmGlobal) return ''
- const bins = [...new Set([dirname(runtimeNode), dirname(process.execPath)])]
+ const bins = [...new Set([dirname(runtimeNode), dirname(baseNode(process.execPath))])]
.map(shellSingleQuote)
.join(' ')
return [
diff --git a/cli/src/masterProcess.spec.ts b/cli/src/masterProcess.spec.ts
index efb029cc1..944671581 100644
--- a/cli/src/masterProcess.spec.ts
+++ b/cli/src/masterProcess.spec.ts
@@ -48,6 +48,17 @@ describe('a master started on cli.js', () => {
expect(calls.logs).toEqual([])
})
+ it('re-executes through the node it is given — the managed one, named harnessd — and checks it is there first', () => {
+ const named = '/rt/node-v1/libexec/harnessd/harnessd'
+ const { given, calls } = deps({ node: () => named })
+ startMasterFromBundle('/cli/cli.js', given)
+ expect(calls.execs.map(({ file, args }) => [file, args[0]])).toEqual([[named, named]])
+ const gone = deps({ node: () => named, exists: (path) => path !== named })
+ startMasterFromBundle('/cli/cli.js', gone.given)
+ expect(gone.calls.execs).toEqual([])
+ expect(gone.calls.logs).toEqual([expect.stringContaining(`${named} is not there to re-execute on`)])
+ })
+
it('runs from cli.js, with the services still from the lean bundle, where this Node cannot re-execute', () => {
const { given, calls } = deps({ execve: null })
startMasterFromBundle('/cli/cli.js', given)
diff --git a/cli/src/masterProcess.ts b/cli/src/masterProcess.ts
index a4cb88d94..cbc32c786 100644
--- a/cli/src/masterProcess.ts
+++ b/cli/src/masterProcess.ts
@@ -14,6 +14,7 @@ import { existsSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import { env } from './config/env.js'
import { processExecve, probeMaster, runMaster, type Execve } from './harnessd/master.js'
+import { baseNode, namedNode } from './harnessd/processName.js'
import { PROBE_ANSWER, PROBE_TIMEOUT_MS } from './harnessd/reexec.js'
import { ensureUtf8Locale } from './lib/childLocale.js'
import { DAEMON_LOG_FILE, HARNESSD_STATUS_FILE, PID_FILE } from './lib/daemonState.js'
@@ -56,8 +57,9 @@ export function startMaster(start: MasterStart, exit: (code: number) => void = (
ensureUtf8Locale()
const { serviceScriptPath } = start
return runMaster({
- nodePath: process.execPath,
+ nodePath: baseNode(process.execPath),
execArgv: process.execArgv,
+ runtimeDir: env.ADAPTER_RUNTIME_DIR,
...start,
pidFile: PID_FILE,
statusFile: HARNESSD_STATUS_FILE,
@@ -92,6 +94,10 @@ export interface BundleMasterDeps {
/** Runs `<lean> __harnessd-probe` as the re-executed master would start: whether it answered. */
probe: (leanPath: string, env: NodeJS.ProcessEnv) => { ok: boolean; detail: string }
execve: Execve | null
+ /** The node the master re-executes on: the managed one under the name `harnessd`
+ * (harnessd/processName.ts), so Activity Monitor names it. Asked only when it re-executes; defaults
+ * to this process's. */
+ node?: () => string
start: (start: MasterStart) => unknown
log: (line: string) => void
}
@@ -118,6 +124,7 @@ export const processBundleDeps = (): BundleMasterDeps => ({
write: (lean) => writeLeanBundle(LEAN_DIR, lean),
probe: (leanPath, probeEnv) => probeLean(leanPath, probeEnv),
execve: processExecve(),
+ node: () => namedNode(baseNode(process.execPath), 'harnessd', env.ADAPTER_RUNTIME_DIR, { log: (line) => console.log(`${ts()} ${line}`) }),
start: startMaster,
log: (line) => console.log(`${ts()} ${line}`),
})
@@ -161,13 +168,14 @@ export function startMasterFromBundle(bundlePath: string, deps: BundleMasterDeps
// An exec that fails cannot be caught once it has begun: on Node 22.23 a node binary that is not there
// aborts this process (exit 134), and a script that is not there ends it in the new image
// (MODULE_NOT_FOUND). The probe ran both a moment ago; they are checked again right before.
- const missing = [process.execPath, leanPath].find((path) => !deps.exists(path))
+ const node = deps.node?.() ?? process.execPath
+ const 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}`)
return
}
try {
- deps.execve(process.execPath, [process.execPath, ...process.execArgv, leanPath, '__harnessd'], leanEnv)
+ 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 })
diff --git a/cli/src/serviceProcess.spec.ts b/cli/src/serviceProcess.spec.ts
index 2c3a55a81..d3fb7644b 100644
--- a/cli/src/serviceProcess.spec.ts
+++ b/cli/src/serviceProcess.spec.ts
@@ -30,7 +30,7 @@ describe('a service in its own process', () => {
expect(await startServiceProcess('search', { runners })).toBe(handle)
} finally { delete process.env.HARNESSD_SERVICE_TOKEN }
expect(loaded).toEqual(['search'])
- expect(process.title).toBe('harnessd search')
+ expect(process.title).toBe('harnessd-search')
// Its lines are stamped like the core's and the master's in the log they share.
expect(stamped.times).toBe(1)
expect(seen).toEqual([{ dataDir: expect.any(String), socketPath: '/data/daemon-18473.sock', machineId: expect.any(String), token: 'token' }])
diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.ts
index d7096046f..4bc4fb7f4 100644
--- a/cli/src/serviceProcess.ts
+++ b/cli/src/serviceProcess.ts
@@ -45,7 +45,8 @@ export async function startServiceProcess(name: string | undefined, deps: Servic
console.error(`[service] ${name ?? '(none)'}: ${socketPath ? 'no such service in this build' : 'the core has no local socket to reach'}`)
return exit(2)
}
- process.title = `harnessd ${name}`
+ // The same name as the hard link it was exec'd through (harnessd/processName.ts): one name in ps and Activity Monitor.
+ process.title = `harnessd-${name}`
// Its lines share the daemon's log with the master's: a write a full disk refuses is dropped, not fatal.
ignoreLogWriteErrors()
// As every daemon process did at load: a service that runs `ps` or `git` must not get mangled output.
diff --git a/cli/src/services/models.ts b/cli/src/services/models.ts
index 6c6471e5d..66dd05381 100644
--- a/cli/src/services/models.ts
+++ b/cli/src/services/models.ts
@@ -9,6 +9,7 @@
* reaches it only through `ports.models`, and the apps through the requests it answers.
*/
import { join } from 'node:path'
+import { baseNode } from '../harnessd/baseNode.js'
import type { CoreApi, CorePorts, ModelsPort, ServiceRequest, ServiceRequests } from '../core/api.js'
import { MODEL_MANAGER_ID } from '../dsh/builtins.js'
import { installedDsh } from '../dsh/installed.js'
@@ -145,7 +146,7 @@ function modelsRequests(core: CoreApi, grid: Pick<ModelsPort, 'ensure' | 'setUp'
onChanged: () => { forgetGridModels(); core.clients.gridModelsChanged() },
// Models Ollama, LM Studio and llama.cpp downloaded here, found by the Model Manager's own scan (the
// bundled harness), so the picker and that harness agree on what is here and what starts it.
- appModels: () => scanAppModels({ node: process.execPath, packageDir: installedDsh(MODEL_MANAGER_ID)?.realDir ?? null, env: process.env }),
+ appModels: () => scanAppModels({ node: baseNode(process.execPath), packageDir: installedDsh(MODEL_MANAGER_ID)?.realDir ?? null, env: process.env }),
appEngines: appEngineOps(process.env),
})
/** The grid listing currently out, shared by every `grid_models_list` for the same own grid that lands