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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
perf(cli): cut harnessd's periodic CPU — dial scan, deleted-image lsof, registry rewrites (#909)
0xken1565dba22c951b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex b42013521..fff28a68c 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -236,7 +236,7 @@ jobs:RUN_DARWIN_PROCESS_IMAGES: '1'run: |node scripts/test-process-images-bundled.mjs- npx vitest run src/lib/nativeProcessImages.spec.ts src/lib/processImages.spec.ts src/lib/processImages.real.spec.ts --maxWorkers=1+ npx vitest run src/lib/nativeProcessImages.spec.ts src/lib/processImages.spec.ts src/lib/processImages.real.spec.ts src/lib/periodicCpu.integration.spec.ts --maxWorkers=1# The optional product has its own dependencies, bundle and suites. CLI-only CI# deliberately checks core without installing or building this package.diff --git a/cli/scripts/test-process-images-bundled.mjs b/cli/scripts/test-process-images-bundled.mjsindex dfdb41745..57ab221d9 100644--- a/cli/scripts/test-process-images-bundled.mjs+++ b/cli/scripts/test-process-images-bundled.mjs@@ -25,13 +25,13 @@ try {import { processRows, enrichProcessRows } from ${JSON.stringify(join(cli, 'src/lib/tmux.ts'))};env.ADAPTER_RUNTIME_DIR = process.argv[2];const native = await nativeProcessImages([process.pid], 3000);- assert.equal(realpathSync(native.get(process.pid).path), realpathSync(process.execPath));+ assert.equal(realpathSync(native.images.get(process.pid).path), realpathSync(process.execPath));const rows = await processRows();const own = rows.filter(row => row.pid === process.pid);assert.equal(own.length, 1);const enriched = await enrichProcessRows(own);assert.equal(enriched.length, 1);- assert.equal(enriched[0].imagePath, native.get(process.pid).path);+ assert.equal(enriched[0].imagePath, native.images.get(process.pid).path);assert.ok(enriched[0].imageFileKey);console.log('Bundled native query and discovery passed on ' + process.arch);`diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex 3cf34ed73..1a83e1dcb 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -193,6 +193,15 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {* and the core loads it only to run it in its own process instead (services/inline.ts). With it went the* E2EE manager, the backend link, P2P and STUN, the windows' relay pool, the trust group and the device* key log. What of lib/e2ee the core still loads is the fleet's lane (R3) and Share's own crypto (step 8).+ *+ * Grew by 67 to 95,757 in 420 for the daemon's periodic CPU, measured on harnessd-core 0.3.58/0.3.59: the+ * dial scan runs `ioreg` (~150 ms of CPU every 2 s, about 7.5% of a core) only when /dev/cu.* changes+ * (cable/serial.ts, +31, with one confirming scan after each change or phantom port, since devfs and the+ * IORegistry do not change together); a deleted executable already found by `lsof -d txt` (~18 ms every+ * 5 s, about 0.4%) is not asked about again every 5 s (lib/tmux.ts and lib/nativeProcessImages.ts,+ * +32); and an unchanged registry.json is not rewritten every 5 s (about 720 writes an hour) because+ * its keys were in another order (lib/registry.ts, +4). The dial's part leaves with step 9 (the devices+ * process).*///// Connected TUI shells added a literal-argv launch port and shell service (#893, 160 loaded lines); movingdiff --git a/cli/src/cable/cableFleet.spec.ts b/cli/src/cable/cableFleet.spec.tsindex 9fd95b6e1..58b4969fd 100644--- a/cli/src/cable/cableFleet.spec.ts+++ b/cli/src/cable/cableFleet.spec.ts@@ -9,7 +9,7 @@ import { CableSession, type CableHost, type CablePort } from './cableSession.js'import { CableDecoder, CableType, encodeCableFrame } from './cableFrame.js'import { DialLog } from './dialLog.js'import { DialVerdicts } from './dialPortVerdicts.js'-import { parseDarwinDialPorts, portInUse, type DialPort } from './serial.js'+import { createDarwinDialFinder, parseDarwinDialPorts, portInUse, type DialPort } from './serial.js'// Run the same two-device scenarios against the staged helper before deployment.const CableFleet: typeof SourceFleet = process.env.HARNESS_TEST_USB_FLEET@@ -466,4 +466,137 @@ describe('macOS USB inventory', () => {// The attachment identity is the USB device's own sessionID, not one from a node below it.expect(parseDarwinDialPorts(dump)).toEqual([device('/dev/tim', 'AA:01'), { ...device('/dev/tux', 'BB:02'), session: '14351572441873' }])})++ describe('dial scan gate', () => {+ const dump = `+-o Tim <class IOUSBHostDevice>+ "idVendor" = 12346+ "idProduct" = 4097+ "USB Serial Number" = "AA:01"+ +-o CDC+ +-o serial+ "IOCalloutDevice" = "/dev/cu.usbmodem1101"`+ const base = ['cu.debug-console:623:1', 'cu.usbmodem1101:900:7']+ function rig(entries = base) {+ const state = { entries, now: 0, listDev: () => state.entries }+ const runIoreg = vi.fn(async () => dump)+ const find = createDarwinDialFinder({ listDev: () => state.listDev(), runIoreg, now: () => state.now })+ return { state, runIoreg, find }+ }++ it('runs ioreg once for an unchanged /dev set and serves copies', async () => {+ const { runIoreg, find } = rig()+ for (let i = 0; i < 3; i++) expect(await find()).toEqual([device('/dev/cu.usbmodem1101', 'AA:01')])+ expect(runIoreg).toHaveBeenCalledTimes(1)+ const first = await find()+ first[0].path = 'x'+ expect(await find()).toEqual([device('/dev/cu.usbmodem1101', 'AA:01')])+ })++ it('ignores the order of /dev entries', async () => {+ const { state, runIoreg, find } = rig()+ await find()+ state.entries = [...base].reverse()+ await find()+ expect(runIoreg).toHaveBeenCalledTimes(1)+ })++ it('rescans on an added or removed entry, a new inode, or a new rdev', async () => {+ const { state, runIoreg, find } = rig()+ await find()+ state.entries = [...base, 'cu.usbmodem2:950:8']; await find()+ expect(runIoreg).toHaveBeenCalledTimes(2)+ state.entries = base; await find()+ expect(runIoreg).toHaveBeenCalledTimes(3)+ state.entries = ['cu.debug-console:623:1', 'cu.usbmodem1101:901:7']; await find()+ expect(runIoreg).toHaveBeenCalledTimes(4)+ state.entries = ['cu.debug-console:623:1', 'cu.usbmodem1101:901:8']; await find()+ expect(runIoreg).toHaveBeenCalledTimes(5)+ await find() // the confirm scan after the last change+ expect(runIoreg).toHaveBeenCalledTimes(6)+ await find()+ expect(runIoreg).toHaveBeenCalledTimes(6)+ })++ it('confirms a change with one more scan, so a plug edge cannot cache a half-seen port', async () => {+ const { state, runIoreg, find } = rig()+ await find()+ state.entries = [...base, 'cu.usbmodem2:950:8']+ runIoreg.mockResolvedValueOnce('') // devfs has the node, the IORegistry does not yet+ expect(await find()).toEqual([])+ expect(await find()).toEqual([device('/dev/cu.usbmodem1101', 'AA:01')])+ expect(runIoreg).toHaveBeenCalledTimes(3)+ await find()+ expect(runIoreg).toHaveBeenCalledTimes(3)+ })++ it('rescans after 5 minutes, not before', async () => {+ const { state, runIoreg, find } = rig()+ await find()+ state.now = 299_999; await find()+ expect(runIoreg).toHaveBeenCalledTimes(1)+ state.now = 300_000; await find()+ expect(runIoreg).toHaveBeenCalledTimes(2)+ state.now = 300_001; await find()+ expect(runIoreg).toHaveBeenCalledTimes(2)+ })++ it('rescans when the clock steps back below the last scan', async () => {+ const { state, runIoreg, find } = rig()+ state.now = 1_000_000; await find()+ state.now = 500_000; await find()+ expect(runIoreg).toHaveBeenCalledTimes(2)+ })++ it('treats an empty /dev/cu.* set as a valid fingerprint', async () => {+ const { runIoreg, find } = rig([])+ runIoreg.mockResolvedValue('') // no cu.* nodes, so no dial in the IORegistry either+ for (let i = 0; i < 3; i++) await find()+ expect(runIoreg).toHaveBeenCalledTimes(1)+ })++ it('keeps rescanning while ioreg lists a port whose /dev node is gone, then caches again', async () => {+ const { state, runIoreg, find } = rig()+ await find()+ state.entries = ['cu.debug-console:623:1'] // unplugged: the node left /dev, the IORegistry still lists the dial+ for (let i = 0; i < 3; i++) expect(await find()).toEqual([device('/dev/cu.usbmodem1101', 'AA:01')])+ expect(runIoreg).toHaveBeenCalledTimes(4)+ runIoreg.mockResolvedValue('') // the IORegistry caught up+ expect(await find()).toEqual([])+ expect(runIoreg).toHaveBeenCalledTimes(5)+ await find()+ await find()+ expect(runIoreg).toHaveBeenCalledTimes(5) // nothing left to doubt, so cached+ })++ it('retries after an ioreg failure and never serves stale ports for changed entries', async () => {+ const { state, runIoreg, find } = rig()+ runIoreg.mockRejectedValueOnce(new Error('Could not enumerate USB dials'))+ await expect(find()).rejects.toThrow('Could not enumerate USB dials')+ expect(await find()).toEqual([device('/dev/cu.usbmodem1101', 'AA:01')])+ expect(runIoreg).toHaveBeenCalledTimes(2)+ state.entries = [...base, 'cu.usbmodem2:950:8']+ runIoreg.mockRejectedValueOnce(new Error('Could not enumerate USB dials'))+ await expect(find()).rejects.toThrow('Could not enumerate USB dials')+ await find()+ expect(runIoreg).toHaveBeenCalledTimes(4)+ await find() // confirm scan for the change that the failure interrupted+ expect(runIoreg).toHaveBeenCalledTimes(5)+ await find()+ expect(runIoreg).toHaveBeenCalledTimes(5)+ })++ it('falls back to ioreg every call while /dev cannot be read', async () => {+ const { state, runIoreg, find } = rig()+ state.listDev = () => { throw new Error('EACCES') }+ for (let i = 0; i < 3; i++) await find()+ expect(runIoreg).toHaveBeenCalledTimes(3)+ state.listDev = () => state.entries+ await find()+ expect(runIoreg).toHaveBeenCalledTimes(4)+ await find() // recovery counts as a change, so it is confirmed once+ expect(runIoreg).toHaveBeenCalledTimes(5)+ await find()+ expect(runIoreg).toHaveBeenCalledTimes(5)+ })+ })})diff --git a/cli/src/cable/serial.spec.ts b/cli/src/cable/serial.spec.tsindex 9ff714244..27fd30d2a 100644--- a/cli/src/cable/serial.spec.ts+++ b/cli/src/cable/serial.spec.ts@@ -2,12 +2,12 @@ import { EventEmitter } from 'node:events'import { constants } from 'node:fs'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-const io = vi.hoisted(() => ({ open: vi.fn(), close: vi.fn(), configure: vi.fn(), stream: vi.fn() }))-vi.mock('node:fs', async (original) => ({ ...await original<typeof import('node:fs')>(), openSync: io.open, closeSync: io.close }))+const io = vi.hoisted(() => ({ open: vi.fn(), close: vi.fn(), configure: vi.fn(), stream: vi.fn(), readdir: vi.fn(), lstat: vi.fn() }))+vi.mock('node:fs', async (original) => ({ ...await original<typeof import('node:fs')>(), openSync: io.open, closeSync: io.close, readdirSync: io.readdir, lstatSync: io.lstat }))vi.mock('node:tty', () => ({ ReadStream: io.stream }))vi.mock('node:child_process', () => ({ execFile: io.configure }))-import { SerialLink } from './serial.js'+import { SerialLink, findDialPorts } from './serial.js'function port(nativeFd = 43) {const stream = Object.assign(new EventEmitter(), {@@ -204,3 +204,31 @@ describe('event-driven serial link', () => {await link.close()})})++describe('macOS dial discovery wiring', () => {+ const dump = `+-o Tim <class IOUSBHostDevice>+ "idVendor" = 12346+ "idProduct" = 4097+ +-o serial+ "IOCalloutDevice" = "/dev/cu.usbmodem1101"`+ afterEach(() => vi.resetAllMocks())++ it.skipIf(process.platform !== 'darwin')('stats only cu.* entries, gates ioreg on them and keeps the error text', async () => {+ io.readdir.mockReturnValue(['cu.usbmodem1101', 'tty.usbmodem1101', 'null'])+ io.lstat.mockReturnValue({ ino: 900, rdev: 7 })+ io.configure.mockImplementation((_c, _a, _o, cb) => cb(null, { stdout: dump, stderr: '' }))+ await findDialPorts()+ await findDialPorts()+ expect(io.configure).toHaveBeenCalledTimes(1)+ expect(io.configure.mock.calls[0].slice(0, 2)).toEqual(['ioreg', ['-r', '-c', 'IOUSBHostDevice', '-w0', '-l']])+ expect(io.lstat.mock.calls.every(([path]) => path === '/dev/cu.usbmodem1101')).toBe(true)+ expect(io.lstat).toHaveBeenCalled()++ io.lstat.mockReturnValue({ ino: 901, rdev: 7 })+ io.configure.mockImplementation((_c, _a, _o, cb) => cb(new Error('boom')))+ await expect(findDialPorts()).rejects.toThrow('Could not enumerate USB dials')+ io.configure.mockImplementation((_c, _a, _o, cb) => cb(null, { stdout: dump, stderr: '' }))+ await expect(findDialPorts()).resolves.toHaveLength(1)+ expect(io.configure).toHaveBeenCalledTimes(3)+ })+})diff --git a/cli/src/cable/serial.ts b/cli/src/cable/serial.tsindex c4758e7e3..236170891 100644--- a/cli/src/cable/serial.ts+++ b/cli/src/cable/serial.ts@@ -5,7 +5,8 @@// a per-platform release matrix into a distribution that is currently a download. A tty is a file, `stty`// puts it in raw mode, and that is the whole of what this needs.import { execFile } from 'node:child_process'-import { closeSync, constants, existsSync, openSync, readFileSync, readdirSync } from 'node:fs'+import { closeSync, constants, existsSync, lstatSync, openSync, readFileSync, readdirSync } from 'node:fs'+import { basename } from 'node:path'import { ReadStream } from 'node:tty'import { promisify } from 'node:util'@@ -85,19 +86,49 @@ function depthOf(line: string): number {return m ? m[0].length : 0}-async function findDarwin(): Promise<DialPort[]> {- let dump: string- try {- // Keep each USB device's children (the tty lives below its vendor/product IDs), but do not- // serialize the whole IOService plane every two seconds just to detect a hot-plugged dial.- const { stdout } = await runFile('ioreg', ['-r', '-c', 'IOUSBHostDevice', '-w0', '-l'], { maxBuffer: 64 * 1024 * 1024 })- dump = stdout- } catch {- throw new Error('Could not enumerate USB dials')+// `ioreg` cost ~150 ms CPU every 2 s (~7.5% of a core, measured 2026-10-06) even with no dial attached, so+// it runs only when /dev/cu.* changes (~0.3 ms to fingerprint two cu.* nodes, same measurement).+// `ino` is in the fingerprint because a re-plug makes a new devfs node, and that attachment is what moves+// `session`. No mtime/ctime: I/O on an open tty bumps them, defeating the gate exactly when a dial is+// attached. Every 5 min is a safety net (~0.05%); no name filter, so an odd name is never invisible.+// devfs and the IORegistry do not change atomically, so a scan on a plug/unplug edge can see a missing or+// phantom port; a scan that followed a change, or that lists a port whose /dev node is gone, is therefore+// confirmed by another (one extra ioreg per edge, and one per call while the IORegistry lags an unplug).+const DIAL_RESCAN_MS = 300_000++export function createDarwinDialFinder(deps: { listDev: () => string[]; runIoreg: () => Promise<string>; now: () => number }) {+ let last: { settled: boolean; fingerprint: string | null; ports: DialPort[]; at: number } | null = null+ return async (): Promise<DialPort[]> => {+ let entries: string[] | null+ try { entries = deps.listDev().sort() } catch { entries = null }+ const fingerprint = entries && entries.join('\n')+ const age = last ? deps.now() - last.at : -1 // a clock stepped back (age < 0) must not pin the cache; '' is a valid fingerprint+ if (!(last && last.settled && fingerprint !== null && fingerprint === last.fingerprint && age >= 0 && age < DIAL_RESCAN_MS)) {+ const prev = last // read before the await; the first scan ever is not an edge+ const ports = parseDarwinDialPorts(await deps.runIoreg())+ const names = new Set((entries ?? []).map(entry => entry.replace(/:\d+:\d+$/, '')))+ last = { settled: (!prev || prev.fingerprint === fingerprint) && ports.every(port => names.has(basename(port.path))), fingerprint, ports, at: deps.now() }+ }+ return last.ports.map(port => ({ ...port }))}- return parseDarwinDialPorts(dump)}+const findDarwin = createDarwinDialFinder({+ listDev: () => readdirSync('/dev').filter(name => name.startsWith('cu.')).map(name => {+ const { ino, rdev } = lstatSync(`/dev/${name}`)+ return `${name}:${ino}:${rdev}`+ }),+ runIoreg: async () => {+ try {+ // Keep each USB device's children (the tty lives below its vendor/product IDs), but skip the rest of the IOService plane.+ return (await runFile('ioreg', ['-r', '-c', 'IOUSBHostDevice', '-w0', '-l'], { maxBuffer: 64 * 1024 * 1024 })).stdout+ } catch {+ throw new Error('Could not enumerate USB dials')+ }+ },+ now: () => Date.now(),+})+export function parseDarwinDialPorts(dump: string): DialPort[] {const lines = dump.split('\n')const ports: DialPort[] = []diff --git a/cli/src/lib/nativeProcessImages.spec.ts b/cli/src/lib/nativeProcessImages.spec.tsindex 9ce5555c2..dc8ebf325 100644--- a/cli/src/lib/nativeProcessImages.spec.ts+++ b/cli/src/lib/nativeProcessImages.spec.ts@@ -47,21 +47,34 @@ afterEach(async () => {describe('native process-image protocol', () => {it('preserves valid UTF-8 paths including JSON delimiters and newlines', () => {const path = '/fixture/引擎 "quote"\nnew line\\tail'- expect(parseNativeProcessImages(output(record(10, path)), new Set([10])).get(10))+ expect(parseNativeProcessImages(output(record(10, path)), new Set([10])).images.get(10)).toEqual({ path, startMarker: record(10).startMarker })})it('requires the protocol header and ignores unrequested processes', () => {- expect(parseNativeProcessImages(JSON.stringify(record(10)) + '\n', new Set([10])).size).toBe(0)- expect(parseNativeProcessImages(output(record(20)), new Set([10])).size).toBe(0)- expect(parseNativeProcessImages(output(record(10)).replace('"schema":1', '"schema":2'), new Set([10])).size).toBe(0)+ expect(parseNativeProcessImages(JSON.stringify(record(10)) + '\n', new Set([10])).images.size).toBe(0)+ expect(parseNativeProcessImages(output(record(20)), new Set([10])).images.size).toBe(0)+ expect(parseNativeProcessImages(output(record(10)).replace('"schema":1', '"schema":2'), new Set([10])).images.size).toBe(0)+ })++ it('reports only requested unavailable PIDs separately from readable images', () => {+ const result = parseNativeProcessImages(output(+ { pid: 10, unavailable: true }, record(20), { pid: 30, unavailable: true },+ ), new Set([10, 20]))+ expect([...result.images.keys()]).toEqual([20])+ expect(result.unavailable).toEqual(new Set([10]))})it('keeps complete records before a truncated tail but refuses conflicting duplicates', () => {const partial = output(record(10)) + JSON.stringify(record(20)).slice(0, -4)- expect([...parseNativeProcessImages(partial, new Set([10, 20])).keys()]).toEqual([10])+ expect([...parseNativeProcessImages(partial, new Set([10, 20])).images.keys()]).toEqual([10])const conflict = output(record(10), { pid: 10, unavailable: true }, record(20), record(10))- expect([...parseNativeProcessImages(conflict, new Set([10, 20])).keys()]).toEqual([20])+ const result = parseNativeProcessImages(conflict, new Set([10, 20]))+ expect([...result.images.keys()]).toEqual([20])+ expect(result.unavailable).toEqual(new Set())+ expect(parseNativeProcessImages(output(+ { pid: 10, unavailable: true }, { pid: 10, unavailable: true },+ ), new Set([10]))).toEqual({ images: new Map(), unavailable: new Set() })})it('rejects malformed bytes, relative paths and unavailable birth metadata', () => {@@ -71,7 +84,7 @@ describe('native process-image protocol', () => {{ ...record(10), imageHex: '2f'.repeat(4096) }, { ...record(10), startSeconds: -1 },{ ...record(10), startMicros: 1_000_000 }, { ...record(10), startMarker: 'unknown' },{ ...record(10), unavailable: true }, { ...record(10), pid: 10.5 },- ]) expect(parseNativeProcessImages(output(row), new Set([10])).size).toBe(0)+ ]) expect(parseNativeProcessImages(output(row), new Set([10])).images.size).toBe(0)})})@@ -117,20 +130,29 @@ describe('bundled native helper preparation', () => {describe('fresh native image reads', () => {it('does nothing on other platforms or when no native artifact was bundled', async () => {- expect((await nativeProcessImages([10], 500)).size).toBe(0)+ expect(await nativeProcessImages([10], 500)).toEqual({ images: new Map(), unavailable: new Set() })vi.stubGlobal('__DARWIN_PROCESS_IMAGES__', JSON.stringify(artifact))host.platform = 'linux'- expect((await nativeProcessImages([10], 500)).size).toBe(0)+ expect(await nativeProcessImages([10], 500)).toEqual({ images: new Map(), unavailable: new Set() })expect(host.execFile).not.toHaveBeenCalled()expect(await readdir(root)).toEqual([])})+ it('returns readable images and unavailable PIDs from the helper together', async () => {+ vi.stubGlobal('__DARWIN_PROCESS_IMAGES__', JSON.stringify(artifact))+ host.execFile.mockImplementationOnce((_path, _args, _options, done) =>+ done(null, output(record(10), { pid: 20, unavailable: true })))+ const result = await nativeProcessImages([10, 20], 500)+ expect([...result.images.keys()]).toEqual([10])+ expect(result.unavailable).toEqual(new Set([20]))+ })+it('shares only executable preparation and issues a fresh query after exec', async () => {vi.stubGlobal('__DARWIN_PROCESS_IMAGES__', JSON.stringify(artifact))host.execFile.mockImplementationOnce((_path, _args, _options, done) => done(null, output(record(10, '/before')))).mockImplementationOnce((_path, _args, _options, done) => done(null, output(record(10, '/after'))))- expect((await nativeProcessImages([10], 500)).get(10)?.path).toBe('/before')- expect((await nativeProcessImages([10], 500)).get(10)?.path).toBe('/after')+ expect((await nativeProcessImages([10], 500)).images.get(10)?.path).toBe('/before')+ expect((await nativeProcessImages([10], 500)).images.get(10)?.path).toBe('/after')expect(host.execFile).toHaveBeenCalledTimes(2)for (const [path, args, options] of host.execFile.mock.calls) {expect(path).toBe(join(root, 'process-images', artifact.sha256))@@ -145,16 +167,16 @@ describe('fresh native image reads', () => {vi.stubGlobal('__DARWIN_PROCESS_IMAGES__', JSON.stringify(artifact))host.execFile.mockImplementationOnce((_path, _args, _options, done) => done(new Error('timeout'), output(record(10)) + '{')).mockImplementationOnce((_path, _args, _options, done) => done(new Error('cannot execute'), ''))- expect([...(await nativeProcessImages([10, 20], 500)).keys()]).toEqual([10])- expect((await nativeProcessImages([10], 500)).size).toBe(0)+ expect([...(await nativeProcessImages([10, 20], 500)).images.keys()]).toEqual([10])+ expect((await nativeProcessImages([10], 500)).images.size).toBe(0)})it('rejects unbounded or invalid requests without preparing an executable', async () => {vi.stubGlobal('__DARWIN_PROCESS_IMAGES__', JSON.stringify(artifact))for (const pids of [[], [0], [-1], [10.1], [0x80000000], new Array(4097).fill(7)]) {- expect((await nativeProcessImages(pids, 500)).size).toBe(0)+ expect((await nativeProcessImages(pids, 500)).images.size).toBe(0)}- expect((await nativeProcessImages([10], 0)).size).toBe(0)+ expect((await nativeProcessImages([10], 0)).images.size).toBe(0)expect(host.execFile).not.toHaveBeenCalled()expect(await readdir(root)).toEqual([])})@@ -166,14 +188,14 @@ describe('fresh native image reads', () => {host.execFile.mockImplementationOnce((_path, _args, _options, done) => done(null, output(record(10)))).mockImplementationOnce((_path, _args, _options, done) => done(Object.assign(new Error('missing'), { code: 'ENOENT' }), '')).mockImplementationOnce((_path, _args, _options, done) => done(null, output(record(10, '/new'))))- expect((await nativeProcessImages([10], 500)).size).toBe(1)+ expect((await nativeProcessImages([10], 500)).images.size).toBe(1)const path = join(root, 'process-images', artifact.sha256)await rm(path)- expect((await nativeProcessImages([10], 500)).size).toBe(0)- expect((await nativeProcessImages([10], 500)).size).toBe(0)+ expect((await nativeProcessImages([10], 500)).images.size).toBe(0)+ expect((await nativeProcessImages([10], 500)).images.size).toBe(0)expect(host.execFile).toHaveBeenCalledTimes(2)now = 60_001- expect((await nativeProcessImages([10], 500)).get(10)?.path).toBe('/new')+ expect((await nativeProcessImages([10], 500)).images.get(10)?.path).toBe('/new')expect(await readFile(path)).toEqual(bytes)})@@ -181,7 +203,7 @@ describe('fresh native image reads', () => {vi.stubGlobal('__DARWIN_PROCESS_IMAGES__', JSON.stringify(artifact))let resume!: () => voidhost.beforeStat = new Promise<void>(resolve => { resume = resolve })- expect((await nativeProcessImages([10], 20)).size).toBe(0)+ expect((await nativeProcessImages([10], 20)).images.size).toBe(0)expect(host.execFile).not.toHaveBeenCalled()resume()await vi.waitFor(async () => expect(await readFile(join(root, 'process-images', artifact.sha256))).toEqual(bytes))diff --git a/cli/src/lib/nativeProcessImages.ts b/cli/src/lib/nativeProcessImages.tsindex 6a0e275c8..74316948c 100644--- a/cli/src/lib/nativeProcessImages.ts+++ b/cli/src/lib/nativeProcessImages.ts@@ -100,25 +100,27 @@ export async function prepareProcessImageHelper(finally { if (temporary) await unlink(temporary).catch(() => {}) }}-/** Keep complete, uniquely identified records only. A timeout may leave usable+/** Keep complete, unique images and unavailable PIDs. A timeout may leave usable* records before a truncated line, exactly as with the ordinary image reader. */export function parseNativeProcessImages(stdout: string, requested: ReadonlySet<number>,-): Map<number, NativeProcessImage> {+): { images: Map<number, NativeProcessImage>; unavailable: Set<number> } {const images = new Map<number, NativeProcessImage>()+ const unavailable = new Set<number>()const lines = stdout.slice(0, stdout.lastIndexOf('\n') + 1).split('\n')try {const header = JSON.parse(lines.shift() ?? '')- if (header?.schema !== 1 || header?.mode !== 'paths') return images- } catch { return images }+ if (header?.schema !== 1 || header?.mode !== 'paths') return { images, unavailable }+ } catch { return { images, unavailable } }const seen = new Set<number>()for (const line of lines) {let rowtry { row = JSON.parse(line) } catch { continue }if (!row || !validPid(row.pid) || !requested.has(row.pid)) continue- if (seen.has(row.pid)) { images.delete(row.pid); continue }+ if (seen.has(row.pid)) { images.delete(row.pid); unavailable.delete(row.pid); continue }seen.add(row.pid)- if (row.unavailable === true || typeof row.imageHex !== 'string'+ if (row.unavailable === true) { unavailable.add(row.pid); continue }+ if (typeof row.imageHex !== 'string'|| row.imageHex.length < 2 || row.imageHex.length >= MAX_PATH_BYTES * 2|| row.imageHex.length % 2 !== 0 || !/^[0-9a-f]+$/i.test(row.imageHex)|| typeof row.startMarker !== 'string'@@ -130,7 +132,7 @@ export function parseNativeProcessImages(if (path.startsWith('/') && !path.includes('\0')) images.set(row.pid, { path, startMarker: row.startMarker })} catch { /* Invalid filesystem bytes cannot identify a JS string path. Fall back. */ }}- return images+ return { images, unavailable }}async function bundledHelper(): Promise<{ path: string; key: string } | null> {@@ -162,11 +164,11 @@ async function bundledHelper(): Promise<{ path: string; key: string } | null> {}/** A fresh kernel query on every call. Only the immutable executable's- * preparation is shared; no PID, image or completed process result is cached. */+ * preparation is shared; neither images nor unavailable PID results are cached. */export async function nativeProcessImages(pids: readonly number[], timeout: number,-): Promise<Map<number, NativeProcessImage>> {- const empty = new Map<number, NativeProcessImage>()+): Promise<{ images: Map<number, NativeProcessImage>; unavailable: Set<number> }> {+ const empty = { images: new Map<number, NativeProcessImage>(), unavailable: new Set<number>() }if (platform() !== 'darwin' || !pids.length || pids.length > MAX_PIDS|| !pids.every(validPid) || !Number.isFinite(timeout) || timeout <= 0) return emptyconst deadline = performance.now() + timeout@@ -181,14 +183,14 @@ export async function nativeProcessImages(return await new Promise(resolve => {execFile(helper.path, ['--paths', ...new Set(pids).values()].map(String),{ timeout: remaining, maxBuffer: 4 * 1024 * 1024, env: psEnv() }, (error, stdout) => {- const images = parseNativeProcessImages(stdout ?? '', new Set(pids))- if (error && !images.size) {+ const result = parseNativeProcessImages(stdout ?? '', new Set(pids))+ if (error && !result.images.size) {// A missing/blocked helper must not become a failed spawn every// reconcile. Retry preparation later; ordinary discovery continues.prepared.delete(helper.key)retryAfter.set(helper.key, performance.now() + 60_000)}- resolve(images)+ resolve(result)})})} catch { return empty }diff --git a/cli/src/lib/periodicCpu.integration.spec.ts b/cli/src/lib/periodicCpu.integration.spec.tsnew file mode 100644index 000000000..6377e7bd9--- /dev/null+++ b/cli/src/lib/periodicCpu.integration.spec.ts@@ -0,0 +1,165 @@+// Two of the periodic-CPU fixes, checked where mocks cannot reach. The deleted-image memo (tmux.ts) runs end+// to end against the real native helper and the real lsof: it rests on the helper reporting a deleted+// executable as `unavailable` (nativeProcessImages.ts) while lsof still names the old path. That part runs+// on macOS only, with the same opt-in as processImages.real.spec.ts (RUN_DARWIN_PROCESS_IMAGES=1 and a built+// artifact). The dial gate (cable/serial.ts) is checked under overlapping finds on every platform.+import { execFile as realExecFile, spawn, type ChildProcess } from 'node:child_process'+import { once } from 'node:events'+import { mkdtemp, readFile, realpath, rm, unlink, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { promisify } from 'node:util'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const commands = vi.hoisted(() => [] as string[])+vi.mock('child_process', async original => {+ const actual = await original<typeof import('child_process')>()+ return {+ ...actual,+ execFile: (...args: Parameters<typeof actual.execFile>) => {+ commands.push(String(args[0]))+ return (actual.execFile as (...a: unknown[]) => unknown)(...args)+ },+ }+})++const { env } = await import('../config/env.js')+const { nativeProcessImages } = await import('./nativeProcessImages.js')+const { enrichProcessRows, processRows } = await import('./tmux.js')+const { createDarwinDialFinder } = await import('../cable/serial.js')+const { executableFileIdentity } = await import('./engineBin.js')++const realDescribe = process.platform === 'darwin' && process.env.RUN_DARWIN_PROCESS_IMAGES === '1'+ && process.env.HARNESS_PROCESS_IMAGES_ARTIFACT ? describe : describe.skip+const exec = promisify(realExecFile)+const children: ChildProcess[] = []+const folders: string[] = []+const originalRuntime = env.ADAPTER_RUNTIME_DIR+const lsofCalls = () => commands.filter(command => command.endsWith('lsof')).length++async function fixture(): Promise<string> {+ const path = await realpath(await mkdtemp(join(tmpdir(), 'harness-periodic-cpu-')))+ folders.push(path)+ return path+}++afterEach(async () => {+ for (const child of children.splice(0)) {+ if (child.exitCode !== null || child.signalCode !== null) continue+ const closed = once(child, 'close')+ child.kill('SIGTERM')+ await closed+ }+ vi.unstubAllGlobals()+ env.ADAPTER_RUNTIME_DIR = originalRuntime+ for (const path of folders.splice(0)) await rm(path, { recursive: true, force: true })+})++realDescribe.sequential('deleted executable image memo against the real helper and lsof', () => {+ beforeEach(async () => {+ vi.stubGlobal('__DARWIN_PROCESS_IMAGES__', await readFile(process.env.HARNESS_PROCESS_IMAGES_ARTIFACT!, 'utf8'))+ env.ADAPTER_RUNTIME_DIR = await fixture()+ // Warm the helper so the first pass below is the native path, not a cold-start fallback.+ expect((await nativeProcessImages([process.pid], 3000)).images.size).toBe(1)+ })++ it('asks lsof once for a deleted image, with identical rows, and stops vouching once the path exists', async () => {+ const root = await fixture()+ const binary = join(root, 'claude-2.1.0')+ await writeFile(join(root, 'sleeper.c'), '#include <unistd.h>\nint main(int argc, char **argv) { (void)argv; sleep(argc > 2 ? 0 : 30); return 0; }\n')+ await exec('/usr/bin/clang', [join(root, 'sleeper.c'), '-o', binary], { timeout: 30_000 })+ // macOS inspects a freshly written Mach-O on its first exec, and unlinking it during that inspection+ // got the child SIGKILLed (seen here): run it to completion once so the sleeper below is a later exec.+ await exec(binary, ['warm', 'up'], { timeout: 30_000 }).catch(() => {})+ const child = spawn(binary, ['30'], { stdio: 'ignore' })+ children.push(child)+ await once(child, 'spawn')+ const pid = child.pid!+ await vi.waitFor(async () => expect((await nativeProcessImages([pid], 3000)).images.has(pid)).toBe(true),+ { timeout: 10_000, interval: 100 })+ await new Promise(resolve => setTimeout(resolve, 500))+ await unlink(binary) // what an auto-update does to a running Claude+ await new Promise(resolve => setTimeout(resolve, 300))+ expect({ exit: child.exitCode, signal: child.signalCode }).toEqual({ exit: null, signal: null })++ // The premise: the helper cannot read a deleted image, and says so instead of omitting the PID.+ const native = await nativeProcessImages([pid], 3000)+ expect(native.images.has(pid)).toBe(false)+ expect(native.unavailable.has(pid)).toBe(true)++ const pass = async () => {+ const rows = await processRows()+ expect(rows).not.toBeNull()+ // The full table, one PID selected: exactly how probeTerminalAgents/lookupPaneEngineProcess call it.+ return (await enrichProcessRows(rows!, new Set([pid]))).find(row => row.pid === pid)!+ }+ commands.length = 0+ const first = await pass()+ expect(first.imagePath).toBe(binary)+ expect(first.imageFileKey).toBeUndefined()+ const afterFirst = lsofCalls()+ expect(afterFirst).toBeGreaterThanOrEqual(1)++ const second = await pass()+ expect(second).toEqual(first)+ expect(lsofCalls()).toBe(afterFirst)++ // Something exists at that path again. The helper then reads the PID's (stale) name as available, so+ // the row is whatever the code without the memo produced: the new file's identity, not a memo answer.+ await writeFile(binary, 'not the running image')+ const third = await pass()+ expect(third.imagePath).toBe(binary)+ expect(third.imageFileKey).toBe(executableFileIdentity(binary)!.fileKey)+ }, 45_000)+})++// findDialPort() and the fleet's scan can overlap. Whatever order their ioreg answers land in, a scan+// taken on a plug edge must never be the one served from cache: the next call confirms it.+describe('dial gate with overlapping finds on a plug edge', () => {+ const dump = `+-o Tim <class IOUSBHostDevice>+ "idVendor" = 12346+ "idProduct" = 4097+ "USB Serial Number" = "AA:01"+ +-o CDC+ +-o serial+ "IOCalloutDevice" = "/dev/cu.usbmodem1101"+`+ const tim = [{ path: '/dev/cu.usbmodem1101', serialNumber: 'AA:01', vendorId: 0x303a, productId: 0x1001 }]++ for (const order of ['half-seen answer lands last', 'half-seen answer lands first']) {+ it(`confirms after both finish (${order})`, async () => {+ let entries = ['cu.debug-console:623:1']+ const answers: ((text: string) => void)[] = []+ const runIoreg = vi.fn(() => new Promise<string>(resolve => answers.push(resolve)))+ const find = createDarwinDialFinder({ listDev: () => entries, runIoreg, now: () => 0 })+ const boot = find(); answers.shift()!(''); expect(await boot).toEqual([])++ entries = [...entries, 'cu.usbmodem1101:900:7'] // the dial is plugged in+ const a = find(), b = find()+ expect(runIoreg).toHaveBeenCalledTimes(3)+ const [answerA, answerB] = answers.splice(0)+ if (order === 'half-seen answer lands last') { answerB(dump); await b; answerA(''); await a }+ else { answerA(''); await a; answerB(dump); await b }++ const confirm = find()+ expect(runIoreg).toHaveBeenCalledTimes(4)+ answers.shift()!(dump)+ expect(await confirm).toEqual(tim)+ expect(await find()).toEqual(tim)+ expect(runIoreg).toHaveBeenCalledTimes(4)+ })+ }++ // The phantom check matches ports to /dev/cu.* by basename. A callout path outside that set can never be+ // confirmed, so it must cost the old every-call ioreg, never a cached answer that outlives the device.+ it('never caches a port whose callout path is not a /dev/cu.* node', async () => {+ const odd = dump.replace('/dev/cu.usbmodem1101', '/dev/tty.usbmodem1101')+ let answer = odd+ const runIoreg = vi.fn(async () => answer)+ const find = createDarwinDialFinder({ listDev: () => ['cu.usbmodem1101:900:7'], runIoreg, now: () => 0 })+ for (let i = 0; i < 3; i++) expect(await find()).toEqual([{ ...tim[0], path: '/dev/tty.usbmodem1101' }])+ expect(runIoreg).toHaveBeenCalledTimes(3)+ answer = ''+ expect(await find()).toEqual([])+ })+})diff --git a/cli/src/lib/processImages.real.spec.ts b/cli/src/lib/processImages.real.spec.tsindex ddeda0ff7..bfb834090 100644--- a/cli/src/lib/processImages.real.spec.ts+++ b/cli/src/lib/processImages.real.spec.ts@@ -69,7 +69,7 @@ realDescribe.sequential('real macOS executable identity', () => {// First execution of a freshly written Mach-O may wait on macOS signature// inspection. Production can use lsof during that cold start; warm the// private helper here before requiring the native integration path.- expect((await nativeProcessImages([process.pid], 3000)).size).toBe(1)+ expect((await nativeProcessImages([process.pid], 3000)).images.size).toBe(1)})it('resolves renamed, Unicode, symlinked and hard-linked native images', async () => {diff --git a/cli/src/lib/processImages.spec.ts b/cli/src/lib/processImages.spec.tsindex 999ee4d5f..2cce50d2c 100644--- a/cli/src/lib/processImages.spec.ts+++ b/cli/src/lib/processImages.spec.ts@@ -1,4 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { NativeProcessImage } from './nativeProcessImages.js'import type { ProcessRow } from './tmux.js'const execFile = vi.hoisted(() => vi.fn())@@ -10,7 +11,7 @@ vi.mock('child_process', async original => ({vi.mock('node:os', async original => ({...await original<typeof import('node:os')>(), platform: () => 'darwin',}))-const { enrichProcessRows } = await import('./tmux.js')+const { createDeletedImageMemo, enrichProcessRows } = await import('./tmux.js')const row = (pid: number): ProcessRow => ({pid, parentPid: 1, executable: 'unidentified', args: 'unidentified',@@ -19,23 +20,26 @@ const row = (pid: number): ProcessRow => ({const image = (pid: number, path: string) => `p${pid}\nftxt\nn${path}\n`const answer = (text: string, error: Error | null = null) =>execFile.mockImplementationOnce((_command, _args, _options, callback) => callback(error, text))+const native = (images: [number, NativeProcessImage][] = [], unavailable: number[] = []) =>+ ({ images: new Map(images), unavailable: new Set(unavailable) })-beforeEach(() => {+beforeEach(async () => {execFile.mockReset()- nativeImages.mockReset().mockResolvedValue(new Map())+ nativeImages.mockReset().mockResolvedValue(native())+ await enrichProcessRows([])})afterEach(() => vi.restoreAllMocks())describe('macOS executable images', () => {it('uses fresh native paths without starting lsof when all births match', async () => {- nativeImages.mockResolvedValue(new Map([[10, { path: '/fixture/native', startMarker: 'Fri Oct 2 10:00:00 2026' }]]))+ nativeImages.mockResolvedValue(native([[10, { path: '/fixture/native', startMarker: 'Fri Oct 2 10:00:00 2026' }]]))expect((await enrichProcessRows([row(10)]))[0].imagePath).toBe('/fixture/native')expect(nativeImages).toHaveBeenCalledWith([10], 500)expect(execFile).not.toHaveBeenCalled()})it('uses the ordinary reader only for native identities that are unavailable', async () => {- nativeImages.mockResolvedValue(new Map([[10, { path: '/fixture/native', startMarker: row(10).startMarker }]]))+ nativeImages.mockResolvedValue(native([[10, { path: '/fixture/native', startMarker: row(10).startMarker }]]))answer(image(20, '/fixture/fallback'))expect((await enrichProcessRows([row(10), row(20)])).map(row => row.imagePath)).toEqual(['/fixture/native', '/fixture/fallback'])@@ -43,7 +47,7 @@ describe('macOS executable images', () => {})it('drops a PID with a proven new birth instead of combining new identity and old arguments', async () => {- nativeImages.mockResolvedValue(new Map([[10, { path: '/fixture/new-owner', startMarker: 'Fri Oct 2 10:00:01 2026' }]]))+ nativeImages.mockResolvedValue(native([[10, { path: '/fixture/new-owner', startMarker: 'Fri Oct 2 10:00:01 2026' }]]))const rows = [row(10), row(20)]expect(await enrichProcessRows(rows, new Set([10]))).toEqual([rows[1]])expect(rows).toHaveLength(2)@@ -53,7 +57,7 @@ describe('macOS executable images', () => {it('includes native-query time in the overall fallback deadline', async () => {let now = 0vi.spyOn(performance, 'now').mockImplementation(() => now)- nativeImages.mockImplementation(async () => { now = 500; return new Map() })+ nativeImages.mockImplementation(async () => { now = 500; return native() })execFile.mockImplementationOnce((_command, _args, _options, callback) => {now = 1500callback(new Error('timeout'), '')@@ -156,3 +160,114 @@ describe('macOS executable images', () => {expect(rows[0].imagePath).toBeUndefined()})})++describe('deleted executable image memo', () => {+ it('reuses a deleted path while the helper still reports unavailable', async () => {+ nativeImages.mockResolvedValue(native([], [30]))+ answer(image(30, '/fixture/deleted-30'))+ answer(image(30, '/fixture/deleted-30'))+ expect((await enrichProcessRows([row(30)]))[0].imagePath).toBe('/fixture/deleted-30')+ expect((await enrichProcessRows([row(30)]))[0].imagePath).toBe('/fixture/deleted-30')+ expect(execFile).toHaveBeenCalledOnce()+ })++ it('reads again when the helper says nothing about a remembered PID', async () => {+ nativeImages.mockResolvedValueOnce(native([], [30])).mockResolvedValueOnce(native())+ answer(image(30, '/fixture/deleted-30'))+ answer(image(30, '/fixture/fallback-30'))+ expect((await enrichProcessRows([row(30)]))[0].imagePath).toBe('/fixture/deleted-30')+ const result = await enrichProcessRows([row(30)])+ expect(execFile).toHaveBeenCalledTimes(2)+ expect(result[0].imagePath).toBe('/fixture/fallback-30')+ })++ it('reads an existing path on every pass even when the helper reports unavailable', async () => {+ nativeImages.mockResolvedValue(native([], [31]))+ answer(image(31, process.execPath))+ answer(image(31, process.execPath))+ expect((await enrichProcessRows([row(31)]))[0].imagePath).toBe(process.execPath)+ expect((await enrichProcessRows([row(31)]))[0].imagePath).toBe(process.execPath)+ expect(execFile).toHaveBeenCalledTimes(2)+ })++ it('reads again when arguments or the process birth change', async () => {+ nativeImages.mockResolvedValue(native([], [32]))+ for (let pass = 0; pass < 3; pass++) answer(image(32, '/fixture/deleted-32'))+ const resumed = { ...row(32), args: 'claude --resume' }+ for (const current of [row(32), resumed, { ...resumed, startMarker: 'Fri Oct 02 10:00:05 2026' }]) {+ expect((await enrichProcessRows([current]))[0].imagePath).toBe('/fixture/deleted-32')+ }+ expect(execFile).toHaveBeenCalledTimes(3)+ })++ it('uses a readable native image instead of the memo', async () => {+ nativeImages.mockResolvedValueOnce(native([], [33]))+ .mockResolvedValueOnce(native([[33, { path: '/fixture/native-33', startMarker: row(33).startMarker }]]))+ .mockResolvedValueOnce(native([], [33]))+ answer(image(33, '/fixture/deleted-33'))+ answer(image(33, '/fixture/after-native-33'))+ expect((await enrichProcessRows([row(33)]))[0].imagePath).toBe('/fixture/deleted-33')+ expect((await enrichProcessRows([row(33)]))[0].imagePath).toBe('/fixture/native-33')+ expect(execFile).toHaveBeenCalledOnce()+ const result = await enrichProcessRows([row(33)])+ expect(execFile).toHaveBeenCalledTimes(2)+ expect(result[0].imagePath).toBe('/fixture/after-native-33')+ })++ it('forgets PIDs that disappear from the full table', async () => {+ nativeImages.mockResolvedValueOnce(native([], [34]))+ .mockResolvedValueOnce(native([[35, { path: '/fixture/native-35', startMarker: row(35).startMarker }]]))+ .mockResolvedValueOnce(native([], [34]))+ answer(image(34, '/fixture/deleted-34'))+ answer(image(34, '/fixture/deleted-34'))+ answer(image(34, '/fixture/deleted-34'))+ expect((await enrichProcessRows([row(34)]))[0].imagePath).toBe('/fixture/deleted-34')+ expect((await enrichProcessRows([row(35)]))[0].imagePath).toBe('/fixture/native-35')+ expect((await enrichProcessRows([row(34)]))[0].imagePath).toBe('/fixture/deleted-34')+ expect(execFile).toHaveBeenCalledTimes(2)+ })++ it('checks existence, arguments and birth, forgets existing paths and prunes absent PIDs', () => {+ let exists = false+ const memo = createDeletedImageMemo({ exists: () => exists })+ const original = row(1)+ memo.remember(original, '/fixture/deleted')+ expect(memo.recall(original)).toBe('/fixture/deleted')+ expect(memo.recall({ ...original, args: 'claude --resume' })).toBeUndefined()+ expect(memo.recall({ ...original, startMarker: 'Fri Oct 02 10:00:05 2026' })).toBeUndefined()+ exists = true+ expect(memo.recall(original)).toBeUndefined()+ memo.remember(original, '/fixture/deleted')+ exists = false+ expect(memo.recall(original)).toBeUndefined()+ memo.remember(original, '/fixture/deleted')+ memo.prune([row(2)])+ expect(memo.recall(original)).toBeUndefined()+ })++ it('keeps other panes memoised when only one pane is selected', async () => {+ nativeImages.mockResolvedValueOnce(native([], [36]))+ .mockResolvedValueOnce(native([[37, { path: '/fixture/native-37', startMarker: row(37).startMarker }]]))+ .mockResolvedValueOnce(native([], [36]))+ answer(image(36, '/fixture/deleted-36'))+ answer(image(36, '/fixture/deleted-36'))+ answer(image(36, '/fixture/deleted-36'))+ expect((await enrichProcessRows([row(36)]))[0].imagePath).toBe('/fixture/deleted-36')+ const selected = await enrichProcessRows([row(36), row(37)], new Set([37]))+ expect(selected[1].imagePath).toBe('/fixture/native-37')+ expect((await enrichProcessRows([row(36)]))[0].imagePath).toBe('/fixture/deleted-36')+ expect(execFile).toHaveBeenCalledOnce()+ })++ it('prunes when the full table or selected set is empty', async () => {+ nativeImages.mockResolvedValue(native([], [31]))+ for (let pass = 0; pass < 3; pass++) answer(image(31, '/fixture/deleted-31'))+ expect((await enrichProcessRows([row(31)]))[0].imagePath).toBe('/fixture/deleted-31')+ const unselected = [row(37)]+ expect(await enrichProcessRows(unselected, new Set())).toBe(unselected)+ expect((await enrichProcessRows([row(31)]))[0].imagePath).toBe('/fixture/deleted-31')+ expect(await enrichProcessRows([])).toEqual([])+ expect((await enrichProcessRows([row(31)]))[0].imagePath).toBe('/fixture/deleted-31')+ expect(execFile).toHaveBeenCalledTimes(3)+ })+})diff --git a/cli/src/lib/registry.fingerprint.spec.ts b/cli/src/lib/registry.fingerprint.spec.tsnew file mode 100644index 000000000..659668b51--- /dev/null+++ b/cli/src/lib/registry.fingerprint.spec.ts@@ -0,0 +1,217 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { fsyncSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs'+import { tmpdir } from 'os'+import { join } from 'path'+import type { registry as Registry } from './registry.js'++// Rows are compared without regard to key order. These cases check that this hides only key order:+// another writer's real changes still land, local real changes still write, and the file keeps its format.+vi.mock('fs', async (importOriginal) => {+ const fs = await importOriginal<typeof import('fs')>()+ return { ...fs, fsyncSync: vi.fn(fs.fsyncSync), renameSync: vi.fn(fs.renameSync), mkdirSync: vi.fn(fs.mkdirSync) }+})++type Row = Record<string, unknown>+let directory: string+let file: string+let registry: typeof Registry+const input = {+ agentId: 'observed-agent', engine: 'claude' as const, tmuxPane: '%31', cwd: '/fixture/project',+ processIdentity: { pid: 1031, executable: '/fixture/claude', startMarker: 'fixture-1031' },+}+const plan = {+ id: '12345678-1234-1234-1234-123456789012', identity: 'fixture-conversation',+ requestedAt: 1790900000000, state: 'waiting' as const,+}+const readRows = (): Row[] => JSON.parse(readFileSync(file, 'utf8'))+const writeRows = (rows: unknown[]) => writeFileSync(file, JSON.stringify(rows, null, 2))+const clearCounts = () => vi.clearAllMocks()+const registryWrites = () => vi.mocked(renameSync).mock.calls.filter(([, target]) => target === file).length+const lockAttempts = () => vi.mocked(mkdirSync).mock.calls.filter(([target]) => target === `${file}.lock`).length+/** Every object's keys reversed, at every depth; array order kept. Same data, as another writer may order it. */+const reversedDeep = (value: unknown): unknown => Array.isArray(value)+ ? value.map(reversedDeep)+ : value && typeof value === 'object'+ ? Object.fromEntries(Object.entries(value).reverse().map(([key, inner]) => [key, reversedDeep(inner)]))+ : value+const tick = () => vi.setSystemTime(Date.now() + 5000)++async function observe(on: typeof Registry = registry, identity: Row = { ...input.processIdentity }) {+ const row = on.byAgent(input.agentId)!+ await on.transaction(() => {+ expect(on.updateRuntimes(row.agentId, row.runtimes, row.primaryRuntimeKey)).toBe(true)+ expect(on.updateProcessIdentity(row.agentId, identity as typeof input.processIdentity)).toBe(true)+ })+}++async function freshRegistry(): Promise<typeof Registry> {+ vi.resetModules()+ const next = (await import('./registry.js')).registry+ next.load()+ return next+}++beforeEach(async () => {+ vi.resetModules()+ vi.useFakeTimers()+ vi.setSystemTime(1790900000000)+ directory = mkdtempSync(join(tmpdir(), 'registry-fingerprint-'))+ file = join(directory, 'registry.json')+ for (const key of ['ADAPTER_DATA_DIR', 'CLAUDE_PROJECTS_DIR', 'CODEX_HOME', 'CURSOR_HOME']) vi.stubEnv(key, directory)+ registry = (await import('./registry.js')).registry+ registry.load()+ expect(registry.openProcessAgent(input)).not.toBeNull()+ clearCounts()+ tick()+})++afterEach(() => {+ vi.mocked(fsyncSync).mockReset()+ vi.useRealTimers()+ vi.unstubAllEnvs()+ vi.restoreAllMocks()+ rmSync(directory, { recursive: true, force: true })+})++describe('key-order-insensitive row comparison', () => {+ it('adopts another writer\'s nested change while idle, then stays quiet', async () => {+ registry.setClosePlan(input.agentId, plan)+ const [saved] = readRows()+ const external = { ...saved, closePlan: { ...plan, state: 'failed', detail: 'external' } }+ writeRows([reversedDeep(external)])+ clearCounts()+ await observe()+ expect(registryWrites()).toBe(1)+ expect(registry.byAgent(input.agentId)?.closePlan).toMatchObject({ state: 'failed', detail: 'external' })+ const bytes = readFileSync(file, 'utf8')+ clearCounts()+ for (let pass = 0; pass < 3; pass++) { tick(); await observe() }+ expect(registryWrites()).toBe(0)+ expect(lockAttempts()).toBe(0)+ expect(readFileSync(file, 'utf8')).toBe(bytes)+ expect(readRows()[0]).toEqual(external)+ })++ it('does not bring back a close plan another process removed when a different field changes here', () => {+ registry.setClosePlan(input.agentId, plan)+ const [saved] = readRows()+ const { closePlan: _removed, ...withoutPlan } = saved+ writeRows([reversedDeep(withoutPlan)])+ expect(registry.updateProcessIdentity(input.agentId, input.processIdentity, 'ori')).toBe(true)+ expect(readRows()[0]).toMatchObject({ gateway: 'ori' })+ expect(readRows()[0]).not.toHaveProperty('closePlan')+ expect(registry.byAgent(input.agentId)).not.toHaveProperty('closePlan')+ })++ it('does not let a reordered copy of the old process identity overwrite another writer\'s new one', async () => {+ const [saved] = readRows()+ const next = { ...input.processIdentity, startMarker: 'external-generation' }+ writeRows([reversedDeep({ ...saved, processIdentity: next })])+ await observe(registry, reversedDeep(input.processIdentity) as Row)+ expect(readRows()[0].processIdentity).toEqual(next)+ expect(registry.byAgent(input.agentId)?.processIdentity).toEqual(next)+ })++ it('keeps the local value when both sides changed the same nested field, whatever the key order', async () => {+ const [saved] = readRows()+ writeRows([reversedDeep({ ...saved, processIdentity: { ...input.processIdentity, startMarker: 'external' } })])+ const local = { ...input.processIdentity, startMarker: 'local' }+ await observe(registry, reversedDeep(local) as Row)+ expect(readRows()[0].processIdentity).toEqual(local)+ expect(registry.byAgent(input.agentId)?.processIdentity).toEqual(local)+ })++ it('treats a reordered grid as unchanged but writes a changed or cleared one', () => {+ const grid = { baseUrl: 'https://relay.example/v1', model: null }+ expect(registry.updateProcessIdentity(input.agentId, input.processIdentity, undefined, grid)).toBe(true)+ expect(registryWrites()).toBe(1)+ const touchedAt = registry.byAgent(input.agentId)!.touchedAt+ const bytes = readFileSync(file, 'utf8')+ clearCounts()+ tick()+ registry.updateProcessIdentity(input.agentId, reversedDeep(input.processIdentity) as typeof input.processIdentity,+ undefined, { model: null, baseUrl: grid.baseUrl })+ expect(registryWrites()).toBe(0)+ expect(lockAttempts()).toBe(0)+ expect(registry.byAgent(input.agentId)!.touchedAt).toBe(touchedAt)+ expect(readFileSync(file, 'utf8')).toBe(bytes)+ tick()+ registry.updateProcessIdentity(input.agentId, input.processIdentity, undefined, { model: 'other', baseUrl: grid.baseUrl })+ expect(registryWrites()).toBe(1)+ expect(readRows()[0]).toMatchObject({ grid: { model: 'other' }, touchedAt: Date.now() })+ tick()+ registry.updateProcessIdentity(input.agentId, input.processIdentity, undefined, null)+ expect(registryWrites()).toBe(2)+ expect(readRows()[0]).toMatchObject({ grid: null, touchedAt: Date.now() })+ })++ it('keeps the saved file format: two-space JSON in insertion order, never sorted keys', async () => {+ // One load first, so the row carries load()'s own normalisation (dshRuntime, gridWebSearch).+ registry.load()+ await observe()+ const [saved] = readRows()+ expect(readFileSync(file, 'utf8')).toBe(JSON.stringify([saved], null, 2))+ expect(Object.keys(saved)).not.toEqual(Object.keys(saved).sort())+ expect(Object.keys(saved.processIdentity as Row)).toEqual(['pid', 'executable', 'startMarker'])+ // A file another writer ordered differently is written back in that order, not canonicalised.+ writeRows([reversedDeep(saved)])+ registry.load()+ await observe()+ const [written] = readRows()+ expect(readFileSync(file, 'utf8')).toBe(JSON.stringify([written], null, 2))+ expect(written).toEqual(saved)+ expect(Object.keys(written)).not.toEqual(Object.keys(written).sort())+ expect(Object.keys(written.processIdentity as Row)).toEqual(['startMarker', 'executable', 'pid'])+ })++ it('a hand-written file with runtimes out of order saves once in canonical order, then stays quiet', async () => {+ const [saved] = readRows()+ writeRows([{+ ...saved,+ runtimes: [{ paneId: '%32', backend: 'tmux' }, { backend: 'tmux', paneId: '%31' }],+ primaryRuntimeKey: 'tmux\u0000%32',+ tmuxPane: '%31',+ }])+ clearCounts()+ registry.load()+ await observe()+ expect(registryWrites()).toBe(1)+ const row = registry.byAgent(input.agentId)!+ expect(row.runtimes.map((runtime) => runtime.paneId)).toEqual(['%31', '%32'])+ expect(row.primaryRuntimeKey).toBe('tmux\u0000%32')+ expect((readRows()[0].runtimes as Row[]).map((runtime) => runtime.paneId)).toEqual(['%31', '%32'])+ expect(readRows()[0]).toMatchObject({ primaryRuntimeKey: 'tmux\u0000%32', tmuxPane: '%31' })+ clearCounts()+ for (let pass = 0; pass < 3; pass++) { tick(); await observe() }+ expect(registryWrites()).toBe(0)+ expect(lockAttempts()).toBe(0)+ })++ it('two registries over one file keep each other\'s changes and converge instead of rewriting back and forth', async () => {+ const first = registry+ const second = await freshRegistry()+ expect(second.updateProcessIdentity(input.agentId, input.processIdentity, 'ori')).toBe(true)+ tick()+ expect(first.updateProcessIdentity(input.agentId, input.processIdentity, undefined,+ { baseUrl: 'https://relay.example/v1', model: null })).toBe(true)+ clearCounts()+ for (let pass = 0; pass < 2; pass++) {+ tick(); await observe(first)+ tick(); await observe(second)+ }+ // Each side may adopt the other's last commit once; after that, neither writes.+ expect(registryWrites()).toBeLessThanOrEqual(2)+ clearCounts()+ for (let pass = 0; pass < 3; pass++) {+ tick(); await observe(first)+ tick(); await observe(second)+ }+ expect(registryWrites()).toBe(0)+ expect(lockAttempts()).toBe(0)+ expect(fsyncSync).not.toHaveBeenCalled()+ const expected = { gateway: 'ori', grid: { baseUrl: 'https://relay.example/v1', model: null } }+ expect(readRows()[0]).toMatchObject(expected)+ expect(first.byAgent(input.agentId)).toMatchObject(expected)+ expect(second.byAgent(input.agentId)).toMatchObject(expected)+ })+})diff --git a/cli/src/lib/registry.observation.spec.ts b/cli/src/lib/registry.observation.spec.tsindex 036e10a8d..edd1529fe 100644--- a/cli/src/lib/registry.observation.spec.ts+++ b/cli/src/lib/registry.observation.spec.ts@@ -79,6 +79,53 @@ describe('unchanged discovery observations', () => {expect(fsyncSync).not.toHaveBeenCalled()})+ // The daemon rewrote registry.json every 5 s when only key order differed (2026-10-06 profile).+ it('does not rewrite a registry saved with another key order, yet writes a real change', async () => {+ const reversed = <T extends object>(o: T): T => Object.fromEntries(Object.entries(o).reverse()) as T+ const [saved] = readRows()+ writeFileSync(file, JSON.stringify([reversed({+ ...saved, processIdentity: reversed(saved.processIdentity), runtimes: saved.runtimes.map(reversed),+ launch: { state: 'ready' }, forkedFrom: { name: 'Parent', agentId: 'parent-agent' },+ closePlan: reversed(plan), lastOpenedAt: 1790900000000,+ })], null, 2))+ clearCounts()+ registry.load()+ const discover = () => registry.transaction(() => {+ registry.updateRuntimes(input.agentId, [{ backend: 'tmux', paneId: '%31' }])+ registry.updateProcessIdentity(input.agentId, { ...input.processIdentity })+ })+ await discover()+ expect(registryWrites()).toBe(1)+ const bytes = readFileSync(file, 'utf8')+ const touchedAt = readRows()[0].touchedAt+ clearCounts()+ for (let pass = 0; pass < 3; pass++) {+ vi.setSystemTime(Date.now() + 5000)+ await discover()+ }+ expect(registryWrites()).toBe(0)+ expect(lockAttempts()).toBe(0)+ expect(fsyncSync).not.toHaveBeenCalled()+ expect(readFileSync(file, 'utf8')).toBe(bytes)+ expect(readRows()[0]).toMatchObject({ touchedAt, launch: { state: 'ready' }, closePlan: plan,+ forkedFrom: { name: 'Parent', agentId: 'parent-agent' }, lastOpenedAt: 1790900000000 })+ await registry.transaction(() => {+ registry.updateProcessIdentity(input.agentId, { ...input.processIdentity, startMarker: 'fixture-next' })+ })+ expect(registryWrites()).toBe(1)+ expect(fsyncSync).toHaveBeenCalledTimes(3)+ expect(readRows()[0]).toMatchObject({ processIdentity: { startMarker: 'fixture-next' }, touchedAt: Date.now() })+ })++ it('keeps another process\'s change to a nested field when a different field changes here', () => {+ registry.setClosePlan(input.agentId, plan)+ const [saved] = readRows()+ writeFileSync(file, JSON.stringify([{ ...saved, closePlan: { ...plan, state: 'failed', detail: 'external' } }], null, 2))+ registry.updateProcessIdentity(input.agentId, input.processIdentity, 'ori')+ expect(readRows()[0]).toMatchObject({ gateway: 'ori', closePlan: { state: 'failed', detail: 'external' } })+ expect(registry.byAgent(input.agentId)?.closePlan?.state).toBe('failed')+ })+it('still persists a changed route and process generation in one durable transaction', async () => {const row = registry.byAgent(input.agentId)!const identity = { ...input.processIdentity, startMarker: 'replacement-generation', executable: '/fixture/new-claude' }diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex 556be3120..8050ac679 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -439,8 +439,12 @@ function rowId(row: unknown): string {: typeof candidate.launcherId === 'string' ? candidate.launcherId : ''}+// Key order carries no meaning but differs between load()'s literal, register(), strictPersistedRow and+// setters that add keys (`launch`); compared as JSON text it rewrote registry.json (lock, 3 fsyncs, rename)+// every 5 s on an unchanged row, ~720 writes/hour measured 2026-10-06. Array order still counts.function rowFingerprint(row: unknown): string {- return JSON.stringify(row)+ return JSON.stringify(row, (_key, value) => value && typeof value === 'object' && !Array.isArray(value)+ ? Object.fromEntries(Object.keys(value).sort().map((key) => [key, value[key]])) : value)}export function atomicWriteJson(file: string, value: unknown, exclusive = false): void {@@ -715,7 +719,7 @@ function threeWayRow(if (!(key in current)) delete merged[key]}for (const [key, value] of Object.entries(current)) {- if (JSON.stringify(value) !== JSON.stringify(baseline[key])) merged[key] = value+ if (rowFingerprint(value) !== rowFingerprint(baseline[key])) merged[key] = value}return merged}diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.tsindex 5520295f6..5e20833a1 100644--- a/cli/src/lib/tmux.ts+++ b/cli/src/lib/tmux.ts@@ -359,9 +359,31 @@ function parseDarwinProcessImages(stdout: string | null): Map<number, string> {return images}-/** macOS has no /proc. Prefer the bundled read-only kernel image probe; retain- * both lsof readers for missing paths, inside the same total 3s budget.- * Never cache by PID: exec can replace an image without changing its birth. */+export function createDeletedImageMemo({ exists }: { exists: (path: string) => boolean }) {+ const memo = new Map<number, { startMarker: string; args: string; path: string }>()+ return {+ recall(row: ProcessRow): string | undefined {+ const entry = memo.get(row.pid)+ return entry && entry.startMarker === row.startMarker && entry.args === row.args && !exists(entry.path) ? entry.path : undefined+ },+ remember({ pid, startMarker, args }: ProcessRow, path: string): void {+ if (exists(path)) memo.delete(pid)+ else memo.set(pid, { startMarker, args, path })+ },+ forget(pid: number): void { memo.delete(pid) },+ prune(rows: readonly ProcessRow[]): void { for (const pid of memo.keys()) if (!rows.some(row => row.pid === pid)) memo.delete(pid) },+ }+}+const deletedImages = createDeletedImageMemo({ exists: existsSync })++/** macOS has no /proc. Prefer the bundled kernel probe and retain both lsof+ * fallbacks within the same 3s budget. Never cache by PID alone: exec can replace+ * an image without changing its birth. Memo safety rests on !exists(path) and+ * the helper reporting the PID unavailable this same pass; birth and args must match.+ * We accept an exec into another binary keeping argv and birth, then deletion+ * before the helper reads it: only the imagePath evidence string can be wrong.+ * Claude auto-updates left deleted images costing lsof -d txt ~18 ms every+ * 5 s (~0.4% core), measured 2026-10-06. */async function darwinProcessImages(rows: readonly ProcessRow[]): Promise<{images: Map<number, string>; stale: Set<number>}> {@@ -374,8 +396,13 @@ async function darwinProcessImages(rows: readonly ProcessRow[]): Promise<{const normalizeStart = (marker: string) => marker.trim().split(/\s+/).map((part, index) => index === 2 ? String(Number(part)) : part).join(' ')for (const row of rows) {- const image = native.get(row.pid)- if (!image) continue+ const image = native.images.get(row.pid)+ if (!image) {+ const path = native.unavailable.has(row.pid) && deletedImages.recall(row)+ if (path) images.set(row.pid, path)+ continue+ }+ deletedImages.forget(row.pid)if (normalizeStart(image.startMarker) === normalizeStart(row.startMarker)) images.set(row.pid, image.path)// The PID changed owners since ps. Do not combine the new executable with// old ancestry/arguments, or let the fallback reintroduce that stale row.@@ -396,20 +423,23 @@ async function darwinProcessImages(rows: readonly ProcessRow[]): Promise<{images.set(pid, path)}}+ for (const row of rows) if (native.unavailable.has(row.pid) && images.has(row.pid)) deletedImages.remember(row, images.get(row.pid)!)return { images, stale }}/*** Attach executable-image and entrypoint identity to selected process rows.*- * Callers pass only descendants of terminal roots (or one saved PID during validation), so native- * binary ownership is available for every engine without asking lsof to inspect the whole machine.+ * The rows argument is the whole process table used for memo pruning.+ * Only selectedPids are probed: terminal descendants or one saved PID during validation.*/export async function enrichProcessRows(rows: ProcessRow[],selectedPids: ReadonlySet<number> = new Set(rows.map((row) => row.pid)),): Promise<ProcessRow[]> {const candidates = rows.filter((row) => selectedPids.has(row.pid))+ // Prune the full table so one-pane lookups keep other panes' memo (18 ms/pass, 2026-10-06).+ if (platform() === 'darwin') deletedImages.prune(rows)if (!candidates.length) return rowsconst imagePaths = new Map<number, string>()const imageIdentities = new Map<number, ReturnType<typeof executableFileIdentity>>()