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.

Harness OS keeps its agent runtime under harness-daemon.service

bitcoinbuilder8d006093f999
diff --git a/cli/src/harnessd/platform.spec.ts b/cli/src/harnessd/platform.spec.ts
index 60f004add..614d6d3d2 100644
--- a/cli/src/harnessd/platform.spec.ts
+++ b/cli/src/harnessd/platform.spec.ts
@@ -5,7 +5,7 @@ import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { fakePlatform, type FakePlatform } from '../testing/fakePlatform.js'
import {
- COMMAND_TIMEOUT_MS, LAUNCHD_LABEL, PLATFORM_ENV, PlatformService, RESTART_THROTTLE_S, STOP_TIMEOUT_S, SYSTEMD_UNIT,
+ COMMAND_TIMEOUT_MS, LAUNCHD_LABEL, OS_SYSTEMD_UNIT, OS_UNIT_FILE, PLATFORM_ENV, PlatformService, RESTART_THROTTLE_S, STOP_TIMEOUT_S, SYSTEMD_UNIT,
currentUid, defaultPlatformDeps, launchdPlist, platformFor, platformFromEnv, systemdUnit,
type CommandResult, type PlatformDeps, type ServiceDefinition,
} from './platform.js'
@@ -372,6 +372,52 @@ describe('PlatformService over fake systemctl', { timeout: FAKE_COMMANDS_TIMEOUT
})
})
+describe('Harness OS\'s own unit', () => {
+ const unitFile = { [OS_UNIT_FILE]: '[Service]\nExecStart=/usr/bin/harness start --foreground\n' }
+
+ it('is the package\'s harness-daemon.service, and only under systemd', () => {
+ const { deps } = stubDeps({}, { ...unitFile })
+ const service = new PlatformService('systemd', deps, true)
+ expect(service.file).toBe(OS_UNIT_FILE)
+ expect(service.target).toBe(OS_SYSTEMD_UNIT)
+ expect(() => new PlatformService('launchd', deps, true)).toThrow('Harness OS runs harnessd under systemd')
+ })
+
+ it('is never written, registered or removed from here, and counts as this daemon\'s while it is on disk', () => {
+ const { deps, calls, files } = stubDeps({}, { ...unitFile })
+ const service = new PlatformService('systemd', deps, true)
+ expect(service.write(definition())).toBe(false)
+ expect(service.current(definition())).toBe(true)
+ expect(service.ownedBy('/anything/harness.log')).toBe(true)
+ expect(service.register()).toEqual({ ok: false, detail: `Harness OS runs harnessd under ${OS_SYSTEMD_UNIT}` })
+ expect(service.unregister()).toEqual({ ok: false, detail: `Harness OS runs harnessd under ${OS_SYSTEMD_UNIT}` })
+ service.discard()
+ expect(files).toEqual(unitFile)
+ expect(calls).toEqual([])
+ expect(new PlatformService('systemd', stubDeps({}).deps, true).ownedBy('/anything/harness.log')).toBe(false)
+ })
+
+ it('starts the unit without waiting on its readiness check, and stops its main process with a signal, never a stop job', () => {
+ const { deps, calls } = stubDeps({ 'systemctl --user show harness-daemon.service --property=MainPID': ok('MainPID=1347\n') }, { ...unitFile })
+ const service = new PlatformService('systemd', deps, true)
+ expect(service.start(false)).toEqual({ ok: true })
+ expect(service.stop()).toEqual({ ok: true })
+ expect(calls).toEqual([
+ `systemctl --user reset-failed ${OS_SYSTEMD_UNIT}`,
+ `systemctl --user start --no-block ${OS_SYSTEMD_UNIT}`,
+ `systemctl --user show ${OS_SYSTEMD_UNIT} --property=MainPID`,
+ `systemctl --user kill --kill-who=main --signal=SIGTERM ${OS_SYSTEMD_UNIT}`,
+ ])
+ })
+
+ it('counts as registered once systemd has loaded it: the OS pulls it in with the screen rather than enabling it', () => {
+ const { deps } = stubDeps({ 'systemctl --user show': ok('LoadState=loaded\nUnitFileState=disabled\nActiveState=active\nSubState=running\nMainPID=1347\nResult=success\n') }, { ...unitFile })
+ expect(new PlatformService('systemd', deps, true).inspect()).toMatchObject({ installed: true, registered: true, pid: 1347, state: 'active (running)', target: OS_SYSTEMD_UNIT })
+ const { deps: gone } = stubDeps({ 'systemctl --user show': ok('LoadState=not-found\nActiveState=inactive\nMainPID=0\n') })
+ expect(new PlatformService('systemd', gone, true).inspect()).toMatchObject({ installed: false, registered: false, pid: null })
+ })
+})
+
describe('discarding a definition that could not be registered', () => {
it('removes the file alone, and has systemd forget it', () => {
for (const platform of ['launchd', 'systemd'] as const) {
diff --git a/cli/src/harnessd/platform.ts b/cli/src/harnessd/platform.ts
index 0f3a19e75..1a76240d7 100644
--- a/cli/src/harnessd/platform.ts
+++ b/cli/src/harnessd/platform.ts
@@ -29,6 +29,18 @@ export const PLATFORM_ENV = 'HARNESSD_PLATFORM'
export const LAUNCHD_LABEL = 'ai.autonomous.harness.harnessd'
export const SYSTEMD_UNIT = 'harnessd.service'
+/**
+ * Harness OS ships its own user unit for the daemon (os/root/usr/lib/systemd/user/harness-daemon.service):
+ * the screen pulls it in, and the OS's updater restarts it to change the CLI. It runs `harness start
+ * --foreground` with HARNESS_NO_MASTER=1, the core alone. A daemon this CLI spawned beside it (a sign-in
+ * stops the unit's core and starts one again) runs where the OS cannot reach it: the updater's restart
+ * then gives the unit a core that finds the port taken and fails until systemd gives up (2026-10-12).
+ * The unit is the package's: this CLI starts and stops it, and never writes, enables or removes it.
+ */
+export const OS_SYSTEMD_UNIT = 'harness-daemon.service'
+export const OS_UNIT_FILE = '/usr/lib/systemd/user/harness-daemon.service'
+const OS_OWNS_IT = `Harness OS runs harnessd under ${OS_SYSTEMD_UNIT}`
+
/**
* launchd starts the job at most once every this many seconds (its own default, written down so it
* does not move under us); systemd waits this long before a restart. A master that dies after running
@@ -310,10 +322,18 @@ function properties(text: string): Record<string, string> {
/** harnessd's definition and registration on one platform. */
export class PlatformService {
- constructor(readonly platform: PlatformName, private readonly deps: PlatformDeps) {}
+ /** `os`: the unit is Harness OS's own (OS_SYSTEMD_UNIT), not the one `harness service install` writes. */
+ constructor(readonly platform: PlatformName, private readonly deps: PlatformDeps, readonly os = false) {
+ if (os && platform !== 'systemd') throw new Error('Harness OS runs harnessd under systemd')
+ }
+
+ private get unit(): string {
+ return this.os ? OS_SYSTEMD_UNIT : SYSTEMD_UNIT
+ }
/** Where the definition lives. */
get file(): string {
+ if (this.os) return OS_UNIT_FILE
return this.platform === 'launchd'
? join(this.deps.home, 'Library', 'LaunchAgents', `${LAUNCHD_LABEL}.plist`)
: join(this.deps.configHome ?? join(this.deps.home, '.config'), 'systemd', 'user', SYSTEMD_UNIT)
@@ -321,7 +341,7 @@ export class PlatformService {
/** What launchctl or systemctl is told to act on. */
get target(): string {
- return this.platform === 'launchd' ? `gui/${this.deps.uid}/${LAUNCHD_LABEL}` : SYSTEMD_UNIT
+ return this.platform === 'launchd' ? `gui/${this.deps.uid}/${LAUNCHD_LABEL}` : this.unit
}
render(definition: ServiceDefinition): string {
@@ -338,6 +358,9 @@ export class PlatformService {
* or stop, and a test with its own data folder never acts on the person's real registration.
*/
ownedBy(logFile: string): boolean {
+ // The OS's unit logs to the journal. It is only ever built for the data folder it runs
+ // (lib/platformDaemon.ts osDaemonUnit), so its file on disk is enough.
+ if (this.os) return this.installed()
const content = this.deps.readFile(this.file)
if (content === null) return false
return this.platform === 'launchd'
@@ -347,11 +370,13 @@ export class PlatformService {
/** The definition on disk is the one this install would write. */
current(definition: ServiceDefinition): boolean {
+ if (this.os) return true // the package's, not this install's to compare
return this.deps.readFile(this.file) === this.render(definition)
}
/** Write the definition when it differs from the one on disk; says whether it did. */
write(definition: ServiceDefinition): boolean {
+ if (this.os) return false
const content = this.render(definition)
if (this.deps.readFile(this.file) === content) return false
this.deps.writeFile(this.file, content)
@@ -374,7 +399,7 @@ export class PlatformService {
lastExit: /^[ \t]*last exit code = (.+?)[ \t]*$/m.exec(result.stdout)?.[1] ?? null,
}
}
- const args = ['--user', 'show', SYSTEMD_UNIT, '--property=LoadState,UnitFileState,ActiveState,SubState,MainPID,Result']
+ const args = ['--user', 'show', this.unit, '--property=LoadState,UnitFileState,ActiveState,SubState,MainPID,Result']
const result = this.deps.run('systemctl', args)
const linger = this.linger()
if (result.error || result.status !== 0) {
@@ -385,7 +410,8 @@ export class PlatformService {
return {
...base,
linger,
- registered: shown.UnitFileState === 'enabled',
+ // The OS pulls its unit in with the screen rather than enabling it: loaded is registered.
+ registered: this.os ? shown.LoadState === 'loaded' : shown.UnitFileState === 'enabled',
pid: pid > 0 ? pid : null,
state: shown.ActiveState ? `${shown.ActiveState}${shown.SubState ? ` (${shown.SubState})` : ''}` : null,
failed: shown.ActiveState === 'failed',
@@ -409,6 +435,7 @@ export class PlatformService {
/** Register the definition just written, which starts the master: launchd loads the job (RunAtLoad),
* systemd enables the unit and starts it. */
register(): Outcome {
+ if (this.os) return { ok: false, detail: OS_OWNS_IT }
if (this.platform === 'launchd') {
// A job someone disabled stays disabled through a bootstrap; installing is asking for it.
const enabled = this.launchctl('enable', this.target)
@@ -438,8 +465,10 @@ export class PlatformService {
if (!reloaded.ok) return reloaded
}
// After five failed starts systemd refuses a start until it is told to forget them.
- this.deps.run('systemctl', ['--user', 'reset-failed', SYSTEMD_UNIT])
- return this.systemctl('start', SYSTEMD_UNIT)
+ this.deps.run('systemctl', ['--user', 'reset-failed', this.unit])
+ // The OS's unit holds its start until the daemon answers (ExecStartPost), which can outlast
+ // COMMAND_TIMEOUT_MS. Queued instead: the caller waits for the pid file, as for any master.
+ return this.os ? this.systemctl('start', '--no-block', this.unit) : this.systemctl('start', SYSTEMD_UNIT)
}
/**
@@ -458,15 +487,16 @@ export class PlatformService {
if (this.launchctl('print', this.target).status !== 0) return { ok: true }
return this.checked('launchctl', ['bootout', this.target])
}
- const main = Number(properties(this.deps.run('systemctl', ['--user', 'show', SYSTEMD_UNIT, '--property=MainPID']).stdout).MainPID)
+ const main = Number(properties(this.deps.run('systemctl', ['--user', 'show', this.unit, '--property=MainPID']).stdout).MainPID)
if (!(main > 0)) return { ok: true }
// --kill-who: systemd 252 renamed it --kill-whom and kept this spelling, which older ones know.
- return this.systemctl('kill', '--kill-who=main', '--signal=SIGTERM', SYSTEMD_UNIT)
+ return this.systemctl('kill', '--kill-who=main', '--signal=SIGTERM', this.unit)
}
/** Stop the master, unregister it and remove the definition. A unit whose file is already gone is
* stopped all the same. */
unregister(): Outcome {
+ if (this.os) return { ok: false, detail: OS_OWNS_IT }
if (this.platform === 'launchd') {
const stopped = this.stop()
if (!stopped.ok) return stopped
@@ -490,6 +520,7 @@ export class PlatformService {
/** Remove the definition and nothing else: an install that could not register leaves nothing half
* done, so `harness start` runs the daemon as it did before. */
discard(): void {
+ if (this.os) return
this.deps.removeFile(this.file)
// Best effort: a manager that could not take the unit may not take a reload either.
if (this.platform === 'systemd') this.deps.run('systemctl', ['--user', 'daemon-reload'])
diff --git a/cli/src/lib/platformDaemon.spec.ts b/cli/src/lib/platformDaemon.spec.ts
index 4efd21f27..43f5da763 100644
--- a/cli/src/lib/platformDaemon.spec.ts
+++ b/cli/src/lib/platformDaemon.spec.ts
@@ -1,13 +1,15 @@
-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { homedir, tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { env } from '../config/env.js'
-import { PlatformService, defaultPlatformDeps, type PlatformName, type PlatformState } from '../harnessd/platform.js'
+import {
+ OS_SYSTEMD_UNIT, OS_UNIT_FILE, PlatformService, SYSTEMD_UNIT, defaultPlatformDeps, type PlatformName, type PlatformState,
+} from '../harnessd/platform.js'
import { fakePlatform, type FakePlatform } from '../testing/fakePlatform.js'
import { HARNESSD_STATUS_FILE } from './daemonState.js'
import {
- CARRIED_ENV, describeState, installedPlatform, platformDaemonDeps, serviceDefinition, startUnderPlatform, stopUnderPlatform,
+ CARRIED_ENV, describeState, installedPlatform, osDaemonUnit, platformDaemonDeps, serviceDefinition, startUnderPlatform, stopUnderPlatform,
supervisingPlatform, waitForMaster, waitGone, type PlatformDaemonDeps,
} from './platformDaemon.js'
@@ -118,6 +120,50 @@ describe.each(['launchd', 'systemd'] as const)('under %s', (platform) => {
})
})
+describe('on Harness OS', () => {
+ const there = (path: string) => path === OS_UNIT_FILE
+
+ it('runs its daemon under the package\'s unit, for the data folder and port that unit runs', () => {
+ expect(osDaemonUnit('linux', {}, there)).toBe(true)
+ expect(osDaemonUnit('linux', { PORT: '18473' }, there)).toBe(true)
+ expect(osDaemonUnit('linux', {}, () => false)).toBe(false)
+ expect(osDaemonUnit('linux', { ADAPTER_DATA_DIR: '/tmp/test-daemon' }, there)).toBe(false)
+ expect(osDaemonUnit('linux', { PORT: '18474' }, there)).toBe(false)
+ expect(osDaemonUnit('linux', { HARNESSD_TEST_PLATFORM: 'systemd' }, there)).toBe(false)
+ expect(osDaemonUnit('darwin', {}, there)).toBe(false)
+ })
+
+ let w: ReturnType<typeof world>
+ let os: PlatformDaemonDeps
+ beforeEach(() => {
+ w = world('systemd')
+ const base = { ...defaultPlatformDeps({ env: { PATH: w.fake.bin }, uid: 1000, home: w.home }), run: w.fake.run }
+ os = { ...w.deps, service: new PlatformService('systemd', { ...base, readFile: (path) => (there(path) ? '[Service]\n' : base.readFile(path)) }, true) }
+ })
+ afterEach(() => rmSync(w.dir, { recursive: true, force: true }))
+
+ it('starts through the unit and waits for its core, writing no definition of its own', async () => {
+ expect(installedPlatform(os)).toBe('systemd')
+ await expect(startUnderPlatform(w.definition, os, 1_000)).resolves.toEqual({ ok: true, pid: 4242, refreshed: false })
+ expect(existsSync(join(w.home, '.config', 'systemd', 'user', SYSTEMD_UNIT))).toBe(false)
+ expect(w.fake.calls()).toEqual([
+ ['systemctl', '--user', 'reset-failed', OS_SYSTEMD_UNIT],
+ ['systemctl', '--user', 'start', '--no-block', OS_SYSTEMD_UNIT],
+ ])
+ })
+
+ it('stops the unit\'s own core, and leaves a daemon started beside the unit to the signals', () => {
+ w.fake.set({ pid: 4242 })
+ expect(stopUnderPlatform(os)).toEqual({ ok: true, stopped: 4242 })
+ expect(w.fake.calls()).toContainEqual(['systemctl', '--user', 'kill', '--kill-who=main', '--signal=SIGTERM', OS_SYSTEMD_UNIT])
+ // A sign-in before this fix restarted the daemon outside the unit: the unit runs nothing, and
+ // `harness stop` goes on to signal the pid on file, as it stops any daemon `harness start` spawned.
+ writeFileSync(w.pidFile, '2288\n')
+ expect(stopUnderPlatform(os)).toEqual({ ok: true, stopped: null })
+ for (const call of w.fake.calls()) expect(call.filter((word) => ['stop', 'restart'].includes(word))).toEqual([])
+ })
+})
+
describe('waiting', () => {
const clocked = (alive: (pid: number, now: number) => boolean, pid: () => number | null = () => 7) => {
const clock = { now: 0 }
diff --git a/cli/src/lib/platformDaemon.ts b/cli/src/lib/platformDaemon.ts
index 8c40b4aa1..4c6fe4694 100644
--- a/cli/src/lib/platformDaemon.ts
+++ b/cli/src/lib/platformDaemon.ts
@@ -12,12 +12,18 @@
* definition, and a shell in a tmux pane the daemon started inherits it; it would otherwise believe it
* was the platform. What counts is the definition on disk, and what the running master wrote in its
* status file.
+ *
+ * Harness OS is the one computer where nobody opts in: its package ships the unit (OS_UNIT_FILE), so
+ * there every start and stop of its daemon goes through that unit (osDaemonUnit).
*/
+import { existsSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
import { env } from '../config/env.js'
import { readStatusFile } from '../harnessd/master.js'
-import { PlatformService, defaultPlatformDeps, platformFor, type PlatformName, type PlatformState, type ServiceDefinition } from '../harnessd/platform.js'
+import {
+ OS_UNIT_FILE, PlatformService, defaultPlatformDeps, platformFor, type PlatformName, type PlatformState, type ServiceDefinition,
+} from '../harnessd/platform.js'
import { DAEMON_LOG_FILE, HARNESSD_STATUS_FILE, isAlive, readPid } from './daemonState.js'
import { managedNodePath } from './nodeRuntime.js'
@@ -61,11 +67,27 @@ export function supervisingPlatform(os: NodeJS.Platform, env: NodeJS.ProcessEnv)
return forced === 'launchd' || forced === 'systemd' ? forced : platformFor(os)
}
+/** The port Harness OS's unit runs the daemon on: the default, as it sets none. */
+const OS_DAEMON_PORT = '18473'
+
+/**
+ * Whether this CLI's daemon is the one Harness OS runs under its own unit: the unit is on disk, and this
+ * CLI is on the data folder and port the unit runs, the defaults, as it sets neither. A shell with its
+ * own ADAPTER_DATA_DIR or PORT (a test, a second daemon) has a daemon of its own, which the unit is not.
+ * Never under the end-to-end suite's forced platform, whose fakes stand in for this computer's.
+ */
+export function osDaemonUnit(os: NodeJS.Platform, env: NodeJS.ProcessEnv, exists: (path: string) => boolean = existsSync): boolean {
+ if (os !== 'linux' || env.HARNESSD_TEST_PLATFORM) return false
+ if (env.ADAPTER_DATA_DIR || (env.PORT && env.PORT !== OS_DAEMON_PORT)) return false
+ return exists(OS_UNIT_FILE)
+}
+
/** This computer's: its platform, its pid file, the status file its master writes. */
export function platformDaemonDeps(overrides: Partial<PlatformDaemonDeps> = {}): PlatformDaemonDeps {
const platform = supervisingPlatform(process.platform, process.env)
+ const os = platform === 'systemd' && osDaemonUnit(process.platform, process.env)
return {
- service: platform ? new PlatformService(platform, defaultPlatformDeps()) : null,
+ service: platform ? new PlatformService(platform, defaultPlatformDeps(), os) : null,
logFile: DAEMON_LOG_FILE,
readPid,
isAlive,
diff --git a/cli/src/lib/serviceCommand.spec.ts b/cli/src/lib/serviceCommand.spec.ts
index e7a7a5cd9..a121e67e4 100644
--- a/cli/src/lib/serviceCommand.spec.ts
+++ b/cli/src/lib/serviceCommand.spec.ts
@@ -2,7 +2,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { PlatformService, defaultPlatformDeps, type PlatformName } from '../harnessd/platform.js'
+import { OS_SYSTEMD_UNIT, OS_UNIT_FILE, PlatformService, SYSTEMD_UNIT, defaultPlatformDeps, type PlatformName } from '../harnessd/platform.js'
import { fakePlatform, type FakePlatform } from '../testing/fakePlatform.js'
import { serviceDefinition } from './platformDaemon.js'
import { SERVICE_USAGE, serviceCommand, serviceCommandDeps, type ServiceCommandDeps } from './serviceCommand.js'
@@ -89,6 +89,28 @@ describe('harness service', () => {
expect(c.out).toEqual(['{"supported":false}'])
} finally { rmSync(c.dir, { recursive: true, force: true }) }
})
+
+ it('installs and removes nothing on Harness OS, whose package runs harnessd under its own unit, and says how it stands', async () => {
+ const c = computer('systemd')
+ try {
+ const base = { ...defaultPlatformDeps({ env: { PATH: c.fake.bin }, uid: 501, home: c.home }), run: c.fake.run }
+ const os = { ...c.deps, service: new PlatformService('systemd', { ...base, readFile: (path) => (path === OS_UNIT_FILE ? '[Service]\n' : base.readFile(path)) }, true) }
+ c.runOutside(2288)
+ await expect(serviceCommand(['install'], os)).resolves.toBe(1)
+ await expect(serviceCommand(['uninstall'], os)).resolves.toBe(1)
+ expect(c.err).toEqual([
+ `Harness OS runs harnessd under ${OS_SYSTEMD_UNIT} already: \`harness start\` and \`harness stop\` go through it, and there is nothing to install.`,
+ `Harness OS runs harnessd under ${OS_SYSTEMD_UNIT} already: \`harness start\` and \`harness stop\` go through it, and there is nothing to uninstall.`,
+ ])
+ expect(c.stops).toEqual([])
+ expect(c.outside.pid).toBe(2288)
+ expect(c.fake.calls()).toEqual([])
+ expect(existsSync(join(c.home, '.config', 'systemd', 'user', SYSTEMD_UNIT))).toBe(false)
+ c.fake.set({ loaded: true, pid: 4242 })
+ await expect(serviceCommand(['status', '--json'], os)).resolves.toBe(0)
+ expect(JSON.parse(c.out.at(-1)!)).toMatchObject({ supported: true, file: OS_UNIT_FILE, target: OS_SYSTEMD_UNIT, installed: true, current: true, registered: true, pid: 4242 })
+ } finally { rmSync(c.dir, { recursive: true, force: true }) }
+ })
})
describe.each(['launchd', 'systemd'] as const)('harness service under %s', (platform) => {
diff --git a/cli/src/lib/serviceCommand.ts b/cli/src/lib/serviceCommand.ts
index ba45145ed..ac4526188 100644
--- a/cli/src/lib/serviceCommand.ts
+++ b/cli/src/lib/serviceCommand.ts
@@ -68,6 +68,10 @@ export async function serviceCommand(argv: string[], deps: ServiceCommandDeps):
else deps.err('harness service runs harnessd under launchd (macOS) or systemd (Linux); this computer has neither.')
return verb === 'status' ? 0 : 1
}
+ if (deps.service.os && verb !== 'status') {
+ deps.err(`Harness OS runs harnessd under ${deps.service.target} already: \`harness start\` and \`harness stop\` go through it, and there is nothing to ${verb}.`)
+ return 1
+ }
if (verb === 'install') return installService(deps)
if (verb === 'uninstall') return uninstallService(deps)
return serviceStatus(deps, json)
diff --git a/os/DEVELOPMENT.md b/os/DEVELOPMENT.md
index 544a55c4e..c3a450a7d 100644
--- a/os/DEVELOPMENT.md
+++ b/os/DEVELOPMENT.md
@@ -366,7 +366,12 @@ The installed system keeps hn's standard status bar. Super+u records an update
request and selects the Updates terminal; the request starts checking/applying
without another key. `harness updates` opens the same screen for inspection,
with a clickable **Update** button. An hn-only change reconnects the screen;
-a CLI change also restarts its supervised service. Failure restores the previous
+a CLI change also restarts its supervised service. Only `harness-daemon.service`'s own
+daemon counts: one serving beside it is stopped first, and activation fails unless the
+unit's daemon answers afterward. The CLI starts and stops the daemon through that unit
+on Harness OS (`cli/src/lib/platformDaemon.ts`), so a sign-in or sign-out cannot move it
+outside systemd. Never `systemctl stop` the unit: every pane's scope is PartOf it.
+Failure restores the previous
selection. `harness updates rollback` restores the previous runtime and holds
rejected versions until a newer release arrives. Ordinary macOS/Linux hn is unchanged.
diff --git a/os/live_update.py b/os/live_update.py
index 66832972a..0ccd48ee0 100644
--- a/os/live_update.py
+++ b/os/live_update.py
@@ -36,6 +36,8 @@ FILES = ('harness-tui', 'cli.mjs', 'notify.mjs')
LIMIT = 64 * 1024 * 1024
DOWNLOAD_CHUNK = 1024 * 1024
RESTART_REQUIRED = Path('/run/harness-os-restart-required')
+DAEMON_UNIT = 'harness-daemon.service'
+DAEMON_STATUS = 'http://127.0.0.1:18473/api/status'
KEEP_ON = 'Keep the computer on and plugged in until the system update finishes.'
SYSTEM_LOCK = Path('/run/lock/hn-os.lock')
BOOT_ID = Path('/proc/sys/kernel/random/boot_id')
@@ -498,10 +500,36 @@ def select(folder):
sync_directory(STATE)
+def runtime_pids():
+ """The process serving the agent runtime, and harness-daemon.service's main process.
+
+ Either is None: nothing answers on the runtime's port, or the unit runs nothing.
+ """
+ try:
+ with urlopen(Request(DAEMON_STATUS), timeout=3) as response:
+ serving = json.loads(response.read(65536)).get('pid')
+ except (OSError, ValueError, AttributeError):
+ serving = None
+ main = run('systemctl', '--user', 'show', DAEMON_UNIT, '--property=MainPID', '--value', timeout=10)
+ return (serving if type(serving) is int and serving > 0 else None,
+ int(main) if main.isdigit() and int(main) > 0 else None)
+
+
def restart(cli_changed):
if cli_changed:
- run('systemctl', '--user', 'restart', 'harness-daemon.service', timeout=180)
+ # Restarting the unit replaces only its own daemon. One serving beside it (an older CLI's
+ # sign-in restarted the daemon outside systemd) keeps the port: the unit's new core then fails
+ # until systemd gives up, and the old CLI goes on serving. Stop that one first, as `harness
+ # stop` stops any daemon: with signals, which the agents in tmux outlive.
+ serving, main = runtime_pids()
+ if serving is not None and serving != main:
+ run('/usr/bin/harness', 'stop', timeout=90)
+ run('systemctl', '--user', 'restart', DAEMON_UNIT, timeout=180)
+ # wait-runtime accepts whichever daemon answers. Activation needs the unit's own.
run('/usr/lib/harness-os/wait-runtime')
+ serving, main = runtime_pids()
+ if serving is None or serving != main:
+ raise ValueError(f'The agent runtime is not running under {DAEMON_UNIT}.')
# The terminal surface is separate from the processes that own agent PTYs.
run('systemctl', '--user', 'restart', 'hn-screen.service')
run('systemctl', '--user', 'is-active', '--quiet', 'hn-screen.service')
diff --git a/os/tests/test_live_update.py b/os/tests/test_live_update.py
index c56aec369..3e838b23a 100644
--- a/os/tests/test_live_update.py
+++ b/os/tests/test_live_update.py
@@ -941,5 +941,53 @@ class ScreenSelection(unittest.TestCase):
run.assert_not_called()
+class RuntimeSupervision(unittest.TestCase):
+ """A CLI change takes effect only through harness-daemon.service's own daemon."""
+
+ SCREEN = [('systemctl', '--user', 'restart', 'hn-screen.service'),
+ ('systemctl', '--user', 'is-active', '--quiet', 'hn-screen.service')]
+
+ def restart(self, pids, cli_changed=True):
+ calls = []
+ with patch.object(update, 'run', side_effect=lambda *args, **kwargs: calls.append(args) or ''), \
+ patch.object(update, 'runtime_pids', side_effect=pids):
+ update.restart(cli_changed)
+ return calls
+
+ def test_the_units_daemon_is_restarted_and_must_serve_afterwards(self):
+ self.assertEqual(self.restart([(1347, 1347), (42916, 42916)]), [
+ ('systemctl', '--user', 'restart', 'harness-daemon.service'),
+ ('/usr/lib/harness-os/wait-runtime',), *self.SCREEN])
+
+ def test_a_daemon_serving_beside_the_unit_is_stopped_before_the_restart(self):
+ # 2026-10-12: a sign-in restarted the daemon outside systemd. Restarting the unit alone
+ # left that one serving the old CLI while the unit's new core failed on the taken port.
+ calls = self.restart([(2288, None), (42916, 42916)])
+ self.assertEqual(calls[:2], [('/usr/bin/harness', 'stop'), ('systemctl', '--user', 'restart', 'harness-daemon.service')])
+ self.assertEqual(self.restart([(2288, 1347), (42916, 42916)])[0], ('/usr/bin/harness', 'stop'))
+
+ def test_activation_fails_unless_the_units_own_daemon_answers(self):
+ for after in [(2288, None), (2288, 43000), (None, 43000), (None, None)]:
+ with self.subTest(after=after), self.assertRaisesRegex(ValueError, 'not running under harness-daemon.service'):
+ self.restart([(None, None), after])
+
+ def test_an_hn_only_change_leaves_the_daemon_alone(self):
+ self.assertEqual(self.restart([], cli_changed=False), self.SCREEN)
+
+ def test_pids_come_from_the_runtime_and_systemd(self):
+ def ask(answer, main):
+ opened = patch.object(update, 'urlopen', side_effect=answer if isinstance(answer, Exception) else lambda *a, **k: Response(answer))
+ with opened, patch.object(update, 'run', return_value=main) as run:
+ pids = update.runtime_pids()
+ run.assert_called_once_with('systemctl', '--user', 'show', 'harness-daemon.service', '--property=MainPID', '--value', timeout=10)
+ return pids
+ self.assertEqual(ask(b'{"pid": 1347, "version": "0.3.80"}', '1347'), (1347, 1347))
+ self.assertEqual(ask(b'{"pid": 2288}', '0'), (2288, None))
+ self.assertEqual(ask(OSError('Connection refused'), '42916'), (None, 42916))
+ for odd in [b'not json', b'[1347]', b'{"pid": "1347"}', b'{"pid": true}', b'{"pid": 0}']:
+ with self.subTest(odd=odd):
+ self.assertEqual(ask(odd, ''), (None, None))
+
+
if __name__ == '__main__':
unittest.main()