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.

Hook, handoff, engine-launch and password-pairing specs: wait on what they test, not on the load (#958)

Dee1efdb84520d4
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjs
index 83540497a..f8de6c910 100644
--- a/cli/hook/notify.mjs
+++ b/cli/hook/notify.mjs
@@ -47,7 +47,18 @@ const HOOK_STARTED_AT = performance.now()
// parallel test run, a busy CI box) a cold Node start plus lock retries can eat it before the offline
// registry fallback is reached, and the fallback then silently does nothing. Tests set it explicitly so
// they measure behaviour instead of the host's load. Clamped, and never below the shipped default.
-const HOOK_DEADLINE_MS = Math.min(60_000, Math.max(4500, Number(process.env.HARNESS_HOOK_DEADLINE_MS) || 0))
+const SHIPPED_DEADLINE_MS = 4500
+const HOOK_DEADLINE_MS = Math.min(60_000, Math.max(SHIPPED_DEADLINE_MS, Number(process.env.HARNESS_HOOK_DEADLINE_MS) || 0))
+// Each step's own limit (`execFileText`: tmux 2 s, ps and sqlite3 3 s, lsof 1.5 s) is a wall-clock assumption too, and
+// the override has to move them with the budget or it does not do what it says: under a loaded full test
+// run (load 36, six workers) the Hermes fallback's fake tmux, ps and sqlite3 each took longer than their
+// step's limit with 30 s of budget left, the lookup read as no answer, and no registry was written
+// (hookNotify.spec.ts, 3 of 3 Hermes cases). 1 with the shipped budget: a hook as shipped is unchanged.
+const STEP_SCALE = HOOK_DEADLINE_MS / SHIPPED_DEADLINE_MS
+/** A step's limit under the budget in force. Whole milliseconds: child_process refuses a fractional timeout. */
+function stepLimit(ms) {
+ return Math.round(ms * STEP_SCALE)
+}
const EXIT_RESERVE_MS = 500
const LOCK_RETRIES = 60
const LOCK_RETRY_MS = 25
@@ -393,7 +404,11 @@ function sleep(ms) {
function execFileText(cmd, args, timeout, env) {
return new Promise((resolve) => {
- const budget = Math.min(timeout, remainingBudget())
+ // Whole milliseconds. What is left of the budget is a fraction off the whole (performance.now()),
+ // and `execFile` throws ERR_OUT_OF_RANGE on a fractional timeout: once less was left than a step's
+ // own limit, as on the shipped 4.5 s budget after a second of earlier steps on a loaded machine, the
+ // step threw, and the offline registration it was part of was dropped.
+ const budget = Math.floor(Math.min(stepLimit(timeout), remainingBudget()))
if (budget < 50) { resolve(null); return }
execFile(cmd, args, { timeout: budget, ...(env && { env }) }, (err, stdout) => {
resolve(err ? null : stdout)
diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.ts
index 28198adcc..52ccb487d 100644
--- a/cli/src/hookNotify.spec.ts
+++ b/cli/src/hookNotify.spec.ts
@@ -44,6 +44,8 @@ interface RunHookOpts {
/** The tmux session the pane is in, and the daemon tag on it (`@harness_daemon`). */
paneSession?: string
paneOwner?: string
+ /** How long the fake tmux takes to answer each call, in seconds: a hook that spent its budget early. */
+ tmuxDelaySeconds?: number
/** Override the fixture's ps `comm` and full argv to exercise install-root-independent matching. */
processExecutable?: string
processArgs?: string
@@ -56,7 +58,9 @@ interface RunHookOpts {
hermesHome?: string
/** Fake Hermes SQLite source; null means the session row has not appeared. */
hermesSource?: 'cli' | 'tui' | 'subagent' | null
- /** How long Hermes' store takes to answer: a loaded machine. */
+ /** How long Hermes' store takes to answer, in the shipped hook's seconds: a loaded machine. Stretched
+ * as the hook stretches its own step limits under HARNESS_HOOK_DEADLINE_MS (notify.mjs STEP_SCALE),
+ * so the delay keeps the same share of the sqlite3 limit whatever the budget. */
hermesDelaySeconds?: number
grokHome?: string
devinHome?: string
@@ -90,7 +94,8 @@ function runHook(opts: RunHookOpts): Promise<string> {
// The pane as tmux describes it: its root process, and the session and tag that say whose agent it
// is (a Harness session, untagged, unless the test says otherwise).
const paneFacts = `${opts.paneSession ?? 'harness-claude-1790000000000'}|${opts.paneOwner ?? ''}`
- writeFileSync(join(binDir, 'tmux'), `#!/bin/sh\nprintf '%s\\n' ${shellQuote(`7000|${paneFacts}`)}\n`, { mode: 0o755 })
+ const tmuxDelay = opts.tmuxDelaySeconds ? `sleep ${opts.tmuxDelaySeconds}\n` : ''
+ writeFileSync(join(binDir, 'tmux'), `#!/bin/sh\n${tmuxDelay}printf '%s\\n' ${shellQuote(`7000|${paneFacts}`)}\n`, { mode: 0o755 })
env.PATH = `${binDir}:${env.PATH ?? ''}`
}
if (opts.processEngine) {
@@ -113,7 +118,8 @@ function runHook(opts: RunHookOpts): Promise<string> {
}
if (opts.hermesSource !== undefined) {
const rows = opts.hermesSource === null ? '[]' : JSON.stringify([{ source: opts.hermesSource }])
- const delay = opts.hermesDelaySeconds ? `sleep ${opts.hermesDelaySeconds}\n` : ''
+ const stepScale = Number(env.HARNESS_HOOK_DEADLINE_MS) / 4500
+ const delay = opts.hermesDelaySeconds ? `sleep ${opts.hermesDelaySeconds * stepScale}\n` : ''
writeFileSync(join(binDir, 'sqlite3'), `#!/bin/sh\n${delay}printf '%s\\n' '${rows}'\n`, { mode: 0o755 })
}
env.PATH = `${binDir}:${env.PATH ?? ''}`
@@ -592,6 +598,33 @@ describe('hook notify terminal scope', () => {
}
})
+ // A step's limit is cut to what is left of the hook's budget, and what is left is a fraction of a
+ // millisecond off the whole: `execFile` refuses a fractional timeout (ERR_OUT_OF_RANGE), so once the
+ // budget left was under a step's own limit, that step threw, and the offline registration with it.
+ // On the shipped 4.5 s budget that is any hook whose earlier steps took a second, as a loaded machine's
+ // do. Here tmux answers each of its two calls in 1.5 s of a 9 s budget, which leaves the process scan
+ // under its 6 s limit.
+ it('still registers offline when its earlier steps took a third of its budget', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-late-'))
+ tmpDirs.push(dir)
+ const claudeProjectsDir = join(dir, 'claude-projects')
+ const dataDir = join(dir, 'data')
+ const transcriptPath = join(claudeProjectsDir, 'demo', 'session-late.jsonl')
+ mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })
+ writeFileSync(transcriptPath, '{}\n')
+ await runHook({
+ port: 9,
+ tmuxPane: '%7',
+ processEngine: 'claude',
+ tmuxDelaySeconds: 1.5,
+ env: { HARNESS_HOOK_DEADLINE_MS: '9000' },
+ dataDir,
+ claudeProjectsDir,
+ input: { hook_event_name: 'SessionStart', session_id: 'session-late', transcript_path: transcriptPath, cwd: '/tmp/demo' },
+ })
+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toMatchObject([{ sessionId: 'session-late', tmuxPane: '%7' }])
+ })
+
it('falls back with Codex engine under CODEX_HOME/sessions', async () => {
const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-codex-'))
tmpDirs.push(dir)
@@ -723,7 +756,11 @@ 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' },
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/agentHandoff.spec.ts b/cli/src/lib/agentHandoff.spec.ts
index e168fc0d1..eef7525ec 100644
--- a/cli/src/lib/agentHandoff.spec.ts
+++ b/cli/src/lib/agentHandoff.spec.ts
@@ -71,6 +71,11 @@ const session = (over: Record<string, unknown> = {}): RegisteredSession => ({
function depsFor(sessions: RegisteredSession[], over: Partial<HandoffDeps> = {}): HandoffDeps {
return {
+ // The 2 s limit on one git command is not what any case here is about, and a loaded run spends it on
+ // starting git: under a full run at load 36 a `rev-parse` went over it, the repository read as unclear,
+ // and "finds the exclude file" and "goes by one clock" answered `gitRepo: false`. The preparation's own
+ // deadline (`deadlineMs`, or the injected clock) still bounds every case.
+ gitTimeoutMs: 30_000,
resolve: (id) => sessions.find((s) => s.agentId === id) ?? null,
readHistory: () => undefined,
recentAsks: () => ['floor ask'],
@@ -506,14 +511,16 @@ describe('prepareAgentHandoff: a repository', () => {
await expect(prepareAgentHandoff(d, request())).rejects.toMatchObject({ code: 'TIMEOUT' })
// The git that was already running when the deadline hit logs its call (late: a script's first run is slow);
// nothing new may start after it, not even when the read finally finishes.
- for (let waited = 0; !lines().length && waited < 5_000; waited += 50) await new Promise((resolve) => setTimeout(resolve, 50))
+ while (!lines().length) await new Promise((resolve) => setTimeout(resolve, 50))
const atTimeout = lines().length
expect(atTimeout).toBe(1)
await new Promise((resolve) => setTimeout(resolve, 1_200))
expect(lines()).toHaveLength(atTimeout)
expect(lines().join('\n')).not.toContain('status')
expect(existsSync(join(ws, '.harness'))).toBe(false)
- })
+ // Waits on a real git started through a shell script, and then 1.2 s more: past vitest's 5 s default on
+ // a loaded run (load 36, six workers), where the script took seconds to log its call.
+ }, 30_000)
// The git limits are raised: under a loaded suite a 2 s limit made the repository look "unclear" and nothing was written.
it('says a git field is not available when its command failed, and "(none)" when it ran and found nothing', async () => {
diff --git a/cli/src/lib/e2ee/manager.test.ts b/cli/src/lib/e2ee/manager.test.ts
index 17503a62a..c918b4a5a 100644
--- a/cli/src/lib/e2ee/manager.test.ts
+++ b/cli/src/lib/e2ee/manager.test.ts
@@ -105,6 +105,20 @@ class WebPeer {
}
}
+/**
+ * A joiner's stretched password, computed once per password for the whole file. `stretchPassword` is
+ * deterministic for a password and machine, and each call is a real scrypt (~0.5-1 s and 128 MB idle;
+ * the cost is a security control, never lowered for a test). Under a loaded full run (load 36, six
+ * workers) "keeps at most two password attempts in flight" spent five of them, one per joiner, and
+ * timed out. The manager's own stretch (`setRemotePassword`) is still real every time.
+ */
+const stretchedPasswords = new Map<string, Promise<Uint8Array>>()
+function stretchedOnce(password: string): Promise<Uint8Array> {
+ let stretched = stretchedPasswords.get(password)
+ if (!stretched) stretchedPasswords.set(password, stretched = stretchPassword(password, AGENT))
+ return stretched
+}
+
/** A minimal remote-password joiner that runs the CPace 'b' role directly against the manager via
* handleFrame — mirrors WebPeer above, but for the persistent remote-password flow: no human "arm"
* step (intent() carries the stretched password straight away), and connId-keyed on the manager side
@@ -118,7 +132,7 @@ class PwPeer {
async intent(password: string): Promise<Frame> {
const sid = C.newPairId()
- const stretched = await stretchPassword(password, AGENT)
+ const stretched = await stretchedOnce(password)
this.pr = { sid, sidB64: C.b64e(sid), stretched }
return { type: 'e2e_pw_pair_intent', payload: { requestId: 'pwr1', sid: this.pr.sidB64 } }
}
@@ -518,7 +532,9 @@ describe('E2eeManager revoke', () => {
})
})
-describe('E2eeManager persistent remote-password pairing', () => {
+// Every case here runs at least one real scrypt in the manager (`setRemotePassword`) and one for its
+// joiner: PW_SCRYPT_TEST_TIMEOUT_MS, the budget the lockout cases already carried, for all of them.
+describe('E2eeManager persistent remote-password pairing', { timeout: PW_SCRYPT_TEST_TIMEOUT_MS }, () => {
const PASSWORD = 'correct horse battery staple'
it('NO_REMOTE_PASSWORD when no password has been set', async () => {
diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.ts
index 44baf9c97..a003a1a52 100644
--- a/cli/src/lib/engineLaunch.spec.ts
+++ b/cli/src/lib/engineLaunch.spec.ts
@@ -49,6 +49,14 @@ import { launchScriptOf } from '../testing/launchScript.js'
import { buildGridEngineLaunch, gridConflictingEnvToClear } from './gridLaunch.js'
import { TmuxBackend } from './tmuxBackend.js'
+// What these cases test is what real shells make of the scripts this module writes: sh, dash, bash and
+// zsh run each one, and nothing here could be faked without faking the subject. Each run carries its own
+// bound (a probe's 5 s in engineLaunch.ts, the 10 s of the runs below), and vitest's 5 s default sat under
+// them: a slow shell timed the case out instead of answering as its bound says. Under a full run at load
+// 36 (six workers), 11 cases here hit it, one of them on a single probe; under 8 busy and 8 spawning loops
+// the four-probe case took 4.9 s. Room for four probes at their limit, and a margin.
+vi.setConfig({ testTimeout: 30_000 })
+
// The launch script names the `grid` the daemon resolved, and a developer's own HARNESS_GRID_BIN
// would resolve to THEIR grid. The suite's runtime dir is already a throwaway (vitest.setup.ts), so
// with the override gone every case below resolves to the bare name.