Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion packages/daemon/src/adapters/codex-runtime-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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
Expand All @@ -96,12 +100,14 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
launchPath?: string;
verifyProfilePreflight?: (profile: string) => Promise<CodexProfileProbeResult>;
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));
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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).
Expand Down
48 changes: 48 additions & 0 deletions packages/daemon/src/domain/codex-git-add-dirs.ts
Original file line number Diff line number Diff line change
@@ -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<string[]>;

const GIT_TIMEOUT_MS = 5000;

/**
* Issue #121. `<cwd>/.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: `[<cwd>/.git]`, as before.
* - `.git` does not exist: `[<cwd>/.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<string | null>((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;
}
});
};
159 changes: 159 additions & 0 deletions packages/daemon/test/codex-git-add-dirs.test.ts
Original file line number Diff line number Diff line change
@@ -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 `<cwd>/.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<string> {
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 <cwd>/.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: [<cwd>/.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: [<cwd>/.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 <cwd>/.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);
}
});
});
Loading