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.

Isolate daemon tests from their host and finish load-stability fixes (#1007)

Dee4fb12b5102aa
diff --git a/cli/e2e/harness/daemon.ts b/cli/e2e/harness/daemon.ts
index 53f512633..40a823859 100644
--- a/cli/e2e/harness/daemon.ts
+++ b/cli/e2e/harness/daemon.ts
@@ -19,6 +19,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url'
import { promisify } from 'node:util'
import { isolatedTmux, type IsolatedTmux } from '../../src/testing/isolatedTmux.js'
import { artifactLog, artifactsEnabled } from './artifacts.js'
+import { daemonEnvironment } from '../../src/testing/daemonEnvironment.js'
const exec = promisify(execFile)
const here = dirname(fileURLToPath(import.meta.url))
@@ -219,8 +220,7 @@ export class IsolatedDaemon {
`#!${process.execPath}\nimport(${JSON.stringify(engine)}).then((m) => m.run(${JSON.stringify(name)}, ${JSON.stringify(config)}))\n`,
{ mode: 0o755 })
}
- const env: NodeJS.ProcessEnv = {
- ...tmux.env,
+ const env = daemonEnvironment(tmux.env, {
NODE_ENV: 'test',
HOME: dirs.home,
// A login shell in a pane must not load anyone's zsh configuration.
@@ -258,7 +258,7 @@ export class IsolatedDaemon {
TMUX_REAP_INTERVAL_MS: '5000',
TERMINAL_RECONCILE_INTERVAL_MS: '5000',
...options.env,
- }
+ })
// A Claude Code home moved in the environment this run was started from is the person's: the daemon
// would adopt it and install its hooks there (lib/engineHomes.ts). Only a test may move one.
if (!options.env || !('CLAUDE_CONFIG_DIR' in options.env)) delete env.CLAUDE_CONFIG_DIR
diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.ts
index 77ad3341b..8c5cb484d 100644
--- a/cli/src/cable/cableSession.spec.ts
+++ b/cli/src/cable/cableSession.spec.ts
@@ -127,6 +127,11 @@ async function connect(host: CableHost = makeHost(), log = tmpLog()) {
/** Let the microtask queue drain — every send is async. */
const settle = () => new Promise((r) => setTimeout(r, 0))
+/** For a push that only the session's own tick sends: it ticks every second, and a change made just after a
+ * tick waits a whole one. vi.waitFor's default second raced that tick, and lost under load (a full unit run
+ * with 12 busy loops, load 93). Several ticks' room. */
+const NEXT_TICKS = { timeout: 5_000 }
+
describe('cable session', () => {
const companionSettings = {
brightness: 40, character: 2, face: 466, muted: true, quiet: false,
@@ -711,7 +716,7 @@ describe('cable session', () => {
await settle()
expect(host.selectSwarm).toHaveBeenCalledWith('s2')
swarms = { ...swarms, selected: 's2' }
- await vi.waitFor(() => expect(port.sent.filter((m) => m.t === 'swarms')).toHaveLength(2))
+ await vi.waitFor(() => expect(port.sent.filter((m) => m.t === 'swarms')).toHaveLength(2), NEXT_TICKS)
expect(port.sent.filter((m) => m.t === 'swarms')[1]).toMatchObject({ selected: 's2' })
await session.stop()
})
@@ -727,7 +732,7 @@ describe('cable session', () => {
await vi.waitFor(() => expect(port.sent.filter((m) => m.t === 'swarms')).toHaveLength(1))
swarms = { selected: 's1', swarms: [{ id: 's1', name: 'Shell', agents: 0, panes: 1 }], tiles: [] }
- await vi.waitFor(() => expect(port.sent.filter((m) => m.t === 'swarms')).toHaveLength(2))
+ await vi.waitFor(() => expect(port.sent.filter((m) => m.t === 'swarms')).toHaveLength(2), NEXT_TICKS)
expect(port.sent.filter((m) => m.t === 'swarms')[1]).toMatchObject({
items: [{ id: 's1', agents: 0, panes: 1 }],
})
diff --git a/cli/src/cliCommand.spec.ts b/cli/src/cliCommand.spec.ts
index 1105f8c9a..adcb23577 100644
--- a/cli/src/cliCommand.spec.ts
+++ b/cli/src/cliCommand.spec.ts
@@ -75,13 +75,23 @@ function envFor(root: string, extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv
}
}
+/**
+ * How long one CLI run may take before it is ended as a hang. Every run here is the CLI itself under tsx:
+ * node, then cli.ts and everything it imports, before the command runs. About 2 s on a quiet Mac; past the
+ * old 15 s for `harness join` in a full unit run under load (12 busy loops, load 110), where it only prints
+ * a refusal. A hang still ends, its group with it; only later.
+ */
+const CLI_RUN_MS = 45_000
+/** A test that makes one such run: room for the run's own deadline and its teardown. */
+const ONE_RUN_TEST_MS = CLI_RUN_MS + 15_000
+
/** `harness [args]` under a throwaway HOME, to the end. Never 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. One that has not ended within 15s is ended, everything it started with it, and
- * comes back with `timedOut`. */
+ * child asks for it. One that has not ended within CLI_RUN_MS is ended, everything it started with it,
+ * and comes back with `timedOut`. */
async function runAsync(root: string, args: string[], extra: NodeJS.ProcessEnv): Promise<{ status: number | null; stdout: string; stderr: string; timedOut: boolean }> {
const { status, stdout, stderr, timedOut } = await runs.complete(root, [TSX, CLI_SOURCE, ...args], {
- cwd: CLI_ROOT, env: envFor(root, extra), label: `harness ${args.join(' ')}`,
+ cwd: CLI_ROOT, env: envFor(root, extra), label: `harness ${args.join(' ')}`, ms: CLI_RUN_MS,
})
return { status, stdout, stderr, timedOut }
}
@@ -169,21 +179,21 @@ describe('CLI login/start command contract', () => {
expect(result.status).toBe(1)
expect(result.stderr).toContain('`harness join` has been removed.')
expect(result.stderr).toContain('`harness login`, then `harness start`')
- }, 20_000)
+ }, ONE_RUN_TEST_MS)
it('no longer has an analytics command (usage metering upload was removed)', async () => {
const result = await run('analytics')
expect(result.status).toBe(1)
expect(result.stderr).toContain('Unknown command: analytics')
- }, 20_000)
+ }, ONE_RUN_TEST_MS)
it('returns a nonzero status for an unknown command', async () => {
const result = await run('not-a-command')
expect(result.status).toBe(1)
expect(result.stderr).toContain('Unknown command: not-a-command')
- }, 20_000)
+ }, ONE_RUN_TEST_MS)
})
describe('the processes this spec starts', () => {
@@ -273,7 +283,7 @@ describe('start --repair beside a running daemon', () => {
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)
+ }, ONE_RUN_TEST_MS)
it('a plain start beside a running daemon touches nothing', async () => {
const root = freshRoot()
@@ -286,7 +296,7 @@ describe('start --repair beside a running daemon', () => {
expect(result.status).toBe(0)
expect(result.stdout).toContain('already running')
expect(result.stdout).not.toContain('installing the Harness grid runtime')
- }, 20_000)
+ }, ONE_RUN_TEST_MS)
})
describe('start beside a daemon that serves another account', () => {
@@ -313,7 +323,7 @@ describe('start beside a daemon that serves another account', () => {
// consulted (start no longer resolves the machine when the session already names one).
expect(result.status).toBe(1)
expect(result.stdout + result.stderr).not.toContain('resolve-computer')
- }, 20_000)
+ }, ONE_RUN_TEST_MS)
it('starts without the backend: a session that already names its machine never calls it', async () => {
// Offline is the case this exists for. The backend here is port 1 — refused instantly — and the
@@ -328,7 +338,7 @@ describe('start beside a daemon that serves another account', () => {
expect(result.stderr).not.toContain('fetch failed')
expect(result.stdout + result.stderr).not.toContain('resolve-computer')
expect(result.stdout).toContain('dev mode — running in the foreground')
- }, 20_000)
+ }, ONE_RUN_TEST_MS)
it('starts without the backend even when the session has no machine id yet, on the computer id', async () => {
const root = freshRoot()
@@ -343,7 +353,7 @@ describe('start beside a daemon that serves another account', () => {
expect(result.stdout).toContain('machine id not resolved yet')
expect(result.stdout).toContain('dev mode — running in the foreground')
- }, 20_000)
+ }, ONE_RUN_TEST_MS)
it('leaves one that serves this session alone', async () => {
const root = freshRoot()
@@ -358,7 +368,7 @@ describe('start beside a daemon that serves another account', () => {
expect(existsSync(join(root, 'data', 'adapter.pid'))).toBe(true)
await expect(Promise.race([daemon.exited.then(() => 'exited'), new Promise((r) => setTimeout(() => r('alive'), 300))]))
.resolves.toBe('alive')
- }, 20_000)
+ }, ONE_RUN_TEST_MS)
})
describe('harness service, through the CLI', () => {
@@ -421,5 +431,5 @@ describe('harness service, through the CLI', () => {
expect(uninstall.stdout).toContain(`no longer runs harnessd`)
expect(uninstall.stdout).not.toContain('starting it the usual way')
expect(existsSync(file)).toBe(false)
- }, 60_000)
+ }, 6 * ONE_RUN_TEST_MS) // six runs, one after another
})
diff --git a/cli/src/core/deviceInput.spec.ts b/cli/src/core/deviceInput.spec.ts
index 94b5c0c81..fdce70610 100644
--- a/cli/src/core/deviceInput.spec.ts
+++ b/cli/src/core/deviceInput.spec.ts
@@ -409,13 +409,17 @@ it('says why a write the pane refused was not typed, when a dialog opened after
device.forget('agent')
})
+// "Later" on a fake clock: past every retry the device could schedule (VERIFY_MS, 1.5 s) several times over,
+// at no cost in real time. It waited 2 s of real time, which with the wait before it took the case past
+// vitest's 5 s in a full run under load.
it('refuses with the reason a message typed but not sent, its Enter withheld as a dialog opened, and presses no Enter later', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] })
const onDelivery = vi.fn(), sendKey = vi.fn(async () => true)
const device = makeDevice({ inject: async () => ({ state: 'unknown', dispatch: 'possibly_executed', reason: 'enter_withheld:question_open' }),
isAwaitingUser: async () => false, onDelivery, sendKey, capture: async () => '› A' })
device.submit('agent', 'A', 'delivery-A')
await vi.waitFor(() => expect(onDelivery).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'delivery-A', state: 'rejected', reason: 'enter_withheld' })))
- await new Promise((resolve) => setTimeout(resolve, 2_000))
+ await vi.advanceTimersByTimeAsync(10_000)
expect(sendKey).not.toHaveBeenCalled()
device.forget('agent')
})
diff --git a/cli/src/dsh/shell.spec.ts b/cli/src/dsh/shell.spec.ts
index eaecb67d2..3deeb2c04 100644
--- a/cli/src/dsh/shell.spec.ts
+++ b/cli/src/dsh/shell.spec.ts
@@ -19,7 +19,7 @@ vi.mock('node:child_process', async (importOriginal) => {
})
const { managedNodePath } = await import('../lib/nodeRuntime.js')
-const { dshNodeFallback, dshShellArgv, isShellNoise, killProcessGroup, runDshCommand, spawnDshCommand } = await import('./shell.js')
+const { dshNodeFallback, dshShellArgv, isKilledJobReport, isShellNoise, killProcessGroup, runDshCommand, spawnDshCommand } = await import('./shell.js')
describe('dshShellArgv', () => {
const original = process.env.SHELL
@@ -133,6 +133,27 @@ describe('runDshCommand', () => {
expect(Date.now() - started).toBeLessThan(10_000)
})
+ it('does not take the shell\'s report of the job its stop ended for the command\'s output', async () => {
+ // The shell outlives its job here on purpose: it ignores SIGTERM, so it is in `wait` when the job the stop
+ // ended dies, and reports it, as it did under load when the job's death reached it first.
+ const report = '/bin/sh: line 1: 31849 Terminated: 15 sleep 30'
+ const result = await runDshCommand(`echo started; trap 'echo "${report}" >&2; printf "${report}" >&2; exit 0' TERM; sleep 30 & wait`, { cwd: dir, timeoutMs: 300 })
+ expect(result.timedOut).toBe(true)
+ expect(result.lines).toEqual(['started'])
+ // Before a stop, the same words are the command's own.
+ expect((await runDshCommand(`echo "${report}"`, { cwd: dir })).lines).toEqual([report])
+ })
+
+ it('knows the shell\'s report of a job a signal ended, as bash words it on macOS and Linux', () => {
+ expect(isKilledJobReport('/bin/sh: line 1: 31849 Terminated: 15 sleep 30')).toBe(true)
+ expect(isKilledJobReport('bash: line 1: 10678 Terminated: 15 ( sleep 0.2; kill -TERM $$ )')).toBe(true)
+ expect(isKilledJobReport('bash: line 1: 4242 Terminated sleep 30')).toBe(true)
+ expect(isKilledJobReport('bash: line 3: 86178 Killed: 9 sleep 30')).toBe(true)
+ expect(isKilledJobReport('Terminated: 15')).toBe(false)
+ expect(isKilledJobReport('sh: line 1: 12 Segmentation fault: 11 ./tool')).toBe(false)
+ expect(isKilledJobReport('started')).toBe(false)
+ })
+
it('a command that cannot start is exit 127 with the reason as its one line, never a rejection', async () => {
const missingCwd = await runDshCommand('true', { cwd: join(dir, 'missing') })
expect(missingCwd.code).toBe(127)
diff --git a/cli/src/dsh/shell.ts b/cli/src/dsh/shell.ts
index 917101084..628d7c0b3 100644
--- a/cli/src/dsh/shell.ts
+++ b/cli/src/dsh/shell.ts
@@ -37,6 +37,17 @@ export function isShellNoise(line: string): boolean {
const BASH_NO_TTY = /^(?:\S*\/)?bash: (?:cannot set terminal process group \(-?\d+\): Inappropriate ioctl for device|no job control in this shell)$/
+/**
+ * The shell's report of a job of its own that a signal ended (`/bin/sh: line 1: 31849 Terminated: 15 sleep 30`
+ * on macOS, `bash: line 1: 31849 Terminated sleep 30` on Linux). Once a command has outlived its timeout its
+ * whole group is sent SIGTERM, and a shell that is still in `wait` when its job dies says so before it goes:
+ * that is the stop, told by the shell, not the command's output. Seen under load (a full unit run with 12
+ * busy loops), where the job's death reached the shell before the shell's own SIGTERM did.
+ */
+export function isKilledJobReport(line: string): boolean {
+ return /^(?:\S*\/)?(?:ba)?sh: line \d+: +\d+ (?:Terminated|Killed)(?::\s*\d+)?\s+\S/.test(line)
+}
+
/**
* `[path, ...args]` that runs `script` through the user's shell, or `/bin/sh -c` when none is known.
*
@@ -103,7 +114,7 @@ export function runDshCommand(script: string, opts: DshCommandOptions): Promise<
while ((at = carry.rest.indexOf('\n')) >= 0) {
const line = carry.rest.slice(0, at).replace(/\r$/, '')
carry.rest = carry.rest.slice(at + 1)
- if (isShellNoise(line)) continue
+ if (isShellNoise(line) || (timedOut && isKilledJobReport(line))) continue
lines.push(line)
opts.onLine?.(line)
}
@@ -117,7 +128,7 @@ export function runDshCommand(script: string, opts: DshCommandOptions): Promise<
settled = true
if (timer) clearTimeout(timer)
for (const carry of [out, err]) {
- if (carry.rest) { lines.push(carry.rest); opts.onLine?.(carry.rest) }
+ if (carry.rest && !(timedOut && isKilledJobReport(carry.rest))) { lines.push(carry.rest); opts.onLine?.(carry.rest) }
}
resolve({ code, signal, lines, timedOut })
}
diff --git a/cli/src/harnessd/master.spec.ts b/cli/src/harnessd/master.spec.ts
index ebe0ac9bc..9a3f2808c 100644
--- a/cli/src/harnessd/master.spec.ts
+++ b/cli/src/harnessd/master.spec.ts
@@ -860,10 +860,14 @@ describe('runMaster', { timeout: 60_000 }, () => {
it('abandons a probe still running when it is stopped, and replaces nothing', async () => {
const script = bundle(`if (process.env.HARNESSD_RESTARTS === '0') setTimeout(() => { fs.appendFileSync(__filename, '\\n// a newer build\\n'); process.exit(75) }, 100)`,
- `fs.writeFileSync(${JSON.stringify(join(dir, 'probing'))}, String(process.pid)); setInterval(() => {}, 1000)`)
+ `fs.writeFileSync(${JSON.stringify(join(dir, 'probing.tmp'))}, String(process.pid)); fs.renameSync(${JSON.stringify(join(dir, 'probing.tmp'))}, ${JSON.stringify(join(dir, 'probing'))}); setInterval(() => {}, 1000)`)
const master = start(script)
+ // Written whole, then renamed into place: the file seen created but not yet written read as pid 0,
+ // and `kill(0, 0)` asks after this process's own group, which is always there. The probe was never
+ // seen gone (a full unit run under 12 busy loops, load 87).
await until('the probe to be running', () => existsSync(join(dir, 'probing')))
const probe = Number(readFileSync(join(dir, 'probing'), 'utf8'))
+ expect(probe).toBeGreaterThan(0)
await master.stop()
await until('the probe to be gone', () => { try { process.kill(probe, 0); return false } catch { return true } })
expect(master.execs).toEqual([])
diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.ts
index 4c8e2bca1..b1726b86a 100644
--- a/cli/src/hookNotify.spec.ts
+++ b/cli/src/hookNotify.spec.ts
@@ -770,11 +770,13 @@ describe('hook notify terminal scope', () => {
hermesHome: join(dir, 'hermes'),
dataDir,
hermesSource: 'cli',
- // 1.5 s against the shipped 3 s limit: a store slower than the old 1 s limit still binds. Twice the
- // shipped budget doubles both (3 s against 6 s), and leaves a loaded machine 3 s to start sqlite3,
- // rather than the 20 s limit and 10 s wait the suite's 30 s budget would make of them.
- hermesDelaySeconds: 1.5,
- env: { HARNESS_HOOK_DEADLINE_MS: '9000' },
+ // 1.2 s against the shipped 3 s limit: a store slower than the old 1 s limit still binds. Four times
+ // the shipped budget stretches all three (4.8 s against 12 s; the old limit would be 4 s, so this
+ // still tells them apart) and leaves a loaded machine over 7 s for what is not the store: starting
+ // the hook's fake tmux, ps and sqlite3. At twice the budget (3 s against 6 s, 9 s in all) the earlier
+ // steps under a full run at load 110 left sqlite3 less than its 3 s, and nothing was registered.
+ hermesDelaySeconds: 1.2,
+ env: { HARNESS_HOOK_DEADLINE_MS: '18000' },
input: { hook_event_name: 'on_session_start', session_id: '20260810_120003_a1b2c3' },
})
expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))).toMatchObject([{
diff --git a/cli/src/lib/__fixtures__/fakeRelay.ts b/cli/src/lib/__fixtures__/fakeRelay.ts
index 0493a9b9c..57c04fb12 100644
--- a/cli/src/lib/__fixtures__/fakeRelay.ts
+++ b/cli/src/lib/__fixtures__/fakeRelay.ts
@@ -25,6 +25,12 @@ export async function startFakeRelay(): Promise<FakeRelay> {
const seen: RelayRequest[] = []
const answers = new Map<string, RelayAnswer | (() => RelayAnswer)>()
const server = createServer((req, res) => {
+ // Only what was sent to a grid's address is the spec's: a request with Node's own User-Agent, which no
+ // grid read sends, reached gridReads.spec.ts's relay port under load, from outside the code under test.
+ if (!req.url?.startsWith('/g/')) {
+ res.writeHead(404).end()
+ return
+ }
seen.push({ method: req.method ?? '', path: req.url ?? '', headers: req.headers })
const planned = answers.get(req.url ?? '')
const found = (typeof planned === 'function' ? planned() : planned) ?? { status: 404, body: { detail: 'Not Found' } }
diff --git a/cli/src/lib/e2ee/passwordPake.spec.ts b/cli/src/lib/e2ee/passwordPake.spec.ts
index cf3326341..787d61769 100644
--- a/cli/src/lib/e2ee/passwordPake.spec.ts
+++ b/cli/src/lib/e2ee/passwordPake.spec.ts
@@ -1,7 +1,12 @@
-import { describe, expect, it } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
import { RistrettoPoint } from '@noble/curves/ed25519'
import * as C from './core.js'
-import { pwCpaceGenerator, pwContext, stretchPassword } from './passwordPake.js'
+import { PW_SCRYPT_TEST_TIMEOUT_MS, pwCpaceGenerator, pwContext, stretchPassword } from './passwordPake.js'
+
+// Most cases here run one or two real scrypts (N=2^17), the cost being the point: the budget the other password
+// suites give theirs. One with two of them ran past vitest's 5 s in a full unit run under load (12 busy loops,
+// load 87).
+vi.setConfig({ testTimeout: PW_SCRYPT_TEST_TIMEOUT_MS })
const MACHINE_A = 'f2e0383771b734e4fc00f0bc8ccf060f'
const MACHINE_B = 'a1b2c3d4e5f60718293a4b5c6d7e8f90'
diff --git a/cli/src/lib/gridActs.spec.ts b/cli/src/lib/gridActs.spec.ts
index 0abb230af..8578500d8 100644
--- a/cli/src/lib/gridActs.spec.ts
+++ b/cli/src/lib/gridActs.spec.ts
@@ -18,6 +18,11 @@ import { annotate, glanceFor } from './gridAnnotation.js'
import { presentGridSections, resetGridModels, type GridModelsService, type GridSection } from './gridModels.js'
import type { RegisteredSession } from './registry.js'
+// Every look starts the fake `grid`, a node process, for its list and each grid's info: the seam under test
+// is that subprocess, as in gridReads.spec.ts. A one-look case took 0.3 to 0.5 s under 12 busy loops (load
+// 50 to 72) and past vitest's 5 s in a full run under more. Room for a loaded machine, not for a hang.
+vi.setConfig({ testTimeout: 30_000 })
+
const OWN = 'mine', OWN_ID = 'net-own', TEAM = 'team', TEAM_ID = 'net-team'
const EMAIL = '[email protected]', TOKEN = 'grid-token-123'
const OVERVIEW = '/relay/v1/grid/overview', MODELS = '/relay/v1/models'
diff --git a/cli/src/lib/transcriptPages.spec.ts b/cli/src/lib/transcriptPages.spec.ts
index 28b9f001a..024362965 100644
--- a/cli/src/lib/transcriptPages.spec.ts
+++ b/cli/src/lib/transcriptPages.spec.ts
@@ -39,7 +39,14 @@ async function pageThrough(engine: Engine, file: string, limit: number): Promise
}
}
-describe('history pages equal the windows cut from the whole file', () => {
+/** These cases do a fixed amount of real file work, the subject here: a page read is reads of a file on disk.
+ * One cut is up to 16 sweeps of a file page by page, and the growing-file case 600 appends, each with an
+ * index update and a whole-file read: hundreds of reads either way. 1.2 to 3.1 s under 12 busy loops on a
+ * 12-core Mac (load 50 to 77), and past vitest's 5 s in a full run under more. Room for the reads, not a
+ * wait for anything: none of them waits on a clock. */
+const FILE_WORK_TIMEOUT_MS = 30_000
+
+describe('history pages equal the windows cut from the whole file', { timeout: FILE_WORK_TIMEOUT_MS }, () => {
describe.each([['claude', claudeScenario], ['codex', codexScenario]] as const)('%s', (engine, scenario) => {
const records = scenario()
const cuts = records.map((_, index) => index + 1)
@@ -233,7 +240,7 @@ describe('a page held to its size', () => {
})
})
-describe('LineIndex', () => {
+describe('LineIndex', { timeout: FILE_WORK_TIMEOUT_MS }, () => {
const tricky = [
'{"a":1}', '', ' ', '\t', ' ', ' 
', '', '\u0001', 'é', '{"b":2}',
Buffer.from([0xff, 0xfe]).toString('latin1'),
diff --git a/cli/src/orchestrator/command.spec.ts b/cli/src/orchestrator/command.spec.ts
index bea23ef98..b3fa4019b 100644
--- a/cli/src/orchestrator/command.spec.ts
+++ b/cli/src/orchestrator/command.spec.ts
@@ -96,9 +96,12 @@ describe('real loopback orchestrator transport', () => {
expect(peer.received[0]).toEqual({ type: 'machine_select', payload: { machineId: 'test-machine', localProtocolVersion: 1 } })
expect(peer.received[1].payload).toMatchObject({ action: 'list', requestId: expect.stringMatching(/^[a-f0-9]{32}$/) })
})
- it.each([['disconnect', /disconnected/], ['invalid', /invalid response/], ['silent', /did not confirm/]] as const)('fails safely on %s without retrying', async (mode, message) => {
+ // Only the silent daemon is waited out; a disconnect and a bad answer end the request as they arrive. At one
+ // 50 ms deadline for all three, a full unit run under load (12 busy loops, load 122) ran out of it before
+ // the close reached the client, and the disconnect read as a daemon that did not confirm.
+ it.each([['disconnect', /disconnected/, 20_000], ['invalid', /invalid response/, 20_000], ['silent', /did not confirm/, 50]] as const)('fails safely on %s without retrying', async (mode, message, deadline) => {
const peer = await server(mode)
- await expect(localOrchestratorRequest(peer.port, 'machine', { action: 'list' }, 50)).rejects.toThrow(message)
+ await expect(localOrchestratorRequest(peer.port, 'machine', { action: 'list' }, deadline)).rejects.toThrow(message)
expect(peer.received.filter(frame => frame.type === 'machine_select')).toHaveLength(1)
})
it('surfaces connection errors and command exit codes', async () => {
diff --git a/cli/src/testing/daemonEnvironment.spec.ts b/cli/src/testing/daemonEnvironment.spec.ts
new file mode 100644
index 000000000..51d3b4d27
--- /dev/null
+++ b/cli/src/testing/daemonEnvironment.spec.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest'
+import { daemonEnvironment } from './daemonEnvironment.js'
+
+describe('a daemon under test', () => {
+ it('starts the unit worker outside the host supervisor too', () => {
+ expect(Object.keys(process.env).filter(key => key.startsWith('HARNESSD_'))).toEqual([])
+ })
+ it('does not borrow the host supervisor, credentials, service subset or injected faults', () => {
+ expect(daemonEnvironment({
+ PATH: '/test/bin', HOME: '/host', HARNESSD_SUPERVISED: '1', HARNESSD_SERVICE_TOKEN: 'host-token',
+ HARNESSD_SERVICES: 'search,workspaces', HARNESSD_SERVICE_PROCESSES: 'search,workspaces',
+ HARNESSD_TEST_FAULTS: 'core.stall:10', HARNESSD_FUTURE_SETTING: 'host',
+ }, { HOME: '/test/home', HARNESSD_SERVICES: 'edge' })).toEqual({
+ PATH: '/test/bin', HOME: '/test/home', HARNESSD_SERVICES: 'edge',
+ })
+ })
+})
diff --git a/cli/src/testing/daemonEnvironment.ts b/cli/src/testing/daemonEnvironment.ts
new file mode 100644
index 000000000..1a4f371b5
--- /dev/null
+++ b/cli/src/testing/daemonEnvironment.ts
@@ -0,0 +1,5 @@
+/** A test daemon starts its own supervisor; it must not inherit the host daemon's topology or token. */
+export function daemonEnvironment(inherited: NodeJS.ProcessEnv, own: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
+ const clean = Object.fromEntries(Object.entries(inherited).filter(([key]) => !key.startsWith('HARNESSD_')))
+ return { ...clean, ...own }
+}
diff --git a/cli/vitest.setup.ts b/cli/vitest.setup.ts
index 21f23a9b3..56d00a96e 100644
--- a/cli/vitest.setup.ts
+++ b/cli/vitest.setup.ts
@@ -22,6 +22,10 @@ import { join } from 'node:path'
delete process.env.npm_config_prefix
delete process.env.NPM_CONFIG_PREFIX
+// Coding sessions can themselves run under harnessd. Its token, topology and supervision flags belong
+// to that host, never to a fixture or the Vitest worker. Tests set their own explicit overrides.
+for (const name of Object.keys(process.env)) if (name.startsWith('HARNESSD_')) delete process.env[name]
+
// The home folder itself is a throwaway one, before any module asks for it. Every engine's home, the Harness
// folder and the machine's identity default to a folder in it (config/env.ts: ~/.claude, ~/.codex, ~/.cursor,
// ~/.harness/computer-id, …), and a spec that did not name its own read the developer's. Traced on one Mac,