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
Hold session control on incomplete native ownership evidence (#1131)
Dee9eafacf3b512
diff --git a/cli/e2e/enginehomes.e2e.ts b/cli/e2e/enginehomes.e2e.tsindex f959c291b..6c3f11c23 100644--- a/cli/e2e/enginehomes.e2e.ts+++ b/cli/e2e/enginehomes.e2e.ts@@ -7,7 +7,7 @@* without the profile. An agent must still bind, take turns and come back after a restart.*/import { execFileSync } from 'node:child_process'-import { mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs'+import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs'import { join } from 'node:path'import { pathToFileURL } from 'node:url'import { afterEach, describe, expect, it, onTestFailed } from 'vitest'@@ -397,6 +397,71 @@ describe('the person\'s engines keeping their data elsewhere', () => {client.close()}, 240_000)+ it.runIf(process.platform === 'darwin')('Codex binding does not wait for the optional native discovery cooldown', async () => {+ const d = await IsolatedDaemon.create({ env: { HOOK_INSTALL_ENGINES: 'claude' } }); daemon = d+ onTestFailed(() => console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`))+ const fault = join(d.root, 'optional-native-discovery-unavailable')+ writeFileSync(fault, 'hold', { mode: 0o600 })+ d.env.HARNESS_NATIVE_DISCOVERY_FAULT_FILE = fault+ d.env.NODE_OPTIONS = `--import=${pathToFileURL(join(CLI_ROOT, 'e2e/harness/nativeDescriptorFault.mjs')).href}`+ await d.start()+ const client = await LocalClient.connect(d)+ const opened = await client.request('agent_create', { engine: 'terminal', cwd: d.projectsDir }, 60_000)+ expect(opened.error, JSON.stringify(opened)).toBeUndefined()+ const tile = await until('the private terminal tile', async () => {+ const now = await row(client, opened.agent.id); return now?.tmuxPane ? now : null+ })+ await until('the optional native discovery failure', () => existsSync(fault + '.observed'), 20_000)+ await type(d, tile.tmuxPane, 'codex')+ const sessionId = await until('the private Codex rollout', () => conversationIn('codex', d.env.CODEX_HOME!), 10_000)+ await until('binding under the optional discovery cooldown', async () => {+ const now = await row(client, tile.id)+ return now?.status === 'active' && now.sessionId === sessionId+ }, 20_000, 250)+ expect(Date.now() - Number(readFileSync(fault + '.observed', 'utf8'))).toBeLessThan(60_000)+ client.close()+ }, 120_000)++ it('unavailable Codex descriptor evidence holds binding, Stop and Close, then recovers the same conversation', async () => {+ const d = await IsolatedDaemon.create({ env: { HOOK_INSTALL_ENGINES: 'claude' } }); daemon = d+ onTestFailed(() => console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`))+ const fault = join(d.root, 'native-descriptors-unavailable')+ d.env.HARNESS_DESCRIPTOR_FAULT_FILE = fault+ d.env.NODE_OPTIONS = `--import=${pathToFileURL(join(CLI_ROOT, 'e2e/harness/nativeDescriptorFault.mjs')).href}`+ await d.start()+ let client = await LocalClient.connect(d)+ const opened = await client.request('agent_create', { engine: 'terminal', cwd: d.projectsDir }, 60_000)+ expect(opened.error, JSON.stringify(opened)).toBeUndefined()+ const tile = await until('the private terminal tile', async () => {+ const now = await row(client, opened.agent.id); return now?.tmuxPane ? now : null+ })+ client.close(); await d.stop()+ await type(d, tile.tmuxPane, 'codex')+ const sessionId = await until('the private Codex rollout', () => conversationIn('codex', d.env.CODEX_HOME!), 30_000)+ writeFileSync(fault, 'hold', { mode: 0o600 })+ await d.start()+ client = await LocalClient.connect(d)+ await until('the descriptor binding hold after readiness', () => /binding held · Conversation identity is held: the native (?:lsof|descriptor)/.test(d.log()), 45_000)+ const held = await row(client, tile.id)+ expect(held).toMatchObject({ engine: 'codex', status: 'active' })+ expect(held?.sessionId).toBeFalsy()+ const sibling = await client.request('agent_create', { engine: 'claude', cwd: d.projectsDir, bypassPermission: true }, 90_000)+ expect(sibling.error, JSON.stringify(sibling)).toBeUndefined()+ await until('the independent sibling to bind', async () => (await row(client, sibling.agent.id))?.sessionId, 45_000)+ const stopped = await client.request('agent_delete', { agentId: tile.id }, 60_000)+ expect(stopped.error, JSON.stringify(stopped)).toBeTruthy()+ const closed = await client.request('agent_close', { agentId: tile.id, sessionId: held!.sessionId, createdAt: held!.createdAt, mode: 'now' }, 60_000)+ expect(closed).toMatchObject({ error: 'IDENTITY_UNAVAILABLE', detail: expect.stringMatching(/native (?:lsof|descriptor)/) })+ expect((await row(client, tile.id))?.status).toBe('active')+ expect(conversationIn('codex', d.env.CODEX_HOME!)).toBe(sessionId)+ renameSync(fault, fault + '.recovered')+ await until('the same live Codex conversation to bind after native evidence recovers', async () => {+ const now = await row(client, tile.id)+ return now?.status === 'active' && now.sessionId === sessionId+ }, 60_000, 250)+ client.close()+ }, 240_000)+// A Codex agent in a moved CODEX_HOME, restarted, then stopped and opened again. Its rollout was held to the// daemon's own CODEX_HOME before the relaunch (portableHistory.ts) and refused as outside the profile: the// restart failed after Codex had already been stopped, and the reopen said RESUME_PREPARATION_FAILED. Anddiff --git a/cli/e2e/harness/nativeDescriptorFault.mjs b/cli/e2e/harness/nativeDescriptorFault.mjsnew file mode 100644index 000000000..cdea1b001--- /dev/null+++ b/cli/e2e/harness/nativeDescriptorFault.mjs@@ -0,0 +1,43 @@+// Private e2e fault: deny only complete native descriptor reads while a fixture flag exists.+// An independent optional-discovery fault checks that its cooldown cannot gate control.+import childProcess from 'node:child_process'+import { EventEmitter } from 'node:events'+import fs from 'node:fs'+import promises from 'node:fs/promises'+import { syncBuiltinESMExports } from 'node:module'+import { promisify } from 'node:util'++const blocked = () => !!process.env.HARNESS_DESCRIPTOR_FAULT_FILE && fs.existsSync(process.env.HARNESS_DESCRIPTOR_FAULT_FILE)+const denied = () => Object.assign(new Error('fixture: native descriptor evidence is unavailable'), { code: 'EACCES' })+const isDescriptor = path => /^\/proc\/\d+\/fd$/.test(String(path))+const execFile = childProcess.execFile, execAsync = promisify(execFile)+const rejectProbe = (file, args) => file === 'lsof' && args?.includes('-F0pftDin') && blocked()+const rejectDiscovery = (file, args) => String(file).includes('/process-images/') && args?.[0] === '--paths'+ && process.env.HARNESS_NATIVE_DISCOVERY_FAULT_FILE && fs.existsSync(process.env.HARNESS_NATIVE_DISCOVERY_FAULT_FILE)+childProcess.execFile = function (file, args, ...rest) {+ if (rejectDiscovery(file, args)) {+ const observed = process.env.HARNESS_NATIVE_DISCOVERY_FAULT_FILE + '.observed'+ if (!fs.existsSync(observed)) fs.writeFileSync(observed, String(Date.now()), { mode: 0o600 })+ const child = new EventEmitter(), callback = rest.find(value => typeof value === 'function')+ queueMicrotask(() => {+ callback?.(Object.assign(new Error('fixture optional discovery timeout'), { code: 'ETIMEDOUT' }), '', '')+ child.emit('close', 1)+ })+ return child+ }+ if (!rejectProbe(file, args)) return execFile.call(this, file, args, ...rest)+ const child = new EventEmitter(), callback = rest.find(value => typeof value === 'function')+ queueMicrotask(() => { callback?.(denied(), Buffer.from('p1\0\n'), Buffer.alloc(0)); child.emit('close', 1) })+ return child+}+childProcess.execFile[promisify.custom] = (file, args, ...rest) => rejectProbe(file, args) ? Promise.reject(denied()) : execAsync(file, args, ...rest)+const opendir = promises.opendir, opendirSync = fs.opendirSync+promises.opendir = async function (path, ...rest) {+ if (isDescriptor(path) && blocked()) throw denied()+ return opendir.call(this, path, ...rest)+}+fs.opendirSync = function (path, ...rest) {+ if (isDescriptor(path) && blocked()) throw denied()+ return opendirSync.call(this, path, ...rest)+}+syncBuiltinESMExports()diff --git a/cli/native/darwin-process-images.c b/cli/native/darwin-process-images.cindex 08b3992d1..3fe126d5a 100644--- a/cli/native/darwin-process-images.c+++ b/cli/native/darwin-process-images.c@@ -1,7 +1,7 @@/*- * Read-only macOS executable-image probe. No process arguments or environment- * are read. PID/birth and a repeated path read bracket each result; callers- * retain their normal process-reader fallback for any unavailable identity.+ * Read-only macOS process evidence. The optional --paths discovery mode reads+ * executable images only. Strict --control reads bounded argv and descriptors,+ * never emits environment data, and rejects an incomplete observation in full.** stdout is versioned JSON lines. Paths are hex-encoded filesystem bytes, not* interpolated JSON or assumed UTF-8. A consumer must validate them before use.@@ -16,6 +16,10 @@#include <time.h>#include <libproc.h>#include <sys/proc_info.h>+#include <sys/proc.h>+#include <sys/stat.h>+#include <sys/sysctl.h>+#include <CommonCrypto/CommonDigest.h>#define MAX_PIDS 4096@@ -33,11 +37,12 @@ static int parse_pid(const char *text, pid_t *pid) {return 1;}-static int birth(pid_t pid, struct proc_bsdinfo *info) {+static int birth_including_zombies(pid_t pid, int zombies, struct proc_bsdinfo *info) {memset(info, 0, sizeof(*info));- return proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, info, sizeof(*info)) == sizeof(*info)- && info->pbi_pid == (uint32_t)pid && info->pbi_start_tvsec > 0;+ return proc_pidinfo(pid, PROC_PIDTBSDINFO, zombies, info, sizeof(*info)) == sizeof(*info)+ && info->pbi_pid == (uint32_t)pid && info->pbi_start_tvsec > 0 && info->pbi_start_tvusec < 1000000;}+static int birth(pid_t pid, struct proc_bsdinfo *info) { return birth_including_zombies(pid, 0, info); }static int image_path(pid_t pid, char *path, size_t capacity, size_t *length) {memset(path, 0, capacity);@@ -89,7 +94,178 @@ static void print_image(pid_t pid) {puts("\"}");}+/* A joined control observation has no interleaved ps/lsof subprocess waits. It+ * reads only the requested processes, argv (never environment output), numeric+ * descriptors and an optional direct-child set. No signals or filesystem writes.+ * The two bounded passes detect change; this is not an atomic kernel snapshot. */+#define CONTROL_PIDS 33+#define CONTROL_FDS 4096+#define CONTROL_ARGS 65536+struct control_fd { int32_t fd; uint32_t type, mode, device; uint64_t inode; };+struct control_row {+ pid_t pid;+ uint32_t parent, fd_capacity;+ uint64_t seconds, micros;+ char command[MAXCOMLEN + 1], image[PROC_PIDPATHINFO_MAXSIZE];+ unsigned char command_digest[CC_SHA256_DIGEST_LENGTH];+ int fd_count;+ struct control_fd fds[CONTROL_FDS];+};+static struct timespec control_deadline;+static int control_work = 32768;+static int control_step(void) {+ struct timespec now;+ if (--control_work < 0 || clock_gettime(CLOCK_MONOTONIC, &now)) return 0;+ return now.tv_sec < control_deadline.tv_sec+ || (now.tv_sec == control_deadline.tv_sec && now.tv_nsec < control_deadline.tv_nsec);+}+static int control_birth(pid_t pid, struct proc_bsdinfo *info) {+ return control_step() && birth(pid, info) && info->pbi_status != SZOMB+ && !(info->pbi_flags & PROC_FLAG_INEXIT);+}+static int same_birth(const struct proc_bsdinfo *a, const struct proc_bsdinfo *b) {+ return a->pbi_start_tvsec == b->pbi_start_tvsec && a->pbi_start_tvusec == b->pbi_start_tvusec+ && a->pbi_ppid == b->pbi_ppid && a->pbi_nfiles == b->pbi_nfiles+ && !memcmp(a->pbi_comm, b->pbi_comm, sizeof(a->pbi_comm));+}+static int control_command_digest(pid_t pid, unsigned char *out) {+ unsigned char raw[CONTROL_ARGS];+ size_t size = sizeof(raw);+ int mib[] = { CTL_KERN, KERN_PROCARGS2, pid };+ if (!control_step() || sysctl(mib, 3, raw, &size, NULL, 0) || size <= sizeof(int) || size >= sizeof(raw)) return 0;+ int argc;+ memcpy(&argc, raw, sizeof(argc));+ if (argc <= 0 || argc > 4096) return 0;+ /* A rewritten title can destroy argv boundaries while the kernel retains+ * the original argc. This view can also include environment strings. Never+ * interpret or emit them as arguments: only compare a digest of the complete+ * bounded view. Darwin's existing command reader supplies display text. */+ return CC_SHA256(raw, (CC_LONG)size, out) != NULL;+}+static int compare_fd(const void *a, const void *b) {+ int left = ((const struct control_fd *)a)->fd, right = ((const struct control_fd *)b)->fd;+ return (left > right) - (left < right);+}+static int control_fds(pid_t pid, struct control_row *row, int *total) {+ struct proc_fdinfo list[CONTROL_FDS + 1];+ if (!control_step()) return 0;+ errno = 0;+ int size = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, list, sizeof(list));+ if (errno || size < 0 || size % sizeof(list[0]) || (size_t)size >= sizeof(list)) return 0;+ row->fd_count = size / (int)sizeof(list[0]);+ *total += row->fd_count;+ if (*total > CONTROL_FDS) return 0;+ for (int index = 0; index < row->fd_count; index++) {+ if (!control_step() || list[index].proc_fd < 0) return 0;+ struct control_fd *fd = &row->fds[index];+ fd->fd = list[index].proc_fd; fd->type = list[index].proc_fdtype;+ if (fd->type > PROX_FDTYPE_NEXUS || fd->type == 8) return 0;+ if (fd->type == PROX_FDTYPE_VNODE) {+ struct vnode_fdinfo info;+ memset(&info, 0, sizeof(info));+ if (proc_pidfdinfo(pid, fd->fd, PROC_PIDFDVNODEINFO, &info, sizeof(info)) != sizeof(info)) return 0;+ fd->mode = info.pvi.vi_stat.vst_mode & S_IFMT;+ fd->device = info.pvi.vi_stat.vst_dev;+ fd->inode = info.pvi.vi_stat.vst_ino;+ if (!fd->mode || !fd->inode) return 0;+ }+ }+ qsort(row->fds, row->fd_count, sizeof(row->fds[0]), compare_fd);+ for (int index = 1; index < row->fd_count; index++) if (row->fds[index - 1].fd == row->fds[index].fd) return 0;+ return 1;+}+static int control_read(pid_t pid, struct control_row *row, int *fds) {+ struct proc_bsdinfo before, after;+ char final_image[PROC_PIDPATHINFO_MAXSIZE];+ unsigned char final_digest[CC_SHA256_DIGEST_LENGTH];+ size_t size, final_size;+ memset(row, 0, sizeof(*row)); row->pid = pid;+ if (!control_birth(pid, &before) || !control_step()+ || !image_path(pid, row->image, sizeof(row->image), &size)+ || !control_command_digest(pid, row->command_digest)+ || !control_fds(pid, row, fds) || !control_step()+ || !image_path(pid, final_image, sizeof(final_image), &final_size)+ || !control_command_digest(pid, final_digest)+ || !control_birth(pid, &after) || !same_birth(&before, &after)+ || size != final_size || memcmp(row->image, final_image, size)+ || memcmp(row->command_digest, final_digest, sizeof(final_digest))) return 0;+ row->parent = before.pbi_ppid; row->fd_capacity = before.pbi_nfiles;+ row->seconds = before.pbi_start_tvsec; row->micros = before.pbi_start_tvusec;+ memcpy(row->command, before.pbi_comm, sizeof(before.pbi_comm));+ return row->command[0] != 0;+}+static int compare_pid(const void *a, const void *b) {+ int left = *(const pid_t *)a, right = *(const pid_t *)b;+ return (left > right) - (left < right);+}+static int control_children(pid_t parent, pid_t *children) {+ if (!parent) return 0;+ if (!control_step()) return -1;+ errno = 0;+ int count = proc_listchildpids(parent, children, sizeof(pid_t) * CONTROL_PIDS);+ if (errno || count < 0 || count >= CONTROL_PIDS) return -1;+ int live = 0;+ for (int index = 0; index < count; index++) {+ struct proc_bsdinfo info;+ /* Enumeration includes zombies. A complete BSD record can exclude one;+ * ESRCH from the ordinary live-only read cannot establish its state. */+ if (!control_step() || children[index] <= 0 || !birth_including_zombies(children[index], 1, &info)+ || info.pbi_ppid != (uint32_t)parent) return -1;+ if (info.pbi_status != SZOMB && !(info.pbi_flags & PROC_FLAG_INEXIT)) children[live++] = children[index];+ }+ qsort(children, live, sizeof(pid_t), compare_pid);+ for (int index = 1; index < live; index++) if (children[index] == children[index - 1]) return -1;+ return live;+}+static int control_main(int argc, char **argv) {+ if (argc < 5 || argc > CONTROL_PIDS + 4) return 64;+ pid_t timeout, parent = 0, pids[CONTROL_PIDS], first_children[CONTROL_PIDS], last_children[CONTROL_PIDS];+ if (!parse_pid(argv[2], &timeout) || timeout > 3000+ || (strcmp(argv[3], "0") && !parse_pid(argv[3], &parent))) return 64;+ for (int i = 4; i < argc; i++) {+ if (!parse_pid(argv[i], &pids[i - 4])) return 64;+ for (int j = 4; j < i; j++) if (pids[i - 4] == pids[j - 4]) return 64;+ }+ if (clock_gettime(CLOCK_MONOTONIC, &control_deadline)) return 74;+ control_deadline.tv_sec += timeout / 1000;+ control_deadline.tv_nsec += (timeout % 1000) * 1000000L;+ if (control_deadline.tv_nsec >= 1000000000L) { control_deadline.tv_sec++; control_deadline.tv_nsec -= 1000000000L; }+ int count = argc - 4, okay = 0, first_count = control_children(parent, first_children), final_count;+ struct control_row *first = calloc(count, sizeof(*first)), *last = calloc(count, sizeof(*last));+ if (!first || !last || first_count < 0) goto done;+ int fds = 0;+ for (int i = 0; i < count; i++) if (!control_read(pids[i], &first[i], &fds)) goto done;+ fds = 0;+ for (int i = 0; i < count; i++) if (!control_read(pids[i], &last[i], &fds)+ || memcmp(&first[i], &last[i], sizeof(first[i]))) goto done;+ final_count = control_children(parent, last_children);+ if (final_count != first_count || memcmp(first_children, last_children, first_count * sizeof(pid_t)) || !control_step()) goto done;+ printf("{\"schema\":2,\"mode\":\"control\",\"parent\":%d,\"children\":[", parent);+ for (int i = 0; i < first_count; i++) printf("%s%d", i ? "," : "", first_children[i]);+ puts("]}");+ for (int i = 0; i < count; i++) {+ struct control_row *row = &last[i];+ printf("{\"pid\":%d,\"parentPid\":%u,\"startSeconds\":%llu,\"startMicros\":%llu,\"commandHex\":\"", row->pid, row->parent,+ (unsigned long long)row->seconds, (unsigned long long)row->micros);+ print_hex((unsigned char *)row->command, strlen(row->command));+ printf("\",\"imageHex\":\""); print_hex((unsigned char *)row->image, strlen(row->image));+ printf("\",\"commandDigest\":\""); print_hex(row->command_digest, sizeof(row->command_digest));+ printf("\",\"fds\":[");+ for (int f = 0; f < row->fd_count; f++) {+ struct control_fd *fd = &row->fds[f];+ printf("%s{\"fd\":%d,\"type\":%u,\"mode\":%u,\"device\":\"%u\",\"inode\":\"%llu\"}",+ f ? "," : "", fd->fd, fd->type, fd->mode, fd->device, (unsigned long long)fd->inode);+ }+ puts("]}");+ }+ okay = !ferror(stdout) && !fflush(stdout);+done:+ free(first); free(last);+ return okay ? 0 : 75;+}+int main(int argc, char **argv) {+ if (argc >= 2 && !strcmp(argv[1], "--control")) return control_main(argc, argv);if (argc < 3 || argc > MAX_PIDS + 2 || strcmp(argv[1], "--paths") != 0) return 64;pid_t pids[MAX_PIDS];for (int i = 2; i < argc; ++i) {diff --git a/cli/native/test_process_images.py b/cli/native/test_process_images.pyindex 452e09d8d..86dee71ff 100644--- a/cli/native/test_process_images.py+++ b/cli/native/test_process_images.py@@ -22,23 +22,69 @@ STUB = r'''#include <string.h>#include <libproc.h>#include <sys/proc_info.h>+#include <sys/proc.h>+#include <sys/stat.h>+#include <sys/sysctl.h>-static unsigned births, paths;+static unsigned births, paths, commands, lists;static int scenario(const char *name) {const char *value = getenv("PROBE_FIXTURE_CASE");return value && strcmp(value, name) == 0;}int fixture_proc_pidinfo(int pid, int flavor, uint64_t arg, void *buffer, int size) {- (void)flavor; (void)arg;if (scenario("denied")) { errno = EPERM; return 0; }if (scenario("short-info")) return size - 1;+ if (flavor == PROC_PIDLISTFDS) {+ lists++;+ if (scenario("short-fds")) return 1;+ if (scenario("full-fds")) return size;+ struct proc_fdinfo *fds = buffer;+ fds[0].proc_fd = 3; fds[0].proc_fdtype = PROX_FDTYPE_VNODE;+ if (scenario("fd-changed") && lists > 1) fds[0].proc_fd = 4;+ return sizeof(*fds);+ }struct proc_bsdinfo *info = buffer;memset(info, 0, sizeof(*info));info->pbi_pid = (uint32_t)(pid + (scenario("pid-mismatch") ? 1 : 0));info->pbi_start_tvsec = scenario("bad-start") ? 0 : 1770000000;info->pbi_start_tvusec = scenario("pid-reused") ? ++births : 123456;+ info->pbi_ppid = pid == 7 ? 1 : 7;+ info->pbi_status = pid == 8 && scenario("zombie-child") ? SZOMB : SRUN;+ if (info->pbi_status == SZOMB && !arg) { errno = ESRCH; return 0; }+ info->pbi_nfiles = scenario("fd-capacity-grew") && lists ? 64 : 32;+ memcpy(info->pbi_comm, "fixture", 8);return sizeof(*info);}+int fixture_proc_pidfdinfo(int pid, int fd, int flavor, void *buffer, int size) {+ (void)pid; (void)fd; (void)flavor;+ if (scenario("fd-denied")) { errno = EPERM; return 0; }+ struct vnode_fdinfo *info = buffer;+ memset(info, 0, sizeof(*info));+ info->pvi.vi_stat.vst_mode = S_IFREG;+ info->pvi.vi_stat.vst_dev = 17;+ info->pvi.vi_stat.vst_ino = 9007199254740993ULL;+ return size;+}+int fixture_proc_listchildpids(pid_t parent, void *buffer, int size) {+ (void)parent; (void)size;+ if (scenario("children-full")) return 33;+ if (scenario("children-denied")) { errno = EPERM; return -1; }+ if (scenario("zombie-child")) { ((pid_t *)buffer)[0] = 8; return 1; }+ return 0;+}+int fixture_sysctl(int *name, unsigned int count, void *buffer, size_t *size, void *value, size_t value_size) {+ (void)name; (void)count; (void)value; (void)value_size;+ if (scenario("command-denied")) { errno = EPERM; return -1; }+ if (scenario("command-full")) { memset(buffer, 0, *size); return 0; }+ unsigned char *out = buffer;+ int argc = 1;+ memcpy(out, &argc, sizeof(argc));+ const char data[] = "/fixture/probe\0\0fixture\0FIXTURE_SECRET=never-output\0";+ memcpy(out + sizeof(argc), data, sizeof(data));+ *size = sizeof(argc) + sizeof(data);+ if (scenario("command-changed") && ++commands > 1) out[sizeof(argc) + 16] = 'x';+ return 0;+}int fixture_proc_pidpath(int pid, void *buffer, uint32_t size) {(void)pid; ++paths;if (scenario("missing-second-path") && paths == 2) return 0;@@ -80,11 +126,16 @@ class ProcessImagesTest(unittest.TestCase):cls.stub = cls.root / 'stub-probe'command(['/usr/bin/xcrun', 'clang', '-std=c11', '-Wall', '-Wextra', '-Werror','-Dproc_pidinfo=fixture_proc_pidinfo', '-Dproc_pidpath=fixture_proc_pidpath',+ '-Dproc_pidfdinfo=fixture_proc_pidfdinfo', '-Dproc_listchildpids=fixture_proc_listchildpids',+ '-Dsysctl=fixture_sysctl',str(SOURCE), str(stub), '-o', str(cls.stub)])sleeper = cls.root / 'sleeper.c'- sleeper.write_text('#include <stdio.h>\n#include <unistd.h>\n'- 'int main(void) { puts("ready"); fflush(stdout); '- 'char c; while (read(0, &c, 1) > 0) {} return 0; }\n')+ sleeper.write_text('#include <stdio.h>\n#include <string.h>\n#include <unistd.h>\n'+ 'int main(int argc, char **argv) { (void)argc; '+ 'puts("ready"); fflush(stdout); char c; while (read(0, &c, 1) > 0) { '+ 'if (c == \'t\') { size_t n = strlen(argv[0]); if (n >= 5) { '+ 'memset(argv[0], 0, n); memcpy(argv[0], "codex", 5); } '+ 'puts("ready"); fflush(stdout); } } return 0; }\n')cls.sleeper = cls.root / 'renamed 引擎 2.9.0'command(['/usr/bin/xcrun', 'clang', '-Wall', '-Wextra', '-Werror',str(sleeper), '-o', str(cls.sleeper)])@@ -107,9 +158,9 @@ class ProcessImagesTest(unittest.TestCase):if stream:stream.close()- def launch(self, argv):+ def launch(self, argv, **kwargs):child = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE,- stderr=subprocess.PIPE)+ stderr=subprocess.PIPE, **kwargs)self.children.append(child)return child@@ -205,6 +256,74 @@ class ProcessImagesTest(unittest.TestCase):env={**os.environ, 'LC_ALL': '', 'LC_TIME': 'C'}).stdout.decode().strip()self.assertEqual(row['startMarker'], expected)+ def control(self, pids, parent=0, *, stub=False, case='stable', okay=True):+ result = subprocess.run([str(self.stub if stub else self.probe), '--control', '2000', str(parent), *map(str, pids)],+ capture_output=True, timeout=5, env={**os.environ, 'PROBE_FIXTURE_CASE': case})+ if not okay:+ self.assertEqual(result.returncode, 75)+ self.assertEqual(result.stdout, b'')+ return+ self.assertEqual(result.returncode, 0, result.stderr)+ records = [json.loads(line) for line in result.stdout.splitlines()]+ self.assertEqual(records.pop(0), {'schema': 2, 'mode': 'control', 'parent': parent, 'children': []})+ self.assertEqual([row['pid'] for row in records], pids)+ return records++ def test_control_protocol_preserves_lossless_keys_and_never_emits_argument_or_environment_strings(self):+ [row] = self.control([7], stub=True)+ self.assertEqual(row['fds'], [{'fd': 3, 'type': 1, 'mode': 32768, 'device': '17', 'inode': '9007199254740993'}])+ self.assertRegex(row['commandDigest'], '^[a-f0-9]{64}$')+ self.assertNotIn('argvHex', row)+ self.assertNotIn('argc', row)+ self.assertNotIn('SECRET', json.dumps(row))++ def test_control_holds_partial_changed_denied_and_capacity_truncated_evidence(self):+ for case in ['denied', 'short-info', 'pid-mismatch', 'pid-reused', 'exec-changed',+ 'missing-second-path', 'truncated-path', 'relative-path', 'bad-start',+ 'short-fds', 'full-fds', 'fd-changed', 'fd-denied', 'fd-capacity-grew',+ 'children-full', 'children-denied', 'command-denied', 'command-full', 'command-changed']:+ with self.subTest(case=case):+ self.control([7], parent=7, stub=True, case=case, okay=False)++ def test_control_excludes_a_proven_unreaped_zombie(self):+ self.control([7], parent=7, stub=True, case='zombie-child')++ def test_control_reads_a_private_process_with_empty_argv_without_exposing_environment(self):+ child = self.launch([''], executable=str(self.sleeper), env={**os.environ, 'PRIVATE_FIXTURE_SECRET': 'never-output'})+ self.wait_ready(child)+ [row] = self.control([child.pid])+ self.assertRegex(row['commandDigest'], '^[a-f0-9]{64}$')+ self.assertNotIn('PRIVATE_FIXTURE_SECRET', json.dumps(row))+ self.assertNotIn('argvHex', row)++ def test_control_retains_same_process_generation_and_fd_file_identity(self):+ child = self.launch([str(self.sleeper)])+ self.wait_ready(child)+ [first] = self.control([child.pid])+ [second] = self.control([child.pid])+ self.assertEqual(first, second)+ self.assertTrue(any(fd['type'] == 6 for fd in first['fds']))++ def test_control_fences_a_rewritten_title_without_inventing_argv_boundaries(self):+ child = self.launch([str(self.sleeper), 'original-argument'], env={**os.environ, 'PRIVATE_FIXTURE_SECRET': 'never-output'})+ self.wait_ready(child)+ [before] = self.control([child.pid])+ child.stdin.write(b't'); child.stdin.flush(); self.wait_ready(child)+ [after] = self.control([child.pid])+ self.assertNotEqual(before['commandDigest'], after['commandDigest'])+ for key in ['pid', 'parentPid', 'startSeconds', 'startMicros', 'imageHex', 'fds']:+ self.assertEqual(before[key], after[key])+ self.assertNotIn('argvHex', after)+ self.assertNotIn('PRIVATE_FIXTURE_SECRET', json.dumps(after))++ def test_control_rejects_invalid_requests_before_output(self):+ for args in [[], ['0', '0', '7'], ['3001', '0', '7'], ['1', '0', '7', '7'], ['100', '0', 'bad'],+ ['100', '0', *map(str, range(1, 35))]]:+ with self.subTest(args=args[:4]):+ result = subprocess.run([str(self.stub), '--control', *args], capture_output=True, timeout=5)+ self.assertEqual(result.returncode, 64)+ self.assertEqual(result.stdout, b'')+if __name__ == '__main__':unittest.main(verbosity=2)diff --git a/cli/scripts/handoff-2026-10-08/mutate-native-descriptors.py b/cli/scripts/handoff-2026-10-08/mutate-native-descriptors.pynew file mode 100644index 000000000..54d2130df--- /dev/null+++ b/cli/scripts/handoff-2026-10-08/mutate-native-descriptors.py@@ -0,0 +1,70 @@+"""Owned disposable worktree only; incomplete native evidence must assertion-fail."""+import os+from pathlib import Path+import subprocess+import sys++cli = Path(sys.argv[1]).resolve()+conversation = 'src/lib/nativeConversation.ts'+control = 'src/lib/nativeProcessControl.ts'+paths = 'src/engines/kit/nativePaths.ts'+header = 'src/engines/kit/nativeHeader.ts'+conversation_spec = 'src/lib/nativeConversation.spec.ts'+control_spec = 'src/lib/nativeProcessControl.spec.ts'+bounds = 'src/lib/sessionRepair.bounds.spec.ts'+golden = 'src/engines/nativeDescriptors.golden.spec.ts'+mutations = [+ ('optional discovery cooldown blocks control', control, 'bundledProcessImageHelper({ retryUnavailable: true })', 'bundledProcessImageHelper()', control_spec),+ ('inconclusive Darwin state rejected globally', 'src/lib/processEvidence.ts', '([?A-Za-z+<>NsLsl-]{1,8})', '([A-Za-z+<>NsLsl-]{1,8})', 'src/lib/processEvidence.spec.ts'),+ ('native finder disconnected', 'src/lib/sessionRepair.ts', 'return nativeOpenFileSession(engine, pid, typeof roots === \'string\' ? [roots] : roots, cwd, options)', 'return Promise.resolve(null)', golden),+ ('binding owner disconnected', 'src/core/agents/bind.ts', 'expectedProcess: observed.processIdentity,', '', 'src/core/agents/bind.spec.ts'),+ ('probe error prefix accepted', 'src/engines/kit/nativeEvidence.ts', 'if (error || stderr.length)', 'if (false)', 'src/engines/kit/nativeEvidence.spec.ts'),+ ('process graph EOF ignored', 'src/lib/processEvidence.ts', "if (!text || !text.endsWith('\\n'))", "if (text && !text.endsWith('\\n')) text += '\\n'; if (!text)", 'src/lib/processEvidence.spec.ts'),+ ('launcher child ignored', conversation, "return [parent.executable, parent.nativeArgv?.[0] ?? argvTokens(parent.args)[0] ?? '']", "return own.descriptors.length ? false : [parent.executable, parent.nativeArgv?.[0] ?? argvTokens(parent.args)[0] ?? '']", conversation_spec),+ ('ambiguous rollouts become absence', conversation, "if (found.size > 1) return nativeUnavailable('more than one open rollout could own the conversation')", 'if (found.size > 1) return null', conversation_spec),+ ('unknown source ignored', header, 'if (first.source)', 'if (false)', conversation_spec),+ ('child id ignored', conversation, "if (!('id' in store.byId) || !store.byId.id.test(meta.id)", "if (!meta.isSubagent && !('id' in store.byId) || !meta.isSubagent && !store.byId.id.test(meta.id)", conversation_spec),+ ('symlink target fence removed', paths, '|| target !== before.target', '|| false', conversation_spec),+ ('ordinary ancestor fence removed', paths, 'identity(now) !== identity(before.info)', "before.target !== undefined && identity(now) !== identity(before.info)", conversation_spec),+ ('workspace physical alias ignored', conversation, 'nativeFileKey(declared.info) === nativeFileKey(requested.info)', 'declared.path === requested.path', conversation_spec),+ ('cwd type ignored', conversation, "if ((declared && !declared.info.isDirectory()) || (requested && !requested.info.isDirectory()))", 'if (false)', conversation_spec),+ ('final joined evidence disconnected', conversation, 'await process.verifyDescriptors(new Map(pools.map(pool => [pool.pid, pool.proof.descriptors])), children[0]?.pid)', 'void 0', conversation_spec),+ ('lossless opened file key ignored', 'src/engines/kit/identityScan.ts', 'if (expected?.fileKey)', 'if (false)', bounds),+ ('header close loses typed hold', header, "nativeUnavailable('the native rollout header could not be closed')", "throw Error('fixture untyped close')", conversation_spec),+ ('nonleader children ignored', control, 'for (const task of tasks)', 'for (const task of tasks.filter(task => task === String(parent)))', control_spec),+ ('missing helper cache never invalidated', control, 'invalidateProcessImageHelper(helper.key)', 'void 0', control_spec),+ ('native control error prefix accepted', control, 'if (error || stderr.length)', 'if (false)', control_spec),+ ('final process-record claim disconnected', 'src/lib/captureResumeIdentity.ts', ' claim.verify()', ' void 0', bounds),+]+env = {**os.environ, 'TZ': 'UTC', 'TMPDIR': '/tmp'}+for key in list(env):+ if key in ['TMUX', 'TMUX_PANE'] or key.startswith('RECORD_'):+ env.pop(key)+if not Path(env.get('TMUX_TMPDIR', '/missing-private-tmux')).is_dir():+ raise SystemExit('An existing private TMUX_TMPDIR is required')+++def run(specs):+ return subprocess.run(['node', 'node_modules/vitest/vitest.mjs', 'run', *specs, '--maxWorkers=1'],+ cwd=cli, env=env, capture_output=True, text=True, timeout=120)+++baseline = run(sorted({target for _, _, _, _, target in mutations}))+if baseline.returncode:+ print(baseline.stdout + baseline.stderr)+ raise SystemExit('baseline failed; no mutants ran')+print('unchanged baseline passed', flush=True)+for label, relative, before, after, target in mutations:+ path = cli / relative+ original = path.read_text()+ assert original.count(before) == 1, (label, original.count(before))+ try:+ path.write_text(original.replace(before, after))+ result = run([target])+ output = result.stdout + result.stderr+ if result.returncode == 0 or 'AssertionError' not in output:+ print(output)+ raise SystemExit(f'{label}: not caught by an assertion')+ print(f'{label}: caught by assertion', flush=True)+ finally:+ path.write_text(original)diff --git a/cli/scripts/handoff-2026-10-08/native-descriptor-cost.ts b/cli/scripts/handoff-2026-10-08/native-descriptor-cost.tsnew file mode 100644index 000000000..a8652c4f8--- /dev/null+++ b/cli/scripts/handoff-2026-10-08/native-descriptor-cost.ts@@ -0,0 +1,52 @@+/** Matched native descriptor lookup, private process and homes only; no daemon or input. */+import { spawn } from 'node:child_process'+import { once } from 'node:events'+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { dirname, join, resolve } from 'node:path'+import { pathToFileURL } from 'node:url'+import { performance } from 'node:perf_hooks'++const workload = process.argv[2] ?? 'one'+if (!['one', 'duplicate', 'competing'].includes(workload)) throw Error('Unknown workload')+const cli = process.env.NATIVE_COST_CLI ?? resolve(import.meta.dirname, '../..')+const root = realpathSync(mkdtempSync(join(tmpdir(), 'native-descriptor-cost-')))+for (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR']) process.env[name] = join(root, name)+process.env.CLAUDE_PROJECTS_DIR = join(process.env.CLAUDE_CONFIG_DIR!, 'projects')+const cwd = join(root, 'workspace'), home = join(process.env.CODEX_HOME!, 'sessions')+mkdirSync(cwd); mkdirSync(home, { recursive: true })+if (process.env.HARNESS_PROCESS_IMAGES_ARTIFACT) {+ const artifact = JSON.parse(readFileSync(process.env.HARNESS_PROCESS_IMAGES_ARTIFACT, 'utf8'))+ Object.assign(globalThis, { __DARWIN_PROCESS_IMAGES__: JSON.stringify({ schema: 1, size: artifact.size, sha256: artifact.sha256, base64: artifact.base64 }) })+}+const files = [1, 2].map(n => {+ const id = `aaaaaaaa-1111-4222-8333-${String(n).padStart(12, '0')}`+ const path = join(home, 'day', `rollout-${id}.jsonl`)+ mkdirSync(dirname(path), { recursive: true })+ writeFileSync(path, JSON.stringify({ type: 'session_meta', payload: { id, cwd, source: 'cli' } }) + '\n')+ return path+})+const held = workload === 'competing' ? files : workload === 'duplicate' ? [files[0], files[0]] : [files[0]]+const code = `const fs = require('node:fs'); const fds = ${JSON.stringify(held)}.map(path => fs.openSync(path, 'r')); process.title = 'codex'; process.stdout.write('ready\\n'); setTimeout(() => process.exit(0), 30_000);`+const child = spawn(process.execPath, ['-e', code], { env: { PATH: process.env.PATH }, stdio: ['ignore', 'pipe', 'pipe'] })+try {+ await Promise.race([once(child.stdout!, 'data'), once(child, 'exit').then(() => { throw Error('Private fixture did not become ready') })])+ const { openFileSessionOf } = await import(pathToFileURL(join(cli, 'src/lib/sessionRepair.ts')).href)+ const latenciesMs: number[] = [], outcomes: Record<string, number> = {}, holds: string[] = []+ const cpu = process.cpuUsage()+ for (let i = 0; i < 5; i++) {+ const started = performance.now()+ let outcome: string+ try { outcome = (await openFileSessionOf('codex', child.pid!, home, cwd))?.sessionId ? 'bound' : 'empty' }+ catch (error) { if ((error as { code?: string }).code !== 'IDENTITY_UNAVAILABLE') throw error; outcome = 'held'; holds.push((error as Error).message) }+ latenciesMs.push(Number((performance.now() - started).toFixed(4)))+ outcomes[outcome] = (outcomes[outcome] ?? 0) + 1+ }+ const used = process.cpuUsage(cpu)+ console.log(JSON.stringify({ workload, iterations: 5, outcomes, holds, latenciesMs,+ cpuMs: (used.user + used.system) / 1000, peakRssMiB: process.resourceUsage().maxRSS / 1024,+ node: process.version, platform: process.platform, arch: process.arch }))+} finally {+ if (child.exitCode === null && child.signalCode === null) { child.kill(); await once(child, 'exit') }+ rmSync(root, { recursive: true, force: true })+}diff --git a/cli/scripts/test-process-images-bundled.mjs b/cli/scripts/test-process-images-bundled.mjsindex 57ab221d9..3f74aa33a 100644--- a/cli/scripts/test-process-images-bundled.mjs+++ b/cli/scripts/test-process-images-bundled.mjs@@ -19,9 +19,13 @@ try {writeFileSync(join(noLsof, 'lsof'), '#!/bin/sh\nprintf "unexpected fallback" >&2\nexit 64\n', { mode: 0o700 })const entry = `import assert from 'node:assert/strict';- import { realpathSync } from 'node:fs';+ import { realpathSync, rmSync } from 'node:fs';+ import { spawn } from 'node:child_process';+ import { once } from 'node:events';import { env } from ${JSON.stringify(join(cli, 'src/config/env.ts'))};- import { nativeProcessImages } from ${JSON.stringify(join(cli, 'src/lib/nativeProcessImages.ts'))};+ import { nativeProcessControl } from ${JSON.stringify(join(cli, 'src/lib/nativeProcessControl.ts'))};+ import { NativeEvidenceBudget } from ${JSON.stringify(join(cli, 'src/engines/kit/nativeEvidence.ts'))};+ import { bundledProcessImageHelper, nativeProcessImages } from ${JSON.stringify(join(cli, 'src/lib/nativeProcessImages.ts'))};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);@@ -33,7 +37,23 @@ try {assert.equal(enriched.length, 1);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);+ const child = spawn(process.execPath, ['-e', ${JSON.stringify('process.stdout.write("ready\\n"); setTimeout(() => process.exit(0), 30_000)')}], {+ env: { PATH: process.env.PATH }, stdio: ['ignore', 'pipe', 'pipe'] });+ try {+ await Promise.race([once(child.stdout, 'data'), once(child, 'exit').then(() => { throw new Error('Private control fixture exited before readiness'); })]);+ const control = () => nativeProcessControl([child.pid], 0, new NativeEvidenceBudget());+ const first = await control();+ assert.equal(first.rows.size, 1);+ assert.equal(realpathSync(first.rows.get(child.pid).imagePath), realpathSync(process.execPath));+ assert.ok(first.rows.get(child.pid).commandDigest);+ const prepared = await bundledProcessImageHelper();+ assert.ok(prepared);+ rmSync(prepared.path); // Only the private cache this smoke check created.+ await assert.rejects(control, /identity is held/i);+ const recovered = await control();+ assert.equal(recovered.rows.get(child.pid).birth, first.rows.get(child.pid).birth);+ } finally { if (child.exitCode === null && child.signalCode === null) { child.kill(); await once(child, 'exit'); } }+ console.log('Bundled native query, discovery, control and cache recovery passed on ' + process.arch);`const outfile = join(root, 'probe.mjs')await build({ stdin: { contents: entry, resolveDir: cli, sourcefile: 'probe.mjs' },diff --git a/cli/src/core/agents/bind.spec.ts b/cli/src/core/agents/bind.spec.tsindex 20c4fb309..9b87e2860 100644--- a/cli/src/core/agents/bind.spec.ts+++ b/cli/src/core/agents/bind.spec.ts@@ -645,6 +645,20 @@ describe('binding a running process to its session', () => {})describe('a repair', () => {+ it.each(['rebound', 'stopped'] as const)('does not publish native Codex evidence after its owner was %s', async change => {+ const run = setup(), entry = agent({ engine: 'codex', sessionId: '' }), seen = observed({ engine: 'codex' })+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(entry)+ let answer!: (value: { sessionId: string; transcriptPath: string }) => void+ vi.mocked(findLiveSession).mockReturnValueOnce(new Promise(resolve => { answer = resolve }))+ const pending = run.binding.bindObservedAgent(seen)+ expect(findLiveSession).toHaveBeenCalledWith('codex', '/work', expect.any(Number), expect.objectContaining({ expectedProcess: seen.processIdentity }))+ if (change === 'rebound') entry.sessionId = 'replacement'+ else vi.mocked(run.deps.registry.byProcess).mockReturnValue(undefined)+ answer({ sessionId: 'native', transcriptPath: '/fixture/rollout.jsonl' }); await pending+ expect(run.deps.registry.register).not.toHaveBeenCalled()+ expect(run.deps.attachSession).not.toHaveBeenCalled()+ })+it('looks for the session a new process opened, sweeping eagerly, then once a minute', async () => {vi.useFakeTimers()vi.setSystemTime(Date.parse('2026-10-04T10:00:00Z'))@@ -655,7 +669,7 @@ describe('binding a running process to its session', () => {vi.advanceTimersByTime(60_000)await run.binding.bindObservedAgent(observed())expect(findLiveSession).toHaveBeenCalledTimes(25)- expect(findLiveSession).toHaveBeenLastCalledWith('claude', '/work', Date.parse('2026-10-04T10:00:00Z'), { bornOnly: true, pid: 42, codexHome: undefined, hermesHome: undefined })+ expect(findLiveSession).toHaveBeenLastCalledWith('claude', '/work', Date.parse('2026-10-04T10:00:00Z'), { bornOnly: true, pid: 42, codexHome: undefined, hermesHome: undefined, expectedProcess: observed().processIdentity })})it('binds what it finds, with the Hermes home it was found in, and starts the count over', async () => {diff --git a/cli/src/core/agents/bind.ts b/cli/src/core/agents/bind.tsindex fec734959..c695a8326 100644--- a/cli/src/core/agents/bind.ts+++ b/cli/src/core/agents/bind.ts@@ -342,6 +342,7 @@ export function createBinding({const located = await read(() => findLiveSession(observed.engine, observed.cwd, startedAtMs, {bornOnly: true,pid: observed.processIdentity.pid,+ expectedProcess: observed.processIdentity,codexHome: agent.codexHome ?? undefined,hermesHome: agent.hermesHome ?? undefined,}))diff --git a/cli/src/engines/__fixtures__/native-descriptors.golden.json b/cli/src/engines/__fixtures__/native-descriptors.golden.jsonnew file mode 100644index 000000000..1dfedeba7--- /dev/null+++ b/cli/src/engines/__fixtures__/native-descriptors.golden.json@@ -0,0 +1,165 @@+{+ "descriptors:native": [+ "<root>/codex/sessions/day/rollout-aaaaaaaa-1111-4222-8333-000000000001.jsonl",+ "<root>/notes"+ ],+ "descriptors:empty": [],+ "descriptors:invalid": [],+ "process:native-ignores-nested-tool": [+ "<root>/codex/sessions/day/rollout-aaaaaaaa-1111-4222-8333-000000000001.jsonl",+ "<root>/notes"+ ],+ "process:other-engine": [],+ "process:launcher-child": [+ "<root>/codex/sessions/day/rollout-aaaaaaaa-1111-4222-8333-000000000001.jsonl",+ "<root>/notes"+ ],+ "process:direct-native-child": [+ "<root>/codex/sessions/day/rollout-aaaaaaaa-1111-4222-8333-000000000001.jsonl"+ ],+ "identity:one": {+ "sessionId": "aaaaaaaa-1111-4222-8333-000000000011",+ "transcriptPath": "<root>/codex/sessions/day/rollout-aaaaaaaa-1111-4222-8333-000000000011.jsonl"+ },+ "identity:repeated-descriptors": {+ "sessionId": "aaaaaaaa-1111-4222-8333-000000000011",+ "transcriptPath": "<root>/codex/sessions/day/rollout-aaaaaaaa-1111-4222-8333-000000000011.jsonl"+ },+ "identity:alias": {+ "sessionId": "aaaaaaaa-1111-4222-8333-000000000011",+ "transcriptPath": "<root>/codex/sessions/day/rollout-aaaaaaaa-1111-4222-8333-000000000011.jsonl"+ },+ "identity:child-excluded": {+ "sessionId": "aaaaaaaa-1111-4222-8333-000000000011",+ "transcriptPath": "<root>/codex/sessions/day/rollout-aaaaaaaa-1111-4222-8333-000000000011.jsonl"+ },+ "identity:other-cwd-excluded": {+ "sessionId": "aaaaaaaa-1111-4222-8333-000000000011",+ "transcriptPath": "<root>/codex/sessions/day/rollout-aaaaaaaa-1111-4222-8333-000000000011.jsonl"+ },+ "identity:outside-profile-excluded": {+ "sessionId": "aaaaaaaa-1111-4222-8333-000000000011",+ "transcriptPath": "<root>/codex/sessions/day/rollout-aaaaaaaa-1111-4222-8333-000000000011.jsonl"+ },+ "identity:only-child": null,+ "identity:only-other-cwd": null,+ "identity:empty": null,+ "identity:moved-home": {+ "sessionId": "aaaaaaaa-1111-4222-8333-000000000014",+ "transcriptPath": "<root>/other-home/sessions/day/rollout-aaaaaaaa-1111-4222-8333-000000000014.jsonl"+ },+ "identity:other-engine": null,+ "capture:native": {+ "agentId": "fixture-agent",+ "engine": "codex",+ "sessionId": "aaaaaaaa-1111-4222-8333-000000000021",+ "transcriptPath": "<root>/codex/sessions/day/rollout-aaaaaaaa-1111-4222-8333-000000000021.jsonl",+ "cwd": "<root>/work",+ "codexHome": "<root>/codex",+ "processIdentity": {+ "pid": 42,+ "executable": "/fixture-tools/codex",+ "startMarker": "Fri Oct 9 11:59:00 2026",+ "startTicks": 4200+ },+ "source": "stop-repair",+ "boundAt": 1791547200000+ },+ "capture:complete-binding": {+ "agentId": "fixture-agent",+ "engine": "codex",+ "sessionId": "aaaaaaaa-1111-4222-8333-000000000021",+ "transcriptPath": "<root>/codex/sessions/day/rollout-aaaaaaaa-1111-4222-8333-000000000021.jsonl",+ "cwd": "<root>/work",+ "codexHome": "<root>/codex",+ "processIdentity": {+ "pid": 42,+ "executable": "/fixture-tools/codex",+ "startMarker": "Fri Oct 9 11:59:00 2026",+ "startTicks": 4200+ },+ "source": "discovery",+ "boundAt": 0+ },+ "capture:terminal": {+ "agentId": "fixture-agent",+ "engine": "terminal",+ "sessionId": "",+ "transcriptPath": null,+ "cwd": "<root>/work",+ "codexHome": "<root>/codex",+ "processIdentity": {+ "pid": 42,+ "executable": "/fixture-tools/codex",+ "startMarker": "Fri Oct 9 11:59:00 2026",+ "startTicks": 4200+ },+ "source": "discovery",+ "boundAt": 0+ },+ "capture:launcher": {+ "agentId": "fixture-agent",+ "engine": "codex",+ "sessionId": "aaaaaaaa-1111-4222-8333-000000000021",+ "transcriptPath": "<root>/codex/sessions/day/rollout-aaaaaaaa-1111-4222-8333-000000000021.jsonl",+ "cwd": "<root>/work",+ "codexHome": "<root>/codex",+ "processIdentity": {+ "pid": 42,+ "executable": "/fixture-tools/node",+ "startMarker": "Fri Oct 9 11:59:00 2026",+ "startTicks": 4200+ },+ "source": "stop-repair",+ "boundAt": 1791547200000+ },+ "capture:complete-empty": {+ "agentId": "fixture-agent",+ "engine": "codex",+ "sessionId": "",+ "transcriptPath": null,+ "cwd": "<root>/work",+ "codexHome": "<root>/codex",+ "processIdentity": {+ "pid": 42,+ "executable": "/fixture-tools/node",+ "startMarker": "Fri Oct 9 11:59:00 2026",+ "startTicks": 4200+ },+ "source": "discovery",+ "boundAt": 0+ },+ "darwin:descriptors": [+ "<root>/codex/sessions/day/rollout-aaaaaaaa-1111-4222-8333-000000000031.jsonl",+ "<root>/notes-mac"+ ],+ "darwin:empty": [],+ "darwin:identity": {+ "sessionId": "aaaaaaaa-1111-4222-8333-000000000031",+ "transcriptPath": "<root>/codex/sessions/day/rollout-aaaaaaaa-1111-4222-8333-000000000031.jsonl"+ },+ "darwin:capture": {+ "agentId": "fixture-agent",+ "engine": "codex",+ "sessionId": "aaaaaaaa-1111-4222-8333-000000000031",+ "transcriptPath": "<root>/codex/sessions/day/rollout-aaaaaaaa-1111-4222-8333-000000000031.jsonl",+ "cwd": "<root>/work",+ "codexHome": "<root>/codex",+ "processIdentity": {+ "pid": 42,+ "executable": "/fixture-tools/codex",+ "startMarker": "Fri Oct 9 11:59:00 2026",+ "startTicks": 4200+ },+ "source": "stop-repair",+ "boundAt": 1791547200000+ },+ "darwin:unicode": {+ "sessionId": "aaaaaaaa-1111-4222-8333-000000000032",+ "transcriptPath": "<root>/café-home/sessions/day/rollout-aaaaaaaa-1111-4222-8333-000000000032.jsonl"+ },+ "darwin:launcher": [+ "<root>/codex/sessions/day/rollout-aaaaaaaa-1111-4222-8333-000000000031.jsonl",+ "<root>/notes-mac"+ ]+}diff --git a/cli/src/engines/codex/sessionStore.ts b/cli/src/engines/codex/sessionStore.tsindex d109dc839..40e4a0a03 100644--- a/cli/src/engines/codex/sessionStore.ts+++ b/cli/src/engines/codex/sessionStore.ts@@ -31,6 +31,9 @@ export const sessionStore: SessionStoreContract = {first: {type: hooks.children!.type, id: ['payload', 'id'], cwd: ['payload', 'cwd'], child: hooks.children!.child,parent: [...hooks.children!.child, 'thread_spawn', 'parent_thread_id'], maxBytes: 128 * 1024,+ // Native SessionSource is an externally tagged enum. Legacy rollouts omitted it;+ // present unknown object shapes cannot establish that a rollout is interactive.+ source: { field: ['payload', 'source'], values: ['cli', 'vscode', 'exec', 'mcp', 'unknown'], named: ['custom'], legacyMissing: true },},scan: { from: 'first' },/**diff --git a/cli/src/engines/facets/sessionStore.ts b/cli/src/engines/facets/sessionStore.tsindex a3b3540ab..04f8fba14 100644--- a/cli/src/engines/facets/sessionStore.ts+++ b/cli/src/engines/facets/sessionStore.ts@@ -33,7 +33,10 @@ export interface SessionStoreContract {* What a session file's first record says about it, read within `maxBytes`: its `type`, and where it keeps* the id, the folder, the field whose presence marks a session another one delegated to, and that one's parent.*/- first?: { type: string; id: readonly string[]; cwd: readonly string[]; child: readonly string[]; parent: readonly string[]; maxBytes: number }+ first?: { type: string; id: readonly string[]; cwd: readonly string[]; child: readonly string[]; parent: readonly string[]; maxBytes: number+ /** Native source variants that can conclusively exclude the delegated variant. */+ source?: { field: readonly string[]; values: readonly string[]; named: readonly string[]; legacyMissing: boolean }+ }/*** How a scan of the store tells which folder a session belongs to. `first`: the first record above, a child* never counts. `head`: the first `cwd` in its opening lines, never a file below a `childFolder` segment or onediff --git a/cli/src/engines/kit/identityScan.ts b/cli/src/engines/kit/identityScan.tsindex abaee8634..c3a5ca41e 100644--- a/cli/src/engines/kit/identityScan.ts+++ b/cli/src/engines/kit/identityScan.ts@@ -7,17 +7,30 @@ export class IdentityReadUnavailable extends Error {constructor(reason: string, message = `Conversation identity is held: ${reason}.`) { super(message) }}-export type IdentityVersion = Pick<Stats, 'dev' | 'ino' | 'size' | 'mtimeMs' | 'ctimeMs'>+export type IdentityVersion = Pick<Stats, 'dev' | 'ino' | 'size' | 'mtimeMs' | 'ctimeMs'> & {+ /** Descriptor numbers can exceed Number's exact range; never round kernel ownership evidence. */+ fileKey?: { device: bigint; inode: bigint }+}/** Shared across every directory/root in one lookup, including entries that are not transcripts. */export const identityScanBudget = () => ({ remaining: 4096 })/** A regular file only. Nonblocking open prevents a native-store FIFO from hanging session control. */-export async function identityBytes(path: string, maxBytes: number, expected?: IdentityVersion): Promise<Buffer> {+export async function identityBytes(path: string, maxBytes: number, expected?: IdentityVersion,+ budget?: { step(bytes?: number): void },+): Promise<Buffer> {+ budget?.step()const handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK)try {+ budget?.step()const before = await handle.stat()if (!before.isFile()) throw new IdentityReadUnavailable('the native record is not a regular file')+ if (expected?.fileKey) {+ const exact = await handle.stat({ bigint: true })+ if (exact.dev !== expected.fileKey.device || exact.ino !== expected.fileKey.inode) {+ throw new IdentityReadUnavailable('the opened native record is not the file held by the process')+ }+ }// A pathname can switch to another inode and back while a caller awaits its header. The// opened descriptor must be the candidate that authorized this read, not only the path at return.if (expected && (before.dev !== expected.dev || before.ino !== expected.ino || before.size !== expected.size@@ -27,12 +40,17 @@ export async function identityBytes(path: string, maxBytes: number, expected?: Iconst length = Math.min(before.size, maxBytes)const bytes = Buffer.alloc(length)let read = 0+ let calls = 0while (read < length) {+ budget?.step()+ if (budget && ++calls > 64) throw new IdentityReadUnavailable('the native header read-operation limit was reached')const next = await handle.read(bytes, read, length - read, read)+ budget?.step(next.bytesRead)if (!next.bytesRead) throw new IdentityReadUnavailable('the native record ended during the read')read += next.bytesRead}const after = await handle.stat()+ budget?.step()if (after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs) {throw new IdentityReadUnavailable('the native record changed during the read')}@@ -43,6 +61,7 @@ export async function identityBytes(path: string, maxBytes: number, expected?: I})try {const now = await current.stat()+ budget?.step()if (now.dev !== before.dev || now.ino !== before.ino || now.size !== before.size|| now.mtimeMs !== before.mtimeMs || now.ctimeMs !== before.ctimeMs) {throw new IdentityReadUnavailable('the native record was replaced during the read')diff --git a/cli/src/engines/kit/nativeDescriptors.spec.ts b/cli/src/engines/kit/nativeDescriptors.spec.tsnew file mode 100644index 000000000..58460485b--- /dev/null+++ b/cli/src/engines/kit/nativeDescriptors.spec.ts@@ -0,0 +1,40 @@+import { expect, it } from 'vitest'+import { descriptorPaths, parseDescriptors } from './nativeDescriptors.js'+import { NativeEvidenceBudget } from './nativeEvidence.js'+const file = (fd = '3', path = '/rollout.jsonl', inode = '9007199254740993') => `f${fd}\0tREG\0D0x100000000000001\0i${inode}\0n${path}\0\n`+const parse = (text: string) => parseDescriptors(text, 42, new NativeEvidenceBudget())++it('retains exact device/inode numbers, repeated library maps and complete empty listings', () => {+ const rows = parse('p42\0\n' + file() + file('txt', '/a', '2') + file('txt', '/b', '3'))+ expect(rows[0]).toMatchObject({ fd: '3', path: '/rollout.jsonl', inode: 9007199254740993n, device: 0x100000000000001n })+ expect(rows).toHaveLength(3)+ expect(parse('p42\0\n')).toEqual([])+ expect(parse('p42\0\nf4\0tPIPE\0n->pipe\0\n')).toEqual([{ fd: '4', kind: 'PIPE', path: '->pipe' }])+})+it.each([+ '', 'p42\n', 'p42\0\n' + file().slice(0, -1), 'p41\0\n' + file(),+ file(), 'p42\0\np42\0\n', 'p42\0xextra\0\n',+ 'p42\0\n' + file().replace('tREG\0', ''), 'p42\0\n' + file().replace('i9007199254740993\0', ''),+ 'p42\0\n' + file().replace('D0x100000000000001', 'Dbad'),+ 'p42\0\n' + file().replace('i9007199254740993', 'i-1'),+ 'p42\0\n' + file().replace('tREG', 'tREG\0tREG'),+ 'p42\0\n' + file() + file('3', '/other', '2'),+ 'p42\0\n' + file('3', 'unavailable'),+ 'p42\0\n' + file().replace('tREG', 'tUNKNOWN'),+ 'p42\0\n' + file('3', '/rollout', '18446744073709551616'),+ 'p42\0\n' + file('3', '/' + 'a'.repeat(16_384)),+ 'p42\0\n' + file('NOFD'),+ 'p42\0\nfNOFD\0nunknown error: Permission denied\0\n',+])('holds malformed, truncated, duplicate or wrong-owner fields %j', text => {+ expect(() => parse(text)).toThrow('identity is held')+})+it('bounds a syntactically valid descriptor pool', () => {+ expect(() => parse('p42\0\n' + Array.from({ length: 4097 }, (_, index) => file(String(index))).join(''))).toThrow('exceeds its limit')+})+it('offers literal and escaped spellings without guessing which file the kernel held', () => {+ expect(descriptorPaths('/café/rollout.jsonl')).toEqual(['/café/rollout.jsonl'])+ expect(descriptorPaths('/caf\\xc3\\xa9/rollout.jsonl')).toEqual(['/caf\\xc3\\xa9/rollout.jsonl', '/café/rollout.jsonl'])+ expect(descriptorPaths('/a\\\\n/rollout.jsonl')).toEqual(['/a\\\\n/rollout.jsonl', '/a\\n/rollout.jsonl'])+ expect(descriptorPaths('/a\\n/rollout.jsonl')).toEqual(['/a\\n/rollout.jsonl', '/a\n/rollout.jsonl'])+ expect(descriptorPaths('/a\\xff/rollout.jsonl')).toEqual(['/a\\xff/rollout.jsonl'])+})diff --git a/cli/src/engines/kit/nativeDescriptors.ts b/cli/src/engines/kit/nativeDescriptors.tsnew file mode 100644index 000000000..d779a3b8a--- /dev/null+++ b/cli/src/engines/kit/nativeDescriptors.ts@@ -0,0 +1,122 @@+/** Fresh descriptor evidence. An incomplete listing is never an empty conversation pool. */+import { opendir, readlink, stat } from 'node:fs/promises'+import { NativeEvidenceBudget, nativeProbe, nativeUnavailable } from './nativeEvidence.js'+import { IdentityReadUnavailable } from './identityScan.js'++export interface NativeDescriptor {+ fd: string+ path: string+ kind: string+ device?: bigint+ inode?: bigint+}+export interface DescriptorEvidence {+ descriptors: readonly NativeDescriptor[]+ verify(): Promise<void>+}+export const descriptorKey = (row: NativeDescriptor) => `${row.device}:${row.inode}`+const signature = (rows: readonly NativeDescriptor[]) => rows.map(row =>+ JSON.stringify([row.fd, row.path, row.kind, String(row.device), String(row.inode)])).sort().join('\n')+const knownKinds = new Set(['REG', 'DIR', 'CHR', 'BLK', 'FIFO', 'PIPE', 'unix', 'IPv4', 'IPv6', 'KQUEUE', 'FSEVENT', 'PSXSEM', 'PSXSHM', 'systm', 'NDRV', 'LINK'])++/** -F0 still terminates each process/file set with NL after its final NUL field. */+export function parseDescriptors(output: string, pid: number, budget: NativeEvidenceBudget): NativeDescriptor[] {+ if (!output.endsWith('\0\n')) return nativeUnavailable('the native descriptor listing is incomplete')+ const groups = output.slice(0, -1).split('\n')+ const rows: NativeDescriptor[] = [], seen = new Set<string>()+ let processSeen = false+ for (const group of groups) {+ budget.step()+ if (!group.endsWith('\0')) return nativeUnavailable('the native descriptor fields are incomplete')+ const fields = new Map<string, string>()+ for (const field of group.slice(0, -1).split('\0')) {+ if (!field || !'pftDin'.includes(field[0]) || fields.has(field[0])) return nativeUnavailable('the native descriptor fields are ambiguous')+ if (Buffer.byteLength(field) > (field[0] === 'n' ? 16_385 : 65)) return nativeUnavailable('a native descriptor field exceeds its limit')+ fields.set(field[0], field.slice(1))+ }+ if (fields.has('p')) {+ if (processSeen || fields.size !== 1 || fields.get('p') !== String(pid)) return nativeUnavailable('the native descriptor owner is ambiguous')+ processSeen = true+ continue+ }+ const fd = fields.get('f'), kind = fields.get('t'), path = fields.get('n')+ if (!processSeen || !fd || !kind || !path || rows.length >= 4096) {+ return nativeUnavailable('the native descriptor pool is incomplete or exceeds its limit')+ }+ if (!/^(?:\d{1,10}|cwd|rtd|txt|mem)$/.test(fd) || !knownKinds.has(kind)) return nativeUnavailable('a native descriptor is unreadable or has an unknown type')+ const device = fields.get('D'), inode = fields.get('i')+ if ((device !== undefined && !/^0x[0-9a-f]{1,16}$/i.test(device)) || (inode !== undefined && !/^\d{1,20}$/.test(inode))+ || (inode !== undefined && BigInt(inode) > 0xffffffffffffffffn)+ || (kind === 'REG' && (device === undefined || inode === undefined || !path.startsWith('/')))) {+ return nativeUnavailable('a native file descriptor has no conclusive file identity')+ }+ // A mapped executable/library is reported as another `txt` row. Numeric descriptors+ // remain unique; treating all `txt` records as one silently loses mapped files.+ const key = /^\d+$/.test(fd) ? fd : JSON.stringify([fd, device, inode, path])+ if (seen.has(key)) return nativeUnavailable('the native descriptor pool has duplicate entries')+ seen.add(key)+ rows.push({ fd, kind, path, ...(device === undefined ? {} : { device: BigInt(device) }),+ ...(inode === undefined ? {} : { inode: BigInt(inode) }) })+ }+ if (!processSeen) return nativeUnavailable('the native descriptor owner is missing')+ return rows+}++async function linuxDescriptors(pid: number, budget: NativeEvidenceBudget): Promise<NativeDescriptor[]> {+ const rows: NativeDescriptor[] = []+ budget.step()+ try {+ const directory = await opendir(`/proc/${pid}/fd`, { bufferSize: 32 })+ for await (const entry of directory) {+ budget.step()+ if (!/^\d+$/.test(entry.name) || rows.length >= 4096) return nativeUnavailable('the native descriptor pool exceeds its limit or has an invalid entry')+ const location = `/proc/${pid}/fd/${entry.name}`, path = await readlink(location)+ budget.step(Buffer.byteLength(path))+ if (path.startsWith('/')) {+ const info = await stat(location, { bigint: true })+ rows.push({ fd: entry.name, path, kind: info.isFile() ? 'REG' : 'OTHER', device: info.dev, inode: info.ino })+ } else {+ if (!/^(?:socket:\[\d+\]|pipe:\[\d+\]|anon_inode:.*)$/.test(path)) return nativeUnavailable('a native descriptor target is unreadable')+ rows.push({ fd: entry.name, path, kind: 'OTHER' })+ }+ }+ } catch (error) {+ if (error instanceof IdentityReadUnavailable) throw error+ return nativeUnavailable('the native descriptor pool could not be read completely')+ }+ budget.step()+ return rows+}++export async function readDescriptorEvidence(pid: number, budget: NativeEvidenceBudget): Promise<DescriptorEvidence> {+ if (!Number.isSafeInteger(pid) || pid <= 0) return nativeUnavailable('the native descriptor owner is invalid')+ const read = () => process.platform === 'linux' ? linuxDescriptors(pid, budget)+ : nativeProbe('lsof', ['-n', '-P', '-p', String(pid), '-F0pftDin'], budget, 1024 * 1024)+ .then(output => parseDescriptors(output, pid, budget))+ const descriptors = await read(), before = signature(descriptors)+ return { descriptors, verify: async () => {+ if (signature(await read()) !== before) nativeUnavailable('the native descriptor pool changed during inspection')+ } }+}++/** lsof can escape control and non-ASCII bytes even in field mode. The kernel inode, not+ * a guessed spelling, chooses between literal and escaped names. Unresolvable names hold. */+export function descriptorPaths(path: string): string[] {+ if (Buffer.byteLength(path) > 16_384) return nativeUnavailable('a native descriptor path exceeds its limit')+ const bytes: Buffer[] = []+ for (let index = 0; index < path.length;) {+ const escape = /^\\(?:x([0-9a-fA-F]{2})|([abfnrtv\\]))/.exec(path.slice(index))+ if (escape) {+ const special: Record<string, number> = { a: 7, b: 8, f: 12, n: 10, r: 13, t: 9, v: 11, '\\': 92 }+ bytes.push(Buffer.from([escape[1] ? parseInt(escape[1], 16) : special[escape[2]]]))+ index += escape[0].length+ } else {+ const char = String.fromCodePoint(path.codePointAt(index)!)+ bytes.push(Buffer.from(char)); index += char.length+ }+ }+ try {+ const decoded = new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(bytes))+ return [...new Set([path, decoded])]+ } catch { return [path] }+}diff --git a/cli/src/engines/kit/nativeEvidence.spec.ts b/cli/src/engines/kit/nativeEvidence.spec.tsnew file mode 100644index 000000000..7cec96745--- /dev/null+++ b/cli/src/engines/kit/nativeEvidence.spec.ts@@ -0,0 +1,58 @@+import { execFile } from 'node:child_process'+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { performance } from 'node:perf_hooks'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { NativeEvidenceBudget, nativeBytes, nativeProbe, nativeText } from './nativeEvidence.js'++vi.mock('node:child_process', async original => ({ ...await original<object>(), execFile: vi.fn() }))+let root: string+beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'native-evidence-')); vi.resetAllMocks() })+afterEach(() => { vi.restoreAllMocks(); rmSync(root, { recursive: true, force: true }) })++it.each(['error', 'stderr', 'utf8'] as const)('rejects %s even beside a readable probe prefix', async mode => {+ vi.mocked(execFile).mockImplementation(((...args: unknown[]) => {+ const done = args.at(-1) as (error: Error | null, stdout: Buffer, stderr: Buffer) => void+ done(mode === 'error' ? new Error('maxBuffer') : null, mode === 'utf8' ? Buffer.from([255]) : Buffer.from('p42\0\n'),+ Buffer.from(mode === 'stderr' ? 'partial results' : ''))+ }) as never)+ await expect(nativeProbe('lsof', [], new NativeEvidenceBudget())).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })+})+it('holds a failed spawn and never launches a probe after the shared deadline', async () => {+ vi.mocked(execFile).mockImplementation(() => { throw new Error('spawn failed') })+ await expect(nativeProbe('ps', [], new NativeEvidenceBudget())).rejects.toThrow('could not start')+ vi.mocked(execFile).mockClear()+ await expect(nativeProbe('ps', [], new NativeEvidenceBudget(-1))).rejects.toThrow('deadline')+ expect(execFile).not.toHaveBeenCalled()+})+it('passes a decreasing shared timeout, hard kill and byte limit to every probe', async () => {+ let now = 100+ vi.spyOn(performance, 'now').mockImplementation(() => now)+ vi.mocked(execFile).mockImplementation(((...args: unknown[]) => {+ (args.at(-1) as Function)(null, Buffer.from('complete\n'), Buffer.alloc(0))+ }) as never)+ const budget = new NativeEvidenceBudget(1000)+ await expect(nativeProbe('ps', [], budget, 1234)).resolves.toBe('complete\n')+ now += 100+ await nativeProbe('lsof', [], budget)+ expect(vi.mocked(execFile).mock.calls[0][2]).toMatchObject({ timeout: 1000, killSignal: 'SIGKILL', maxBuffer: 1234, encoding: 'buffer', env: { LC_TIME: 'C' } })+ expect(vi.mocked(execFile).mock.calls[1][2]).toMatchObject({ timeout: 900 })+})+it('bounds cumulative bytes, operations and subprocesses, not just one read', () => {+ expect(() => new NativeEvidenceBudget().step(16 * 1024 * 1024 + 1)).toThrow('work limit')+ const work = new NativeEvidenceBudget()+ expect(() => { for (let index = 0; index <= 32768; index++) work.step() }).toThrow('work limit')+ const probes = new NativeEvidenceBudget()+ expect(() => { for (let index = 0; index <= 64; index++) probes.probe() }).toThrow('probe limit')+})+it('reads bounded EOF and refuses an oversized, missing or nonregular process record', async () => {+ const path = join(root, 'record')+ writeFileSync(path, Buffer.from([65, 0, 66]))+ await expect(nativeBytes(path, 3, new NativeEvidenceBudget())).resolves.toEqual(Buffer.from([65, 0, 66]))+ await expect(nativeBytes(path, 2, new NativeEvidenceBudget())).rejects.toThrow('byte limit')+ await expect(nativeBytes(join(root, 'missing'), 3, new NativeEvidenceBudget())).rejects.toThrow('read completely')+ mkdirSync(join(root, 'directory'))+ await expect(nativeBytes(join(root, 'directory'), 3, new NativeEvidenceBudget())).rejects.toThrow('not a regular file')+ expect(() => nativeText(Buffer.from([255]))).toThrow('UTF-8')+})diff --git a/cli/src/engines/kit/nativeEvidence.ts b/cli/src/engines/kit/nativeEvidence.tsnew file mode 100644index 000000000..aff1471ee--- /dev/null+++ b/cli/src/engines/kit/nativeEvidence.ts@@ -0,0 +1,83 @@+/** One native lookup owns one work budget, including its final verification. */+import { execFile } from 'node:child_process'+import { constants } from 'node:fs'+import { open } from 'node:fs/promises'+import { performance } from 'node:perf_hooks'+import { psEnv } from '../../lib/childLocale.js'+import { IdentityReadUnavailable } from './identityScan.js'++export const nativeUnavailable = (reason: string): never => { throw new IdentityReadUnavailable(reason) }++export class NativeEvidenceBudget {+ private readonly deadline: number+ private operations = 32_768+ private bytes = 16 * 1024 * 1024+ private probes = 64+ constructor(timeoutMs = 3_000) { this.deadline = performance.now() + timeoutMs }+ remaining(): number {+ const left = Math.floor(this.deadline - performance.now())+ if (left <= 0) nativeUnavailable('the native process evidence deadline was reached')+ return left+ }+ step(bytes = 0): void {+ this.remaining()+ if (--this.operations < 0 || (this.bytes -= bytes) < 0) nativeUnavailable('the native process evidence work limit was reached')+ }+ probe(): number {+ this.step()+ if (--this.probes < 0) nativeUnavailable('the native process probe limit was reached')+ return this.remaining()+ }+}++/** Error plus a readable prefix still means that the probe did not finish. */+export async function nativeProbe(command: 'ps' | 'lsof', args: string[], budget: NativeEvidenceBudget,+ maxBuffer = 512 * 1024,+): Promise<string> {+ const timeout = budget.probe()+ const bytes = await new Promise<Buffer>((resolve, reject) => {+ execFile(command, args, { encoding: 'buffer', timeout, killSignal: 'SIGKILL', maxBuffer,+ env: psEnv({ ...process.env, LC_ALL: '', LC_CTYPE: process.platform === 'darwin' ? 'UTF-8' : 'C.UTF-8' }),+ }, (error, stdout, stderr) => {+ if (error || stderr.length) { reject(new IdentityReadUnavailable(`the native ${command} probe did not complete`)); return }+ resolve(stdout)+ })+ }).catch((error: unknown) => {+ if (error instanceof IdentityReadUnavailable) throw error+ return nativeUnavailable(`the native ${command} probe could not start`)+ })+ budget.step(bytes.length)+ try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes) }+ catch { return nativeUnavailable(`the native ${command} output is not complete UTF-8`) }+}++/** /proc reports zero file sizes. Read to a bounded EOF rather than trusting that size. */+export async function nativeBytes(path: string, maxBytes: number, budget: NativeEvidenceBudget): Promise<Buffer> {+ budget.step()+ let handle+ try {+ handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK)+ if (!(await handle.stat()).isFile()) nativeUnavailable('a native process record is not a regular file')+ const chunks: Buffer[] = []+ let total = 0+ for (let calls = 0; calls < 64; calls++) {+ budget.step()+ const buffer = Buffer.alloc(Math.min(4096, maxBytes + 1 - total))+ const read = await handle.read(buffer, 0, buffer.length, total)+ budget.step(read.bytesRead)+ if (!read.bytesRead) return Buffer.concat(chunks, total)+ total += read.bytesRead+ if (total > maxBytes) nativeUnavailable('a native process record exceeds its byte limit')+ chunks.push(buffer.subarray(0, read.bytesRead))+ }+ return nativeUnavailable('a native process record exceeds its read-operation limit')+ } catch (error) {+ if (error instanceof IdentityReadUnavailable) throw error+ return nativeUnavailable('a native process record could not be read completely')+ } finally { await handle?.close().catch(() => nativeUnavailable('a native process record could not be closed')) }+}++export function nativeText(bytes: Buffer): string {+ try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes) }+ catch { return nativeUnavailable('a native process record is not complete UTF-8') }+}diff --git a/cli/src/engines/kit/nativeHeader.ts b/cli/src/engines/kit/nativeHeader.tsnew file mode 100644index 000000000..8391ff5bf--- /dev/null+++ b/cli/src/engines/kit/nativeHeader.ts@@ -0,0 +1,88 @@+/** A descriptor's first record, fenced again after all asynchronous ownership reads. */+import { constants, openSync, closeSync, fstatSync, readSync, type BigIntStats } from 'node:fs'+import { lstat } from 'node:fs/promises'+import type { SessionStoreContract } from '../facets/sessionStore.js'+import { identityBytes, IdentityReadUnavailable } from './identityScan.js'+import { firstRecordMeta, type SessionMeta } from './sessionRecords.js'+import { NativeEvidenceBudget, nativeText, nativeUnavailable } from './nativeEvidence.js'+import { nativeFileKey } from './nativePaths.js'++type First = NonNullable<SessionStoreContract['first']>+const stamp = (info: BigIntStats) => `${nativeFileKey(info)}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`+function firstLine(bytes: Buffer, maxBytes: number): string {+ // Do not decode a truncated UTF-8 character in the body after the complete metadata line.+ let start = 0+ while (start < Math.min(bytes.length, maxBytes)) {+ const end = bytes.indexOf(10, start)+ if ((end < 0 && bytes.length > maxBytes) || end > maxBytes) break+ const line = nativeText(bytes.subarray(start, end < 0 ? bytes.length : end))+ if (line.trim()) return line+ if (end < 0) break+ start = end + 1+ }+ return nativeUnavailable('the native rollout header is incomplete or exceeds its limit')+}++export async function descriptorHeader(path: string, identity: { device: bigint; inode: bigint },+ first: First, budget: NativeEvidenceBudget,+): Promise<{ meta: SessionMeta; verify(): void }> {+ budget.step()+ let line: string, meta: SessionMeta | null+ try {+ const version = await lstat(path)+ const bytes = await identityBytes(path, first.maxBytes + 1, { ...version, fileKey: identity }, budget)+ budget.step()+ line = firstLine(bytes, first.maxBytes)+ meta = firstRecordMeta(line, first)+ if (!meta || (!meta.isSubagent && (!meta.id || !meta.cwd || !meta.cwd.startsWith('/')))) return nativeUnavailable('the native rollout header is invalid')+ const record: unknown = JSON.parse(line)+ const field = (path: readonly string[]) => path.reduce((at: any, key) => at && typeof at === 'object' && !Array.isArray(at) ? at[key] : undefined, record)+ if (first.source) {+ const source: unknown = field(first.source.field)+ const object = source && typeof source === 'object' && !Array.isArray(source) ? source as Record<string, unknown> : null+ const keys = object ? Object.keys(object) : []+ const named = keys.length === 1 && first.source.named.includes(keys[0]) && typeof object![keys[0]] === 'string' && String(object![keys[0]]).trim()+ const child = keys.length === 1 && keys[0] === first.child.at(-1) && meta.isSubagent+ if (!(source === undefined && first.source.legacyMissing)+ && !(typeof source === 'string' && first.source.values.includes(source)) && !named && !child) {+ return nativeUnavailable('the native rollout source is invalid or unknown')+ }+ }+ if (meta.isSubagent) {+ const claim: unknown = field(first.child)+ if (!(typeof claim === 'string' && claim.trim())+ && !(claim && typeof claim === 'object' && !Array.isArray(claim) && meta.parentThreadId)) {+ return nativeUnavailable('the native rollout delegated-source claim is invalid')+ }+ }+ } catch (error) {+ if (error instanceof IdentityReadUnavailable) throw error+ return nativeUnavailable('the native rollout header could not be read completely')+ }+ return { meta, verify: () => {+ budget.step()+ let fd: number | undefined+ try {+ fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK)+ const before = fstatSync(fd, { bigint: true })+ if (!before.isFile() || before.dev !== identity.device || before.ino !== identity.inode) return nativeUnavailable('the native rollout was replaced after inspection')+ const bytes = Buffer.alloc(first.maxBytes + 1)+ let length = 0+ for (let calls = 0; length < bytes.length; calls++) {+ budget.step()+ if (calls >= 64) return nativeUnavailable('the native header verification read limit was reached')+ const read = readSync(fd, bytes, length, bytes.length - length, length)+ budget.step(read)+ if (!read) break+ length += read+ }+ if (stamp(fstatSync(fd, { bigint: true })) !== stamp(before)+ || firstLine(bytes.subarray(0, length), first.maxBytes) !== line) return nativeUnavailable('the native rollout header changed during inspection')+ } catch (error) {+ if (error instanceof IdentityReadUnavailable) throw error+ return nativeUnavailable('the native rollout header became unreadable')+ } finally {+ if (fd !== undefined) { try { closeSync(fd) } catch { nativeUnavailable('the native rollout header could not be closed') } }+ }+ } }+}diff --git a/cli/src/engines/kit/nativePaths.ts b/cli/src/engines/kit/nativePaths.tsnew file mode 100644index 000000000..22203132a--- /dev/null+++ b/cli/src/engines/kit/nativePaths.ts@@ -0,0 +1,95 @@+/** Canonical path evidence for a bounded native descriptor pool, including excluded candidates. */+import { lstatSync, readlinkSync, type BigIntStats } from 'node:fs'+import { lstat, readlink } from 'node:fs/promises'+import { dirname, isAbsolute, join } from 'node:path'+import { NativeEvidenceBudget, nativeUnavailable } from './nativeEvidence.js'++export const nativeFileKey = (info: Pick<BigIntStats, 'dev' | 'ino'>) => `${info.dev}:${info.ino}`+const identity = (info: BigIntStats | null) => info && `${nativeFileKey(info)}:${info.mode}`+const version = (info: BigIntStats) => `${identity(info)}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`+type Part = { info: BigIntStats | null; target?: string }++export class NativePaths {+ private readonly parts = new Map<string, Part>()+ constructor(private readonly budget: NativeEvidenceBudget) {}++ async resolve(path: string, missingOkay = false): Promise<{ path: string; info: BigIntStats } | null> {+ if (!isAbsolute(path) || path.includes('\0') || Buffer.byteLength(path) > 4096) return nativeUnavailable('a native location is invalid or exceeds its limit')+ // Follow links in component order. Normalizing bridge/../home first would skip bridge.+ let prefix = '/', pending = path.slice(1).split('/').filter(Boolean), links = 0+ let info: BigIntStats | null = null+ if (!pending.length) pending = ['.']+ for (let index = 0; pending.length; index++) {+ this.budget.step()+ if (index >= 256) return nativeUnavailable('the native path component limit was reached')+ const part = pending.shift()!+ if (part === '..') { prefix = dirname(prefix); if (!pending.length) pending = ['.']; continue }+ if (part === '.' && pending.length) continue+ const next = part === '.' ? prefix : join(prefix, part)+ let proof = this.parts.get(next)+ if (!proof) {+ try {+ info = await lstat(next, { bigint: true })+ proof = { info, ...(info.isSymbolicLink() ? { target: await readlink(next) } : {}) }+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') proof = { info: null }+ else return nativeUnavailable('a native location could not be inspected')+ }+ this.parts.set(next, proof)+ }+ info = proof.info+ if (!info) {+ if (missingOkay) return null+ return nativeUnavailable('a native location is missing')+ }+ if (proof.target !== undefined) {+ if (++links > 32) return nativeUnavailable('the native alias depth limit was reached')+ if (isAbsolute(proof.target)) prefix = '/'+ pending = [...proof.target.split('/').filter(Boolean), ...pending]+ if (!pending.length) pending = ['.']+ } else {+ if (pending.length && !info.isDirectory()) return nativeUnavailable('a native path ancestor is not a directory')+ prefix = next+ }+ }+ this.budget.step()+ return { path: prefix, info: info! }+ }++ /** Case/normalization aliases and bind mounts can have different spellings for+ * the same directory. Only the observed physical ancestor chain proves membership. */+ within(path: string, roots: readonly BigIntStats[]): boolean {+ const keys = new Set(roots.map(nativeFileKey))+ for (let parent = dirname(path);;) {+ this.budget.step()+ const part = this.parts.get(parent)+ if (part?.info && !part.target && part.info.isDirectory() && keys.has(nativeFileKey(part.info))) return true+ if (parent === '/') return false+ if (!part?.info || part.target !== undefined || !part.info.isDirectory()) return nativeUnavailable('the native directory ancestry is incomplete')+ parent = dirname(parent)+ }+ }++ /** No asynchronous work follows the caller's last header fence. Unrelated directory+ * contents may change; replacing an ordinary ancestor or any alias may not. */+ verify(): void {+ for (const [path, before] of this.parts) {+ this.budget.step()+ let now: BigIntStats | null+ try { now = lstatSync(path, { bigint: true }) }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') now = null+ else return nativeUnavailable('a native location became unreadable')+ }+ let target: string | undefined+ if (before.target !== undefined && now?.isSymbolicLink()) {+ try { target = readlinkSync(path) } catch { return nativeUnavailable('a native alias became unreadable') }+ }+ if (identity(now) !== identity(before.info)+ || (before.target !== undefined && (!now || version(now) !== version(before.info!)+ || target !== before.target))) {+ return nativeUnavailable('a native path or alias changed during inspection')+ }+ }+ }+}diff --git a/cli/src/engines/kit/processRecordEvidence.ts b/cli/src/engines/kit/processRecordEvidence.tsnew file mode 100644index 000000000..da11df1c4--- /dev/null+++ b/cli/src/engines/kit/processRecordEvidence.ts@@ -0,0 +1,38 @@+/** Final PID-record proof after asynchronous process ownership checks. */+import { constants, openSync, closeSync, fstatSync, statSync, readSync, type BigIntStats } from 'node:fs'+import { NativeEvidenceBudget, nativeText, nativeUnavailable } from './nativeEvidence.js'+import { IdentityReadUnavailable } from './identityScan.js'++const stamp = (info: BigIntStats) => `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`+/** Whole records only, bounded independently of the file's reported size. Missing records+ * are evidence too: a new native claim invalidates an earlier directory fallback. */+export function verifyProcessRecord(file: string, text: string | null, budget: NativeEvidenceBudget): void {+ budget.step()+ let fd: number+ try { fd = openSync(file, constants.O_RDONLY | constants.O_NONBLOCK) }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT' && text === null) return+ return nativeUnavailable('the process records changed or became unreadable during discovery')+ }+ try {+ const before = fstatSync(fd, { bigint: true })+ if (!before.isFile() || before.size > 64n * 1024n) return nativeUnavailable('the process record is not a bounded regular file')+ const bytes = Buffer.alloc(Number(before.size))+ let length = 0+ for (let calls = 0; length < bytes.length; calls++) {+ budget.step()+ if (calls >= 64) return nativeUnavailable('the process record verification read limit was reached')+ const read = readSync(fd, bytes, length, bytes.length - length, length)+ budget.step(read)+ if (!read) return nativeUnavailable('the process record ended during verification')+ length += read+ }+ if (nativeText(bytes) !== text || stamp(fstatSync(fd, { bigint: true })) !== stamp(before)+ || stamp(statSync(file, { bigint: true })) !== stamp(before)) return nativeUnavailable('the process records changed during discovery')+ } catch (error) {+ if (error instanceof IdentityReadUnavailable) throw error+ return nativeUnavailable('the process record became unreadable during verification')+ } finally {+ try { closeSync(fd) } catch { nativeUnavailable('the process record could not be closed after verification') }+ }+}diff --git a/cli/src/engines/kit/sessionRecords.ts b/cli/src/engines/kit/sessionRecords.tsindex 9af8b6b92..eda13372e 100644--- a/cli/src/engines/kit/sessionRecords.ts+++ b/cli/src/engines/kit/sessionRecords.ts@@ -62,7 +62,7 @@ function valueAt(value: unknown, path: readonly string[]): unknown {return at}-function firstRecordMeta(firstLine: string, first: NonNullable<SessionStoreContract['first']>): SessionMeta | null {+export function firstRecordMeta(firstLine: string, first: NonNullable<SessionStoreContract['first']>): SessionMeta | null {const record = object(JSON.parse(firstLine))if (record?.type !== first.type || !object(valueAt(record, first.id.slice(0, -1)))) return nullconst id = valueAt(record, first.id)diff --git a/cli/src/engines/kit/storePool.spec.ts b/cli/src/engines/kit/storePool.spec.tsindex 86a7acdb8..b6b95e2a6 100644--- a/cli/src/engines/kit/storePool.spec.ts+++ b/cli/src/engines/kit/storePool.spec.ts@@ -14,6 +14,11 @@ const control = vi.hoisted(() => ({processes: [] as import('../../lib/tmux.js').ProcessRow[],}))vi.mock('../../lib/tmux.js', async original => ({ ...await original<object>(), processRows: async () => control.processes }))+vi.mock('../../lib/processEvidence.js', async () => {+ const { nativeConversationFixture } = await import('../../testing/nativeConversationEvidence.js')+ return { readProcessEvidence: (...args: Parameters<typeof import('../../lib/processEvidence.js')['readProcessEvidence']>) =>+ nativeConversationFixture(async () => [], async () => control.processes).processes(...args) }+})vi.mock('../../lib/deleteAgentFallback.js', () => ({ checkPidRuntime: vi.fn(), terminateDeletedAgent: vi.fn(async () => 'gone') }))vi.mock('../../core/engines/cursorTasks.js', () => ({ removePendingCursorTasks: vi.fn(async () => {}) }))vi.mock('node:child_process', async original => ({ ...await original<object>(),diff --git a/cli/src/engines/nativeDescriptors.golden.spec.ts b/cli/src/engines/nativeDescriptors.golden.spec.tsnew file mode 100644index 000000000..fa8449088--- /dev/null+++ b/cli/src/engines/nativeDescriptors.golden.spec.ts@@ -0,0 +1,217 @@+/** Healthy native descriptor answers from former main. Pinned Linux/macOS, UTC, fixed time and private files;+ * every host binary is forbidden. Record before changing process or descriptor authority. */+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { afterAll, beforeAll, expect, it, vi } from 'vitest'+import type { ProcessRow } from '../lib/tmux.js'+import type { RegisteredSession } from '../lib/registry.js'++const fixture = vi.hoisted(() => ({ root: '', rows: [] as ProcessRow[], lsof: new Map<number, string[]>() }))+vi.mock('node:fs', async original => {+ const fs = await original<typeof import('node:fs')>()+ const mapped = (path: unknown) => String(path).startsWith('/proc/')+ ? join(fixture.root, 'proc', String(path).slice('/proc/'.length)) : path+ return { ...fs,+ openSync: (path: unknown, ...args: unknown[]) => Reflect.apply(fs.openSync, fs, [mapped(path), ...args]),+ readlinkSync: (path: unknown, ...args: unknown[]) => Reflect.apply(fs.readlinkSync, fs, [mapped(path), ...args]),+ statSync: (path: unknown, ...args: unknown[]) => Reflect.apply(fs.statSync, fs, [mapped(path), ...args]),+ opendirSync: (path: unknown, ...args: unknown[]) => {+ const task = /^\/proc\/(\d+)\/task$/.exec(String(path))+ if (task) {+ const folder = join(String(mapped(path)), task[1]); fs.mkdirSync(folder, { recursive: true })+ const children = fixture.rows.filter(row => row.parentPid === Number(task[1])).map(row => row.pid)+ fs.writeFileSync(join(folder, 'children'), children.length ? children.join(' ') + ' ' : '')+ }+ return Reflect.apply(fs.opendirSync, fs, [mapped(path), ...args])+ },+ }+})+vi.mock('node:fs/promises', async original => {+ const fs = await original<typeof import('node:fs/promises')>()+ const mapped = (path: unknown) => String(path).startsWith('/proc/')+ ? join(fixture.root, 'proc', String(path).slice('/proc/'.length)) : path+ return { ...fs,+ open: (path: unknown, ...args: unknown[]) => Reflect.apply(fs.open, fs, [mapped(path), ...args]),+ readdir: (path: unknown, ...args: unknown[]) => Reflect.apply(fs.readdir, fs, [mapped(path), ...args]),+ opendir: (path: unknown, ...args: unknown[]) => Reflect.apply(fs.opendir, fs, [mapped(path), ...args]),+ readlink: (path: unknown, ...args: unknown[]) => Reflect.apply(fs.readlink, fs, [mapped(path), ...args]),+ stat: (path: unknown, ...args: unknown[]) => Reflect.apply(fs.stat, fs, [mapped(path), ...args]),+ }+})+vi.mock('node:child_process', async original => {+ const forbidden = () => { throw new Error('This golden must never run a host binary') }+ return { ...await original<object>(), execFile: (command: string, args: string[], _options: unknown, done: (error: Error | null, out: Buffer, err: Buffer) => void) => {+ const pid = Number(args[args.indexOf('-p') + 1])+ let output: string+ if (command === 'ps' && args.join(' ') === '-axo pid=,ppid=,state=,lstart=') {+ output = fixture.rows.map(row => `${row.pid} ${row.parentPid} S ${row.startMarker}\n`).join('')+ } else if (command === 'ps' && args[0] === '-ww') {+ const row = fixture.rows.find(row => row.pid === pid)+ if (!row) return forbidden()+ output = `${row.parentPid} S ${row.executable} ${row.startMarker} ${row.args}\n`+ } else if (command === 'lsof' && args.includes('-F0pftDin')) {+ const paths = fixture.lsof.get(pid)+ if (!paths) return forbidden()+ output = `p${pid}\0\n` + paths.map((path, index) => {+ const info = statSync(path, { bigint: true })+ return `f${index + 3}\0tREG\0D0x${info.dev.toString(16)}\0i${info.ino}\0n${path}\0\n`+ }).join('')+ } else if (command === '/fixture-tools/native-control' && args[0] === '--control') {+ const parent = Number(args[2]), ids = args.slice(3).map(Number)+ output = JSON.stringify({ schema: 2, mode: 'control', parent,+ children: parent ? fixture.rows.filter(row => row.parentPid === parent).map(row => row.pid) : [] }) + '\n'+ for (const id of ids) {+ const row = fixture.rows.find(row => row.pid === id)!+ output += JSON.stringify({ pid: id, parentPid: row.parentPid, startSeconds: Date.parse(row.startMarker) / 1000,+ startMicros: 123456, commandHex: Buffer.from(row.executable.split('/').at(-1)!).toString('hex'),+ imageHex: Buffer.from(row.executable).toString('hex'), commandDigest: 'a'.repeat(64),+ fds: (fixture.lsof.get(id) ?? []).map((path, index) => {+ const info = statSync(path, { bigint: true })+ return { fd: index + 3, type: 1, mode: 0o100000, device: String(info.dev), inode: String(info.ino) }+ }),+ }) + '\n'+ }+ } else return forbidden()+ done(null, Buffer.from(output), Buffer.alloc(0))+ }, execFileSync: forbidden, spawn: forbidden, spawnSync: forbidden }+})+vi.mock('../lib/tmux.js', async original => ({ ...await original<object>(), processRows: async () => fixture.rows }))+vi.mock('../lib/loginShellEnv.js', () => ({ loginShellEnvironment: () => ({}) }))+vi.mock('../lib/nativeProcessImages.js', async original => ({ ...await original<object>(),+ bundledProcessImageHelper: async () => ({ path: '/fixture-tools/native-control', key: 'fixture' }),+}))++const GOLDEN = fileURLToPath(new URL('./__fixtures__/native-descriptors.golden.json', import.meta.url))+const RECORD = process.env.RECORD_NATIVE_DESCRIPTORS_GOLDEN === '1'+const platform = Object.getOwnPropertyDescriptor(process, 'platform')!+const now = Date.parse('2026-10-09T12:00:00Z')+const startMarker = 'Fri Oct 9 11:59:00 2026'+const id = (n: number) => `aaaaaaaa-1111-4222-8333-${String(n).padStart(12, '0')}`+const path = (...parts: string[]) => join(fixture.root, ...parts)+const captured: Record<string, unknown> = {}+let expected: Record<string, unknown>+let repair: typeof import('../lib/sessionRepair.js')+let capture: typeof import('../lib/captureResumeIdentity.js')['captureResumeIdentity']++function file(name: string, text = ''): string {+ mkdirSync(dirname(name), { recursive: true }); writeFileSync(name, text)+ return name+}+function rollout(n: number, options: { home?: string; cwd?: string; child?: boolean } = {}): string {+ return file(join(options.home ?? path('codex'), 'sessions', 'day', `rollout-${id(n)}.jsonl`), JSON.stringify({+ type: 'session_meta', payload: { id: id(n), cwd: options.cwd ?? path('work'),+ source: options.child ? { subagent: { thread_spawn: { parent_thread_id: id(99) } } } : 'cli' },+ }) + '\n')+}+function descriptors(pid: number, targets: string[]): void {+ const folder = path('proc', String(pid), 'fd')+ rmSync(folder, { recursive: true, force: true }); mkdirSync(folder, { recursive: true })+ targets.forEach((target, index) => symlinkSync(target, join(folder, String(index + 3))))+}+function processRow(pid: number, parentPid: number, executable = '/fixture-tools/codex', args = executable): ProcessRow {+ mkdirSync(path('proc', String(pid), 'fd'), { recursive: true })+ const fields = ['S', String(parentPid), ...Array(17).fill('0'), String(pid * 100)]+ file(path('proc', String(pid), 'stat'), `${pid} (${executable}) ${fields.join(' ')}\n`)+ file(path('proc', String(pid), 'cmdline'), args.split(' ').join('\0') + '\0')+ const exe = path('proc', String(pid), 'exe'); rmSync(exe, { force: true }); symlinkSync(executable, exe)+ return { pid, parentPid, executable, args, startMarker, startTicks: pid * 100 }+}+function row(pid = 42): RegisteredSession {+ const live = fixture.rows.find(item => item.pid === pid)!+ return { agentId: 'fixture-agent', engine: 'codex', sessionId: '', transcriptPath: null, cwd: path('work'),+ codexHome: path('codex'), processIdentity: { pid, executable: live.executable, startMarker, startTicks: live.startTicks },+ source: 'discovery', boundAt: 0 } as RegisteredSession+}+async function check(key: string, work: Promise<unknown> | unknown): Promise<void> {+ captured[key] = JSON.parse(JSON.stringify(await work ?? null).split(fixture.root).join('<root>'))+ if (!RECORD) expect({ key, value: captured[key] }).toEqual({ key, value: expected[key] })+}++beforeAll(async () => {+ fixture.root = realpathSync(mkdtempSync(join(tmpdir(), 'native-descriptors-golden-')))+ for (const [name, value] of Object.entries({ HOME: path('home'), TZ: 'UTC',+ ADAPTER_DATA_DIR: path('data'), ADAPTER_RUNTIME_DIR: path('runtime'), CODEX_HOME: path('codex'),+ CLAUDE_CONFIG_DIR: path('claude'), CLAUDE_PROJECTS_DIR: path('claude', 'projects'),+ })) vi.stubEnv(name, value)+ for (const folder of ['home', 'data', 'runtime', 'work', 'elsewhere']) mkdirSync(path(folder), { recursive: true })+ Object.defineProperty(globalThis.process, 'platform', { ...platform, value: 'linux' })+ vi.useFakeTimers({ toFake: ['Date'], now }); vi.resetModules()+ repair = await import('../lib/sessionRepair.js')+ capture = (await import('../lib/captureResumeIdentity.js')).captureResumeIdentity+ expected = RECORD ? {} : JSON.parse(readFileSync(GOLDEN, 'utf8'))+})+afterAll(() => {+ if (RECORD) writeFileSync(GOLDEN, JSON.stringify(captured, null, 2) + '\n')+ Object.defineProperty(globalThis.process, 'platform', platform); vi.useRealTimers(); vi.unstubAllEnvs()+ rmSync(fixture.root, { recursive: true, force: true })+})++it('records complete private descriptor listings and one launcher child', async () => {+ const own = rollout(1), other = rollout(2), noise = file(path('notes'))+ fixture.rows = [processRow(42, 1), processRow(50, 1), processRow(51, 42)]+ descriptors(42, [noise, own, 'socket:[123]']); descriptors(50, []); descriptors(51, [other])+ await check('descriptors:native', repair.openFiles(42).then(paths => paths.sort()))+ await check('descriptors:empty', repair.openFiles(50))+ await check('descriptors:invalid', repair.openFiles(0))+ await check('process:native-ignores-nested-tool', repair.processFilesOf('codex', 42).then(paths => paths.sort()))+ await check('process:other-engine', repair.processFilesOf('claude', 42))+ fixture.rows = [processRow(42, 1, '/fixture-tools/node', 'node /fixture-tools/codex.js'), processRow(43, 42), processRow(50, 1), processRow(51, 43)]+ descriptors(42, [noise]); descriptors(43, [own]); descriptors(50, [other]); descriptors(51, [other])+ await check('process:launcher-child', repair.processFilesOf('codex', 42).then(paths => paths.sort()))+ await check('process:direct-native-child', repair.processFilesOf('codex', 43))+})++it('records healthy exact native headers, roots and exclusions', async () => {+ const own = rollout(11), child = rollout(12, { child: true }), other = rollout(13, { cwd: path('elsewhere') })+ const outside = rollout(14, { home: path('other-home') }), root = path('codex', 'sessions')+ const alias = path('rollout-alias.jsonl'); symlinkSync(own, alias)+ fixture.rows = [processRow(42, 1)]+ for (const [name, held, cwd, roots] of [+ ['one', [own], path('work'), root],+ ['repeated-descriptors', [own, own], path('work'), root],+ ['alias', [own, alias], path('work'), root],+ ['child-excluded', [own, child], path('work'), root],+ ['other-cwd-excluded', [own, other], path('work'), root],+ ['outside-profile-excluded', [own, outside], path('work'), root],+ ['only-child', [child], path('work'), root],+ ['only-other-cwd', [other], path('work'), root],+ ['empty', [], path('work'), root],+ ['moved-home', [outside], path('work'), [root, path('other-home', 'sessions')]],+ ] as const) {+ descriptors(42, [...held])+ await check(`identity:${name}`, repair.openFileSessionOf('codex', 42, typeof roots === 'string' ? roots : [...roots], cwd))+ }+ await check('identity:other-engine', repair.openFileSessionOf('claude', 42, root, path('work')))+})++it('records native and launcher capture before Stop without native writes', async () => {+ const own = rollout(21)+ fixture.rows = [processRow(42, 1)]; descriptors(42, [own])+ await check('capture:native', capture(row()))+ await check('capture:complete-binding', capture({ ...row(), sessionId: id(21), transcriptPath: own }))+ await check('capture:terminal', capture({ ...row(), engine: 'terminal' }))+ fixture.rows = [processRow(42, 1, '/fixture-tools/node', 'node /fixture-tools/codex.js'), processRow(43, 42)]+ descriptors(42, []); descriptors(43, [own])+ await check('capture:launcher', capture(row()))+ descriptors(43, [])+ await check('capture:complete-empty', capture(row()))+})+it('records healthy macOS descriptor and capture answers through a placeholder lsof', async () => {+ Object.defineProperty(globalThis.process, 'platform', { ...platform, value: 'darwin' })+ const own = rollout(31), unicode = rollout(32, { home: path('café-home') }), noise = file(path('notes-mac'))+ fixture.rows = [processRow(42, 1), processRow(50, 1)]+ fixture.lsof.set(42, [noise, own]); fixture.lsof.set(50, [])+ await check('darwin:descriptors', repair.openFiles(42).then(paths => paths.sort()))+ await check('darwin:empty', repair.openFiles(50))+ await check('darwin:identity', repair.openFileSessionOf('codex', 42, path('codex', 'sessions'), path('work')))+ await check('darwin:capture', capture(row()))+ fixture.lsof.set(42, [unicode])+ await check('darwin:unicode', repair.openFileSessionOf('codex', 42, path('café-home', 'sessions'), path('work')))+ fixture.rows = [processRow(42, 1, '/fixture-tools/node', 'node /fixture-tools/codex.js'), processRow(43, 42)]+ fixture.lsof.set(42, [noise]); fixture.lsof.set(43, [own])+ await check('darwin:launcher', repair.processFilesOf('codex', 42).then(paths => paths.sort()))+ Object.defineProperty(globalThis.process, 'platform', { ...platform, value: 'linux' })+})+it('has exactly the recorded observations', () => { if (!RECORD) expect(Object.keys(captured).sort()).toEqual(Object.keys(expected).sort()) })diff --git a/cli/src/engines/sessionStore.golden.spec.ts b/cli/src/engines/sessionStore.golden.spec.tsindex 919c1bcc0..898e29bed 100644--- a/cli/src/engines/sessionStore.golden.spec.ts+++ b/cli/src/engines/sessionStore.golden.spec.ts@@ -1,3 +1,4 @@+import { nativeConversationFixture } from '../testing/nativeConversationEvidence.js'/*** Where Claude Code and Codex keep their sessions, and what core reads there, answer for answer: recorded* from the code as it stood before their session stores became declared data applied by the kit@@ -28,6 +29,14 @@ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'import type { RegisteredSession } from '../lib/registry.js'const fixtureClock = vi.hoisted(() => ({ root: '', now: Date.parse('2026-10-09T00:00:00Z') }))+vi.mock('../lib/bootId.js', async original => ({ ...await original<object>(), currentBootId: () => 'fixture-boot', bootChanged: () => false }))+vi.mock('../lib/processLiveness.js', async original => ({ ...await original<object>(),+ processLockIdentity: () => ({ startMarker: 'fixture-start', generationMarker: 'fixture-generation' }), lockOwnerAlive: () => true,+}))+vi.mock('../lib/processEvidence.js', async () => {+ const { nativeConversationFixture } = await import('../testing/nativeConversationEvidence.js')+ return { readProcessEvidence: nativeConversationFixture(async () => [], async () => []).processes }+})vi.mock('fs/promises', async original => {const fs = await original<typeof import('node:fs/promises')>()return { ...fs, stat: async (path: string, ...args: unknown[]) => {@@ -349,7 +358,7 @@ async function findCases(): Promise<Record<string, unknown>> {}for (const [name, files] of Object.entries(held)) {for (const [cwdName, cwd] of [['a', work('a')], ['c', work('c')]] as const) {- cases[`open files · ${name} · ${cwdName}`] = await attempt(() => s.openFileSessionOf('codex', 7, sessions, cwd, async () => files))+ cases[`open files · ${name} · ${cwdName}`] = await attempt(() => s.openFileSessionOf('codex', 7, sessions, cwd, { sources: nativeConversationFixture(async () => files) }))}}// Only a file named as a rollout counts, however its first record reads.@@ -357,9 +366,9 @@ async function findCases(): Promise<Record<string, unknown>> {write(join(heldRoot, `rollout-held-${B}.jsonl`), jsonl(meta(B, work('a'))))write(join(heldRoot, `notes-${C}.jsonl`), jsonl(meta(C, work('a'))))cases['open files · a rollout and another session-shaped file'] = await attempt(() => s.openFileSessionOf('codex', 7, heldRoot, work('a'),- async () => [join(heldRoot, `notes-${C}.jsonl`), join(heldRoot, `rollout-held-${B}.jsonl`)]))- cases['open files · one root'] = await attempt(() => s.openFileSessionOf('codex', 7, join(root, 'codex', 'sessions'), work('a'), async () => [paths.codexA]))- cases['open files · claude'] = await attempt(() => s.openFileSessionOf('claude', 7, sessions, work('a'), async () => [paths.codexA]))+ { sources: nativeConversationFixture(async () => [join(heldRoot, `notes-${C}.jsonl`), join(heldRoot, `rollout-held-${B}.jsonl`)]) }))+ cases['open files · one root'] = await attempt(() => s.openFileSessionOf('codex', 7, join(root, 'codex', 'sessions'), work('a'), { sources: nativeConversationFixture(async () => [paths.codexA]) }))+ cases['open files · claude'] = await attempt(() => s.openFileSessionOf('claude', 7, sessions, work('a'), { sources: nativeConversationFixture(async () => [paths.codexA]) }))const rows = (args: string, executable: string) => async () => [{ pid: 7, parentPid: 1, executable, args },{ pid: 8, parentPid: 7, executable: 'codex', args: 'codex --no-daemon' },@@ -372,12 +381,12 @@ async function findCases(): Promise<Record<string, unknown>> {['nodejs launcher', [], '/usr/bin/nodejs /opt/codex.js', '/usr/bin/nodejs'],['not a launcher', ['/dev/null'], 'python3 x', 'python3'],] as const) {- cases[`process files · ${name}`] = await attempt(() => s.processFilesOf('codex', 7, filesOf({ 7: [...own], 8: [paths.codexB] }), rows(launcher, executable)))+ cases[`process files · ${name}`] = await attempt(() => s.processFilesOf('codex', 7, { sources: nativeConversationFixture(filesOf({ 7: [...own], 8: [paths.codexB] }), rows(launcher, executable)) }))}- cases['process files · no process table'] = await attempt(() => s.processFilesOf('codex', 7, filesOf({ 7: ['/dev/null'] }), async () => null))- cases['process files · two children'] = await attempt(() => s.processFilesOf('codex', 7, filesOf({ 7: [], 8: [paths.codexB], 10: [paths.codexA] }), async () => [+ cases['process files · no process table'] = await attempt(() => s.processFilesOf('codex', 7, { sources: nativeConversationFixture(filesOf({ 7: ['/dev/null'] }), async () => null) }))+ cases['process files · two children'] = await attempt(() => s.processFilesOf('codex', 7, { sources: nativeConversationFixture(filesOf({ 7: [], 8: [paths.codexB], 10: [paths.codexA] }), async () => [{ pid: 7, parentPid: 1, executable: 'node', args: 'node /opt/codex.js' },- { pid: 8, parentPid: 7, executable: 'codex', args: 'codex' }, { pid: 10, parentPid: 7, executable: 'codex', args: 'codex' }]))+ { pid: 8, parentPid: 7, executable: 'codex', args: 'codex' }, { pid: 10, parentPid: 7, executable: 'codex', args: 'codex' }]) }))return cases}@@ -607,8 +616,16 @@ describe('core finds sessions where it did before Claude Code and Codex declared[`process record · ${home} · no transcript`, 'the process names a conversation whose transcript is unavailable'] as const,[`process record · ${home} · another folder`, 'the current process record names a different working directory'] as const,]))- const reason = section === 'find' ? held.get(key) : undefined- if (reason) expect(value, `${platform} · ${key} · former refusal`).toBeNull()+ const descriptorCorrections = new Map<string, { before: unknown; reason: string }>([+ ...['a', 'c'].map(cwd => [`open files · outside the sessions · ${cwd}`, {+ before: null, reason: 'the open rollout pathname does not name the process file',+ }] as const),+ ['process files · no process table', { before: ['/dev/null'], reason: 'the native process graph is incomplete' }],+ ['process files · two children', { before: [], reason: 'more than one native child could own the conversation' }],+ ])+ const corrected = section === 'find' ? descriptorCorrections.get(key) : undefined+ const reason = corrected?.reason ?? (section === 'find' ? held.get(key) : undefined)+ if (reason) expect(value, `${platform} · ${key} · former refusal`).toEqual(corrected ? corrected.before : null)expect(actual[section]![key], `${platform} · ${section} · ${key}`).toEqual(reason ? { threw: `Conversation identity is held: ${reason}.` } : value)}diff --git a/cli/src/lib/captureResumeIdentity.spec.ts b/cli/src/lib/captureResumeIdentity.spec.tsindex a1d490cff..701dc3ad8 100644--- a/cli/src/lib/captureResumeIdentity.spec.ts+++ b/cli/src/lib/captureResumeIdentity.spec.ts@@ -1,11 +1,17 @@import { beforeEach, expect, it, vi } from 'vitest'import { captureResumeIdentity } from './captureResumeIdentity.js'import { engineKeepsTranscriptFile, validTranscriptPath, type RegisteredSession } from './registry.js'-import { findLiveSession, findResumedTranscript, processSessionOf } from './sessionRepair.js'+import { findLiveSession, findResumedTranscript, processSessionEvidence } from './sessionRepair.js'import { processRows, resumeSessionId } from './tmux.js'vi.mock('./registry.js', () => ({ validTranscriptPath: vi.fn(() => true), engineKeepsTranscriptFile: vi.fn(() => true) }))-vi.mock('./sessionRepair.js', () => ({ processSessionOf: vi.fn(), findLiveSession: vi.fn(), findResumedTranscript: vi.fn() }))+vi.mock('./sessionRepair.js', () => ({ processSessionEvidence: vi.fn(), findLiveSession: vi.fn(), findResumedTranscript: vi.fn() }))vi.mock('./tmux.js', () => ({ processRows: vi.fn(), resumeSessionId: vi.fn() }))+vi.mock('./processEvidence.js', async () => {+ const { nativeConversationFixture } = await import('../testing/nativeConversationEvidence.js')+ const { processRows } = await import('./tmux.js')+ return { readProcessEvidence: (...args: Parameters<typeof import('./processEvidence.js')['readProcessEvidence']>) =>+ nativeConversationFixture(async () => [], processRows).processes(...args) }+})let row: RegisteredSessionbeforeEach(() => {vi.resetAllMocks()@@ -15,7 +21,7 @@ beforeEach(() => {vi.mocked(validTranscriptPath).mockReturnValue(true)vi.mocked(engineKeepsTranscriptFile).mockReturnValue(true)vi.mocked(resumeSessionId).mockReturnValue(null)- vi.mocked(processSessionOf).mockResolvedValue(null)+ vi.mocked(processSessionEvidence).mockResolvedValue({ session: null, verify: vi.fn() })vi.mocked(findLiveSession).mockResolvedValue(null)vi.mocked(findResumedTranscript).mockResolvedValue(null)})@@ -83,7 +89,9 @@ it.each(['identity', 'cwd', 'unknown', 'gone', 'pid', 'executable', 'start'])('rif (mode === 'pid') row.processIdentity!.pid++if (mode === 'executable') row.processIdentity!.executable = 'other'if (mode === 'start') row.processIdentity!.startMarker = 'later'- expect(await captureResumeIdentity(row)).toBe(row); expect(findLiveSession).not.toHaveBeenCalled()+ if (['unknown', 'executable', 'start'].includes(mode)) await expect(captureResumeIdentity(row)).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })+ else expect(await captureResumeIdentity(row)).toBe(row)+ expect(findLiveSession).not.toHaveBeenCalled()})it.each(['claude', 'codex'] as const)('captures an explicit %s resume without guessing by directory', async engine => {row.engine = engine; vi.mocked(resumeSessionId).mockReturnValue('exact')@@ -99,15 +107,15 @@ it('keeps an explicit file-backed resume unbound while its transcript is still u})it('prefers current Claude native metadata to old resume argv', async () => {vi.mocked(resumeSessionId).mockReturnValue('old')- vi.mocked(processSessionOf).mockResolvedValue({ sessionId: 'current', transcriptPath: '/current' })+ vi.mocked(processSessionEvidence).mockResolvedValue({ session: { sessionId: 'current', transcriptPath: '/current' }, verify: vi.fn() })expect(await captureResumeIdentity(row)).toMatchObject({ sessionId: 'current' }); expect(findResumedTranscript).not.toHaveBeenCalled()- expect(processSessionOf).toHaveBeenCalledWith('claude', 77, '/work', Date.parse(row.processIdentity!.startMarker))+ expect(processSessionEvidence).toHaveBeenCalledWith('claude', 77, '/work', Date.parse(row.processIdentity!.startMarker), expect.anything())})it('captures a unique fresh session before its first hook arrives', async () => {vi.mocked(findLiveSession).mockResolvedValue({ sessionId: 'new', transcriptPath: '/new' })expect(await captureResumeIdentity(row)).toMatchObject({ sessionId: 'new', transcriptPath: '/new' })expect(row.sessionId).toBe('')- expect(findLiveSession).toHaveBeenCalledWith('claude', '/work', Date.parse(row.processIdentity!.startMarker), { pid: 77, bornOnly: true, codexHome: undefined })+ expect(findLiveSession).toHaveBeenCalledWith('claude', '/work', Date.parse(row.processIdentity!.startMarker), expect.objectContaining({ pid: 77, bornOnly: true, codexHome: undefined, expectedProcess: row.processIdentity }))})it.each([null, { sessionId: 'missing' }, { sessionId: 'unsafe', transcriptPath: '/unsafe' }])('does not bind ambiguous or unsafe history: %s', async found => {vi.mocked(findLiveSession).mockResolvedValue(found); vi.mocked(validTranscriptPath).mockReturnValue(false)diff --git a/cli/src/lib/captureResumeIdentity.ts b/cli/src/lib/captureResumeIdentity.tsindex 06df32e85..815943072 100644--- a/cli/src/lib/captureResumeIdentity.ts+++ b/cli/src/lib/captureResumeIdentity.ts@@ -8,9 +8,10 @@* including the four that keep theirs in a database rather than a file.*/import { engineKeepsTranscriptFile, validTranscriptPath, type RegisteredSession } from './registry.js'-import { findLiveSession, findResumedTranscript, processSessionOf, type RepairedSession } from './sessionRepair.js'-import { processRows, resumeSessionId } from './tmux.js'-import { sameProcessIdentity } from './terminalRuntime.js'+import { findLiveSession, findResumedTranscript, processSessionEvidence, type RepairedSession } from './sessionRepair.js'+import { resumeSessionId } from './tmux.js'+import { readProcessEvidence } from './processEvidence.js'+import { NativeEvidenceBudget } from '../engines/kit/nativeEvidence.js'import { isTerminalEngine } from '../engines/types.js'export async function captureResumeIdentity(session: RegisteredSession): Promise<RegisteredSession> {@@ -29,17 +30,24 @@ export async function captureResumeIdentity(session: RegisteredSession): Promise}const expected = session.processIdentityif (!expected || !session.cwd) return session- const live = (await processRows())?.find(row => sameProcessIdentity(row, expected)- && row.executable === expected.executable)- if (!live) return session- const explicit = resumeSessionId(session.engine, live.args)+ const budget = new NativeEvidenceBudget()+ const owner = await readProcessEvidence(expected.pid, budget, undefined, expected)+ const live = owner.parent+ if (!live) { await owner.verify(); return session }+ const explicit = resumeSessionId(session.engine, live.args, live.nativeArgv)// An engine whose process names its own session in a record (Claude Code's, removed at exit) is read now.- const native = await processSessionOf(session.engine, expected.pid, session.cwd, Date.parse(expected.startMarker))+ const claim = await processSessionEvidence(session.engine, expected.pid, session.cwd, Date.parse(expected.startMarker), budget)+ const native = claim.sessionconst found: RepairedSession | null = native ?? (explicit? { sessionId: explicit, transcriptPath: await findResumedTranscript(session.engine, explicit, options) ?? undefined }: await findLiveSession(session.engine, session.cwd, Date.parse(expected.startMarker), {...options, hermesHome: session.hermesHome ?? undefined, pid: expected.pid, bornOnly: true,+ expectedProcess: expected, nativeBudget: budget,}))+ // Codex's open-file finder verifies this owner, all candidate headers and its descriptor+ // pool together. Other finders still need this final process fence before a Stop may proceed.+ if (native || explicit || session.engine !== 'codex') await owner.verify()+ claim.verify()if (!found?.sessionId) return session// A file-backed engine still has to produce a transcript this daemon can point a resume at; a// database-backed one has nothing to check and is taken on its id alone.diff --git a/cli/src/lib/nativeConversation.spec.ts b/cli/src/lib/nativeConversation.spec.tsnew file mode 100644index 000000000..6dec377ab--- /dev/null+++ b/cli/src/lib/nativeConversation.spec.ts@@ -0,0 +1,245 @@+import { linkSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'+import * as fs from 'node:fs/promises'+import * as syncFs from 'node:fs'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { nativeConversationFixture } from '../testing/nativeConversationEvidence.js'+import { NativeEvidenceBudget } from '../engines/kit/nativeEvidence.js'+import { nativeOpenFileSession, type NativeConversationOptions, type NativeConversationSources } from './nativeConversation.js'++vi.mock('node:fs/promises', async original => {+ const actual = await original<typeof import('node:fs/promises')>()+ return { ...actual, open: vi.fn(actual.open), readlink: vi.fn(actual.readlink), lstat: vi.fn(actual.lstat) }+})+vi.mock('node:fs', async original => {+ const actual = await original<typeof import('node:fs')>()+ return { ...actual, closeSync: vi.fn(actual.closeSync), lstatSync: vi.fn(actual.lstatSync) }+})+const platform = Object.getOwnPropertyDescriptor(process, 'platform')!+let root: string, cwd: string, home: string, held: string[], sources: NativeConversationSources+const id = (n = 1) => `aaaaaaaa-1111-4222-8333-${String(n).padStart(12, '0')}`+const header = (sessionId = id(), folder = cwd) => JSON.stringify({ type: 'session_meta', payload: { id: sessionId, cwd: folder, source: 'cli' } }) + '\n'+function rollout(n = 1, folder = cwd, base = home): string {+ const file = join(base, 'day', `rollout-${id(n)}.jsonl`)+ mkdirSync(dirname(file), { recursive: true }); writeFileSync(file, header(id(n), folder)); return file+}+const find = (options: Pick<NativeConversationOptions, 'expected' | 'budget'> = {}) =>+ nativeOpenFileSession('codex', 42, [home], cwd, { sources, ...options })+beforeEach(async () => {+ Object.defineProperty(process, 'platform', { ...platform, value: 'linux' })+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ vi.mocked(fs.open).mockReset().mockImplementation(actual.open)+ vi.mocked(fs.readlink).mockReset().mockImplementation(actual.readlink)+ vi.mocked(fs.lstat).mockReset().mockImplementation(actual.lstat)+ const sync = await vi.importActual<typeof import('node:fs')>('node:fs')+ vi.mocked(syncFs.closeSync).mockReset().mockImplementation(sync.closeSync)+ vi.mocked(syncFs.lstatSync).mockReset().mockImplementation(sync.lstatSync)+ root = realpathSync(mkdtempSync(join(tmpdir(), 'native-conversation-')))+ cwd = join(root, 'work'); home = join(root, 'sessions'); mkdirSync(cwd); mkdirSync(home)+ held = []; sources = nativeConversationFixture(async () => held)+})+afterEach(() => { Object.defineProperty(process, 'platform', platform); vi.restoreAllMocks(); rmSync(root, { recursive: true, force: true }) })++it('deduplicates multiple descriptors, aliases and hard links for the same open file', async () => {+ const own = rollout(), alias = join(home, 'rollout-alias.jsonl'), link = join(home, 'rollout-hardlink.jsonl')+ symlinkSync(own, alias); linkSync(own, link); held = [own, own, alias, link]+ await expect(find()).resolves.toEqual({ sessionId: id(), transcriptPath: own })+})+it('holds two eligible files rather than letting Stop accept an empty identity', async () => {+ held = [rollout(1), rollout(2)]+ await expect(find()).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })+})+it.each(['missing', 'invalid', 'empty', 'wrong-id', 'unknown-folder'] as const)('cannot exclude a %s competitor to make a healthy file unique', async mode => {+ const own = rollout(1), other = rollout(2)+ held = [own, other]+ if (mode === 'missing') rmSync(other)+ if (mode === 'invalid') writeFileSync(other, '{bad')+ if (mode === 'empty') writeFileSync(other, '')+ if (mode === 'wrong-id') writeFileSync(other, header('not-an-id'))+ if (mode === 'unknown-folder') writeFileSync(other, header(id(2), join(root, 'missing')))+ await expect(find()).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })+})+it('retains excluded-header evidence until the whole pool has been read', async () => {+ const otherCwd = join(root, 'other'); mkdirSync(otherCwd)+ const own = rollout(), other = rollout(2, otherCwd); held = [own, other]+ const read = sources.descriptors+ sources.descriptors = async (...args) => {+ const pool = await read(...args)+ return { ...pool, verify: async () => { await pool.verify(); writeFileSync(other, header(id(2))) } }+ }+ await expect(find()).rejects.toThrow('header changed')+})+it('checks descriptors after asynchronous process verification so a new conversation holds', async () => {+ const own = rollout(), next = rollout(2); held = [own]+ const read = sources.processes+ sources.processes = async (...args) => {+ const proof = await read(...args)+ return { ...proof, verify: async () => { await proof.verify(); held.push(next) } }+ }+ await expect(find()).rejects.toThrow('descriptors changed')+})+it('catches ordinary ancestor replacement even when the same file inode and header survive', async () => {+ const own = rollout(), replacement = join(root, 'replacement')+ mkdirSync(replacement); linkSync(own, join(replacement, 'rollout-' + id() + '.jsonl')); held = [own]+ const read = sources.descriptors+ sources.descriptors = async (...args) => {+ const pool = await read(...args)+ return { ...pool, verify: async () => {+ await pool.verify(); renameSync(dirname(own), join(root, 'original')); renameSync(replacement, dirname(own))+ } }+ }+ await expect(find()).rejects.toThrow('path or alias changed')+})+it('binds the opened header descriptor to the process inode across a path swap and restoration', async () => {+ const own = rollout(), foreign = rollout(2); held = [own]+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ let swapped = false+ vi.mocked(fs.open).mockImplementation(async (path, flags, mode) => {+ if (String(path) !== own || swapped) return actual.open(path, flags, mode)+ swapped = true+ const file = await actual.open(foreign, flags, mode)+ // The pathname is already back to the expected file when control resumes.+ return file+ })+ await expect(find()).rejects.toThrow('not the file held by the process')+})+it('ignores appended body text while retaining the exact metadata header', async () => {+ const own = rollout(); held = [own]+ const read = sources.descriptors+ sources.descriptors = async (...args) => {+ const pool = await read(...args)+ return { ...pool, verify: async () => { await pool.verify(); writeFileSync(own, readFileSync(own, 'utf8') + '{"body":"new output"}\n') } }+ }+ await expect(find()).resolves.toEqual({ sessionId: id(), transcriptPath: own })+})+it('does not decode a partial body character after a valid header with leading blank lines', async () => {+ const own = rollout(); held = [own]+ writeFileSync(own, Buffer.concat([Buffer.from('\n\n' + header()), Buffer.from([0xc3])]))+ await expect(find()).resolves.toEqual({ sessionId: id(), transcriptPath: own })+})+it('holds path aliases that loop and pools that exceed the candidate budget', async () => {+ const loop = join(home, 'rollout-loop.jsonl'); symlinkSync(loop, loop); held = [loop]+ await expect(find()).rejects.toThrow('alias depth limit')+ const own = rollout(); held = Array(65).fill(own)+ await expect(find()).rejects.toThrow('descriptor limit')+})+it('keeps one deadline across pool inspection and final verification', async () => {+ held = [rollout()]+ await expect(find({ budget: new NativeEvidenceBudget(-1) })).rejects.toThrow('deadline')+})+it('checks core\'s expected owner before accepting the current occupant of the pid', async () => {+ held = [rollout()]+ await expect(find({ expected: { pid: 42, executable: '/fixture-tools/codex', startMarker: 'different' } })).rejects.toThrow('process changed')+})+it.each(['café', 'back\\n', 'newline\n', 'literal\\xc3\\xa9'])('uses kernel file identity to resolve macOS spelling %j', async folder => {+ Object.defineProperty(process, 'platform', { ...platform, value: 'darwin' })+ const own = rollout(1, cwd, join(home, folder)); held = [own]+ const read = sources.descriptors+ sources.descriptors = async (...args) => {+ const proof = await read(...args)+ return { ...proof, descriptors: proof.descriptors.map(row => ({ ...row,+ path: row.path.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/é/g, '\\xc3\\xa9') })) }+ }+ await expect(find()).resolves.toEqual({ sessionId: id(), transcriptPath: own })+})+it('does not round large inode values to accept a different file', async () => {+ const own = rollout(); held = [own]+ const read = sources.descriptors+ sources.descriptors = async (...args) => {+ const proof = await read(...args)+ return { ...proof, descriptors: proof.descriptors.map(row => ({ ...row, inode: statSync(own, { bigint: true }).ino + 1n })) }+ }+ await expect(find()).rejects.toThrow('does not name the process file')+})+it.each([false, 0, {}, [], { thread_spawn: {} }])('holds a malformed delegated-source claim %j', async claim => {+ const own = rollout(), other = rollout(2); held = [own, other]+ writeFileSync(other, JSON.stringify({ type: 'session_meta', payload: { id: id(2), cwd, source: { subagent: claim } } }) + '\n')+ await expect(find()).rejects.toThrow('delegated-source claim is invalid')+})+it.each([false, 0, null, [], {}, { future: 'unknown' }, { custom: '' }, { custom: 'fixture', subagent: 'review' }, 'future'].map(source => ({ source })))('holds an invalid or unknown source variant $source', async ({ source }) => {+ const own = rollout(); held = [own]+ writeFileSync(own, JSON.stringify({ type: 'session_meta', payload: { id: id(), cwd, source } }) + '\n')+ await expect(find()).rejects.toThrow('source is invalid or unknown')+})+it.each([undefined, 'cli', 'vscode', 'exec', 'mcp', 'unknown', { custom: 'fixture' }].map(source => ({ source })))('retains declared native or legacy source $source', async ({ source }) => {+ const own = rollout(); held = [own]+ writeFileSync(own, JSON.stringify({ type: 'session_meta', payload: { id: id(), cwd, source } }) + '\n')+ await expect(find()).resolves.toEqual({ sessionId: id(), transcriptPath: own })+})+it('does not exclude a malformed workspace claim to make a healthy rollout unique', async () => {+ const malformed = join(root, 'regular-file'); writeFileSync(malformed, 'not a directory')+ held = [rollout(), rollout(2, malformed)]+ await expect(find()).rejects.toThrow('folder is not a directory')+})+it('requires a valid child id even when a delegated header would otherwise be excluded', async () => {+ const own = rollout(), other = rollout(2); held = [own, other]+ writeFileSync(other, JSON.stringify({ type: 'session_meta', payload: { cwd, source: { subagent: 'review' } } }) + '\n')+ await expect(find()).rejects.toThrow('conclusive conversation id')+})+it('reads a launcher child even when the launcher holds another profile\'s rollout', async () => {+ const own = rollout(), outside = rollout(2, cwd, join(root, 'other-profile'))+ const rows = [{ pid: 42, parentPid: 1, executable: 'node', args: 'node /fixture/codex.js' },+ { pid: 43, parentPid: 42, executable: 'codex', args: 'codex' }]+ sources = nativeConversationFixture(async pid => pid === 42 ? [outside] : [own], async () => rows)+ await expect(find()).resolves.toEqual({ sessionId: id(), transcriptPath: own })+ sources = nativeConversationFixture(async pid => pid === 42 ? [rollout(2)] : [own], async () => rows)+ await expect(find()).rejects.toThrow('more than one open rollout')+})+it('rejects a symlink target borrowed during ancestor replacement even after the ancestor is restored', async () => {+ const own = rollout(), active = join(root, 'active'), spare = join(root, 'spare'), saved = join(root, 'saved')+ mkdirSync(active); mkdirSync(spare)+ symlinkSync(join(root, 'decoy'), join(active, 'bridge')); symlinkSync(home, join(spare, 'bridge'))+ held = [own]+ const read = sources.descriptors+ sources.descriptors = async (...args) => {+ const pool = await read(...args)+ return { ...pool, descriptors: pool.descriptors.map(row => ({ ...row, path: join(active, 'bridge', 'day', `rollout-${id()}.jsonl`) })) }+ }+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ vi.mocked(fs.readlink).mockImplementation(async (path, options) => {+ if (String(path) !== join(active, 'bridge')) return actual.readlink(path, options as never)+ renameSync(active, saved); renameSync(spare, active)+ try { return await actual.readlink(path, options as never) }+ finally { renameSync(active, spare); renameSync(saved, active) }+ })+ await expect(find()).rejects.toThrow('path or alias changed')+})+it('preserves a typed hold if closing the final header descriptor fails', async () => {+ held = [rollout()]+ const actual = await vi.importActual<typeof import('node:fs')>('node:fs')+ vi.mocked(syncFs.closeSync).mockImplementationOnce(fd => { actual.closeSync(fd); throw Error('fixture close failure') })+ await expect(find()).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE', message: expect.stringContaining('the native rollout header could not be closed') })+})+it('retains workspace competitors across distinct spellings of the same physical directory', async () => {+ const alias = join(root, 'other-workspace-spelling')+ held = [rollout(), rollout(2, alias)]+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ const sync = await vi.importActual<typeof import('node:fs')>('node:fs')+ vi.mocked(fs.lstat).mockImplementation((path, ...args) => actual.lstat(String(path) === alias ? cwd : path, ...args) as never)+ vi.mocked(syncFs.lstatSync).mockImplementation((path, ...args) => sync.lstatSync(String(path) === alias ? cwd : path, ...args) as never)+ await expect(find()).rejects.toThrow('more than one open rollout')+})+it('recognizes a native home through a distinct spelling of the same physical directory', async () => {+ const own = rollout(), alias = join(root, 'other-home-spelling'); held = [own]+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ const sync = await vi.importActual<typeof import('node:fs')>('node:fs')+ vi.mocked(fs.lstat).mockImplementation((path, ...args) => actual.lstat(String(path) === alias ? home : path, ...args) as never)+ vi.mocked(syncFs.lstatSync).mockImplementation((path, ...args) => sync.lstatSync(String(path) === alias ? home : path, ...args) as never)+ await expect(nativeOpenFileSession('codex', 42, [alias], cwd, { sources })).resolves.toEqual({ sessionId: id(), transcriptPath: own })+})+it.each(['descriptors', 'process'])('rechecks %s changed during the last asynchronous descriptor read', async mode => {+ const own = rollout(), next = rollout(2); held = [own]+ const rows = [{ pid: 42, parentPid: 1, executable: 'codex', args: 'codex' }]+ sources = nativeConversationFixture(async () => held, async () => rows)+ const read = sources.descriptors+ sources.descriptors = async (...args) => {+ const pool = await read(...args)+ return { ...pool, verify: async () => {+ await pool.verify()+ if (mode === 'descriptors') held = [next]+ else rows[0].args = 'codex resume a different conversation'+ } }+ }+ await expect(find()).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })+})diff --git a/cli/src/lib/nativeConversation.ts b/cli/src/lib/nativeConversation.tsnew file mode 100644index 000000000..cd5fe9e2d--- /dev/null+++ b/cli/src/lib/nativeConversation.ts@@ -0,0 +1,122 @@+/** Eager native conversation authority. Legacy search/listing helpers cannot authorize control. */+import { basename } from 'node:path'+import type { BigIntStats } from 'node:fs'+import { sessionStoreOf } from '../engines/sessionStoreContracts.js'+import type { AgentEngine } from '../engines/types.js'+import { NativeEvidenceBudget, nativeUnavailable } from '../engines/kit/nativeEvidence.js'+import { readDescriptorEvidence, descriptorPaths, descriptorKey, type DescriptorEvidence, type NativeDescriptor } from '../engines/kit/nativeDescriptors.js'+import { NativePaths, nativeFileKey } from '../engines/kit/nativePaths.js'+import { descriptorHeader } from '../engines/kit/nativeHeader.js'+import { readProcessEvidence } from './processEvidence.js'+import { argvTokens, engineProcessMatchScore } from './tmux.js'+import type { ProcessIdentity } from './terminalTypes.js'+import type { RepairedSession } from './sessionRepair.js'++export interface NativeConversationSources {+ processes: typeof readProcessEvidence+ descriptors: typeof readDescriptorEvidence+}+export interface NativeConversationOptions {+ expected?: ProcessIdentity+ budget?: NativeEvidenceBudget+ sources?: NativeConversationSources+}+const nativeSources: NativeConversationSources = { processes: readProcessEvidence, descriptors: readDescriptorEvidence }++export async function nativeOpenFiles(pid: number): Promise<string[]> {+ if (!Number.isSafeInteger(pid) || pid <= 0) return []+ const evidence = await readDescriptorEvidence(pid, new NativeEvidenceBudget())+ await evidence.verify()+ return evidence.descriptors.map(row => row.path).filter(path => path.startsWith('/'))+}++async function conversationDescriptors(engine: AgentEngine, pid: number, budget: NativeEvidenceBudget,+ { expected, sources = nativeSources }: NativeConversationOptions = {}) {+ const live = sessionStoreOf(engine)?.live+ if (!live || !('open' in live)) return { descriptors: [] as readonly NativeDescriptor[], verify: async () => {} }+ const pools: { pid: number; proof: DescriptorEvidence }[] = []+ const process = await sources.processes(pid, budget, async parent => {+ const own = await sources.descriptors(pid, budget)+ pools.push({ pid, proof: own })+ // A launcher can hold another profile's rollout while its native child owns this one.+ // Its filenames cannot establish ownership before the complete pool and headers are read.+ return [parent.executable, parent.nativeArgv?.[0] ?? argvTokens(parent.args)[0] ?? '']+ .some(path => live.open.launcher.test(basename(path)))+ }, expected)+ const children = process.children.filter(row => engineProcessMatchScore(row, engine) > 0)+ if (children.length > 1) return nativeUnavailable('more than one native child could own the conversation')+ if (children.length) pools.push({ pid: children[0].pid, proof: await sources.descriptors(children[0].pid, budget) })+ return { descriptors: pools.flatMap(pool => pool.proof.descriptors), verify: async () => {+ await process.verify()+ for (const pool of pools) await pool.proof.verify()+ // One joined native read checks process generation/image/argv and the complete numeric FD+ // pool. Alternating asynchronous ps/lsof reads always left one stale across the final await.+ await process.verifyDescriptors(new Map(pools.map(pool => [pool.pid, pool.proof.descriptors])), children[0]?.pid)+ } }+}++export async function nativeProcessFiles(engine: AgentEngine, pid: number, options: NativeConversationOptions = {}): Promise<string[]> {+ const evidence = await conversationDescriptors(engine, pid, options.budget ?? new NativeEvidenceBudget(), options)+ await evidence.verify()+ return evidence.descriptors.map(row => row.path).filter(path => path.startsWith('/'))+}++export async function nativeOpenFileSession(engine: AgentEngine, pid: number, roots: readonly string[], cwd: string,+ options: NativeConversationOptions = {},+): Promise<RepairedSession | null> {+ const store = sessionStoreOf(engine), live = store?.live+ if (!store?.first || !live || !('open' in live)) return null+ const budget = options.budget ?? new NativeEvidenceBudget()+ const evidence = await conversationDescriptors(engine, pid, budget, options)+ const paths = new NativePaths(budget)+ if (roots.length > 64) return nativeUnavailable('the native session-home limit was reached')+ const canonicalRoots: BigIntStats[] = []+ for (const root of roots) {+ const location = await paths.resolve(root, true)+ if (location && !location.info.isDirectory()) return nativeUnavailable('a native session home is not a directory')+ if (location) canonicalRoots.push(location.info)+ }+ const headers: { key: string; verify(): void }[] = [], found = new Map<string, RepairedSession>()+ let candidates = 0+ for (const descriptor of evidence.descriptors) {+ const name = descriptor.path.replace(/ \(deleted\)$/, '')+ if (!live.open.file.test(name)) continue+ if (++candidates > 64) return nativeUnavailable('the native rollout descriptor limit was reached')+ if (!/^\d+$/.test(descriptor.fd) || descriptor.path !== name || descriptor.kind !== 'REG' || descriptor.device === undefined || descriptor.inode === undefined) {+ return nativeUnavailable('an open rollout has no available regular file')+ }+ // On macOS lsof escapes names. On Linux readlink is already literal, including backslashes.+ const spellings = process.platform === 'linux' ? [name] : descriptorPaths(name)+ let location: Awaited<ReturnType<NativePaths['resolve']>> = null+ for (const spelling of spellings) {+ const candidate = await paths.resolve(spelling, true)+ if (candidate && nativeFileKey(candidate.info) === descriptorKey(descriptor)) location ??= candidate+ }+ if (!location || !location.info.isFile()) return nativeUnavailable('the open rollout pathname does not name the process file')+ if (!paths.within(location.path, canonicalRoots)) continue+ const key = descriptorKey(descriptor)+ if (headers.some(header => header.key === key)) continue+ const header = await descriptorHeader(location.path, { device: descriptor.device, inode: descriptor.inode }, store.first, budget)+ headers.push({ key, verify: header.verify })+ const meta = header.meta+ if (!('id' in store.byId) || !store.byId.id.test(meta.id)+ || (meta.parentThreadId !== null && !store.byId.id.test(meta.parentThreadId))) return nativeUnavailable('the native rollout has no conclusive conversation id')+ if (meta.isSubagent) continue+ if (!meta.cwd) return nativeUnavailable('the native rollout has no conclusive conversation folder')+ const declared = await paths.resolve(meta.cwd, true), requested = await paths.resolve(cwd, true)+ // A deleted workspace is still an exact string claim. Different missing spellings cannot+ // conclusively exclude a competitor whose old alias no longer resolves.+ if (meta.cwd !== cwd && (!declared || !requested)) return nativeUnavailable('a native conversation folder could not be compared conclusively')+ if ((declared && !declared.info.isDirectory()) || (requested && !requested.info.isDirectory())) return nativeUnavailable('a native conversation folder is not a directory')+ const same = meta.cwd === cwd || (declared && requested && nativeFileKey(declared.info) === nativeFileKey(requested.info))+ if (!same) continue+ found.set(key, { sessionId: meta.id, transcriptPath: location.path })+ }+ await evidence.verify()+ paths.verify()+ // Excluded headers stay evidence too. Check the selected header last, with no later await.+ const selected = found.size === 1 ? found.keys().next().value : undefined+ for (const header of [...headers.filter(header => header.key !== selected), ...headers.filter(header => header.key === selected)]) header.verify()+ if (found.size > 1) return nativeUnavailable('more than one open rollout could own the conversation')+ return found.values().next().value ?? null+}diff --git a/cli/src/lib/nativeProcessControl.spec.ts b/cli/src/lib/nativeProcessControl.spec.tsnew file mode 100644index 000000000..8bc6d7e62--- /dev/null+++ b/cli/src/lib/nativeProcessControl.spec.ts@@ -0,0 +1,191 @@+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'+import { createHash } from 'node:crypto'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { NativeEvidenceBudget } from '../engines/kit/nativeEvidence.js'+import { controlDescriptors, nativeProcessControl, parseNativeProcessControl } from './nativeProcessControl.js'+import { env } from '../config/env.js'++const host = vi.hoisted(() => ({ root: '', exec: vi.fn(), helper: vi.fn(), before: undefined as undefined | ((operation: string, path: string) => void) }))+vi.mock('node:os', async original => ({ ...await original<object>(), platform: () => process.platform }))+vi.mock('node:child_process', async original => ({ ...await original<object>(), execFile: host.exec }))+vi.mock('./nativeProcessImages.js', async original => ({ ...await original<object>(), bundledProcessImageHelper: host.helper }))+vi.mock('node:fs', async original => {+ const fs = await original<typeof import('node:fs')>()+ const mapped = (path: unknown) => String(path).startsWith('/proc/') ? join(host.root, String(path).slice(1)) : path+ const result = { ...fs }+ for (const method of ['openSync', 'opendirSync', 'readlinkSync', 'statSync'] as const) {+ result[method] = ((path: unknown, ...args: unknown[]) => {+ host.before?.(method, String(path))+ return Reflect.apply(fs[method], fs, [mapped(path), ...args])+ }) as never+ }+ return result+})+const platform = Object.getOwnPropertyDescriptor(process, 'platform')!+const originalRuntime = env.ADAPTER_RUNTIME_DIR+const budget = () => new NativeEvidenceBudget()+const hex = (text: string) => Buffer.from(text).toString('hex')+const regular = { fd: 3, type: 1, mode: 0o100000, device: '17', inode: '9007199254740993' }+const record = (pid = 42) => ({ pid, parentPid: 1, startSeconds: 1_790_000_000, startMicros: 123456,+ commandHex: hex('codex'), imageHex: hex('/fixture/codex'), commandDigest: 'a'.repeat(64), fds: [regular] })+const output = (row: unknown = record(), header: unknown = { schema: 2, mode: 'control', parent: 0, children: [] }) => `${JSON.stringify(header)}\n${JSON.stringify(row)}\n`+const parse = (text: string) => parseNativeProcessControl(text, [42], 0, budget())+function file(path: string, text: string) { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text) }+function processRow(pid = 42, parent = 1, command = 'codex', ticks = 100) {+ const root = join(host.root, 'proc', String(pid))+ mkdirSync(join(root, 'fd'), { recursive: true })+ file(join(root, 'stat'), `${pid} (${command}) S ${parent} ${Array(17).fill(0).join(' ')} ${ticks}\n`)+ file(join(root, 'cmdline'), command + '\0')+ rmSync(join(root, 'exe'), { force: true }); symlinkSync('/fixture/' + command, join(root, 'exe'))+ file(join(root, 'task', String(pid), 'children'), '')+}+beforeEach(() => {+ host.root = realpathSync(mkdtempSync(join(tmpdir(), 'native-control-')))+ host.before = undefined; host.exec.mockReset(); host.helper.mockReset().mockResolvedValue({ path: '/fixture/native-helper', key: 'fixture' })+ Object.defineProperty(process, 'platform', { ...platform, value: 'darwin' })+ host.exec.mockImplementation((_path, _args, _options, callback) => callback(null, Buffer.from(output()), Buffer.alloc(0)))+})+afterEach(() => { Object.defineProperty(process, 'platform', platform); env.ADAPTER_RUNTIME_DIR = originalRuntime; vi.restoreAllMocks(); vi.unstubAllGlobals(); rmSync(host.root, { recursive: true, force: true }) })++describe('strict Darwin control protocol', () => {+ it('retains exact birth, image, command digest and lossless file keys without argv/environment text', () => {+ const snapshot = parse(output()), row = snapshot.rows.get(42)!+ expect(row).toMatchObject({ pid: 42, birth: '1790000000:123456', command: 'codex', imagePath: '/fixture/codex', commandDigest: 'a'.repeat(64) })+ expect(row.argv).toBeUndefined()+ expect(row.fds[0].inode).toBe(9007199254740993n)+ })+ it.each([+ output().slice(0, -1), output() + '{}\n', '{}\n', output(record(43)), output(null),+ output(record(), { schema: 1, mode: 'control', parent: 0, children: [] }),+ output(record(), { schema: 2, mode: 'control', parent: 0, children: [43] }),+ output({ ...record(), startMicros: 1_000_000 }), output({ ...record(), commandDigest: 'bad' }),+ output({ ...record(), imageHex: hex('relative') }), output({ ...record(), imageHex: '2fff' }),+ output({ ...record(), commandHex: hex('co\0dex') }), output({ ...record(), imageHex: 'x' }),+ output({ ...record(), fds: [regular, regular] }),+ output({ ...record(), fds: [{ ...regular, inode: '18446744073709551616' }] }),+ output({ ...record(), fds: [{ ...regular, device: '4294967296' }] }),+ output({ ...record(), fds: [{ ...regular, type: 8 }] }),+ output({ ...record(), fds: [{ ...regular, mode: 0 }] }),+ output({ ...record(), fds: [{ ...regular, type: 2 }] }),+ ])('holds incomplete or invalid native output', text => { expect(() => parse(text)).toThrow('identity is held') })+ it('requires the entire requested pool, including unique child enumeration and all descriptor slots', () => {+ const text = output(record(), { schema: 2, mode: 'control', parent: 42, children: [43, 43] })+ expect(() => parseNativeProcessControl(text, [42], 42, budget())).toThrow('child pool')+ expect(() => parseNativeProcessControl(output() + JSON.stringify(record()) + '\n', [42, 43], 0, budget())).toThrow('invalid process')+ expect(() => parse(output({ ...record(), fds: Array(4097).fill(regular) }))).toThrow('invalid process')+ })+ it.each(['unix', 'IPv4', 'IPv6', 'systm', 'NDRV', 'LINK'])('matches the proven lsof socket family %s', kind => {+ expect(controlDescriptors([{ fd: '7', path: 'irrelevant', kind }])).toBe(controlDescriptors([{ fd: '7', path: '', kind: 'SOCKET' }]))+ })+ it('rejects error or stderr even when the helper returned a complete plausible reply', async () => {+ for (const failure of ['exit', 'stderr']) {+ host.exec.mockImplementationOnce((_path, _args, _options, callback) => callback(failure === 'exit' ? Error('failed') : null,+ Buffer.from(output()), Buffer.from(failure === 'stderr' ? 'partial' : '')))+ await expect(nativeProcessControl([42], 0, budget())).rejects.toThrow('probe did not complete')+ }+ })+ it('uses the remaining deadline and stops a missing, late or failed helper without accepting an empty pool', async () => {+ await expect(nativeProcessControl([42], 0, budget())).resolves.toMatchObject({ parent: 0 })+ expect(host.exec.mock.calls[0][1]).toEqual(['--control', expect.any(String), '0', '42'])+ expect(host.exec.mock.calls[0][2]).toMatchObject({ killSignal: 'SIGKILL', timeout: expect.any(Number), maxBuffer: 5 * 1024 * 1024 })+ host.helper.mockResolvedValueOnce(null)+ await expect(nativeProcessControl([42], 0, budget())).rejects.toThrow('helper is unavailable')+ host.helper.mockImplementationOnce(() => new Promise(() => {}))+ await expect(nativeProcessControl([42], 0, new NativeEvidenceBudget(10))).rejects.toThrow('unavailable')+ host.exec.mockImplementationOnce(() => { throw Error('spawn denied') })+ await expect(nativeProcessControl([42], 0, budget())).rejects.toThrow('could not start')+ })+ it('recovers an evicted helper from pinned bytes using only control calls', async () => {+ const bytes = Buffer.alloc(64, 7)+ env.ADAPTER_RUNTIME_DIR = host.root+ vi.stubGlobal('__DARWIN_PROCESS_IMAGES__', JSON.stringify({ schema: 1, size: bytes.length, base64: bytes.toString('base64'), sha256: createHash('sha256').update(bytes).digest('hex') }))+ const actual = await vi.importActual<typeof import('./nativeProcessImages.js')>('./nativeProcessImages.js')+ host.helper.mockImplementation(actual.bundledProcessImageHelper)+ host.exec.mockImplementation((path, _args, _options, callback) => existsSync(path)+ ? callback(null, Buffer.from(output()), Buffer.alloc(0))+ : callback(Object.assign(Error('fixture executable removed'), { code: 'ENOENT' }), Buffer.alloc(0), Buffer.alloc(0)))+ await nativeProcessControl([42], 0, budget())+ const path = host.exec.mock.calls[0][0]+ unlinkSync(path)+ await expect(nativeProcessControl([42], 0, budget())).rejects.toThrow('probe did not complete')+ await expect(nativeProcessControl([42], 0, budget())).resolves.toMatchObject({ parent: 0 })+ expect(existsSync(path)).toBe(true)+ })+ it.each(['query timeout', 'missing executable', 'preparation failure'])('does not let optional discovery %s delay a healthy control request', async failure => {+ const bytes = Buffer.alloc(64, 7), sha256 = createHash('sha256').update(bytes).digest('hex')+ env.ADAPTER_RUNTIME_DIR = host.root+ vi.stubGlobal('__DARWIN_PROCESS_IMAGES__', JSON.stringify({ schema: 1, size: bytes.length, base64: bytes.toString('base64'), sha256 }))+ const actual = await vi.importActual<typeof import('./nativeProcessImages.js')>('./nativeProcessImages.js')+ host.helper.mockImplementation(actual.bundledProcessImageHelper)+ const path = join(host.root, 'process-images', sha256)+ if (failure === 'preparation failure') {+ mkdirSync(dirname(path), { mode: 0o700 })+ writeFileSync(path, 'fixture unavailable bytes', { mode: 0o500 })+ }+ host.exec.mockImplementation((_path, args, _options, callback) => args[0] === '--paths'+ ? callback(Object.assign(Error('fixture discovery failure'), { code: failure === 'query timeout' ? 'ETIMEDOUT' : 'ENOENT' }), '')+ : callback(null, Buffer.from(output()), Buffer.alloc(0)))+ expect((await actual.nativeProcessImages([42], 500)).images.size).toBe(0)+ const discoveryCalls = host.exec.mock.calls.length+ expect((await actual.nativeProcessImages([42], 500)).images.size).toBe(0)+ expect(host.exec).toHaveBeenCalledTimes(discoveryCalls) // Optional discovery still backs off.+ if (failure === 'preparation failure') {+ await expect(nativeProcessControl([42], 0, budget())).rejects.toThrow('helper is unavailable')+ expect(host.exec).not.toHaveBeenCalled()+ unlinkSync(path) // Recovery affects only this test's private file.+ }+ await expect(nativeProcessControl([42], 0, budget())).resolves.toMatchObject({ parent: 0 })+ expect(host.exec.mock.calls.at(-1)?.[1][0]).toBe('--control')+ expect(existsSync(path)).toBe(true)+ })+ it.each([[], [0], [42, 42], Array(34).fill(42)].map(pids => ({ pids })))('rejects invalid request pools before a probe', async ({ pids }) => {+ await expect(nativeProcessControl(pids, 0, budget())).rejects.toThrow('request is invalid')+ expect(host.exec).not.toHaveBeenCalled()+ })+})++describe('joined Linux control proof', () => {+ beforeEach(() => { Object.defineProperty(process, 'platform', { ...platform, value: 'linux' }); processRow() })+ it('reads only bounded proc records, preserving argv boundaries and every numeric descriptor', async () => {+ const rollout = join(host.root, 'rollout.jsonl'); file(rollout, '{}\n')+ symlinkSync(rollout, join(host.root, 'proc/42/fd/3'))+ file(join(host.root, 'proc/42/cmdline'), 'codex\0--prompt\0quote\ntext\0')+ const proof = await nativeProcessControl([42], 0, budget())+ expect(proof.rows.get(42)).toMatchObject({ argv: ['codex', '--prompt', 'quote\ntext'], birth: '100', fds: [{ fd: '3', path: rollout, kind: 'REG' }] })+ expect(host.exec).not.toHaveBeenCalled()+ })+ it('enumerates children of every thread and excludes proven zombies', async () => {+ processRow(43, 42); processRow(44, 42); processRow(45, 42)+ file(join(host.root, 'proc/42/task/42/children'), '43 ')+ file(join(host.root, 'proc/42/task/99/children'), '44 45 ')+ file(join(host.root, 'proc/45/stat'), `45 (exited) Z 42 ${Array(17).fill(0).join(' ')} 100\n`)+ expect((await nativeProcessControl([42, 43, 44], 42, budget())).children).toEqual([43, 44])+ })+ it.each(['descriptor', 'generation', 'image', 'child', 'task'])('holds a changing %s in the joined observation', async mode => {+ let calls = 0+ host.before = (operation, path) => {+ if (operation !== 'opendirSync' || path !== '/proc/42/fd' || ++calls !== 2) return+ if (mode === 'descriptor') symlinkSync('pipe:[3]', join(host.root, 'proc/42/fd/3'))+ if (mode === 'generation') file(join(host.root, 'proc/42/stat'), `42 (codex) S 1 ${Array(17).fill(0).join(' ')} 101\n`)+ if (mode === 'image') { rmSync(join(host.root, 'proc/42/exe')); symlinkSync('/different', join(host.root, 'proc/42/exe')) }+ if (mode === 'child') { processRow(43, 42); file(join(host.root, 'proc/42/task/42/children'), '43 ') }+ if (mode === 'task') file(join(host.root, 'proc/42/task/99/children'), 'bogus')+ }+ await expect(nativeProcessControl([42], 42, budget())).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })+ })+ it('holds a denied, truncated or oversized record and oversized task/descriptor pools', async () => {+ rmSync(join(host.root, 'proc/42/cmdline'))+ await expect(nativeProcessControl([42], 0, budget())).rejects.toThrow('could not be read completely')+ file(join(host.root, 'proc/42/cmdline'), 'codex')+ await expect(nativeProcessControl([42], 0, budget())).rejects.toThrow('command is incomplete')+ file(join(host.root, 'proc/42/cmdline'), 'c'.repeat(65_537))+ await expect(nativeProcessControl([42], 0, budget())).rejects.toThrow('byte limit')+ file(join(host.root, 'proc/42/cmdline'), 'codex\0')+ for (let i = 100; i < 228; i++) file(join(host.root, 'proc/42/task', String(i), 'children'), '')+ await expect(nativeProcessControl([42], 42, budget())).rejects.toThrow('directory pool')+ for (let i = 0; i < 4097; i++) symlinkSync('pipe:[1]', join(host.root, 'proc/42/fd', String(i)))+ await expect(nativeProcessControl([42], 0, budget())).rejects.toThrow('directory pool')+ })+})diff --git a/cli/src/lib/nativeProcessControl.ts b/cli/src/lib/nativeProcessControl.tsnew file mode 100644index 000000000..91fecd725--- /dev/null+++ b/cli/src/lib/nativeProcessControl.ts@@ -0,0 +1,237 @@+/** Joined, bounded kernel evidence for control. Discovery's partial image reader is not authority. */+import { execFile } from 'node:child_process'+import { constants, closeSync, fstatSync, openSync, opendirSync, readlinkSync, readSync, statSync } from 'node:fs'+import { IdentityReadUnavailable } from '../engines/kit/identityScan.js'+import type { NativeDescriptor } from '../engines/kit/nativeDescriptors.js'+import { NativeEvidenceBudget, nativeText, nativeUnavailable } from '../engines/kit/nativeEvidence.js'+import { bundledProcessImageHelper, invalidateProcessImageHelper } from './nativeProcessImages.js'+import { psEnv } from './childLocale.js'++export interface NativeControlRow {+ pid: number+ parentPid: number+ command: string+ imagePath: string+ argv?: readonly string[]+ commandDigest?: string+ birth: string+ fds: readonly NativeDescriptor[]+}+export interface NativeControlSnapshot {+ parent: number+ children: readonly number[]+ rows: ReadonlyMap<number, NativeControlRow>+}+export const controlIdentity = (row: Omit<NativeControlRow, 'fds'>) =>+ JSON.stringify([row.pid, row.parentPid, row.birth, row.command, row.imagePath, row.argv ?? null, row.commandDigest ?? null])+const validPid = (pid: unknown): pid is number => Number.isInteger(pid) && Number(pid) > 0 && Number(pid) <= 0x7fffffff+const sorted = (pids: readonly number[]) => [...pids].sort((a, b) => a - b).join(',')+const uint = (value: unknown, max: number) => Number.isSafeInteger(value) && Number(value) >= 0 && Number(value) <= max++/** lsof's socket family is immaterial to file ownership; every numeric FD remains in the pool. */+export function controlDescriptors(rows: readonly NativeDescriptor[]): string {+ return rows.filter(row => /^\d+$/.test(row.fd)).map(row => process.platform === 'darwin'+ ? JSON.stringify([row.fd, /^(?:unix|IPv[46]|systm|NDRV|LINK|SOCKET)$/.test(row.kind) ? 'SOCKET' : row.kind,+ String(row.device), String(row.inode)])+ : JSON.stringify([row.fd, row.path, row.kind, String(row.device), String(row.inode)])).sort().join('\n')+}++function hex(value: unknown, max: number, allowNul = false): string {+ if (typeof value !== 'string' || !value.length || value.length > max * 2 || value.length % 2 || !/^[a-f0-9]+$/.test(value)) {+ return nativeUnavailable('the native control reply contains invalid bytes')+ }+ const text = nativeText(Buffer.from(value, 'hex'))+ if (!allowNul && text.includes('\0')) return nativeUnavailable('the native control reply contains an invalid string')+ return text+}++/** No prefixes, duplicate/missing rows, permissive JSON types or rounded inode numbers. */+export function parseNativeProcessControl(output: string, pids: readonly number[], parent: number,+ budget: NativeEvidenceBudget,+): NativeControlSnapshot {+ if (!output.endsWith('\n') || Buffer.byteLength(output) > 5 * 1024 * 1024) return nativeUnavailable('the native control reply is incomplete')+ const lines = output.slice(0, -1).split('\n'), rows = new Map<number, NativeControlRow>()+ if (lines.length !== pids.length + 1) return nativeUnavailable('the native control reply has an incomplete process pool')+ const json = (text: string) => { try { return JSON.parse(text) } catch { return nativeUnavailable('the native control reply is malformed') } }+ const header = json(lines.shift()!)+ if (header?.schema !== 2 || header.mode !== 'control' || header.parent !== parent || !Array.isArray(header.children)+ || header.children.length > 32 || header.children.some((pid: unknown) => !validPid(pid) || pid === parent)+ || new Set(header.children).size !== header.children.length || (!parent && header.children.length)) {+ return nativeUnavailable('the native control reply has an ambiguous child pool')+ }+ let fds = 0+ for (const line of lines) {+ budget.step()+ const row = json(line)+ if (!row || !validPid(row.pid) || !pids.includes(row.pid) || rows.has(row.pid) || !uint(row.parentPid, 0x7fffffff)+ || !uint(row.startSeconds, Number.MAX_SAFE_INTEGER) || !row.startSeconds || !uint(row.startMicros, 999_999)+ || typeof row.commandDigest !== 'string' || !/^[a-f0-9]{64}$/.test(row.commandDigest)+ || !Array.isArray(row.fds) || (fds += row.fds.length) > 4096) {+ return nativeUnavailable('the native control reply has an invalid process record')+ }+ const command = hex(row.commandHex, 16), imagePath = hex(row.imageHex, 4095)+ if (!imagePath.startsWith('/') || imagePath.endsWith(' (deleted)')) {+ return nativeUnavailable('the native control command is incomplete')+ }+ const descriptors: NativeDescriptor[] = [], seen = new Set<number>()+ for (const fd of row.fds) {+ budget.step()+ if (!fd || !uint(fd.fd, 0x7fffffff) || seen.has(fd.fd) || !uint(fd.type, 11) || fd.type === 8+ || !uint(fd.mode, 0xffff) || typeof fd.device !== 'string' || !/^\d{1,10}$/.test(fd.device)+ || BigInt(fd.device) > 0xffffffffn || typeof fd.inode !== 'string' || !/^\d{1,20}$/.test(fd.inode)+ || BigInt(fd.inode) > 0xffffffffffffffffn) return nativeUnavailable('the native control descriptor is invalid')+ seen.add(fd.fd)+ const kinds: Record<number, string> = { 2: 'SOCKET', 3: 'PSXSHM', 4: 'PSXSEM', 5: 'KQUEUE', 6: 'PIPE', 7: 'FSEVENT' }+ const modes: Record<number, string> = { [0o100000]: 'REG', [0o040000]: 'DIR', [0o020000]: 'CHR', [0o060000]: 'BLK', [0o010000]: 'FIFO' }+ const kind = fd.type === 1 ? modes[fd.mode] : kinds[fd.type]+ if (!kind || (fd.type === 1 ? fd.inode === '0' : fd.mode !== 0 || fd.device !== '0' || fd.inode !== '0')) {+ return nativeUnavailable('the native control descriptor type is unavailable')+ }+ descriptors.push({ fd: String(fd.fd), path: '', kind,+ ...(fd.type === 1 ? { device: BigInt(fd.device), inode: BigInt(fd.inode) } : {}) })+ }+ rows.set(row.pid, { pid: row.pid, parentPid: row.parentPid, command, imagePath, commandDigest: row.commandDigest,+ birth: `${row.startSeconds}:${row.startMicros}`, fds: descriptors })+ }+ return { parent, children: header.children, rows }+}++export function linuxProcessStat(text: string, pid: number): { command: string; parentPid: number; state: string; startTicks: number } {+ const start = text.indexOf('('), end = text.lastIndexOf(')')+ if (start < 1 || end <= start || Number(text.slice(0, start).trim()) !== pid) return nativeUnavailable('the native process generation is malformed')+ const fields = text.slice(end + 1).trim().split(/\s+/), startTicks = Number(fields[19])+ if (!/^[A-Za-z]$/.test(fields[0] ?? '') || !/^\d+$/.test(fields[1] ?? '') || !uint(Number(fields[1]), 0x7fffffff)+ || !/^\d+$/.test(fields[19] ?? '') || !Number.isSafeInteger(startTicks)) return nativeUnavailable('the native process generation is incomplete')+ return { command: text.slice(start + 1, end), parentPid: Number(fields[1]), state: fields[0], startTicks }+}++function linuxControl(pids: readonly number[], parent: number, budget: NativeEvidenceBudget): NativeControlSnapshot {+ const bytes = (path: string, limit: number) => {+ budget.step()+ const fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK)+ try {+ if (!fstatSync(fd).isFile()) return nativeUnavailable('a native process record is not regular')+ const result = Buffer.alloc(limit + 1)+ let used = 0+ for (let calls = 0; calls < 64; calls++) {+ budget.step()+ const count = readSync(fd, result, used, Math.min(4096, result.length - used), used)+ budget.step(count); used += count+ if (used > limit) return nativeUnavailable('a native process record exceeds its byte limit')+ if (!count) return nativeText(result.subarray(0, used))+ }+ return nativeUnavailable('a native process record exceeds its read limit')+ } finally { closeSync(fd) }+ }+ const entries = (path: string, limit: number) => {+ budget.step()+ const directory = opendirSync(path, { bufferSize: 32 }), names: string[] = []+ try {+ for (;;) {+ budget.step()+ const next = directory.readSync()+ if (!next) return names+ if (!/^\d+$/.test(next.name) || names.length >= limit) return nativeUnavailable('the native directory pool exceeds its limit')+ names.push(next.name)+ }+ } finally { directory.closeSync() }+ }+ const stat = (pid: number) => linuxProcessStat(bytes(`/proc/${pid}/stat`, 8192), pid)+ const children = () => {+ if (!parent) return []+ const tasks = entries(`/proc/${parent}/task`, 128), ids: number[] = []+ if (!tasks.length) return nativeUnavailable('the native task pool is empty')+ for (const task of tasks) {+ const text = bytes(`/proc/${parent}/task/${task}/children`, 1024)+ if (!/^(?:\d+\s+)*$/.test(text)) return nativeUnavailable('the native child pool is malformed')+ for (const value of text.trim().split(/\s+/).filter(Boolean)) {+ const id = Number(value)+ if (!validPid(id) || ids.includes(id) || ids.length >= 32) return nativeUnavailable('the native child pool exceeds its limit or is ambiguous')+ const info = stat(id)+ if (info.parentPid !== parent) return nativeUnavailable('the native child changed parent')+ if (!/^[ZXx]/.test(info.state)) ids.push(id)+ }+ }+ if (entries(`/proc/${parent}/task`, 128).sort().join(',') !== tasks.sort().join(',')) return nativeUnavailable('the native task pool changed')+ return ids+ }+ const metadata = (pid: number) => {+ const before = stat(pid)+ if (/^[ZXx]/.test(before.state)) return nativeUnavailable('the native process has exited')+ budget.step()+ const imagePath = readlinkSync(`/proc/${pid}/exe`), args = bytes(`/proc/${pid}/cmdline`, 65_536)+ const after = stat(pid)+ budget.step()+ if (before.parentPid !== after.parentPid || before.startTicks !== after.startTicks || before.command !== after.command+ || /^[ZXx]/.test(after.state) || readlinkSync(`/proc/${pid}/exe`) !== imagePath) return nativeUnavailable('the native process changed during control inspection')+ if (!imagePath.startsWith('/') || imagePath.endsWith(' (deleted)') || !args.endsWith('\0') || !args[0] || args[0] === '\0') return nativeUnavailable('the native process command is incomplete')+ return { pid, parentPid: before.parentPid, command: before.command, imagePath, argv: args.slice(0, -1).split('\0'), birth: String(before.startTicks) }+ }+ const read = () => {+ const rows = new Map<number, NativeControlRow>()+ let total = 0+ for (const pid of pids) {+ const before = metadata(pid), fds: NativeDescriptor[] = []+ for (const fd of entries(`/proc/${pid}/fd`, 4096)) {+ budget.step()+ if (++total > 4096) return nativeUnavailable('the native descriptor pool exceeds its limit')+ const location = `/proc/${pid}/fd/${fd}`, path = readlinkSync(location)+ budget.step(Buffer.byteLength(path))+ if (path.startsWith('/')) {+ const info = statSync(location, { bigint: true })+ fds.push({ fd, path, kind: info.isFile() ? 'REG' : 'OTHER', device: info.dev, inode: info.ino })+ } else {+ if (!/^(?:socket:\[\d+\]|pipe:\[\d+\]|anon_inode:.*)$/.test(path)) return nativeUnavailable('a native descriptor target is unreadable')+ fds.push({ fd, path, kind: 'OTHER' })+ }+ }+ if (controlIdentity(metadata(pid)) !== controlIdentity(before)) return nativeUnavailable('the native process changed around its descriptors')+ rows.set(pid, { ...before, fds })+ }+ return rows+ }+ try {+ const firstChildren = children(), first = read(), rows = read()+ if (sorted(children()) !== sorted(firstChildren)) return nativeUnavailable('the native child pool changed during control inspection')+ for (const [pid, row] of first) {+ const now = rows.get(pid)!+ if (controlIdentity(now) !== controlIdentity(row) || controlDescriptors(now.fds) !== controlDescriptors(row.fds)) return nativeUnavailable('the native control evidence changed during inspection')+ }+ budget.step()+ return { parent, children: firstChildren, rows }+ } catch (error) {+ if (error instanceof IdentityReadUnavailable) throw error+ return nativeUnavailable('the native control evidence could not be read completely')+ }+}++/** No ps/lsof wait separates the last process and descriptor observations. This does not+ * freeze an external process; immutable core ownership is still checked by every caller. */+export async function nativeProcessControl(pids: readonly number[], parent: number, budget: NativeEvidenceBudget): Promise<NativeControlSnapshot> {+ if (!pids.length || pids.length > 33 || pids.some(pid => !validPid(pid)) || new Set(pids).size !== pids.length+ || (parent !== 0 && (!validPid(parent) || !pids.includes(parent)))) return nativeUnavailable('the native control request is invalid')+ if (process.platform === 'linux') return linuxControl(pids, parent, budget)+ if (process.platform !== 'darwin') return nativeUnavailable('native control evidence is unavailable on this platform')+ let timer: ReturnType<typeof setTimeout> | undefined+ try {+ const helper = await Promise.race([bundledProcessImageHelper({ retryUnavailable: true }), new Promise<null>(resolve => {+ timer = setTimeout(() => resolve(null), budget.remaining())+ })])+ if (!helper) return nativeUnavailable('the native control helper is unavailable')+ const timeout = budget.probe()+ const bytes = await new Promise<Buffer>((resolve, reject) => {+ execFile(helper.path, ['--control', String(Math.min(timeout, 3000)), String(parent), ...pids.map(String)],+ { encoding: 'buffer', timeout, maxBuffer: 5 * 1024 * 1024, killSignal: 'SIGKILL', env: psEnv() },+ (error, stdout, stderr) => {+ if (error && ['ENOENT', 'ENOTDIR', 'EACCES', 'ENOEXEC'].includes(String(error.code))) invalidateProcessImageHelper(helper.key)+ if (error || stderr.length) reject(new IdentityReadUnavailable('the native control probe did not complete'))+ else resolve(stdout)+ })+ })+ budget.step(bytes.length)+ return parseNativeProcessControl(nativeText(bytes), pids, parent, budget)+ } catch (error) {+ if (error instanceof IdentityReadUnavailable) throw error+ return nativeUnavailable('the native control probe could not start')+ } finally { if (timer) clearTimeout(timer) }+}diff --git a/cli/src/lib/nativeProcessImages.ts b/cli/src/lib/nativeProcessImages.tsindex 74316948c..4a83ecbb9 100644--- a/cli/src/lib/nativeProcessImages.ts+++ b/cli/src/lib/nativeProcessImages.ts@@ -135,7 +135,7 @@ export function parseNativeProcessImages(return { images, unavailable }}-async function bundledHelper(): Promise<{ path: string; key: string } | null> {+export async function bundledProcessImageHelper(options: { retryUnavailable?: boolean } = {}): Promise<{ path: string; key: string } | null> {const source = typeof __DARWIN_PROCESS_IMAGES__ === 'undefined' ? undefined : __DARWIN_PROCESS_IMAGES__if (typeof source !== 'string') return nullif (source !== artifactSource) {@@ -146,7 +146,9 @@ async function bundledHelper(): Promise<{ path: string; key: string } | null> {const artifact = artifactValueif (!artifact || typeof artifact.sha256 !== 'string') return nullconst key = `${env.ADAPTER_RUNTIME_DIR}\0${artifact.sha256}`- if ((retryAfter.get(key) ?? 0) > performance.now()) return null+ // Optional discovery backs off failed probes. Control must confirm recovery on its own+ // deadline: its healthy owner may be unrelated to the failed discovery request.+ if (!options.retryUnavailable && (retryAfter.get(key) ?? 0) > performance.now()) return nulllet helper = prepared.get(key)if (!helper) {helper = prepareProcessImageHelper(artifact, env.ADAPTER_RUNTIME_DIR)@@ -154,7 +156,7 @@ async function bundledHelper(): Promise<{ path: string; key: string } | null> {if (!path) {prepared.delete(key)retryAfter.set(key, performance.now() + 60_000)- }+ } else retryAfter.delete(key)return path})prepared.set(key, helper)@@ -163,6 +165,14 @@ async function bundledHelper(): Promise<{ path: string; key: string } | null> {return path ? { path, key } : null}+/** An evicted extracted file can be recreated from pinned bundle bytes. This forgets+ * preparation only; no process result is cached or made available by a spawn failure. */+export function invalidateProcessImageHelper(key: string, delay = 0): void {+ prepared.delete(key)+ if (delay) retryAfter.set(key, performance.now() + delay)+ else retryAfter.delete(key)+}+/** A fresh kernel query on every call. Only the immutable executable's* preparation is shared; neither images nor unavailable PID results are cached. */export async function nativeProcessImages(@@ -175,7 +185,7 @@ export async function nativeProcessImages(let timer: ReturnType<typeof setTimeout> | undefinedtry {// A slow cache filesystem must not block discovery or start a late helper.- const helper = await Promise.race([bundledHelper(), new Promise<null>(resolve => {+ const helper = await Promise.race([bundledProcessImageHelper(), new Promise<null>(resolve => {timer = setTimeout(() => resolve(null), timeout)})])const remaining = Math.floor(deadline - performance.now())@@ -187,8 +197,7 @@ export async function nativeProcessImages(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)+ invalidateProcessImageHelper(helper.key, 60_000)}resolve(result)})diff --git a/cli/src/lib/processEvidence.spec.ts b/cli/src/lib/processEvidence.spec.tsnew file mode 100644index 000000000..acf507a80--- /dev/null+++ b/cli/src/lib/processEvidence.spec.ts@@ -0,0 +1,198 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { readlink } from 'node:fs/promises'+import { NativeEvidenceBudget, nativeBytes, nativeProbe, nativeUnavailable } from '../engines/kit/nativeEvidence.js'+import { parseProcessGraph, readProcessEvidence } from './processEvidence.js'+import { engineProcessMatchScore, resumeSessionId } from './tmux.js'+import { nativeProcessControl } from './nativeProcessControl.js'++vi.mock('node:fs/promises', async original => ({ ...await original<object>(), readlink: vi.fn() }))+vi.mock('../engines/kit/nativeEvidence.js', async original => ({ ...await original<object>(), nativeBytes: vi.fn(), nativeProbe: vi.fn() }))+vi.mock('./nativeProcessControl.js', async original => ({ ...await original<object>(), nativeProcessControl: vi.fn() }))+type Process = { pid: number; parentPid: number; command: string; argv: string[]; ticks: number; state: string; marker: string; image: string }+const platform = Object.getOwnPropertyDescriptor(process, 'platform')!+const marker = 'Fri Oct 9 11:59:00 2026'+let rows: Process[]+const make = (pid = 42, parentPid = 1, command = 'codex'): Process => ({ pid, parentPid, command, argv: [command], ticks: pid * 100, state: 'S', marker, image: `/fixture/${command}` })+const graph = () => rows.map(row => `${row.pid} ${row.parentPid} ${row.state} ${row.marker}\n`).join('')+const budget = () => new NativeEvidenceBudget()+const lookup = (path: string) => {+ const row = rows.find(row => row.pid === Number(path.split('/')[2]))+ if (!row) throw new Error('fixture process disappeared')+ return row+}+beforeEach(() => {+ vi.resetAllMocks(); rows = [make()]+ Object.defineProperty(process, 'platform', { ...platform, value: 'linux' })+ vi.mocked(readlink).mockImplementation(async path => lookup(String(path)).image as never)+ vi.mocked(nativeBytes).mockImplementation(async path => {+ const row = lookup(path)+ return Buffer.from(path.endsWith('/cmdline') ? row.argv.join('\0') + '\0'+ : `${row.pid} (${row.command}) ${[row.state, row.parentPid, ...Array(17).fill(0), row.ticks].join(' ')}\n`)+ })+ vi.mocked(nativeProbe).mockImplementation(async (command, args) => {+ expect(command).toBe('ps')+ if (args.includes('-axo')) return graph()+ const row = rows.find(row => row.pid === Number(args[args.indexOf('-p') + 1]))!+ return `${row.parentPid} ${row.state} ${row.command} ${row.marker} ${row.argv.join(' ')}\n`+ })+ vi.mocked(nativeProcessControl).mockImplementation(async (pids, parent) => ({ parent,+ children: parent ? rows.filter(row => row.parentPid === parent && row.state[0] !== 'Z').map(row => row.pid) : [],+ rows: new Map(pids.map(pid => {+ const row = rows.find(row => row.pid === pid)!+ return [pid, { pid, parentPid: row.parentPid, command: row.command, imagePath: row.image,+ argv: [...row.argv], birth: process.platform === 'darwin' ? `${Date.parse(row.marker) / 1000}:123456` : String(row.ticks), fds: [] }]+ })),+ }))+})+afterEach(() => { Object.defineProperty(process, 'platform', platform); vi.restoreAllMocks() })++describe('complete process graph', () => {+ it.each(['', '42 1 S ' + marker, '42 1 S invalid\n', '42 1 S ' + marker + '\nnoise\n',+ '0 1 S ' + marker + '\n', '99999999999999 1 S ' + marker + '\n',+ `42 1 S ${marker}\n42 2 S ${marker}\n`])('holds incomplete or ambiguous graph %j', text => {+ expect(() => parseProcessGraph(text, budget())).toThrow('identity is held')+ })+ it('bounds even a syntactically valid graph', () => {+ const text = Array.from({ length: 4097 }, (_, index) => `${index + 1} 0 S ${marker}\n`).join('')+ expect(() => parseProcessGraph(text, budget())).toThrow('exceeds its limit')+ })+ it('proves absence and death separately from a failed probe, and rechecks absence', async () => {+ rows = [make(50)]+ const proof = await readProcessEvidence(42, budget())+ expect(proof.parent).toBeNull(); await proof.verify()+ rows.push(make())+ await expect(proof.verify()).rejects.toThrow('appeared')+ rows[1].state = 'Z'+ const dead = await readProcessEvidence(42, budget())+ expect(dead.parent).toBeNull(); await dead.verify()+ vi.mocked(nativeProbe).mockRejectedValueOnce(new Error('probe failed'))+ await expect(readProcessEvidence(42, budget())).rejects.toThrow('probe failed')+ })+})++describe('native process incarnation and executable', () => {+ it('preserves argv boundaries, including code, quotes and prompt newlines', async () => {+ rows[0] = { ...make(), command: 'node', image: '/fixture/node', argv: ['node', '-e', '"codex"\n\'resume\' aaaaaaaa-1111-4222-8333-000000000001'] }+ const proof = await readProcessEvidence(42, budget())+ expect(proof.parent?.nativeArgv).toEqual(rows[0].argv)+ expect(engineProcessMatchScore(proof.parent!, 'codex')).toBe(0)+ expect(resumeSessionId('codex', proof.parent!.args, proof.parent!.nativeArgv)).toBeNull()+ const id = 'aaaaaaaa-1111-4222-8333-000000000001'+ expect(resumeSessionId('codex', '', ['codex', 'resume', id])).toBe(id)+ expect(resumeSessionId('codex', '', ['codex', 'resume=' + id])).toBe(id)+ expect(resumeSessionId('codex', '', ['codex', 'fork', id])).toBeNull()+ })+ it('does not mistake clock drift for a different Linux process generation', async () => {+ const proof = await readProcessEvidence(42, budget())+ rows[0].marker = 'Fri Oct 9 11:58:00 2026'+ await expect(proof.verify()).resolves.toBeUndefined()+ })+ it.each(['ticks', 'image', 'args', 'parent', 'dead'] as const)('rejects a changed %s after inspection', async mode => {+ const proof = await readProcessEvidence(42, budget())+ if (mode === 'ticks') rows[0].ticks+++ if (mode === 'image') rows[0].image += '-new'+ if (mode === 'args') rows[0].argv.push('different')+ if (mode === 'parent') rows[0].parentPid+++ if (mode === 'dead') rows[0].state = 'Z'+ await expect(proof.verify()).rejects.toThrow('identity is held')+ })+ it('checks the process observed by core, not merely the current occupant of its pid', async () => {+ await expect(readProcessEvidence(42, budget(), undefined, { pid: 42, executable: 'codex', startMarker: marker, startTicks: 1 }))+ .rejects.toThrow('observed owner')+ })+ it('brackets argv and executable reads with kernel generation and image evidence', async () => {+ vi.mocked(readlink).mockResolvedValueOnce('/fixture/codex' as never).mockResolvedValueOnce('/fixture/other' as never)+ await expect(readProcessEvidence(42, budget())).rejects.toThrow('changed while')+ })+ it.each(['stat', 'cmdline'] as const)('holds a truncated %s record', async kind => {+ const normal = vi.mocked(nativeBytes).getMockImplementation()!+ vi.mocked(nativeBytes).mockImplementation((path, ...args) => path.endsWith('/' + kind)+ ? Promise.resolve(Buffer.from(kind === 'stat' ? '42 (codex) S 1' : 'codex')) : normal(path, ...args))+ await expect(readProcessEvidence(42, budget())).rejects.toThrow('identity is held')+ })+ it('parses comm parentheses and newlines without shifting the generation fields', async () => {+ rows[0].command = 'a (b)\nc'+ expect((await readProcessEvidence(42, budget())).parent?.startTicks).toBe(4200)+ })+ it('reads every direct child before classification and never follows grandchildren', async () => {+ rows = [make(42, 1, 'node'), make(43, 42), make(44, 42, 'other'), make(45, 43)]+ const proof = await readProcessEvidence(42, budget(), () => true)+ expect(proof.children.map(row => row.pid)).toEqual([43, 44])+ expect(vi.mocked(nativeBytes).mock.calls.every(([path]) => !path.includes('/45/'))).toBe(true)+ rows[2].ticks+++ await expect(proof.verify()).rejects.toThrow('child changed')+ })+ it('holds a new, removed or reparented child', async () => {+ rows = [make(42, 1, 'node'), make(43, 42)]+ const proof = await readProcessEvidence(42, budget(), () => true)+ rows[1].parentPid = 50+ await expect(proof.verify()).rejects.toThrow('child set changed')+ rows[1].parentPid = 42; rows.push(make(44, 42))+ await expect(proof.verify()).rejects.toThrow('child set changed')+ })+ it('caps a launcher child pool before opening every child record', async () => {+ rows = [make(), ...Array.from({ length: 33 }, (_, index) => make(index + 50, 42))]+ await expect(readProcessEvidence(42, budget(), () => true)).rejects.toThrow('direct-child limit')+ })+ it('fences the macOS command and coarse native start marker without Linux records', async () => {+ Object.defineProperty(process, 'platform', { ...platform, value: 'darwin' })+ const proof = await readProcessEvidence(42, budget())+ expect(nativeBytes).not.toHaveBeenCalled()+ rows[0].command = 'other'+ await expect(proof.verify()).rejects.toThrow('owner changed')+ })+ it('holds ambiguous macOS command output rather than inventing argv boundaries', async () => {+ Object.defineProperty(process, 'platform', { ...platform, value: 'darwin' })+ rows[0].argv.push('line\nbreak')+ await expect(readProcessEvidence(42, budget())).rejects.toThrow('command has changed ownership')+ })+ it.each(['RX', 'SX', 'R>'])('keeps the live Darwin process state %s', async state => {+ Object.defineProperty(process, 'platform', { ...platform, value: 'darwin' })+ rows[0].state = state+ expect((await readProcessEvidence(42, budget())).parent?.pid).toBe(42)+ })+ it('reads Darwin comm with the same fixed-width column position as discovery', async () => {+ Object.defineProperty(process, 'platform', { ...platform, value: 'darwin' })+ rows[0].argv.push('--no-daemon', '--prompt', 'fixture')+ await expect(readProcessEvidence(42, budget(), undefined, { pid: 42, executable: 'codex', startMarker: marker })).resolves.toMatchObject({ parent: { executable: 'codex' } })+ expect(vi.mocked(nativeProbe).mock.calls.filter(([, args]) => args.includes('-p')).every(([, args]) => args.at(-1) === 'ppid=,state=,comm=,lstart=,args=')).toBe(true)+ })+ it('rejects changed descriptors in the same final native observation as process authority', async () => {+ const proof = await readProcessEvidence(42, budget())+ await expect(proof.verifyDescriptors(new Map([[42, [{ fd: '3', path: '/rollout', kind: 'REG', device: 1n, inode: 2n }]]])))+ .rejects.toThrow('descriptor pool changed')+ rows[0].argv.push('new command')+ await expect(proof.verifyDescriptors(new Map([[42, []]]))).rejects.toThrow('owner changed')+ })+ it('rejects a changed child after a stable parent in the joined final observation', async () => {+ rows = [make(42, 1, 'node'), make(43, 42)]+ const proof = await readProcessEvidence(42, budget(), () => true)+ rows[1].ticks+++ await expect(proof.verifyDescriptors(new Map([[42, []], [43, []]]), 43)).rejects.toThrow('owner changed')+ })+})+++it('retains an unrelated Darwin ?E+ row without holding a healthy owner', async () => {+ Object.defineProperty(process, 'platform', { ...platform, value: 'darwin' })+ rows.push({ ...make(43, 99, 'other'), state: '?E+' })+ const proof = await readProcessEvidence(42, budget(), () => true)+ expect(proof.parent?.pid).toBe(42)+ expect(proof.children).toEqual([])+ await proof.verify()+ expect(vi.mocked(nativeProcessControl).mock.calls.every(([pids]) => !pids.includes(43))).toBe(true)+})+it.each(['owner', 'child'])('cannot treat an inconclusive Darwin %s state as proof of absence', async kind => {+ Object.defineProperty(process, 'platform', { ...platform, value: 'darwin' })+ const unknown = kind === 'owner' ? 42 : 43+ if (kind === 'owner') rows[0].state = '?E+'+ else rows.push({ ...make(43, 42), state: '?E+' })+ const read = vi.mocked(nativeProcessControl).getMockImplementation()!+ vi.mocked(nativeProcessControl).mockImplementation(async (...args) => {+ if (args[0].includes(unknown)) return nativeUnavailable('the fixture kernel owner is unavailable')+ return read(...args)+ })+ await expect(readProcessEvidence(42, budget(), () => true)).rejects.toMatchObject({+ code: 'IDENTITY_UNAVAILABLE', message: expect.stringContaining('kernel owner is unavailable'),+ })+})diff --git a/cli/src/lib/processEvidence.ts b/cli/src/lib/processEvidence.tsnew file mode 100644index 000000000..1524a5951--- /dev/null+++ b/cli/src/lib/processEvidence.ts@@ -0,0 +1,149 @@+/** Complete process topology for native conversation control; ordinary discovery remains best effort. */+import { readlink } from 'node:fs/promises'+import { NativeEvidenceBudget, nativeBytes, nativeProbe, nativeText, nativeUnavailable } from '../engines/kit/nativeEvidence.js'+import type { ProcessRow } from './tmux.js'+import type { ProcessIdentity } from './terminalTypes.js'+import { sameProcessIdentity } from './terminalRuntime.js'+import type { NativeDescriptor } from '../engines/kit/nativeDescriptors.js'+import { controlDescriptors, controlIdentity, linuxProcessStat, nativeProcessControl } from './nativeProcessControl.js'++type GraphRow = { pid: number; parentPid: number; state: string; startMarker: string }+export type NativeProcessRow = ProcessRow & { imagePath: string; evidence: string; controlIdentity?: string }+export interface ProcessEvidence {+ parent: NativeProcessRow | null+ children: readonly NativeProcessRow[]+ verify(selectedPid?: number): Promise<void>+ verifyDescriptors(pools: ReadonlyMap<number, readonly NativeDescriptor[]>, selectedPid?: number): Promise<void>+}+// Darwin's X is a traced/debugged modifier. Its '?' state is inconclusive: retain+// it as a possible owner/child for kernel verification, never as proven absence.+const alive = (state: string) => process.platform === 'darwin' ? state[0] !== 'Z' : !/^[ZXx]/.test(state)+const pidValue = (text: string) => {+ const value = Number(text)+ return Number.isSafeInteger(value) && value >= 0 && value <= 0x7fffffff ? value : nativeUnavailable('the native process graph has an invalid pid')+}++/** Args and command names are separate: neither can inject a second graph row. */+export function parseProcessGraph(text: string, budget: NativeEvidenceBudget): Map<number, GraphRow> {+ if (!text || !text.endsWith('\n')) return nativeUnavailable('the native process graph is incomplete')+ const rows = new Map<number, GraphRow>()+ for (const line of text.slice(0, -1).split('\n')) {+ budget.step()+ const match = /^\s*(\d+)\s+(\d+)\s+([?A-Za-z+<>NsLsl-]{1,8})\s+([A-Z][a-z]{2}\s+[A-Z][a-z]{2}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s*$/.exec(line)+ if (!match || !Number.isFinite(Date.parse(match[4]))) return nativeUnavailable('the native process graph has an unreadable row')+ const pid = pidValue(match[1]), parentPid = pidValue(match[2])+ if (!pid || rows.has(pid) || rows.size >= 4096) return nativeUnavailable('the native process graph is duplicated or exceeds its limit')+ rows.set(pid, { pid, parentPid, state: match[3], startMarker: match[4] })+ }+ return rows+}++/** The comm field can contain spaces, parentheses and newlines; kernel fields follow its final ')'. */+const linuxStat = linuxProcessStat+const linuxIdentity = (row: ReturnType<typeof linuxStat>) => `${row.parentPid}:${row.startTicks}:${alive(row.state)}:${row.command}`+const imageSignature = (row: NativeProcessRow) => `${row.pid}:${row.parentPid}:${row.startTicks ?? row.startMarker}:${row.evidence}`++async function commandEvidence(row: GraphRow, budget: NativeEvidenceBudget): Promise<NativeProcessRow> {+ if (!alive(row.state)) return nativeUnavailable('the native process has exited')+ if (process.platform === 'linux') {+ const record = `/proc/${row.pid}/stat`+ const before = linuxStat(nativeText(await nativeBytes(record, 8192, budget)), row.pid)+ if (!alive(before.state) || before.parentPid !== row.parentPid) return nativeUnavailable('the native process changed before inspection')+ budget.step()+ const imagePath = await readlink(`/proc/${row.pid}/exe`).catch(() => nativeUnavailable('the native process image could not be read'))+ const bytes = await nativeBytes(`/proc/${row.pid}/cmdline`, 64 * 1024, budget)+ if (!bytes.length || bytes[bytes.length - 1] !== 0 || !imagePath.startsWith('/') || imagePath.endsWith(' (deleted)')) {+ return nativeUnavailable('the native process command is incomplete')+ }+ const argv = nativeText(bytes).slice(0, -1).split('\0')+ if (!argv[0]) return nativeUnavailable('the native process command is empty')+ // This display string is never token authority. /proc supplies the actual argv boundaries.+ const args = argv.join(' ')+ const after = linuxStat(nativeText(await nativeBytes(record, 8192, budget)), row.pid)+ budget.step()+ const finalImage = await readlink(`/proc/${row.pid}/exe`).catch(() => '')+ budget.step()+ if (linuxIdentity(before) !== linuxIdentity(after) || finalImage !== imagePath) return nativeUnavailable('the native process changed while its command was read')+ return { ...row, executable: before.command, args, startTicks: before.startTicks, imagePath,+ nativeArgv: argv, evidence: JSON.stringify([imagePath, before.command, argv]),+ controlIdentity: controlIdentity({ pid: row.pid, parentPid: before.parentPid, command: before.command, imagePath, argv, birth: String(before.startTicks) }) }+ }+ const native = (await nativeProcessControl([row.pid], 0, budget)).rows.get(row.pid)!+ if (native.parentPid !== row.parentPid || Number(native.birth.split(':')[0]) !== Date.parse(row.startMarker) / 1000) {+ return nativeUnavailable('the native process changed before inspection')+ }+ // Keep comm before another column, exactly as discovery does. BSD ps prints the+ // entire rewritten title when comm is last, turning healthy `codex --flags` into+ // an executable mismatch with discovery's fixed-width `codex` column.+ const text = await nativeProbe('ps', ['-ww', '-p', String(row.pid), '-o', 'ppid=,state=,comm=,lstart=,args='], budget, 64 * 1024)+ if (!text.endsWith('\n') || text.includes('\0')) return nativeUnavailable('the native process command is incomplete')+ const match = /^\s*(\d+)\s+(\S+)\s+([^\r\n]+?)\s+([A-Z][a-z]{2}\s+[A-Z][a-z]{2}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+([^\r\n]*)\n$/.exec(text)+ if (!match || pidValue(match[1]) !== row.parentPid || !alive(match[2]) || match[4] !== row.startMarker) return nativeUnavailable('the native process command has changed ownership')+ const executable = match[3].trim(), args = match[5].trim()+ if (!executable || !args) return nativeUnavailable('the native process command is ambiguous')+ const after = (await nativeProcessControl([row.pid], 0, budget)).rows.get(row.pid)!+ if (controlIdentity(after) !== controlIdentity(native)) return nativeUnavailable('the native process changed while its command was read')+ return { ...row, executable, args, imagePath: native.imagePath,+ evidence: controlIdentity(native), controlIdentity: controlIdentity(native) }+}++/** Every direct child is inspected before classification. Never follow a nested tool process. */+export async function readProcessEvidence(pid: number, budget: NativeEvidenceBudget,+ includeChildren: (row: NativeProcessRow) => boolean | Promise<boolean> = () => false,+ expected?: ProcessIdentity,+): Promise<ProcessEvidence> {+ if (!Number.isSafeInteger(pid) || pid <= 0) return nativeUnavailable('the native process id is invalid')+ const graph = () => nativeProbe('ps', ['-axo', 'pid=,ppid=,state=,lstart='], budget).then(text => parseProcessGraph(text, budget))+ const first = await graph(), initial = first.get(pid)+ if (!initial || !alive(initial.state)) {+ const verify = async () => {+ const current = (await graph()).get(pid)+ if (current && alive(current.state)) nativeUnavailable('the native process appeared during inspection')+ }+ return { parent: null, children: [], verify, verifyDescriptors: async pools => {+ if (pools.size) return nativeUnavailable('an absent native owner has descriptor evidence')+ await verify()+ } }+ }+ const parent = await commandEvidence(initial, budget)+ if (expected && (!sameProcessIdentity(parent, expected) || parent.executable !== expected.executable)) {+ return nativeUnavailable('the native process no longer matches the observed owner')+ }+ const followsChildren = await includeChildren(parent)+ const childRows = followsChildren ? [...first.values()].filter(row => row.parentPid === pid && alive(row.state)) : []+ if (childRows.length > 32) return nativeUnavailable('the native direct-child limit was reached')+ const children: NativeProcessRow[] = []+ for (const child of childRows) children.push(await commandEvidence(child, budget))+ const verify = async (selectedPid?: number) => {+ const current = await graph(), now = current.get(pid)+ if (!now || !alive(now.state)) return nativeUnavailable('the native process exited during inspection')+ const nextChildren = followsChildren ? [...current.values()].filter(row => row.parentPid === pid && alive(row.state)) : []+ if (nextChildren.map(row => row.pid).sort((a, b) => a - b).join(',') !== children.map(row => row.pid).sort((a, b) => a - b).join(',')) {+ return nativeUnavailable('the native direct-child set changed during inspection')+ }+ if (imageSignature(await commandEvidence(now, budget)) !== imageSignature(parent)) {+ return nativeUnavailable('the native owner changed during inspection')+ }+ for (const prior of [...children.filter(row => row.pid !== selectedPid), ...children.filter(row => row.pid === selectedPid)]) {+ if (imageSignature(await commandEvidence(current.get(prior.pid)!, budget)) !== imageSignature(prior)) {+ return nativeUnavailable('a native child changed during inspection')+ }+ }+ }+ await verify()+ const verifyDescriptors: ProcessEvidence['verifyDescriptors'] = async (pools, selectedPid) => {+ const all = [parent, ...children.filter(row => row.pid !== selectedPid), ...children.filter(row => row.pid === selectedPid)]+ if ([...pools.keys()].some(id => !all.some(row => row.pid === id))) return nativeUnavailable('the native descriptor owner is outside the process pool')+ const current = await nativeProcessControl(all.map(row => row.pid), followsChildren ? pid : 0, budget)+ if (current.children.slice().sort((a, b) => a - b).join(',') !== children.map(row => row.pid).sort((a, b) => a - b).join(',')) {+ return nativeUnavailable('the native direct-child set changed during inspection')+ }+ for (const prior of all) {+ const now = current.rows.get(prior.pid)!+ if (!prior.controlIdentity || controlIdentity(now) !== prior.controlIdentity) return nativeUnavailable('the native owner changed during descriptor inspection')+ const pool = pools.get(prior.pid)+ if (pool && controlDescriptors(now.fds) !== controlDescriptors(pool)) return nativeUnavailable('the native descriptor pool changed during process inspection')+ }+ }+ return { parent, children, verify, verifyDescriptors }+}diff --git a/cli/src/lib/sessionRepair.bounds.spec.ts b/cli/src/lib/sessionRepair.bounds.spec.tsindex 125c9c791..9752d31ca 100644--- a/cli/src/lib/sessionRepair.bounds.spec.ts+++ b/cli/src/lib/sessionRepair.bounds.spec.ts@@ -1,3 +1,4 @@+import { nativeConversationFixture } from '../testing/nativeConversationEvidence.js'import { execFile, execFileSync } from 'node:child_process'import { constants } from 'node:buffer'import { mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, truncateSync, utimesSync, writeFileSync } from 'node:fs'@@ -19,6 +20,17 @@ vi.mock('node:child_process', async original => {return { ...actual, execFile: vi.fn(actual.execFile) }})vi.mock('./tmux.js', async original => ({ ...await original<object>(), processRows: vi.fn() }))+vi.mock('../engines/kit/nativeDescriptors.js', async original => ({ ...await original<object>(), readDescriptorEvidence: vi.fn() }))+vi.mock('./processEvidence.js', async () => {+ const { nativeConversationFixture } = await import('../testing/nativeConversationEvidence.js')+ const { processRows } = await import('./tmux.js')+ const { readDescriptorEvidence } = await import('../engines/kit/nativeDescriptors.js')+ return { readProcessEvidence: (...args: Parameters<typeof import('./processEvidence.js')['readProcessEvidence']>) => {+ const sources = nativeConversationFixture(async () => [], processRows)+ sources.descriptors = readDescriptorEvidence+ return sources.processes(...args)+ } }+})vi.mock('./deleteAgentFallback.js', () => ({ checkPidRuntime: vi.fn(), terminateDeletedAgent: vi.fn() }))const START = Date.parse('2026-10-09T00:00:00Z')@@ -149,13 +161,10 @@ describe('complete bounded evidence before choosing a conversation', () => {const other = codex ? file(join(moved, 'sessions', `rollout-${OTHER}.jsonl`), header(OTHER)): file(join(moved, 'projects', 'work', `${OTHER}.jsonl`), body())if (codex) {- // Both native OS paths are fixtures; never inspect an actual process's descriptors.- vi.mocked(fs.readdir).mockResolvedValueOnce(['0', '1'] as never)- vi.mocked(fs.readlink).mockResolvedValueOnce(own).mockResolvedValueOnce(other)- vi.mocked(execFile).mockImplementationOnce(((...args: unknown[]) => {- (args.at(-1) as (error: null, out: string, err: string) => void)(null, `n${own}\nn${other}\n`, '')- return {}- }) as never)+ const { processRows } = await import('./tmux.js')+ const { readDescriptorEvidence } = await import('../engines/kit/nativeDescriptors.js')+ vi.mocked(processRows).mockResolvedValue([{ pid: 77, parentPid: 1, executable: 'codex', args: 'codex', startMarker: new Date(START).toString() }])+ vi.mocked(readDescriptorEvidence).mockImplementation(nativeConversationFixture(async () => [own, other]).descriptors)}const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')let adopted = false@@ -198,7 +207,7 @@ describe('bounded native metadata', () => {})}await expect(repair.findLiveSession('codex', CWD, START)).rejects.toThrow('identity is held')- await expect(repair.openFileSessionOf('codex', 77, home, CWD, async () => [own, other])).rejects.toThrow('identity is held')+ await expect(repair.openFileSessionOf('codex', 77, home, CWD, { sources: nativeConversationFixture(async () => [own, other]) })).rejects.toThrow('identity is held')})it.each(['empty', 'workspace', 'run'])('holds Muse with a partly written %s identity beside a complete run', async mode => {@@ -363,7 +372,7 @@ describe('bounded native metadata', () => {})})-it.each(['Stop', 'checkpointed Stop'])('%s holds before saving, signalling or retiring when real native identity is incomplete', async action => {+it.each(['Stop', 'checkpointed Stop', 'unknown process', 'unknown descriptors', 'Claude record switch', 'Claude new record'])('%s holds before saving, signalling or retiring when real native identity is incomplete', async action => {transcript(OTHER); record('{')const row = { agentId: 'fixture-agent', engine: 'claude', sessionId: '', cwd: CWD, registeredAt: 1,runtimes: [{ backend: 'tmux', paneId: '%77' }],@@ -371,6 +380,28 @@ it.each(['Stop', 'checkpointed Stop'])('%s holds before saving, signalling or re} as RegisteredSessionconst tmux = await import('./tmux.js')vi.mocked(tmux.processRows).mockResolvedValue([{ ...row.processIdentity!, parentPid: 1, args: 'claude' }])+ let reason = 'process record is incomplete'+ if (action === 'Claude record switch' || action === 'Claude new record') {+ transcript()+ if (action === 'Claude record switch') record(validRecord())+ else rmSync(join(root, 'claude', 'sessions', '77.json'))+ let probes = 0+ vi.mocked(tmux.processRows).mockImplementation(async () => {+ // Same pid, generation, executable and argv. Only the native conversation switches+ // during the final asynchronous process probe, after the first selected record proof.+ if (++probes === 2) { await Promise.resolve(); record(validRecord(OTHER)) }+ return [{ ...row.processIdentity!, parentPid: 1, args: 'claude' }]+ })+ reason = action === 'Claude new record' ? 'native path or alias changed' : 'process records changed'+ }+ if (action === 'unknown process') { vi.mocked(tmux.processRows).mockResolvedValue(null); reason = 'process graph is incomplete' }+ if (action === 'unknown descriptors') {+ row.engine = 'codex'+ const { readDescriptorEvidence } = await import('../engines/kit/nativeDescriptors.js')+ const { IdentityReadUnavailable } = await import('../engines/kit/identityScan.js')+ vi.mocked(readDescriptorEvidence).mockRejectedValueOnce(new IdentityReadUnavailable('the descriptor probe is incomplete'))+ reason = 'descriptor probe is incomplete'+ }const { AgentRestartCoordinator } = await import('./restartAgent.js')const { createStopAgentService } = await import('./stopAgentService.js')const { terminateDeletedAgent } = await import('./deleteAgentFallback.js')@@ -382,10 +413,27 @@ it.each(['Stop', 'checkpointed Stop'])('%s holds before saving, signalling or reforgetSession: vi.fn(), markDeleted: vi.fn(), clearDeleted: vi.fn(), stopNative: vi.fn(),}await expect(createStopAgentService(deps)(row.agentId, action === 'checkpointed Stop' ? { checkpoint } : {}))- .rejects.toThrow('process record is incomplete')+ .rejects.toThrow(reason)expect(save).not.toHaveBeenCalled(); expect(checkpoint).not.toHaveBeenCalled()expect(deps.stopNative).not.toHaveBeenCalled(); expect(terminateDeletedAgent).not.toHaveBeenCalled()expect(deps.tmuxBackend!.kill).not.toHaveBeenCalled(); expect(deps.forgetSession).not.toHaveBeenCalled()expect(deps.markDeleted).not.toHaveBeenCalled(); expect(deps.registry.resolve(row.agentId)).toBe(row)expect(deps.stopJobs.size).toBe(0)})+++it('retains lossless descriptor identity when numeric stat values round two inodes together', async () => {+ const path = file(join(root, 'large-inode'), 'exact')+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ const original = await actual.stat(path)+ const version = { ...original, dev: 5, ino: 9007199254740992, fileKey: { device: 5n, inode: 9007199254740992n } }+ expect(Number(9007199254740993n)).toBe(version.ino)+ vi.mocked(fs.open).mockImplementation(async (...args) => {+ const handle = await actual.open(...args)+ vi.spyOn(handle, 'stat').mockImplementation(async (options?: { bigint?: boolean }) => options?.bigint+ ? { ...original, dev: 5n, ino: 9007199254740993n } as never+ : { ...original, dev: 5, ino: version.ino, isFile: () => true } as never)+ return handle+ })+ await expect(identityBytes(path, 64, version)).rejects.toThrow('not the file held by the process')+})diff --git a/cli/src/lib/sessionRepair.spec.ts b/cli/src/lib/sessionRepair.spec.tsindex 80f3bfeb8..48bf7bc40 100644--- a/cli/src/lib/sessionRepair.spec.ts+++ b/cli/src/lib/sessionRepair.spec.ts@@ -1,5 +1,6 @@+import { nativeConversationFixture } from '../testing/nativeConversationEvidence.js'import { afterEach, describe, expect, it, vi } from 'vitest'-import { mkdirSync, mkdtempSync, realpathSync, rmSync, utimesSync, writeFileSync } from 'fs'+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, utimesSync, writeFileSync } from 'fs'import { execFileSync, spawn } from 'child_process'import { tmpdir } from 'os'import { join } from 'path'@@ -17,6 +18,7 @@ const dirs: string[] = []afterEach(() => {for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })delete process.env.GROK_HOME+ vi.unstubAllGlobals()vi.resetModules()})@@ -512,24 +514,31 @@ describe('session repair — a Codex process names its own rollout', () => {{ pid: 50, parentPid: 1, executable: '/opt/vendor/codex', args: '/opt/vendor/codex' },{ pid: 51, parentPid: 43, executable: '/opt/vendor/codex', args: '/opt/vendor/codex' },]- await expect(processFilesOf('codex', 42, files, async () => rows)).resolves.toEqual(['/dev/null', own])- expect(files.mock.calls.map(([pid]) => pid)).toEqual([42, 43])+ await expect(processFilesOf('codex', 42, { sources: nativeConversationFixture(files, async () => rows) })).resolves.toEqual(['/dev/null', own])+ expect(files.mock.calls.map(([pid]) => pid)).toEqual([42, 43, 42, 43, 42, 43])// macOS's comm column can truncate the full Node path; argv still names the executable.- await expect(processFilesOf('codex', 42, files, async () => rows.map(row => row.pid === 42- ? { ...row, executable: '/Users/demo/.ha', args: '/Users/demo/.harness/node/bin/node /tmp/bin/codex' } : row)))+ await expect(processFilesOf('codex', 42, { sources: nativeConversationFixture(files, async () => rows.map(row => row.pid === 42+ ? { ...row, executable: '/Users/demo/.ha', args: '/Users/demo/.harness/node/bin/node /tmp/bin/codex' } : row)) })).resolves.toEqual(['/dev/null', own])- await expect(processFilesOf('codex', 42, files, async () => null)).resolves.toEqual(['/dev/null'])- await expect(processFilesOf('codex', 42, files, async () => [])).resolves.toEqual(['/dev/null'])- await expect(processFilesOf('codex', 42, files, async () => rows.filter(row => row.pid !== 43))).resolves.toEqual(['/dev/null'])- await expect(processFilesOf('codex', 42, files, async () => [...rows, { ...rows[1], pid: 44 }])).resolves.toEqual(['/dev/null'])+ await expect(processFilesOf('codex', 42, { sources: nativeConversationFixture(files, async () => null) })).rejects.toThrow('graph is incomplete')+ await expect(processFilesOf('codex', 42, { sources: nativeConversationFixture(files, async () => []) })).resolves.toEqual([])+ await expect(processFilesOf('codex', 42, { sources: nativeConversationFixture(files, async () => rows.filter(row => row.pid !== 43)) })).resolves.toEqual(['/dev/null'])+ await expect(processFilesOf('codex', 42, { sources: nativeConversationFixture(files, async () => [...rows, { ...rows[1], pid: 44 }]) })).rejects.toThrow('more than one native child')// A native process owns its file directly. No walk into the tools it launched.const table = vi.fn(async () => rows)- await expect(processFilesOf('codex', 43, files, table)).resolves.toEqual([own])- expect(table).not.toHaveBeenCalled()- await expect(processFilesOf('codex', 51, files, table)).resolves.toEqual(['/dev/null'])+ await expect(processFilesOf('codex', 43, { sources: nativeConversationFixture(files, table) })).resolves.toEqual([own])+ expect(table).toHaveBeenCalledTimes(3)+ await expect(processFilesOf('codex', 51, { sources: nativeConversationFixture(files, table) })).resolves.toEqual(['/dev/null'])})it('does not give a starting process the only sibling rollout before its own file opens', async () => {+ if (process.platform === 'darwin') {+ // Native source tests explicitly supply the same verified artifact as the bundle.+ // A missing helper is itself a held identity, never a permissive ps/lsof fallback.+ const artifact = process.env.HARNESS_PROCESS_IMAGES_ARTIFACT+ expect(artifact, 'Build the private Darwin helper for native integration tests').toBeTruthy()+ vi.stubGlobal('__DARWIN_PROCESS_IMAGES__', readFileSync(artifact!, 'utf8'))+ }const profile = tempRoot()const sibling = 'a1b2c3d4-1111-4a4a-8a8a-000000000009'writeCodexRollout(profile, sibling, CWD, Date.now())@@ -537,9 +546,15 @@ describe('session repair — a Codex process names its own rollout', () => {const { openFileSessionOf, findLiveSession } = await import('./sessionRepair.js')// October 6 full E2E: two Codex processes start together, but only one has written// its rollout yet. This process holds neither: a directory match is not ownership.- await expect(openFileSessionOf('codex', process.pid, join(profile, 'sessions'), CWD)).resolves.toBeNull()- await expect(findLiveSession('codex', CWD, Date.now() - 1_000,- { codexHome: profile, bornOnly: true, pid: process.pid })).resolves.toBeNull()+ // A private idle process has a stable empty pool. Inspecting the Vitest parent would+ // include this lookup's own short-lived ps/lsof children and cannot prove completeness.+ const starting = spawn(process.execPath, ['-e', 'console.log("ready"); setTimeout(() => process.exit(0), 30_000)'], { stdio: ['ignore', 'pipe', 'ignore'] })+ try {+ await new Promise<void>(resolve => starting.stdout!.once('data', () => resolve()))+ await expect(openFileSessionOf('codex', starting.pid!, join(profile, 'sessions'), CWD)).resolves.toBeNull()+ await expect(findLiveSession('codex', CWD, Date.now() - 1_000,+ { codexHome: profile, bornOnly: true, pid: starting.pid! })).resolves.toBeNull()+ } finally { starting.kill(); vi.unstubAllGlobals() }})it('names a fork among its siblings by the rollout its process holds open, where a scan must refuse', async () => {@@ -556,20 +571,24 @@ describe('session repair — a Codex process names its own rollout', () => {await expect(findLiveSession('codex', CWD, STARTED_AT, { codexHome: profile, bornOnly: true })).resolves.toBeNull()// The process holds one of them open, beside files that are not rollouts or not this profile's.const held = async () => [forkFile, '/dev/null', join(profile, 'notes.jsonl'), elsewhere]- await expect(openFileSessionOf('codex', 42, sessions, CWD, held)).resolves.toEqual({ sessionId: fork, transcriptPath: realpathSync(forkFile) })+ await expect(openFileSessionOf('codex', 42, sessions, CWD, { sources: nativeConversationFixture(held) })).resolves.toEqual({ sessionId: fork, transcriptPath: realpathSync(forkFile) })// Two held, or one for another folder: nothing, rather than a guess.- await expect(openFileSessionOf('codex', 42, sessions, CWD, async () => [forkFile, siblingFile])).resolves.toBeNull()- await expect(openFileSessionOf('codex', 42, sessions, '/Users/demo/elsewhere', held)).resolves.toBeNull()- await expect(openFileSessionOf('codex', 42, sessions, CWD, async () => [])).resolves.toBeNull()+ await expect(openFileSessionOf('codex', 42, sessions, CWD, { sources: nativeConversationFixture(async () => [forkFile, siblingFile]) })).rejects.toThrow('more than one open rollout')+ await expect(openFileSessionOf('codex', 42, sessions, '/Users/demo/elsewhere', { sources: nativeConversationFixture(held) })).rejects.toThrow('could not be compared conclusively')+ await expect(openFileSessionOf('codex', 42, sessions, CWD, { sources: nativeConversationFixture(async () => []) })).resolves.toBeNull()})it('reads a live process\'s open files, and binds the repair to the rollout it holds', async () => {+ if (process.platform === 'darwin') {+ expect(process.env.HARNESS_PROCESS_IMAGES_ARTIFACT, 'Build the private Darwin helper for native integration tests').toBeTruthy()+ vi.stubGlobal('__DARWIN_PROCESS_IMAGES__', readFileSync(process.env.HARNESS_PROCESS_IMAGES_ARTIFACT!, 'utf8'))+ }const profile = tempRoot()const fork = 'a1b2c3d4-1111-4a4a-8a8a-000000000006'const forkFile = writeCodexRollout(profile, fork, CWD, STARTED_AT + 1_000)writeCodexRollout(profile, 'a1b2c3d4-1111-4a4a-8a8a-000000000007', CWD, STARTED_AT + 2_000)// A stand-in for Codex: a process that keeps its rollout open.- const holder = spawn(process.execPath, ['-e', 'require("fs").openSync(process.argv[1], "r"); setInterval(() => {}, 60_000)', forkFile], { stdio: 'ignore' })+ const holder = spawn(process.execPath, ['-e', 'require("fs").openSync(process.argv[1], "r"); setTimeout(() => process.exit(0), 30_000)', forkFile], { stdio: 'ignore' })try {vi.resetModules()const { findLiveSession, openFiles } = await import('./sessionRepair.js')@@ -577,6 +596,7 @@ describe('session repair — a Codex process names its own rollout', () => {await expect(findLiveSession('codex', CWD, STARTED_AT, { codexHome: profile, bornOnly: true, pid: holder.pid! })).resolves.toEqual({ sessionId: fork, transcriptPath: realpathSync(forkFile) })expect(await openFiles(-1)).toEqual([])+ vi.unstubAllGlobals()} finally {holder.kill()}@@ -634,7 +654,7 @@ describe('session repair — homes the person moved', () => {const { openFileSessionOf, findLiveSession } = await moved(tempRoot(), codexHome)await expect(findLiveSession('codex', CWD, STARTED_AT, { bornOnly: true })).resolves.toEqual({ sessionId: id, transcriptPath: file })const roots = [join(process.env.CODEX_HOME!, 'sessions'), join(codexHome, 'sessions')]- await expect(openFileSessionOf('codex', 42, roots, CWD, async () => [file])).resolves.toEqual({ sessionId: id, transcriptPath: realpathSync(file) })+ await expect(openFileSessionOf('codex', 42, roots, CWD, { sources: nativeConversationFixture(async () => [file]) })).resolves.toEqual({ sessionId: id, transcriptPath: realpathSync(file) })// One conversation in each home for this folder: two agents, and no guess.writeCodexRollout(process.env.CODEX_HOME!, 'a1b2c3d4-1111-4a4a-8a8a-000000000102', CWD, STARTED_AT + 6_000)await expect(findLiveSession('codex', CWD, STARTED_AT, { bornOnly: true })).resolves.toBeNull()diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.tsindex d01f6fa06..1f274487b 100644--- a/cli/src/lib/sessionRepair.ts+++ b/cli/src/lib/sessionRepair.ts@@ -14,8 +14,7 @@* unbound until its next turn, which is recoverable — mis-binding is not.*/-import { execFile } from 'child_process'-import { readdir, readlink, realpath, stat } from 'fs/promises'+import { realpath, stat } from 'fs/promises'import { basename, dirname, isAbsolute, join, sep } from 'path'import { env } from '../config/env.js'import type { SessionStoreContract } from '../engines/facets/sessionStore.js'@@ -36,7 +35,11 @@ import { recordCwd } from '../engines/kit/sessionLocation.js'import { sqliteReadAll, type SqliteParam } from './sqliteRead.js'import { sqlitePreflightMessage } from './sqliteAvailability.js'import { nativeSessionRoots } from './engineHomes.js'-import { argvTokens, engineProcessMatchScore, processRows, type ProcessRow } from './tmux.js'+import { nativeOpenFileSession, type NativeConversationOptions } from './nativeConversation.js'+import type { ProcessIdentity } from './terminalTypes.js'+import { NativeEvidenceBudget } from '../engines/kit/nativeEvidence.js'+import { verifyProcessRecord } from '../engines/kit/processRecordEvidence.js'+import { NativePaths } from '../engines/kit/nativePaths.js'/*** Clock granularity only. `ps` reports start time to the second, so a file created in the same second@@ -323,7 +326,7 @@ async function storeSession(store: SessionStoreContract,cwd: string,startedAtMs: number,- opts?: { bornOnly?: boolean; pid?: number; codexHome?: string },+ opts?: { bornOnly?: boolean; pid?: number; codexHome?: string; expectedProcess?: ProcessIdentity; nativeBudget?: NativeEvidenceBudget },): Promise<RepairedSession | null> {const scan = scanMeta(engine, store.scan, cwd)if ('record' in store.live) {@@ -332,7 +335,7 @@ async function storeSession(}const sessions = repairRoots(engine, opts?.codexHome)const found = opts?.pid && 'open' in store.live- ? await openFileSessionOf(engine, opts.pid, sessions, cwd)+ ? await openFileSessionOf(engine, opts.pid, sessions, cwd, { expected: opts.expectedProcess, budget: opts.nativeBudget }): await fileEngineSession(sessions, cwd, startedAtMs, scan,{ ...opts, ...(store.scan.from === 'head' ? { excludedDirectory: store.scan.childFolder } : {}) })// The login shell may adopt another home during any native read. Its unseen candidates@@ -349,7 +352,7 @@ export async function findLiveSession(startedAtMs: number,// codexHome: the specific agent's own profile (its CODEX_HOME), when it isn't this machine's default —// see RegisteredSession.codexHome. Read only for an engine whose sessions follow one (`sessions.profile`).- opts?: { bornOnly?: boolean; pid?: number; codexHome?: string; hermesHome?: string },+ opts?: { bornOnly?: boolean; pid?: number; codexHome?: string; hermesHome?: string; expectedProcess?: ProcessIdentity; nativeBudget?: NativeEvidenceBudget },): Promise<RepairedSession | null> {const store = sessionStoreOf(engine)if (store) return storeSession(engine, store, cwd, startedAtMs, opts)@@ -574,78 +577,12 @@ export async function findResumedTranscript(return found}-/** The files a process holds open: `/proc` on Linux, `lsof` elsewhere. Empty when neither can say. */-export async function openFiles(pid: number): Promise<string[]> {- if (!Number.isSafeInteger(pid) || pid <= 0) return []- if (process.platform === 'linux') {- const fds = await readdir(`/proc/${pid}/fd`).catch(() => [] as string[])- const paths = await Promise.all(fds.map((fd) => readlink(`/proc/${pid}/fd/${fd}`).catch(() => null)))- return paths.filter((path): path is string => !!path && path.startsWith('/'))- }- const stdout = await new Promise<string>((resolve) => {- // `-Fn`: one `n<path>` line per open file. A process that is gone answers nothing.- execFile('lsof', ['-n', '-P', '-p', String(pid), '-Fn'], { timeout: 3_000 }, (_error, out) => resolve(out ?? ''))- })- return stdout.split('\n').filter((line) => line.startsWith('n/')).map((line) => line.slice(1))-}--type ProcessTable = () => Promise<readonly Pick<ProcessRow, 'pid' | 'parentPid' | 'executable' | 'args'>[] | null>--/**- * The files a process of an engine that holds its session file open (`live.open`) has open, its native child's- * too behind a launcher (the declared `launcher`, npm's Node one): the launcher holds no session file, its child- * does. October 6 ownership E2E: removing the folder guess exposed that distinction for a manually started Codex- * with no hook. Only one direct child of that engine is read, never a nested tool. Empty for another engine.- */-export async function processFilesOf(- engine: AgentEngine,- pid: number,- files: typeof openFiles = openFiles,- processes: ProcessTable = processRows,-): Promise<string[]> {- const live = sessionStoreOf(engine)?.live- if (!live || !('open' in live)) return []- const { file, launcher } = live.open- const own = await files(pid)- if (own.some(path => file.test(path))) return own- const rows = await processes()- const wrapper = rows?.find(row => row.pid === pid)- if (!wrapper || ![wrapper.executable, argvTokens(wrapper.args)[0] ?? '']- .some(path => launcher.test(basename(path)))) return own- const children = rows!.filter(row => row.parentPid === pid && engineProcessMatchScore(row, engine) > 0)- return children.length === 1 ? [...own, ...await files(children[0].pid)] : own-}--/**- * The conversation a process of an engine that holds its session file open (`live.open`) is writing: the one- * such file it holds below `sessionsRoot`, in `cwd`, never a child's. Null for another engine.- *- * The one way to name a fork's conversation when its start-up hook was lost (a daemon restart in its- * first second). `codex fork <id>` names only its source in argv, and a fork shares its source's- * folder with every sibling started near it, so a scan of that folder finds them all and must refuse- * to guess — the fork stayed without a conversation for good (e2e/chaos.e2e.ts).- */-export async function openFileSessionOf(- engine: AgentEngine,- pid: number,- sessionsRoot: string | string[],- cwd: string,- files: (pid: number) => Promise<string[]> = (one) => processFilesOf(engine, one),+/** Complete native evidence is the sole descriptor authority for discovery and Stop. */+export { nativeOpenFiles as openFiles, nativeProcessFiles as processFilesOf } from './nativeConversation.js'+export function openFileSessionOf(engine: AgentEngine, pid: number, roots: string | string[], cwd: string,+ options: NativeConversationOptions = {},): Promise<RepairedSession | null> {- const live = sessionStoreOf(engine)?.live- if (!live || !('open' in live)) return null- const roots = await Promise.all((typeof sessionsRoot === 'string' ? [sessionsRoot] : sessionsRoot)- .map((one) => realpath(one).catch(() => one)))- const found = new Map<string, RepairedSession>()- for (const path of await files(pid)) {- if (!live.open.file.test(path)) continue- const real = await realpath(path).catch(() => path)- if (!roots.some((root) => real.startsWith(`${root}${sep}`))) continue- const meta = await sessionIdentityMetaOf(engine, real)- if (!meta || meta.isSubagent || !meta.id || !meta.cwd || !await sameDir(meta.cwd, cwd)) continue- found.set(real, { sessionId: meta.id, transcriptPath: real })- }- return found.size === 1 ? [...found.values()][0] : null+ return nativeOpenFileSession(engine, pid, typeof roots === 'string' ? [roots] : roots, cwd, options)}/**@@ -655,9 +592,20 @@ export async function openFileSessionOf(* so Stop captures it before signalling the engine. Null for another engine.*/export async function processSessionOf(engine: AgentEngine, pid: number, cwd: string, startedAtMs: number): Promise<RepairedSession | null> {+ const proof = await processSessionEvidence(engine, pid, cwd, startedAtMs)+ proof.verify()+ return proof.session+}++/** Stop retains this proof across its final process probe and any fallback lookup. */+export async function processSessionEvidence(engine: AgentEngine, pid: number, cwd: string, startedAtMs: number,+ budget = new NativeEvidenceBudget(),+): Promise<{ session: RepairedSession | null; verify(): void }> {const live = sessionStoreOf(engine)?.live- if (!live || !('record' in live)) return null- if (!Number.isSafeInteger(pid) || pid <= 0 || !Number.isFinite(startedAtMs)) return null+ if (!live || !('record' in live) || !Number.isSafeInteger(pid) || pid <= 0 || !Number.isFinite(startedAtMs)) {+ return { session: null, verify() {} }+ }+ const paths = new NativePaths(budget)const rule = live.recordlet result: RepairedSession | null = nulllet selected: string | undefined@@ -669,6 +617,7 @@ export async function processSessionOf(engine: AgentEngine, pid: number, cwd: st})for (const sessions of roots) {const file = join(dirname(sessions), rule.folder, `${pid}${rule.suffix}`)+ await paths.resolve(file, true)const text = await read(file)records.push({ file, text })if (text === null) continue@@ -682,14 +631,20 @@ export async function processSessionOf(engine: AgentEngine, pid: number, cwd: st}// A conversation can change inside the same process while another home is being read.// Recheck absent/stale claims too: a newly created claim invalidates the earlier pool.- // Read the authoritative claim last: otherwise it can change while the later homes- // are being rechecked. No asynchronous work follows that final native read.+ // Read the authoritative claim last, retaining the whole pool for the caller's final fence.+ // Stop still has an asynchronous process probe to finish before it can use this claim.const recheck = [...records.filter(record => record.file !== selected), ...records.filter(record => record.file === selected)]for (const { file, text } of recheck) {if (await read(file) !== text) throw new IdentityReadUnavailable('the process records changed during discovery')}- if (repairRoots(engine).join('\0') !== roots.join('\0')) throw new IdentityReadUnavailable('the known session homes changed during discovery')- return result+ const verify = () => {+ budget.step()+ if (repairRoots(engine).join('\0') !== roots.join('\0')) throw new IdentityReadUnavailable('the known session homes changed during discovery')+ paths.verify()+ // No asynchronous work follows the selected record. This includes negative and stale claims.+ for (const { file, text } of recheck) verifyProcessRecord(file, text, budget)+ }+ return { session: result, verify }}type ProcessRecordRule = Extract<SessionStoreContract['live'], { record: unknown }>['record']diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.tsindex 68dd1315f..84e2a747c 100644--- a/cli/src/lib/tmux.ts+++ b/cli/src/lib/tmux.ts@@ -62,6 +62,8 @@ export function listPaneTitles(): Promise<Map<string, string>> {export interface ProcessRow extends ProcessIdentity {parentPid: numberargs: string+ /** Kernel argv boundaries, when available. Native control must not parse prompt text as flags. */+ nativeArgv?: readonly string[]/** Ephemeral evidence only; never persisted or sent to another machine. */imagePath?: stringimageFileKey?: string@@ -82,7 +84,8 @@ export function argvTokens(args: string): string[] {/** Discovery only needs a command prefix. Do not tokenize a shell script or* prompt suffix once per candidate engine. Keep the same token grammar as* argvTokens, but stop scanning as soon as the consumer has enough evidence. */-function argvPrefix(args: string): () => string | undefined {+function argvPrefix(args: string, nativeArgv?: readonly string[]): () => string | undefined {+ if (nativeArgv) { let index = 0; return () => nativeArgv[index++] }const pattern = new RegExp(ARGV_TOKEN)let done = falsereturn () => {@@ -145,8 +148,8 @@ function processEntrypoint(args: string, next = argvPrefix(args)): string {* In particular, Codex startup runs `codex --help` before the real resume. Adopting* that short-lived PID ends a restart too early and discovery then evicts its pane.* Only a standalone probe argument counts: prompt text and option values do not. */-function engineCapabilityProbe(args: string): boolean {- const next = argvPrefix(args)+function engineCapabilityProbe(args: string, nativeArgv?: readonly string[]): boolean {+ const next = argvPrefix(args, nativeArgv)if (!processEntrypoint(args, next)) return falseconst option = next()return (option === '--help' || option === '-h' || option === '--version' || option === '-V')@@ -705,12 +708,12 @@ export const ENGINE_PROCESS_SIGNATURES: Readonly<Record<RegisteredSession['engin}function heuristicEngineProcessMatchScore(- row: Pick<ProcessRow, 'executable' | 'args' | 'imageFileKey' | 'entrypointFileKey'>,+ row: Pick<ProcessRow, 'executable' | 'args' | 'nativeArgv' | 'imageFileKey' | 'entrypointFileKey'>,engine: RegisteredSession['engine'],ownership = agentCommandOwnershipSnapshot(),): number {const executable = basename(row.executable).toLowerCase()- const entrypoint = processEntrypoint(row.args).toLowerCase()+ const entrypoint = processEntrypoint(row.args, argvPrefix(row.args, row.nativeArgv)).toLowerCase()const entrybase = basename(entrypoint).toLowerCase()// Antigravity also ships an IDE-side `agy` inside its .app bundle. It is not the terminal engine,// even when an AGY_PATH override happens to use the same basename.@@ -768,11 +771,11 @@ export interface EngineProcessMatch {* File identity wins; basename/package rules are compatibility fallbacks for launchers and scripts.*/export function engineProcessMatch(- row: Pick<ProcessRow, 'executable' | 'args' | 'imagePath' | 'imageFileKey' | 'entrypointFileKey'>,+ row: Pick<ProcessRow, 'executable' | 'args' | 'nativeArgv' | 'imagePath' | 'imageFileKey' | 'entrypointFileKey'>,engine: RegisteredSession['engine'],ownership = agentCommandOwnershipSnapshot(),): EngineProcessMatch {- if (engineCapabilityProbe(row.args)) return { score: 0, evidence: 'none' }+ if (engineCapabilityProbe(row.args, row.nativeArgv)) return { score: 0, evidence: 'none' }const owners = engineFileOwners([row.imageFileKey, row.entrypointFileKey], ownership)if (owners.length === 1) {return owners[0] === engine@@ -799,7 +802,7 @@ export function engineProcessMatch(/** Compatibility surface for callers that only need ordering. */export function engineProcessMatchScore(- row: Pick<ProcessRow, 'executable' | 'args' | 'imagePath' | 'imageFileKey' | 'entrypointFileKey'>,+ row: Pick<ProcessRow, 'executable' | 'args' | 'nativeArgv' | 'imagePath' | 'imageFileKey' | 'entrypointFileKey'>,engine: RegisteredSession['engine'],ownership = agentCommandOwnershipSnapshot(),): number {@@ -956,9 +959,21 @@ function flagsInOrder(tokens: readonly string[], want: readonly string[]): boole}/** The session id an engine was told to resume, or null when argv does not name one. */-export function resumeSessionId(engine: RegisteredSession['engine'], args: string): string | null {+export function resumeSessionId(engine: RegisteredSession['engine'], args: string, nativeArgv?: readonly string[]): string | null {const spec = RESUME_ARGS[engine]if (!spec) return null+ if (nativeArgv) {+ if (spec.unless?.some(flag => nativeArgv.includes(flag))) return null+ for (const flag of spec.flags) {+ for (let index = 0; index < nativeArgv.length; index++) {+ const token = nativeArgv[index]+ const value = token.toLowerCase() === flag.toLowerCase() ? nativeArgv[index + 1]+ : token.toLowerCase().startsWith(`${flag.toLowerCase()}=`) ? token.slice(flag.length + 1) : undefined+ if (value && spec.id.test(value)) return value+ }+ }+ return null+ }if (spec.unless) {const tokens = argvTokens(args)if (spec.unless.some((flag) => tokens.includes(flag))) return nulldiff --git a/cli/src/testing/nativeConversationEvidence.ts b/cli/src/testing/nativeConversationEvidence.tsnew file mode 100644index 000000000..f6a37c66d--- /dev/null+++ b/cli/src/testing/nativeConversationEvidence.ts@@ -0,0 +1,62 @@+/** Private, complete evidence fixtures. They replace OS reads, never the control algorithm. */+import { stat } from 'node:fs/promises'+import { nativeUnavailable } from '../engines/kit/nativeEvidence.js'+import type { NativeDescriptor } from '../engines/kit/nativeDescriptors.js'+import type { NativeConversationSources } from '../lib/nativeConversation.js'+import type { NativeProcessRow } from '../lib/processEvidence.js'+import type { ProcessRow } from '../lib/tmux.js'+import { sameProcessIdentity } from '../lib/terminalRuntime.js'+import { controlDescriptors } from '../lib/nativeProcessControl.js'++type Row = Pick<ProcessRow, 'pid' | 'parentPid' | 'executable' | 'args'> & Partial<ProcessRow>+export function nativeConversationFixture(files: (pid: number) => Promise<string[]>,+ processes?: () => Promise<readonly Row[] | null>,+): NativeConversationSources {+ const row = (one: Row): NativeProcessRow => ({ startMarker: 'Fri Oct 9 11:59:00 2026', ...one,+ imagePath: one.imagePath ?? one.executable, evidence: JSON.stringify(one) })+ const sources: NativeConversationSources = {+ descriptors: async (pid, budget) => {+ const read = async () => {+ const names = await files(pid)+ if (names.length > 4096) return nativeUnavailable('the fixture descriptor pool is too large')+ const rows: NativeDescriptor[] = []+ for (const [index, path] of names.entries()) {+ budget.step()+ const info = await stat(path, { bigint: true }).catch(() => null)+ rows.push({ fd: String(index + 3), path, kind: !info || info.isFile() ? 'REG' : 'OTHER',+ device: info?.dev ?? 1n, inode: info?.ino ?? BigInt(pid * 4096 + index) })+ }+ return rows+ }+ const descriptors = await read()+ const text = (rows: NativeDescriptor[]) => JSON.stringify(rows, (_, value) => typeof value === 'bigint' ? String(value) : value)+ return { descriptors, verify: async () => {+ if (text(await read()) !== text(descriptors)) nativeUnavailable('the fixture descriptors changed')+ } }+ },+ processes: async (pid, budget, includeChildren = () => false, expected) => {+ const read = async () => {+ budget.step()+ const rows = processes ? await processes() : [{ pid, parentPid: 1, executable: '/fixture-tools/codex', args: 'codex' }]+ if (!rows) return nativeUnavailable('the native process graph is incomplete')+ return rows.map(row)+ }+ const rows = await read(), parent = rows.find(one => one.pid === pid) ?? null+ if (parent && expected && (!sameProcessIdentity(parent, expected) || parent.executable !== expected.executable)) return nativeUnavailable('the fixture process changed')+ const follows = parent ? await includeChildren(parent) : false+ const children = follows ? rows.filter(one => one.parentPid === pid) : []+ const projection = (rows: NativeProcessRow[]) => JSON.stringify(rows.filter(one => one.pid === pid || (follows && one.parentPid === pid)))+ const verify = async () => {+ if (projection(await read()) !== projection(rows)) nativeUnavailable('the fixture process changed')+ }+ return { parent, children, verify, verifyDescriptors: async pools => {+ await verify()+ for (const [owner, before] of pools) {+ const now = await sources.descriptors(owner, budget)+ if (controlDescriptors(now.descriptors) !== controlDescriptors(before)) nativeUnavailable('the fixture descriptors changed')+ }+ } }+ },+ }+ return sources+}diff --git a/docs/research/2026-10-09-native-descriptor-cost.json b/docs/research/2026-10-09-native-descriptor-cost.jsonnew file mode 100644index 000000000..3bd6838a7--- /dev/null+++ b/docs/research/2026-10-09-native-descriptor-cost.json@@ -0,0 +1,823 @@+{+ "startedAt": "2026-10-10T00:20:09.836589+00:00",+ "finishedAt": "2026-10-10T00:21:16.562389+00:00",+ "formerSource": "5b2be2586ab0e50a857ffe3378adc378060ffcf3",+ "currentSource": "03bb04f5266d503e2fe745f1ef1e41b9a8cc9589",+ "processCount": 30,+ "callsPerProcess": 5,+ "quantileConvention": "sorted[floor((n-1)*p)]",+ "samples": [+ {+ "workload": "one",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 172.0074,+ 169.1529,+ 168.2557,+ 168.7189,+ 169.1506+ ],+ "cpuMs": 12.288,+ "peakRssMiB": 94.0078125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "former",+ "repeat": 0,+ "wholeProcessWallMs": 1236.388651188463,+ "wholeProcessCpuMs": 1368.356+ },+ {+ "workload": "one",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 1169.4033,+ 515.3629,+ 534.8183,+ 509.1663,+ 505.9962+ ],+ "cpuMs": 138.3,+ "peakRssMiB": 103.65234375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "current",+ "repeat": 0,+ "wholeProcessWallMs": 3599.7926210984588,+ "wholeProcessCpuMs": 3121.056+ },+ {+ "workload": "duplicate",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 173.7415,+ 170.1411,+ 171.0964,+ 172.1451,+ 169.3039+ ],+ "cpuMs": 14.456,+ "peakRssMiB": 95.921875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "former",+ "repeat": 0,+ "wholeProcessWallMs": 1201.8355820327997,+ "wholeProcessCpuMs": 1316.1389999999997+ },+ {+ "workload": "duplicate",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 799.7955,+ 512.3228,+ 507.7611,+ 513.1433,+ 505.5341+ ],+ "cpuMs": 137.005,+ "peakRssMiB": 104.05859375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "current",+ "repeat": 0,+ "wholeProcessWallMs": 3191.3781040348113,+ "wholeProcessCpuMs": 3061.2530000000006+ },+ {+ "workload": "competing",+ "iterations": 5,+ "outcomes": {+ "empty": 5+ },+ "holds": [],+ "latenciesMs": [+ 172.4985,+ 168.9362,+ 168.349,+ 168.7892,+ 171.0296+ ],+ "cpuMs": 14.175,+ "peakRssMiB": 95.515625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "former",+ "repeat": 0,+ "wholeProcessWallMs": 1194.3191229365766,+ "wholeProcessCpuMs": 1303.9569999999987+ },+ {+ "workload": "competing",+ "iterations": 5,+ "outcomes": {+ "held": 5+ },+ "holds": [+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation."+ ],+ "latenciesMs": [+ 797.3283,+ 506.5648,+ 511.6254,+ 508.9164,+ 505.2044+ ],+ "cpuMs": 137.961,+ "peakRssMiB": 108.80078125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "current",+ "repeat": 0,+ "wholeProcessWallMs": 3187.6896638423204,+ "wholeProcessCpuMs": 3060.3630000000026+ },+ {+ "workload": "one",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 791.8722,+ 503.5982,+ 509.586,+ 502.3817,+ 505.4674+ ],+ "cpuMs": 132.352,+ "peakRssMiB": 103.73046875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "current",+ "repeat": 1,+ "wholeProcessWallMs": 3168.405038304627,+ "wholeProcessCpuMs": 3038.8649999999975+ },+ {+ "workload": "one",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 170.6877,+ 169.2673,+ 176.1874,+ 169.5407,+ 170.1227+ ],+ "cpuMs": 12.203,+ "peakRssMiB": 96.16796875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "former",+ "repeat": 1,+ "wholeProcessWallMs": 1207.822288852185,+ "wholeProcessCpuMs": 1320.01+ },+ {+ "workload": "duplicate",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 797.291,+ 506.5197,+ 503.9559,+ 506.1163,+ 504.8387+ ],+ "cpuMs": 132.996,+ "peakRssMiB": 105.0703125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "current",+ "repeat": 1,+ "wholeProcessWallMs": 3173.7845139577985,+ "wholeProcessCpuMs": 3039.308000000002+ },+ {+ "workload": "duplicate",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 171.5934,+ 170.3639,+ 169.5574,+ 169.4989,+ 169.1871+ ],+ "cpuMs": 14.326,+ "peakRssMiB": 92.20703125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "former",+ "repeat": 1,+ "wholeProcessWallMs": 1201.0723878629506,+ "wholeProcessCpuMs": 1323.5139999999994+ },+ {+ "workload": "competing",+ "iterations": 5,+ "outcomes": {+ "held": 5+ },+ "holds": [+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation."+ ],+ "latenciesMs": [+ 791.2534,+ 505.3703,+ 503.4909,+ 562.7571,+ 510.5001+ ],+ "cpuMs": 139.237,+ "peakRssMiB": 104.484375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "current",+ "repeat": 1,+ "wholeProcessWallMs": 3246.1578962393105,+ "wholeProcessCpuMs": 3079.808+ },+ {+ "workload": "competing",+ "iterations": 5,+ "outcomes": {+ "empty": 5+ },+ "holds": [],+ "latenciesMs": [+ 171.3002,+ 174.1752,+ 172.5919,+ 170.9621,+ 170.7226+ ],+ "cpuMs": 15.143,+ "peakRssMiB": 96.6171875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "former",+ "repeat": 1,+ "wholeProcessWallMs": 1214.1418689861894,+ "wholeProcessCpuMs": 1329.576000000003+ },+ {+ "workload": "one",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 170.909,+ 169.0114,+ 175.8541,+ 169.9756,+ 172.7186+ ],+ "cpuMs": 12.715,+ "peakRssMiB": 94.99609375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "former",+ "repeat": 2,+ "wholeProcessWallMs": 1203.8684277795255,+ "wholeProcessCpuMs": 1314.820999999995+ },+ {+ "workload": "one",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 788.9856,+ 504.9359,+ 507.3789,+ 507.4093,+ 509.8551+ ],+ "cpuMs": 133.613,+ "peakRssMiB": 106.20703125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "current",+ "repeat": 2,+ "wholeProcessWallMs": 3178.8271660916507,+ "wholeProcessCpuMs": 3046.6280000000056+ },+ {+ "workload": "duplicate",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 171.3285,+ 168.6798,+ 168.5582,+ 168.9792,+ 170.4366+ ],+ "cpuMs": 14.108,+ "peakRssMiB": 94.79296875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "former",+ "repeat": 2,+ "wholeProcessWallMs": 1202.5171122513711,+ "wholeProcessCpuMs": 1324.0029999999977+ },+ {+ "workload": "duplicate",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 795.5358,+ 506.9994,+ 505.6213,+ 505.6656,+ 505.2529+ ],+ "cpuMs": 137.921,+ "peakRssMiB": 101.68359375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "current",+ "repeat": 2,+ "wholeProcessWallMs": 3182.002102956176,+ "wholeProcessCpuMs": 3065.7270000000026+ },+ {+ "workload": "competing",+ "iterations": 5,+ "outcomes": {+ "empty": 5+ },+ "holds": [],+ "latenciesMs": [+ 170.9231,+ 169.4549,+ 169.3231,+ 170.891,+ 168.909+ ],+ "cpuMs": 14.382,+ "peakRssMiB": 91.88671875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "former",+ "repeat": 2,+ "wholeProcessWallMs": 1197.7533069439232,+ "wholeProcessCpuMs": 1311.001999999995+ },+ {+ "workload": "competing",+ "iterations": 5,+ "outcomes": {+ "held": 5+ },+ "holds": [+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation."+ ],+ "latenciesMs": [+ 808.2856,+ 513.9248,+ 506.8023,+ 510.4386,+ 505.0993+ ],+ "cpuMs": 142.103,+ "peakRssMiB": 107.66796875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "current",+ "repeat": 2,+ "wholeProcessWallMs": 3210.6240172870457,+ "wholeProcessCpuMs": 3083.116000000004+ },+ {+ "workload": "one",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 820.6938,+ 509.1637,+ 505.3085,+ 508.7921,+ 507.5542+ ],+ "cpuMs": 137.643,+ "peakRssMiB": 102.6328125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "current",+ "repeat": 3,+ "wholeProcessWallMs": 3212.2653909027576,+ "wholeProcessCpuMs": 3065.908999999998+ },+ {+ "workload": "one",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 171.0879,+ 168.5093,+ 168.912,+ 168.7493,+ 170.839+ ],+ "cpuMs": 12.45,+ "peakRssMiB": 97.09765625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "former",+ "repeat": 3,+ "wholeProcessWallMs": 1194.9855629354715,+ "wholeProcessCpuMs": 1314.3719999999987+ },+ {+ "workload": "duplicate",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 1004.8723,+ 525.505,+ 515.9014,+ 500.4594,+ 510.3873+ ],+ "cpuMs": 159.245,+ "peakRssMiB": 111.65234375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "current",+ "repeat": 3,+ "wholeProcessWallMs": 3521.6087796725333,+ "wholeProcessCpuMs": 3361.9249999999993+ },+ {+ "workload": "duplicate",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 172.3221,+ 170.1254,+ 170.1656,+ 170.4508,+ 169.2894+ ],+ "cpuMs": 14.552,+ "peakRssMiB": 94.125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "former",+ "repeat": 3,+ "wholeProcessWallMs": 1198.623792733997,+ "wholeProcessCpuMs": 1308.4850000000047+ },+ {+ "workload": "competing",+ "iterations": 5,+ "outcomes": {+ "held": 5+ },+ "holds": [+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation."+ ],+ "latenciesMs": [+ 798.2459,+ 513.4137,+ 506.7101,+ 507.6731,+ 504.6198+ ],+ "cpuMs": 137.932,+ "peakRssMiB": 107.69140625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "current",+ "repeat": 3,+ "wholeProcessWallMs": 3189.6598460152745,+ "wholeProcessCpuMs": 3062.9029999999916+ },+ {+ "workload": "competing",+ "iterations": 5,+ "outcomes": {+ "empty": 5+ },+ "holds": [],+ "latenciesMs": [+ 171.7811,+ 169.4175,+ 169.5682,+ 169.3236,+ 172.308+ ],+ "cpuMs": 14.42,+ "peakRssMiB": 93.73046875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "former",+ "repeat": 3,+ "wholeProcessWallMs": 1207.1407423354685,+ "wholeProcessCpuMs": 1329.293000000007+ },+ {+ "workload": "one",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 170.9423,+ 167.6045,+ 169.4886,+ 169.7393,+ 169.5783+ ],+ "cpuMs": 12.397,+ "peakRssMiB": 96.5,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "former",+ "repeat": 4,+ "wholeProcessWallMs": 1200.1481861807406,+ "wholeProcessCpuMs": 1313.3449999999982+ },+ {+ "workload": "one",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 821.1068,+ 502.5129,+ 508.6648,+ 502.5291,+ 510.3555+ ],+ "cpuMs": 135.348,+ "peakRssMiB": 102.7578125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "current",+ "repeat": 4,+ "wholeProcessWallMs": 3199.5812356472015,+ "wholeProcessCpuMs": 3045.9239999999995+ },+ {+ "workload": "duplicate",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 173.2767,+ 170.3651,+ 169.6515,+ 169.5583,+ 168.7383+ ],+ "cpuMs": 14.542,+ "peakRssMiB": 95.8671875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "former",+ "repeat": 4,+ "wholeProcessWallMs": 1200.0730680301785,+ "wholeProcessCpuMs": 1314.0040000000042+ },+ {+ "workload": "duplicate",+ "iterations": 5,+ "outcomes": {+ "bound": 5+ },+ "holds": [],+ "latenciesMs": [+ 789.3203,+ 505.9601,+ 509.0536,+ 519.3348,+ 516.4937+ ],+ "cpuMs": 134.688,+ "peakRssMiB": 105.2890625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "current",+ "repeat": 4,+ "wholeProcessWallMs": 3218.1469560600817,+ "wholeProcessCpuMs": 3079.9299999999976+ },+ {+ "workload": "competing",+ "iterations": 5,+ "outcomes": {+ "empty": 5+ },+ "holds": [],+ "latenciesMs": [+ 171.011,+ 169.9408,+ 169.975,+ 170.5364,+ 170.074+ ],+ "cpuMs": 14.296,+ "peakRssMiB": 92.6015625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "former",+ "repeat": 4,+ "wholeProcessWallMs": 1212.8505548462272,+ "wholeProcessCpuMs": 1331.1640000000011+ },+ {+ "workload": "competing",+ "iterations": 5,+ "outcomes": {+ "held": 5+ },+ "holds": [+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation.",+ "Conversation identity is held: more than one open rollout could own the conversation."+ ],+ "latenciesMs": [+ 792.3395,+ 504.8263,+ 504.478,+ 505.5195,+ 513.6121+ ],+ "cpuMs": 137.025,+ "peakRssMiB": 106.28125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "current",+ "repeat": 4,+ "wholeProcessWallMs": 3171.9114631414413,+ "wholeProcessCpuMs": 3044.826999999998+ }+ ],+ "summary": [+ {+ "source": "former",+ "workload": "one",+ "calls": 25,+ "medianMs": 169.5783,+ "p95Ms": 172.7186,+ "meanLookupCpuMs": 2.48212,+ "meanFreshProcessCpuMs": 1326.1807999999983,+ "meanPeakRssMiB": 95.75390625+ },+ {+ "source": "current",+ "workload": "one",+ "calls": 25,+ "medianMs": 508.7921,+ "p95Ms": 820.6938,+ "meanLookupCpuMs": 27.09024,+ "meanFreshProcessCpuMs": 3063.6764000000003,+ "meanPeakRssMiB": 103.79609375+ },+ {+ "source": "former",+ "workload": "duplicate",+ "calls": 25,+ "medianMs": 170.1411,+ "p95Ms": 172.3221,+ "meanLookupCpuMs": 2.87936,+ "meanFreshProcessCpuMs": 1317.2290000000012,+ "meanPeakRssMiB": 94.5828125+ },+ {+ "source": "current",+ "workload": "duplicate",+ "calls": 25,+ "medianMs": 509.0536,+ "p95Ms": 797.291,+ "meanLookupCpuMs": 28.0742,+ "meanFreshProcessCpuMs": 3121.6286000000005,+ "meanPeakRssMiB": 105.55078125+ },+ {+ "source": "former",+ "workload": "competing",+ "calls": 25,+ "medianMs": 170.5364,+ "p95Ms": 172.4985,+ "meanLookupCpuMs": 2.89664,+ "meanFreshProcessCpuMs": 1320.9984000000009,+ "meanPeakRssMiB": 94.0703125+ },+ {+ "source": "current",+ "workload": "competing",+ "calls": 25,+ "medianMs": 508.9164,+ "p95Ms": 797.3283,+ "meanLookupCpuMs": 27.77032,+ "meanFreshProcessCpuMs": 3066.2033999999994,+ "meanPeakRssMiB": 106.98515625+ }+ ]+}diff --git a/docs/research/2026-10-09-native-descriptor-evidence.md b/docs/research/2026-10-09-native-descriptor-evidence.mdnew file mode 100644index 000000000..46a6c0783--- /dev/null+++ b/docs/research/2026-10-09-native-descriptor-evidence.md@@ -0,0 +1,56 @@+# Native conversation ownership through process and descriptor evidence++A partial process or open-file listing could previously look like an empty or unique Codex conversation. Discovery could choose a sibling; Stop could save no identity before terminating the process. This change makes unavailable, ambiguous and changing native evidence a typed `IDENTITY_UNAVAILABLE` hold. Binding, Stop and Close retain the session and its reason; a later complete lookup can recover without restarting the engine. The private daemon regression verifies readiness and a sibling continue during the outage.++## Authority and bounds++The eager reader retains the expected process generation, executable, actual Linux argv, complete launcher child set, numeric descriptor pool, lossless device/inode keys, physical directory membership and every candidate header. Duplicate descriptors and hard links deduplicate by file identity. Invalid or unknown source metadata, malformed delegated claims and unreadable competing workspaces cannot make another candidate unique. macOS escaped names are resolved against kernel file keys. Directory aliases use physical identity, including case and normalization aliases; ancestor replacement and symlink target changes hold.++The final read joins process and descriptor observations, then synchronously checks path and header evidence with the selected header last. Alternating asynchronous process and descriptor probes always left one observation stale across the last wait. Linux uses bounded synchronous `/proc` reads, including children of every thread. macOS extends the existing bundled read-only helper with a strict `--control` protocol. It compares two complete bounded passes, process birth microseconds, image, command identity, descriptor table capacity, direct children and file keys. The optional discovery `--paths` protocol remains compatible.++The macOS command record can contain environment strings, and a rewritten process title can destroy its argv boundaries. The helper emits only a digest of the bounded raw command record; it never serializes those bytes as argv or environment. The existing single-row `ps` command text is bracketed by native identity checks. This follows the [XNU process-argument implementation](https://github.com/apple-oss-distributions/xnu/blob/main/bsd/kern/kern_sysctl.c); descriptor and zombie handling follow [process inspection](https://github.com/apple-oss-distributions/xnu/blob/main/bsd/kern/proc_info.c) and [libproc](https://github.com/apple-oss-distributions/xnu/blob/main/libsyscall/wrappers/libproc/libproc.c). The lsof parser validates the complete [NUL field protocol](https://lsof.readthedocs.io/en/stable/manpage/), including record terminators, owners, types and numeric fields. Errors or stderr invalidate the entire reply, even beside plausible output.++One lookup shares a three-second monotonic budget, 32,768 work operations, 16 MiB of accounted bytes and 64 subprocess probes. Additional caps cover 4,096 graph entries/descriptors, 32 children, 128 Linux threads, 64 homes/candidates, 64 KiB process commands and 256 path components. Subprocesses receive the remaining deadline and SIGKILL on timeout. Filesystem operations are bounded in count and bytes; this is bounded re-observation, not an atomic OS snapshot or a promise that the OS can cancel a blocked filesystem call.++Claude PID records retain a synchronous proof across Stop's final asynchronous process check. It rechecks the complete positive, stale and absent record pool, path ancestry and home set, with the selected record last. A same-process conversation switch during that final wait holds before checkpointing, saving, signaling, terminating or retiring anything.++Only extraction of the immutable bundled executable is cached. Process, descriptor and header results are always fresh. A deleted private helper cache produces a hold and is recreated from pinned bytes on the next control request without waiting for discovery. Existing foreign or invalid cache files are preserved. On macOS, source development without the native artifact holds strict control reads; it does not fall back to permissive process evidence. Build a fresh artifact before native source integration tests:++```sh+python3 cli/scripts/build-process-images.py --output /tmp/private-process-images.json+export HARNESS_PROCESS_IMAGES_ARTIFACT=/tmp/private-process-images.json+```++Use a fresh output filename, private test homes and tmux sockets, unset `TMUX` and `TMUX_PANE`, and run with `TZ=UTC TMPDIR=/tmp`. Portable CLI builds already require and verify the universal artifact. No release is part of this work.++## Golden, review and validation++Linux observations were committed before production changes in `f247154e6`; six healthy macOS observations followed in `b53acda12`, also before the move. The 29-observation artifact remains byte-for-byte unchanged: SHA-256 `1a3a23dde27f550b8ab0eb68d2e9cddb686722aaedc5d552563e4aa910a9778a`. Tests pin the platform, UTC, time and private filesystem; every host binary in the golden is replaced or forbidden. Former unsafe answers in the older session-store golden are explicitly asserted before named safety corrections expect a hold.++Independent review caught process/descriptor await ordering, alias replacement, malformed metadata, descriptor table growth, source-only helper recovery and the composed Claude record race. The private outage case caught BSD `ps` formatting when `comm` was the last column; using the discovery-compatible column placement preserves healthy titles. Focused regressions cover each correction. The separate reviewer also required bounded fixture lifetimes so a smoke-check timeout cannot orphan a child.++Local acceptance on October 9 passed typecheck, architecture and 589 focused assertions; 1,944 core/service assertions and 265 harnessd assertions met every 100% coverage threshold. The existing harnessd skip remains. All 29 private enginehomes, machine and 70-operation chaos cases passed, as did 57 private tmux cases; 15 vendor-dependent tmux rows were explicitly excluded. Fourteen native C checks passed, and the bundled control/cache-recovery path passed on macOS x64. Receipt: `20261009T234506.200411Z-27373`; native C reused its unchanged source/toolchain evidence from `20261009T232820.565516Z-55666`. Script-only cleanup and fixture lifetime corrections follow this receipt and receive their affected checks separately. Serial resume subsequently passed all 509 assertions with every 100% coverage threshold (`20261009T235550.255500Z-12642`); its earlier three failures came from a Hermes process fixture that lacked the strict probe reply and were retained with the correction. Nineteen deliberate broken boundaries failed by assertion after a green baseline. The first EOF mutation removed a redundant guard; the corrected mutation actually accepts a missing terminator and is caught. Final acceptance after the measured process-state correction below, the twentieth mutation and exact-head review are recorded in the PR. Unfinished or failed runs are not counted as passes.++++The next full acceptance exposed a separate dependency: optional image discovery set a 60-second helper cooldown after a failed probe, so a healthy hookless Codex could not bind. Receipt `20261010T000721.175249Z-68499` retains that failure: 28 of 29 private e2e cases passed; the other gates passed. Strict control now retries verified helper preparation within its own deadline, independently of optional discovery backoff. Three composed regressions failed before the correction and passed afterward; corrupt cached bytes remain refused. A private Darwin e2e forces optional discovery failure and requires binding before the cooldown expires. The focused correction and integrated installer check passed 122 assertions, both selected private e2e cases, typecheck and bundled control (`20261010T001738.240610Z-52368`). The twenty-first mutation removes the actual control retry opt-in. Final complete gates, mutation results and exact-head approval belong in the PR.++## Matched runtime cost++The [raw measurements](2026-10-09-native-descriptor-cost.json) compare former source `5b2be2586ab0e50a857ffe3378adc378060ffcf3` with `03bb04f5266d503e2fe745f1ef1e41b9a8cc9589`. Five interleaved repetitions per source and workload used thirty fresh Node 22.23.2 processes on the same macOS x64 host, with five calls each, UTC, `/tmp`, private homes and one owned idle descriptor holder. No other local validation ran during measurement. The [driver](../../cli/scripts/handoff-2026-10-08/native-descriptor-cost.ts) sends no engine input. Both sources bound all 25 single-file and 25 duplicate-descriptor calls. For competing rollouts, the former source returned empty on all 25 calls; the candidate held with the ambiguity reason on all 25.++| Workload | Former median / p95 | Candidate median / p95 | Former / candidate lookup CPU | Former / candidate peak RSS |+| --- | --- | --- | --- | --- |+| One rollout | 170 / 173 ms | 509 / 821 ms | 2.48 / 27.09 ms | 95.8 / 103.8 MiB |+| Duplicate descriptors | 170 / 172 ms | 509 / 797 ms | 2.88 / 28.07 ms | 94.6 / 105.6 MiB |+| Competing rollouts | 171 / 172 ms | 509 / 797 ms | 2.90 / 27.77 ms | 94.1 / 107.0 MiB |++CPU is the observer's mean per lookup; peak RSS is the mean fresh observer process peak, including startup. Fresh-process CPU, including startup and child probes, increased from about 1.32 seconds to 3.06–3.12 seconds per five-call process. The p95 convention is `sorted[floor((n-1)*0.95)]`. These scopes are separate and do not estimate whole-daemon readiness. The additional observations cost roughly 340 ms at the median and 9–13 MiB in this workload. The three-second lookup budget remains the control bound; these measurements introduce no automatic performance threshold.++Two incomplete pre-fix measurement attempts are not included as passing evidence. Each encountered a hold in the single-file workload. Recording the reason and a bounded process-table observation identified an unrelated exiting process with Darwin state `?E+`; the strict parser had rejected the entire graph. The parser now retains `?` as uncertain state and continues native verification for a relevant owner or child, rather than treating it as absent. Three regressions cover the unrelated row and uncertain owner/child refusal, and a twentieth mutation removes that support. The [Darwin process-state formatter](https://raw.githubusercontent.com/apple-oss-distributions/adv_cmds/main/ps/print.c) describes its exit and foreground modifiers. The complete final run took 66.7 seconds, from October 10 00:20:09 to 00:21:16 UTC, and passed every expected outcome.++## Timing and remaining scope++Work resumed October 9 at 22:25:51 UTC after the owner's pause. Golden preparation ended at 22:32; implementation and independent-review corrections continued through 23:45. The first complete acceptance ran 23:45:06–23:52:08 UTC, overlapping review and the isolated mutation work. Later validation, measurement, CI waiting and merge are recorded separately in the PR. Publication remains zero.++This closes the descriptor authority boundary and the newly exposed PID-record ordering race. It does not complete the [daemon core checklist](2026-10-09-daemon-core-completion.md): durable catalog writers and legacy registry callers, shared hold/retry state, launch preparation and lifecycle intent, and the remaining turn/input/Close acceptance remain separate work.