Fix Codex writer ownership on Vault and CLI restore

Closed
AU
3mo ago
+2330-1011

Summary

Closes https://github.com/manaflow-ai/cmux/issues/11973.

Codex correctly rejects a second writer; cmux was launching one anyway. The shared restore/Vault preflight now probes the exact account's kernel writer lock rather than file existence, persisted snapshots, or tty labels.

  • CLI checks before the binding-generation claim and repeats a cheap check immediately before exec. Saved argv, environment, cwd, provider preflights, and existing generation validation remain intact.
  • Vault Open/Resume/Focus can continue a unique live owner in the current window when exact lock-inode, process birth generation, foreground ancestry, current kernel TTY, and runtime generation agree. Otherwise a localized diagnostic identifies available PID/cwd/lock information before TUI startup.
  • Vault carries its indexed Codex account root, including when transcripts use symlinks. Verification-only home metadata is pinned into the actual launch account.
  • No lock deletion, owner termination, conversation fork, orphan reaper, or app-server redesign.

Concrete regression evidence

Regression tests precede the implementation in separate commits: a8c534a39a (Vault home) and 9f91eebc99 (production CLI execution harness); implementation begins at 0997fb1b35.

CMUX_RESTORE_SOURCE_REF=a8c534a39 arch -arm64 python3 tests/test_codex_writer_restore.py executed the base production planner/exec code: 4 behavioral failures / 6 tests, including a held lock incorrectly reaching the fake agent's exec. The identical harness on the fix: 6/6 passed. Every home, lock, and agent is a disposable fixture; no app or real Codex session is used. CI now runs this harness.

arch -arm64 swift test --package-path Packages/macOS/CMUXAgentLaunch: 373 tests / 50 suites passed before main sync. The focused ownership suite after sync: 15 tests passed, including active/available/released locks, release during discovery, missing/invalid/symlink paths, account isolation, relative homes, remote option parsing, unknown/ambiguous owners, runtime TTY matching, and PID birth generation.

The final current-HEAD full package run passed 384 tests / 51 suites. Project normalization, app test wiring (779 files after main sync), Package.resolved policy, workspace grouping, Swift syntax parse, and diff whitespace checks passed. Seven new UI/CLI keys were audited in English/Japanese, including matching format placeholders. No new Swift warnings; warning budget unchanged.

The earlier hosted test-first run 33921594326 failed in unrelated pre-existing CmuxTuiSurfaceProviderTests compilation before executing tests; it is not used as regression proof.

Scoped trade-offs and limitations

Closeout is currently blocked, not review-clean: three attempts of the canonical autoreview helper (Codex gpt-5.6-sol, high) failed with HTTP 503 because the selected account's refresh token is reused/invalidated and requires reauthentication. All three merge-conflict gates passed. No review-engine switch or gate bypass was used.

Hosted workflow-guard-tests also fails its test-determinism gate on the unchanged cmuxTests/MobileHostConnectionLifecycleTests.swift:236 sleep introduced by main's #11874. This blocks downstream app validation. That unrelated mobile test and the determinism allowlist have not been changed by this PR. CI/review closeout remains queued after those external blockers are resolved.

  • A preflight is advisory, not a reservation. Codex remains the atomic lock authority if a writer starts after cmux checks. The probe never deletes or retains a provider lock.
  • Incomplete process inspection, multiple holders, stale runtime evidence, other windows, remote/mirrored surfaces, and legacy workspace Docks do not authorize guessed focus. Diagnostics provide the safe fallback: continue the original terminal or exit normally and retry.
  • A legacy login-shell command can override the parent's account. Only literal commands with an explicit absolute inline CODEX_HOME can be checked without rewriting/evaluating the saved shell command; ambiguous older records fail closed with recovery instructions. Actual remote Codex argv bypasses local ownership inspection. Existing sanitizer/provider behavior is otherwise retained.
  • SessionEntry and its coordinator/tests were extracted to keep new Swift files below 500 lines and shrink existing large files. The requested .github/swift-file-length-budget.tsv and scripts/swift_file_length_budget.py are absent from both the task base and current main; the prescribed command was attempted and reports ENOENT. No budgets were regenerated or warning allowances changed.
  • Per task instructions, no local app build, app launch, XCUITest, or real-session resume was performed. App checks are delegated to required hosted CI. No dogfood build or merge is authorized in this task.

Build command for the later authorized dogfood step:

CMUX_SKIP_ZIG_BUILD=1 /Users/austinwang/manaflow/cmuxterm-hq/scripts/reload-cloud.sh --tag issue-11973-codex-writer-restore --launch

Summary by CodeRabbit

  • New Features

    • Added safeguards when restoring Codex sessions to prevent conflicts with active writers.
    • Codex restores now verify the correct account, workspace, and active session ownership before continuing.
    • Active sessions can be focused in their existing workspace, while resumed sessions open in a separate workspace.
    • Added clearer warnings for active, unavailable, or unverifiable Codex sessions.
    • Added English and Japanese messaging for Codex restore states.
  • Bug Fixes

    • Preserved the correct Codex account directory during session restoration.
    • Remote Codex sessions now avoid unnecessary local writer checks.
  • Tests

    • Expanded coverage for safe Codex restoration and session resume behavior.

[!NOTE]
Medium Risk
Changes agent restore and Vault session launch paths with kernel/process inspection; mistakes could block legitimate resumes or mis-route focus, but the design fails closed and does not delete locks or kill processes.

Overview
Adds a shared Codex writer preflight in CMUXAgentLaunch that probes each thread’s kernel flock under the effective CODEX_HOME (from final argv, child env, and cwd), optionally discovers a single live holder, and blocks restore when a writer is active or ownership cannot be verified safely. Remote --remote launches skip local lock checks; legacy shell-only resumes are parsed only when they expose a literal absolute CODEX_HOME.

CLI: cmux restore runs the guard before binding claims and again at exec, with fail-closed errors and new localized copy. AgentRestorePlanner tags Codex resume invocations with codexResumeSessionID and pins verification home into the child account.

Vault: Session index entries carry indexedCodexHome; resume/open/focus go through an async SessionEntryResumeCoordinator that either focuses one unambiguous live terminal (lock inode, PID generation, TTY, runtime ancestry) or shows a warning instead of starting another writer. UI session actions use cancellable main-actor tasks.

CI adds tests/test_codex_writer_restore.py; package and coordinator tests cover locks, legacy command scope, and resume behavior.

Reviewed by Cursor Bugbot for commit aae764b331528fc5a699823974e4a72c30758e20. Bugbot is set up for automated code reviews on this repo. Configure here.