Skip to content
Closed
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
49 changes: 40 additions & 9 deletions plugins/codex/scripts/lib/state.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { resolveWorkspaceRoot } from "./workspace.mjs";

const STATE_VERSION = 1;
const PLUGIN_DATA_ENV = "CLAUDE_PLUGIN_DATA";
const CODEX_HOME_ENV = "CODEX_HOME";
const CONFIG_DIR_NAME = path.join("plugin-cc", "config");
const FALLBACK_STATE_ROOT_DIR = path.join(os.tmpdir(), "codex-companion");
const STATE_FILE_NAME = "state.json";
const JOBS_DIR_NAME = "jobs";
Expand All @@ -26,21 +28,29 @@ function defaultState() {
};
}

export function resolveStateDir(cwd) {
function resolveWorkspaceKey(cwd) {
const workspaceRoot = resolveWorkspaceRoot(cwd);
let canonicalWorkspaceRoot = workspaceRoot;
try {
canonicalWorkspaceRoot = fs.realpathSync.native(workspaceRoot);
} catch {
canonicalWorkspaceRoot = workspaceRoot;
}

const slugSource = path.basename(workspaceRoot) || "workspace";
const slug = slugSource.replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "workspace";
const hash = createHash("sha256").update(canonicalWorkspaceRoot).digest("hex").slice(0, 16);
return `${slug}-${hash}`;
}

export function resolveStateDir(cwd) {
const pluginDataDir = process.env[PLUGIN_DATA_ENV];
const stateRoot = pluginDataDir ? path.join(pluginDataDir, "state") : FALLBACK_STATE_ROOT_DIR;
return path.join(stateRoot, `${slug}-${hash}`);
return path.join(stateRoot, resolveWorkspaceKey(cwd));
}

export function resolveConfigFile(cwd) {
const codexHome = path.resolve(process.env[CODEX_HOME_ENV] || path.join(os.homedir(), ".codex"));
return path.join(codexHome, CONFIG_DIR_NAME, `${resolveWorkspaceKey(cwd)}.json`);
}

export function resolveStateFile(cwd) {
Expand Down Expand Up @@ -150,17 +160,38 @@ export function listJobs(cwd) {
return loadState(cwd).jobs;
}

function readDurableConfig(cwd) {
const configFile = resolveConfigFile(cwd);
if (!fs.existsSync(configFile)) {
return null;
}
try {
const parsed = JSON.parse(fs.readFileSync(configFile, "utf8"));
return { ...defaultState().config, ...(parsed ?? {}) };
} catch {
return null;
}
}

function writeDurableConfig(cwd, config) {
const configFile = resolveConfigFile(cwd);
fs.mkdirSync(path.dirname(configFile), { recursive: true });
const nextConfig = { ...defaultState().config, ...(config ?? {}) };
fs.writeFileSync(configFile, `${JSON.stringify(nextConfig, null, 2)}
Comment thread
fscfede-beep marked this conversation as resolved.
`, "utf8");
return nextConfig;
}

export function setConfig(cwd, key, value) {
return updateState(cwd, (state) => {
state.config = {
...state.config,
[key]: value
};
const nextConfig = writeDurableConfig(cwd, { ...getConfig(cwd), [key]: value });
updateState(cwd, (state) => {
state.config = { ...state.config, ...nextConfig };
});
return nextConfig;
}

export function getConfig(cwd) {
return loadState(cwd).config;
return readDurableConfig(cwd) ?? loadState(cwd).config;
}

export function writeJobFile(cwd, jobId, payload) {
Expand Down
1 change: 1 addition & 0 deletions tests/fake-codex-fixture.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,7 @@ export function buildEnv(binDir) {
const sep = process.platform === "win32" ? ";" : ":";
return {
...process.env,
CODEX_HOME: path.join(binDir, "codex-home"),
PATH: `${binDir}${sep}${process.env.PATH}`
};
}
33 changes: 32 additions & 1 deletion tests/runtime.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2036,6 +2036,34 @@ test("stop hook logs running tasks to stderr without blocking when the review ga
assert.match(blocked.stderr, /\/codex:cancel task-live/i);
});

test("review gate enabled under one plugin-data root is enforced by Stop under another", () => {
const repo = makeTempDir();
const binDir = makeTempDir();
const codexHome = makeTempDir();
const pluginDataSetup = makeTempDir();
const pluginDataStop = makeTempDir();
installFakeCodex(binDir);
initGitRepo(repo);
fs.writeFileSync(path.join(repo, "README.md"), "hello\n");
run("git", ["add", "README.md"], { cwd: repo });
run("git", ["commit", "-m", "init"], { cwd: repo });
const setup = run("node", [SCRIPT, "setup", "--enable-review-gate", "--json"], {
cwd: repo,
env: { ...buildEnv(binDir), CODEX_HOME: codexHome, CLAUDE_PLUGIN_DATA: pluginDataSetup }
});
assert.equal(setup.status, 0, setup.stderr);
assert.equal(JSON.parse(setup.stdout).reviewGateEnabled, true);
const stopped = run("node", [STOP_HOOK], {
cwd: repo,
env: { ...buildEnv(binDir), CODEX_HOME: codexHome, CLAUDE_PLUGIN_DATA: pluginDataStop, CODEX_COMPANION_SESSION_ID: "sess-cross-root" },
input: JSON.stringify({ cwd: repo, session_id: "sess-cross-root", last_assistant_message: "I completed the change." })
});
assert.equal(stopped.status, 0, stopped.stderr);
const payload = JSON.parse(stopped.stdout);
assert.equal(payload.decision, "block");
assert.match(payload.reason, /Codex stop-time review found issues/i);
});

test("stop hook allows the stop when the review gate is enabled and the stop-time review task is clean", () => {
const repo = makeTempDir();
const binDir = makeTempDir();
Expand Down Expand Up @@ -2068,15 +2096,18 @@ test("stop hook does not block when Codex is unavailable even if the review gate
run("git", ["add", "README.md"], { cwd: repo });
run("git", ["commit", "-m", "init"], { cwd: repo });

const codexHome = makeTempDir();
const setup = run(process.execPath, [SCRIPT, "setup", "--enable-review-gate", "--json"], {
cwd: repo
cwd: repo,
env: { ...process.env, CODEX_HOME: codexHome }
});
assert.equal(setup.status, 0, setup.stderr);

const allowed = run(process.execPath, [STOP_HOOK], {
cwd: repo,
env: {
...process.env,
CODEX_HOME: codexHome,
PATH: ""
},
input: JSON.stringify({ cwd: repo })
Expand Down
24 changes: 23 additions & 1 deletion tests/state.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import test from "node:test";
import assert from "node:assert/strict";

import { makeTempDir } from "./helpers.mjs";
import { resolveJobFile, resolveJobLogFile, resolveStateDir, resolveStateFile, saveState } from "../plugins/codex/scripts/lib/state.mjs";
import { getConfig, resolveJobFile, resolveJobLogFile, resolveStateDir, resolveStateFile, saveState, setConfig } from "../plugins/codex/scripts/lib/state.mjs";

test("resolveStateDir uses a temp-backed per-workspace directory", () => {
const workspace = makeTempDir();
Expand Down Expand Up @@ -40,6 +40,28 @@ test("resolveStateDir uses CLAUDE_PLUGIN_DATA when it is provided", () => {
}
});

test("review-gate config remains authoritative when CLAUDE_PLUGIN_DATA changes", () => {
const workspace = makeTempDir();
const codexHome = makeTempDir();
const pluginDataA = makeTempDir();
const pluginDataB = makeTempDir();
const previousCodexHome = process.env.CODEX_HOME;
const previousPluginData = process.env.CLAUDE_PLUGIN_DATA;
try {
process.env.CODEX_HOME = codexHome;
process.env.CLAUDE_PLUGIN_DATA = pluginDataA;
setConfig(workspace, "stopReviewGate", true);
process.env.CLAUDE_PLUGIN_DATA = pluginDataB;
assert.equal(getConfig(workspace).stopReviewGate, true);
setConfig(workspace, "stopReviewGate", false);
process.env.CLAUDE_PLUGIN_DATA = pluginDataA;
assert.equal(getConfig(workspace).stopReviewGate, false);
} finally {
if (previousCodexHome == null) delete process.env.CODEX_HOME; else process.env.CODEX_HOME = previousCodexHome;
if (previousPluginData == null) delete process.env.CLAUDE_PLUGIN_DATA; else process.env.CLAUDE_PLUGIN_DATA = previousPluginData;
}
});

test("saveState prunes dropped job artifacts when indexed jobs exceed the cap", () => {
const workspace = makeTempDir();
const stateFile = resolveStateFile(workspace);
Expand Down