From bb18c3eed39b373fc06f1efeb03a1437fc83db33 Mon Sep 17 00:00:00 2001 From: orch-advisor Date: Tue, 29 Sep 2026 07:30:01 +0000 Subject: [PATCH] fix(codex): pass real git dirs, not a worktree's .git file, to --add-dir (#121) In a linked git worktree /.git is a file, and passing it to Codex as --add-dir breaks the Linux sandbox for every command. The fresh launch now resolves the git metadata directories: an ordinary repository keeps /.git; a .git file resolves through git rev-parse to the worktree git dir and the common git dir (existing directories only); anything unresolvable adds nothing. A missing .git keeps the previous argument. Resume and fork are unchanged. Reported with a reproduction and the suggested rev-parse approach by mgall-ibizdigital in #121. --- .../src/adapters/codex-runtime-adapter.ts | 11 +- .../daemon/src/domain/codex-git-add-dirs.ts | 48 ++++++ .../daemon/test/codex-git-add-dirs.test.ts | 159 ++++++++++++++++++ 3 files changed, 217 insertions(+), 1 deletion(-) create mode 100644 packages/daemon/src/domain/codex-git-add-dirs.ts create mode 100644 packages/daemon/test/codex-git-add-dirs.test.ts diff --git a/packages/daemon/src/adapters/codex-runtime-adapter.ts b/packages/daemon/src/adapters/codex-runtime-adapter.ts index 50c65ca63d..9b3748597a 100644 --- a/packages/daemon/src/adapters/codex-runtime-adapter.ts +++ b/packages/daemon/src/adapters/codex-runtime-adapter.ts @@ -24,6 +24,7 @@ import { } from "../domain/codex-thread-id.js"; import { assessNativeResumeProbe, buildCodexResumeCore, type NativeResumeProbeResult } from "../domain/native-resume-probe.js"; import { unknownDaemonSupportMessage, type CodexDaemonSupportDetector } from "../domain/codex-daemon-support.js"; +import { resolveCodexGitAddDirs, type CodexGitAddDirResolver } from "../domain/codex-git-add-dirs.js"; import { mergeManagedBlock } from "../domain/managed-blocks.js"; import { parseSessionName } from "../domain/session-name.js"; import { shellQuote } from "./shell-quote.js"; @@ -77,6 +78,9 @@ export class CodexRuntimeAdapter implements RuntimeAdapter { // #69: whether the installed Codex supports --no-daemon. Startup wires the real probe; // absent (unit tests, other embedders) keeps the existing invocation unchanged. private detectDaemonSupport?: CodexDaemonSupportDetector; + // Issue #121: git metadata dirs for the fresh-launch `--add-dir`s (a linked worktree's `.git` is a file). + // Default = the real resolver; tests may inject a controlled one. + private resolveGitAddDirs: CodexGitAddDirResolver; // OPR.0.4.1.10 FR-B — absolute path to the daemon's own shipped activity-relay.cjs, // resolved by startup from import.meta.dirname. Used by ensureCodexActivityHooks // (FR-A) to write config-layer [hooks] command entries that are cwd-independent and @@ -96,12 +100,14 @@ export class CodexRuntimeAdapter implements RuntimeAdapter { launchPath?: string; verifyProfilePreflight?: (profile: string) => Promise; detectDaemonSupport?: CodexDaemonSupportDetector; + resolveGitAddDirs?: CodexGitAddDirResolver; }) { this.tmux = deps.tmux; this.fs = deps.fsOps; this.codexHome = deps.codexHome; this.launchPath = deps.launchPath; this.detectDaemonSupport = deps.detectDaemonSupport; + this.resolveGitAddDirs = deps.resolveGitAddDirs ?? resolveCodexGitAddDirs; this.activityRelayPath = deps.activityRelayPath; this.listProcesses = deps.listProcesses ?? defaultListProcesses; this.readThreadIdByPid = deps.readThreadIdByPid ?? ((pid) => this.readThreadIdFromLogs(pid)); @@ -347,7 +353,6 @@ export class CodexRuntimeAdapter implements RuntimeAdapter { }; } } - const gitDirArg = ` --add-dir ${shellQuote(nodePath.join(binding.cwd, ".git"))}`; const queueStateDirArg = this.buildQueueStateAddDirArg(opts.name); // #69: one daemon-support decision for this launch, for the Codex the seat pane runs // (its cwd, the launch PATH), applied to fresh, fork and resume. @@ -397,6 +402,10 @@ export class CodexRuntimeAdapter implements RuntimeAdapter { // OPR.0.4.8.2: one posture decision (codexPostureArg) for the fresh launch too — YOLO forces // -s danger-full-access (overrides even a named profile); otherwise the named profile, or // OpenRig's explicit -s workspace-write floor flag. + // Issue #121: only the fresh launch adds git metadata dirs; resume and fork never did. + const gitDirArg = opts.resumeToken + ? "" + : (await this.resolveGitAddDirs(binding.cwd)).map((dir) => ` --add-dir ${shellQuote(dir)}`).join(""); const cmd = opts.resumeToken // 0.5.2-07 A2-3: the pod-aware RESUME path threads the SPEC model too (reverted before — the // grounding map assumed codex parity with the claude adapter, but only fresh emitted -m). diff --git a/packages/daemon/src/domain/codex-git-add-dirs.ts b/packages/daemon/src/domain/codex-git-add-dirs.ts new file mode 100644 index 0000000000..2a6a96a069 --- /dev/null +++ b/packages/daemon/src/domain/codex-git-add-dirs.ts @@ -0,0 +1,48 @@ +import { execFile } from "node:child_process"; +import fs from "node:fs"; +import nodePath from "node:path"; + +/** The git metadata directories a Codex workspace-write seat may write, for its fresh-launch `--add-dir`s. */ +export type CodexGitAddDirResolver = (cwd: string) => Promise; + +const GIT_TIMEOUT_MS = 5000; + +/** + * Issue #121. `/.git` is a directory in an ordinary repository, but a FILE ("gitdir: ...") in a linked + * worktree or submodule; Codex's Linux sandbox cannot mount under a file, so passing it breaks every command. + * + * - `.git` is a directory: `[/.git]`, as before. + * - `.git` does not exist: `[/.git]`, as before. Nothing reported fails for this case, and changing it + * is outside the fix. + * - `.git` is a file: the absolute git dir and common git dir from `git rev-parse`, keeping only existing + * directories (a linked worktree needs both to commit). + * - Anything unresolvable (unreadable `.git`, malformed gitdir, git missing or failing): `[]`. The seat still + * launches; it simply gets no extra git write access, instead of a broken path that fails every command. + */ +export const resolveCodexGitAddDirs: CodexGitAddDirResolver = async (cwd) => { + const dotGit = nodePath.join(cwd, ".git"); + let stat: fs.Stats; + try { + stat = fs.statSync(dotGit); + } catch (error) { + return (error as NodeJS.ErrnoException).code === "ENOENT" ? [dotGit] : []; + } + if (stat.isDirectory()) return [dotGit]; + const stdout = await new Promise((resolve) => { + execFile( + "git", + ["-C", cwd, "rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir"], + { timeout: GIT_TIMEOUT_MS, encoding: "utf8" }, + (error, out) => resolve(error ? null : out), + ); + }); + if (stdout === null) return []; + const dirs = [...new Set(stdout.split("\n").map((line) => line.trim()).filter(Boolean))]; + return dirs.filter((dir) => { + try { + return fs.statSync(dir).isDirectory(); + } catch { + return false; + } + }); +}; diff --git a/packages/daemon/test/codex-git-add-dirs.test.ts b/packages/daemon/test/codex-git-add-dirs.test.ts new file mode 100644 index 0000000000..366553dd71 --- /dev/null +++ b/packages/daemon/test/codex-git-add-dirs.test.ts @@ -0,0 +1,159 @@ +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import nodePath from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { CodexRuntimeAdapter, type CodexAdapterFsOps } from "../src/adapters/codex-runtime-adapter.js"; +import type { TmuxAdapter } from "../src/adapters/tmux.js"; +import type { NodeBinding } from "../src/domain/runtime-adapter.js"; + +// Issue #121: in a linked git worktree `/.git` is a FILE ("gitdir: ..."), so passing it to Codex as +// `--add-dir` breaks the Linux sandbox for every command. These tests use real temporary Git repositories +// and the adapter's real fresh-launch command path; no Codex, daemon or live tmux is started. + +const git = (cwd: string, ...args: string[]) => + execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@example.com", "-c", "init.defaultBranch=main", ...args], { + cwd, stdio: ["ignore", "pipe", "pipe"], encoding: "utf8", + }); + +let root: string; +beforeEach(() => { root = fs.realpathSync(fs.mkdtempSync(nodePath.join(os.tmpdir(), "issue121-"))); }); +afterEach(() => { fs.rmSync(root, { recursive: true, force: true }); }); + +function ordinaryRepo(): string { + const repo = nodePath.join(root, "main repo"); + fs.mkdirSync(repo); + git(repo, "init", "-q"); + git(repo, "commit", "-q", "--allow-empty", "-m", "init"); + return repo; +} + +function linkedWorktree(): { repo: string; worktree: string; worktreeGitDir: string } { + const repo = ordinaryRepo(); + const worktree = nodePath.join(root, "linked worktree"); + git(repo, "worktree", "add", "-q", worktree, "-b", "feature"); + // Git names the per-worktree admin dir itself (it may sanitize the name), so read it from the .git file. + const worktreeGitDir = fs.readFileSync(nodePath.join(worktree, ".git"), "utf8").replace(/^gitdir:\s*/, "").trim(); + return { repo, worktree, worktreeGitDir }; +} + +function mockTmux(): TmuxAdapter { + const tmux = { + sendText: vi.fn(async () => ({ ok: true as const })), + sendKeys: vi.fn(async () => ({ ok: true as const })), + hasSession: vi.fn(async () => true), + getPaneCommand: vi.fn(async () => "codex"), + capturePaneContent: vi.fn(async () => "OpenAI Codex (v0.0.0)\n› Ask Codex to do anything"), + getPanePid: vi.fn(async () => null), + } as unknown as TmuxAdapter; + tmux.sendShellCommand = vi.fn(async (target: string, command: string) => { + await tmux.sendText(target, command); + return tmux.sendKeys(target, ["Enter"]); + }); + return tmux; +} + +const fsOps: CodexAdapterFsOps = { + readFile: (p: string) => { throw new Error(`Not found: ${p}`); }, + writeFile: () => {}, + exists: () => false, + mkdirp: () => {}, +}; + +function binding(cwd: string): NodeBinding { + return { + id: "b1", nodeId: "n1", tmuxSession: "r01-qa", tmuxWindow: null, tmuxPane: null, + cmuxWorkspace: null, cmuxSurface: null, updatedAt: "", cwd, + }; +} + +async function freshLaunchCommand(cwd: string): Promise { + const tmux = mockTmux(); + const adapter = new CodexRuntimeAdapter({ + tmux, fsOps, sleep: async () => {}, listProcesses: () => [], readThreadIdByPid: () => undefined, + }); + await adapter.launchHarness(binding(cwd), { name: "dev@issue121-rig" }); + return vi.mocked(tmux.sendText).mock.calls[0]![1] as string; +} + +function addDirs(command: string): string[] { + const out: string[] = []; + const re = / --add-dir '((?:[^']|'"'"')*)'/g; + for (let m = re.exec(command); m; m = re.exec(command)) out.push(m[1]!.replace(/'"'"'/g, "'")); + return out; +} + +describe("Codex fresh launch git add-dirs (issue #121)", () => { + it("ordinary repository keeps --add-dir /.git", async () => { + const repo = ordinaryRepo(); + const dirs = addDirs(await freshLaunchCommand(repo)); + expect(dirs).toContain(nodePath.join(repo, ".git")); + }); + + it("linked worktree never passes the .git FILE; it passes the worktree git dir and the common git dir", async () => { + const { repo, worktree, worktreeGitDir } = linkedWorktree(); + expect(fs.statSync(nodePath.join(worktree, ".git")).isFile()).toBe(true); + const dirs = addDirs(await freshLaunchCommand(worktree)); + expect(dirs).not.toContain(nodePath.join(worktree, ".git")); + expect(dirs).toContain(worktreeGitDir); + expect(dirs).toContain(nodePath.join(repo, ".git")); + for (const dir of dirs) expect(fs.statSync(dir).isDirectory()).toBe(true); + }); + + it("resume does not resolve or add git dirs (unchanged)", async () => { + const tmux = mockTmux(); + const resolveGitAddDirs = vi.fn(async () => ["/should/not/appear"]); + const adapter = new CodexRuntimeAdapter({ + tmux, fsOps, sleep: async () => {}, listProcesses: () => [], readThreadIdByPid: () => undefined, resolveGitAddDirs, + }); + await adapter.launchHarness(binding(root), { name: "dev@issue121-rig", resumeToken: "thread-1" }); + expect(resolveGitAddDirs).not.toHaveBeenCalled(); + expect(vi.mocked(tmux.sendText).mock.calls[0]![1]).not.toContain("/should/not/appear"); + }); +}); + +describe("resolveCodexGitAddDirs (issue #121)", () => { + it("ordinary repository: [/.git]", async () => { + const { resolveCodexGitAddDirs } = await import("../src/domain/codex-git-add-dirs.js"); + const repo = ordinaryRepo(); + expect(await resolveCodexGitAddDirs(repo)).toEqual([nodePath.join(repo, ".git")]); + }); + + it("missing .git: [/.git], unchanged", async () => { + const { resolveCodexGitAddDirs } = await import("../src/domain/codex-git-add-dirs.js"); + const plain = nodePath.join(root, "not a repo"); + fs.mkdirSync(plain); + expect(await resolveCodexGitAddDirs(plain)).toEqual([nodePath.join(plain, ".git")]); + }); + + it("linked worktree: worktree git dir and common git dir, both existing directories", async () => { + const { resolveCodexGitAddDirs } = await import("../src/domain/codex-git-add-dirs.js"); + const { repo, worktree, worktreeGitDir } = linkedWorktree(); + expect(await resolveCodexGitAddDirs(worktree)).toEqual([worktreeGitDir, nodePath.join(repo, ".git")]); + }); + + it("malformed .git file (gitdir points nowhere): [], never the file", async () => { + const { resolveCodexGitAddDirs } = await import("../src/domain/codex-git-add-dirs.js"); + const broken = nodePath.join(root, "broken worktree"); + fs.mkdirSync(broken); + fs.writeFileSync(nodePath.join(broken, ".git"), `gitdir: ${nodePath.join(root, "missing", "worktrees", "x")}\n`); + expect(await resolveCodexGitAddDirs(broken)).toEqual([]); + }); + + it("unreadable .git (not ENOENT): []", async () => { + const { resolveCodexGitAddDirs } = await import("../src/domain/codex-git-add-dirs.js"); + const parent = nodePath.join(root, "locked"); + fs.mkdirSync(parent); + const cwd = nodePath.join(parent, "cwd"); + fs.mkdirSync(cwd); + fs.chmodSync(parent, 0o000); + try { + // stat of /.git fails with EACCES when the parent is not searchable (non-root users). + const result = await resolveCodexGitAddDirs(cwd); + if (process.getuid && process.getuid() === 0) expect(Array.isArray(result)).toBe(true); + else expect(result).toEqual([]); + } finally { + fs.chmodSync(parent, 0o755); + } + }); +});