Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(codex): the atomic, never-overwrite rollout exposure primitive

Claude Code82b79490143c
diff --git a/src/core/codex-accounts-core.test.ts b/src/core/codex-accounts-core.test.ts
index 15c701d26..b72d8084f 100644
--- a/src/core/codex-accounts-core.test.ts
+++ b/src/core/codex-accounts-core.test.ts
@@ -1,7 +1,18 @@
-import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, existsSync, rmSync } from 'fs'
+import {
+ mkdtempSync,
+ mkdirSync,
+ readFileSync,
+ writeFileSync,
+ existsSync,
+ readdirSync,
+ linkSync,
+ rmSync,
+ statSync,
+ symlinkSync
+} from 'fs'
import os from 'os'
import path from 'path'
-import { describe, expect, it } from 'vitest'
+import { afterEach, describe, expect, it } from 'vitest'
import {
ACCOUNT_ID_RE,
assertCodexAccountId,
@@ -21,7 +32,10 @@ import {
remoteCodexTmuxEnvArgs,
systemCodexHome,
AUTH_ENV_STRIP,
- stripCodexAuthEnv
+ stripCodexAuthEnv,
+ planCodexRolloutExposure,
+ commitCodexRolloutExposure,
+ type CodexRolloutExposurePlan
} from './codex-accounts-core'
describe('Codex account id validation (supply-chain guard)', () => {
@@ -284,3 +298,209 @@ describe('shared id predicate stays renderer-safe', () => {
expect(/from ['"]\.\/codex-accounts-core['"]/.test(src)).toBe(false)
})
})
+
+// ---------------------------------------------------------------------------
+// Cross-account rollout exposure (S6 §5 property 2 — atomic hardlink, never-overwrite).
+// Proven against a REAL temp filesystem: real link(2)/symlink(2)/EEXIST, never a mock. The repo has
+// twice shipped a structural test that passed a real defect, so every assertion here runs the real
+// primitive under mkdtemp. Mirrors @Corvin's tests in PR #112.
+describe('cross-account rollout exposure (atomic, never-overwrite)', () => {
+ const THREAD = 'be28d3d4-c18c-430c-a257-ae550d3dd7ed'
+ // Path of the rollout RELATIVE to the account's `sessions/` root (what a plan reports back).
+ const SESSIONS_REL = path.join('2026', '08', '19', `rollout-2026-08-19T00-00-00-${THREAD}.jsonl`)
+ const REL = path.join('sessions', SESSIONS_REL)
+ const roots: string[] = []
+
+ afterEach(() => {
+ while (roots.length) rmSync(roots.pop()!, { recursive: true, force: true })
+ })
+
+ const newRoot = (): string => {
+ const root = mkdtempSync(path.join(os.tmpdir(), 'cx-rollout-'))
+ roots.push(root)
+ return root
+ }
+
+ /** A real account home whose `sessions/` tree exists; returns the home dir. */
+ const makeHome = (root: string, name: string): string => {
+ const home = path.join(root, name)
+ mkdirSync(path.join(home, 'sessions'), { recursive: true })
+ return home
+ }
+
+ /** Write a real rollout file at the canonical relative path; returns its absolute path. */
+ const writeRollout = (home: string, body = '{"line":1}\n'): string => {
+ const file = path.join(home, REL)
+ mkdirSync(path.dirname(file), { recursive: true })
+ writeFileSync(file, body)
+ return file
+ }
+
+ it('commits A to B to C as one inode and survives removal of the original account', () => {
+ const root = newRoot()
+ const homeA = makeHome(root, 'a')
+ const homeB = makeHome(root, 'b')
+ const homeC = makeHome(root, 'c')
+ const sourcePath = writeRollout(homeA)
+ const originalIno = statSync(sourcePath).ino
+
+ const planAB = planCodexRolloutExposure(homeA, homeB, sourcePath, THREAD)
+ expect(planAB.targetRelativePath).toBe(SESSIONS_REL)
+ commitCodexRolloutExposure(planAB)
+ expect(statSync(planAB.targetPath).ino).toBe(originalIno)
+
+ // Idempotent re-expose: same inode already present ⇒ no throw, still one inode.
+ expect(() => commitCodexRolloutExposure(planAB)).not.toThrow()
+ expect(statSync(planAB.targetPath).ino).toBe(originalIno)
+
+ const planBC = planCodexRolloutExposure(homeB, homeC, planAB.targetPath, THREAD)
+ commitCodexRolloutExposure(planBC)
+ expect(statSync(planBC.targetPath).ino).toBe(originalIno)
+
+ // Deleting the ORIGINAL account home leaves C's link naming the very same inode.
+ rmSync(homeA, { recursive: true, force: true })
+ expect(existsSync(planBC.targetPath)).toBe(true)
+ expect(statSync(planBC.targetPath).ino).toBe(originalIno)
+ })
+
+ it('rejects a source path outside the source account', () => {
+ const root = newRoot()
+ const homeA = makeHome(root, 'a')
+ const homeB = makeHome(root, 'b')
+ // A real regular file whose name still ends <thread>.jsonl, but OUTSIDE homeA/sessions.
+ const outside = path.join(root, `rollout-2026-08-19T00-00-00-${THREAD}.jsonl`)
+ writeFileSync(outside, '{}')
+ expect(() => planCodexRolloutExposure(homeA, homeB, outside, THREAD)).toThrow(
+ 'Source Codex rollout is outside its account home'
+ )
+ })
+
+ it('a rejected plan mutates nothing on disk', () => {
+ const root = newRoot()
+ const homeA = makeHome(root, 'a')
+ const homeB = makeHome(root, 'b')
+ const outside = path.join(root, `rollout-2026-08-19T00-00-00-${THREAD}.jsonl`)
+ writeFileSync(outside, '{}')
+ const before = readdirSync(path.join(homeB, 'sessions'))
+ expect(() => planCodexRolloutExposure(homeA, homeB, outside, THREAD)).toThrow()
+ // The plan writes nothing: the target account's sessions tree is untouched.
+ expect(readdirSync(path.join(homeB, 'sessions'))).toEqual(before)
+ })
+
+ it('refuses to overwrite a conflicting target rollout (different inode)', () => {
+ const root = newRoot()
+ const homeA = makeHome(root, 'a')
+ const homeB = makeHome(root, 'b')
+ const sourcePath = writeRollout(homeA)
+ const plan = planCodexRolloutExposure(homeA, homeB, sourcePath, THREAD)
+ // A DIFFERENT rollout (distinct inode) already occupies the target pathname.
+ mkdirSync(path.dirname(plan.targetPath), { recursive: true })
+ writeFileSync(plan.targetPath, '{"other":true}\n')
+ const foreignIno = statSync(plan.targetPath).ino
+ expect(() => commitCodexRolloutExposure(plan)).toThrow(
+ 'Target Codex account already has a different rollout for this thread'
+ )
+ // Never overwritten: the foreign inode is still what sits at the target.
+ expect(statSync(plan.targetPath).ino).toBe(foreignIno)
+ })
+
+ it('refuses a target sessions symlink without writing through it', () => {
+ const root = newRoot()
+ const homeA = makeHome(root, 'a')
+ const sourcePath = writeRollout(homeA)
+ // homeB/sessions is a SYMLINK pointing at an escape directory.
+ const homeB = path.join(root, 'b')
+ mkdirSync(homeB, { recursive: true })
+ const escape = path.join(root, 'escape')
+ mkdirSync(escape, { recursive: true })
+ symlinkSync(escape, path.join(homeB, 'sessions'))
+
+ const plan = planCodexRolloutExposure(homeA, homeB, sourcePath, THREAD)
+ expect(() => commitCodexRolloutExposure(plan)).toThrow(
+ 'Target Codex rollout path contains an unsafe directory'
+ )
+ // Nothing was written THROUGH the symlink into the escape directory.
+ expect(readdirSync(escape)).toEqual([])
+ })
+
+ it('removes its temporary link when the source inode changes before link creation', () => {
+ const root = newRoot()
+ const homeA = makeHome(root, 'a')
+ const homeB = makeHome(root, 'b')
+ const sourcePath = writeRollout(homeA)
+ const plan = planCodexRolloutExposure(homeA, homeB, sourcePath, THREAD)
+ // A pre-created, kept-alive file gives a distinct inode that cannot be recycled from the freed
+ // original (which would defeat the race we are simulating).
+ const replacement = path.join(root, 'replacement.jsonl')
+ writeFileSync(replacement, '{"line":2}\n')
+ // Race: just before the source→temp link, the source pathname is swapped to that OTHER inode.
+ // The temp link then names the wrong inode, the pre-publish verify fails, and the temp is cleaned up.
+ let swapped = false
+ const racingLink: typeof linkSync = (from, to) => {
+ if (!swapped) {
+ swapped = true
+ rmSync(sourcePath)
+ linkSync(replacement, sourcePath) // sourcePath now names replacement's distinct inode
+ }
+ return linkSync(from as string, to as string)
+ }
+ expect(() => commitCodexRolloutExposure(plan, racingLink)).toThrow(
+ 'Temporary Codex rollout did not preserve the verified source inode'
+ )
+ // No orphaned .nodeterm-link temp file is left behind, and no target was published.
+ const targetDir = path.dirname(plan.targetPath)
+ const leftover = existsSync(targetDir)
+ ? readdirSync(targetDir).filter((n) => n.endsWith('.nodeterm-link'))
+ : []
+ expect(leftover).toEqual([])
+ expect(existsSync(plan.targetPath)).toBe(false)
+ })
+
+ it('re-verifies the inode after publishing and refuses a raced-in wrong inode', () => {
+ const root = newRoot()
+ const homeA = makeHome(root, 'a')
+ const homeB = makeHome(root, 'b')
+ const sourcePath = writeRollout(homeA)
+ const decoy = path.join(root, 'decoy.jsonl')
+ writeFileSync(decoy, '{"decoy":true}\n')
+ const plan = planCodexRolloutExposure(homeA, homeB, sourcePath, THREAD)
+ // The private source→temp link is honest; the publish link is hijacked to a DIFFERENT inode,
+ // so ONLY the post-link re-verify can catch that the target is not our rollout.
+ const hijackPublish: typeof linkSync = (from, to) => {
+ if (to === plan.targetPath) return linkSync(decoy, to as string)
+ return linkSync(from as string, to as string)
+ }
+ expect(() => commitCodexRolloutExposure(plan, hijackPublish)).toThrow(
+ 'Target Codex rollout did not preserve the verified source inode'
+ )
+ })
+
+ it('surfaces a named error on a cross-mount (EXDEV) link — no silent copy fallback', () => {
+ const root = newRoot()
+ const homeA = makeHome(root, 'a')
+ const homeB = makeHome(root, 'b')
+ const sourcePath = writeRollout(homeA)
+ const plan = planCodexRolloutExposure(homeA, homeB, sourcePath, THREAD)
+ const crossMount: typeof linkSync = () => {
+ const error = new Error('cross-device link not permitted') as NodeJS.ErrnoException
+ error.code = 'EXDEV'
+ throw error
+ }
+ expect(() => commitCodexRolloutExposure(plan, crossMount)).toThrow(
+ 'Codex rollout accounts must share a filesystem; cross-mount rollout copy is not supported'
+ )
+ // Fails closed: the target rollout is not created.
+ expect(existsSync(plan.targetPath)).toBe(false)
+ })
+
+ it('plan captures the source dev/ino identity', () => {
+ const root = newRoot()
+ const homeA = makeHome(root, 'a')
+ const homeB = makeHome(root, 'b')
+ const sourcePath = writeRollout(homeA)
+ const plan: CodexRolloutExposurePlan = planCodexRolloutExposure(homeA, homeB, sourcePath, THREAD)
+ const stat = statSync(sourcePath)
+ expect(plan.sourceDev).toBe(stat.dev)
+ expect(plan.sourceIno).toBe(stat.ino)
+ })
+})
diff --git a/src/core/codex-accounts-core.ts b/src/core/codex-accounts-core.ts
index 5290bc528..c93343805 100644
--- a/src/core/codex-accounts-core.ts
+++ b/src/core/codex-accounts-core.ts
@@ -7,8 +7,18 @@
//
// Ships INERT (nothing spawns against it yet) but fully tested. Based on @Corvin's
// `codex-accounts-core.ts` in PR #112, re-sliced to the S6 PR-1 model layer.
-import { createHash } from 'crypto'
-import { existsSync, mkdirSync, readdirSync, renameSync } from 'fs'
+import { createHash, randomUUID } from 'crypto'
+import {
+ existsSync,
+ linkSync,
+ lstatSync,
+ mkdirSync,
+ readdirSync,
+ realpathSync,
+ renameSync,
+ statSync,
+ unlinkSync
+} from 'fs'
import os from 'os'
import path from 'path'
import { ACCOUNT_ID_RE, isSafeAccountId } from '../shared/codex-account'
@@ -251,3 +261,205 @@ export function stripCodexAuthEnv(
for (const key of AUTH_ENV_STRIP) delete out[key]
return out
}
+
+// ---------------------------------------------------------------------------
+// Cross-account rollout exposure (S6 §4.1 same-machine switch; §5 property 2).
+//
+// Exposing a conversation's rollout to another account is an ATOMIC HARDLINK of the source rollout
+// inode into the target account's `sessions/<same relative path>`: the same inode ⇒ a byte-identical
+// conversation id, and the link survives deletion of either account home because each link names the
+// inode independently. `plan` validates and mutates nothing; `commit` performs the link, fails closed
+// on any collision that is not already the same inode, and refuses to write THROUGH a symlinked
+// directory segment. Ships INERT here — the switch protocol (PR 5/6) wires plan → reserve → commit.
+// Based on @Corvin's `planCodexRolloutExposure`/`commitCodexRolloutExposure` in PR #112.
+//
+// PROBE U3 (same-filesystem requirement) — measured 2026-08-19 on Linux ext4 (this build host):
+// `~/.codex` and `~/.nodeterm/cx` are direct children of `$HOME` and shared device 64512; a real
+// `link(2)` between them SUCCEEDED. Both legs of a same-machine switch are LOCAL homes under that
+// tree, so the standard layout is same-device. `link(2)` throws `EXDEV` across mounts, and a `$HOME`
+// subtree CAN be bind-mounted onto another volume (measured: `~/.npm`, `~/.cache` were on a separate
+// device on this host), so v1 does NOT silently fall back to a byte copy (per the approved non-goal,
+// S6-spec §8): `commit` surfaces a NAMED `EXDEV` error instead. A cross-mount copy fallback is
+// explicitly out of scope for S6 v1.
+
+/**
+ * Return `candidate` relative to `root` only when it stays strictly INSIDE `root`; otherwise `null`.
+ * Rejects `..`, a `..`-leading path, and any absolute path — the traversal containment check reused
+ * by both the source-account guard (plan) and the target-segment walk (commit).
+ */
+function containedRelativePath(root: string, candidate: string): string | null {
+ const relative = path.relative(root, candidate)
+ return relative &&
+ !relative.startsWith(`..${path.sep}`) &&
+ relative !== '..' &&
+ !path.isAbsolute(relative)
+ ? relative
+ : null
+}
+
+export interface CodexRolloutExposurePlan {
+ /** Canonicalized (`realpathSync`) absolute path of the source rollout. */
+ sourcePath: string
+ /** `<realpath(targetHome)>/sessions` — the target account's sessions root. */
+ targetSessionsRoot: string
+ /** The rollout's path relative to its account's `sessions/`, preserved verbatim in the target. */
+ targetRelativePath: string
+ /** `targetSessionsRoot`/`targetRelativePath` — where the hardlink is published. */
+ targetPath: string
+ /** Source inode identity, re-verified before and after the link so a mid-flight swap fails closed. */
+ sourceDev: number
+ sourceIno: number
+}
+
+/**
+ * Validate a cross-account rollout exposure and return a plan. MUTATES NOTHING — no directory is
+ * created, no link is made; a rejected request leaves the filesystem untouched (§5 property 2).
+ *
+ * Checks: `sourceHome`/`targetHome`/`sourcePath` absolute; `threadId` matches the id regex; the
+ * filename ends `<threadId>.jsonl`; `sourcePath` is a regular file (via `lstatSync`, so a symlink is
+ * NOT followed here); and the canonicalized source stays strictly inside `<sourceHome>/sessions`
+ * (`realpathSync` + containment) so nothing outside the source account can be exposed.
+ */
+export function planCodexRolloutExposure(
+ sourceHome: string,
+ targetHome: string,
+ sourcePath: string,
+ threadId: string
+): CodexRolloutExposurePlan {
+ if (
+ !path.isAbsolute(sourceHome) ||
+ !path.isAbsolute(targetHome) ||
+ !path.isAbsolute(sourcePath) ||
+ !ACCOUNT_ID_RE.test(threadId) ||
+ !path.basename(sourcePath).endsWith(`${threadId}.jsonl`)
+ ) {
+ throw new Error('Invalid Codex rollout exposure request')
+ }
+ if (!lstatSync(sourcePath).isFile()) throw new Error('Source Codex rollout is not a regular file')
+ const sourceSessions = realpathSync(path.join(sourceHome, 'sessions'))
+ const canonicalSource = realpathSync(sourcePath)
+ const relative = containedRelativePath(sourceSessions, canonicalSource)
+ if (!relative) throw new Error('Source Codex rollout is outside its account home')
+ const sourceStat = statSync(canonicalSource)
+ const targetSessionsRoot = path.join(realpathSync(targetHome), 'sessions')
+ return {
+ sourcePath: canonicalSource,
+ targetSessionsRoot,
+ targetRelativePath: relative,
+ targetPath: path.join(targetSessionsRoot, relative),
+ sourceDev: sourceStat.dev,
+ sourceIno: sourceStat.ino
+ }
+}
+
+/**
+ * Commit a plan by ATOMICALLY hardlinking the source inode into the target account. Fail-closed
+ * throughout (§5 property 2):
+ * - re-verifies the source `dev`/`ino` BEFORE and AFTER the link — a mid-flight source swap throws;
+ * - walks every target directory segment and refuses any that is a symlink (never writes THROUGH a
+ * symlinked `sessions/` or sub-directory — the escape a target `sessions` symlink would open);
+ * - `link(2)` is no-overwrite. On `EEXIST` the collision is tolerated ONLY when the existing target
+ * is the SAME inode (`dev`/`ino` match — an idempotent re-expose); otherwise it throws "Target
+ * Codex account already has a different rollout for this thread" and never overwrites;
+ * - publishes from a private verified temporary link so cleanup can never delete an unrelated entry
+ * raced into the final pathname, and removes that temporary only while it still names our inode.
+ *
+ * A cross-mount source/target throws a NAMED `EXDEV` error (probe U3) — NO silent copy fallback.
+ * `linkFile` is injectable so a test can force a specific `link(2)` failure against a real fs.
+ */
+export function commitCodexRolloutExposure(
+ plan: CodexRolloutExposurePlan,
+ linkFile: typeof linkSync = linkSync
+): void {
+ const isVerifiedRollout = (candidate: string): boolean => {
+ try {
+ const entry = lstatSync(candidate)
+ const linked = statSync(candidate)
+ return (
+ entry.isFile() &&
+ !entry.isSymbolicLink() &&
+ linked.dev === plan.sourceDev &&
+ linked.ino === plan.sourceIno
+ )
+ } catch {
+ return false
+ }
+ }
+ const link = (from: string, to: string): void => {
+ try {
+ linkFile(from, to)
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'EXDEV') {
+ throw new Error(
+ 'Codex rollout accounts must share a filesystem; cross-mount rollout copy is not supported'
+ )
+ }
+ throw error
+ }
+ }
+ const sourceEntry = lstatSync(plan.sourcePath)
+ if (!sourceEntry.isFile() || sourceEntry.isSymbolicLink()) {
+ throw new Error('Source Codex rollout changed before account switch commit')
+ }
+ const current = statSync(plan.sourcePath)
+ if (current.dev !== plan.sourceDev || current.ino !== plan.sourceIno) {
+ throw new Error('Source Codex rollout changed before account switch commit')
+ }
+ const segments = path.dirname(plan.targetRelativePath).split(path.sep).filter(Boolean)
+ let currentDir = plan.targetSessionsRoot
+ for (const segment of ['', ...segments]) {
+ if (segment) currentDir = path.join(currentDir, segment)
+ if (!existsSync(currentDir)) mkdirSync(currentDir, { mode: 0o700 })
+ const entry = lstatSync(currentDir)
+ if (!entry.isDirectory() || entry.isSymbolicLink()) {
+ throw new Error('Target Codex rollout path contains an unsafe directory')
+ }
+ }
+ if (existsSync(plan.targetPath)) {
+ if (!isVerifiedRollout(plan.targetPath)) {
+ throw new Error('Target Codex account already has a different rollout for this thread')
+ }
+ return
+ }
+ const temporaryPath = path.join(
+ path.dirname(plan.targetPath),
+ `.${path.basename(plan.targetPath)}.${randomUUID()}.nodeterm-link`
+ )
+ link(plan.sourcePath, temporaryPath)
+ const createdTemporary = lstatSync(temporaryPath)
+ const temporaryStillOurs = (): boolean => {
+ try {
+ const currentTemporary = lstatSync(temporaryPath)
+ return (
+ currentTemporary.dev === createdTemporary.dev &&
+ currentTemporary.ino === createdTemporary.ino
+ )
+ } catch {
+ return false
+ }
+ }
+ try {
+ if (!isVerifiedRollout(temporaryPath)) {
+ throw new Error('Temporary Codex rollout did not preserve the verified source inode')
+ }
+ try {
+ // link(2) is no-overwrite. Publishing from the verified private name prevents cleanup from
+ // ever deleting an unrelated entry raced into the final pathname.
+ link(temporaryPath, plan.targetPath)
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST' || !isVerifiedRollout(plan.targetPath))
+ throw error
+ }
+ if (!isVerifiedRollout(plan.targetPath)) {
+ throw new Error('Target Codex rollout did not preserve the verified source inode')
+ }
+ } finally {
+ // The private pathname may itself have been replaced. Delete it only while it still names the
+ // exact inode created by our link(2), even when a source race made that inode invalid.
+ if (temporaryStillOurs()) {
+ try {
+ unlinkSync(temporaryPath)
+ } catch {}
+ }
+ }
+}