Skip to content
Open
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
29 changes: 15 additions & 14 deletions plugins/codex/scripts/codex-companion.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
} from "./lib/codex.mjs";
import { resolveClaudeSessionPath } from "./lib/claude-session-transfer.mjs";
import { readStdinIfPiped } from "./lib/fs.mjs";
import { readTaskPromptInput } from "./lib/task-prompt.mjs";
import { collectReviewContext, ensureGitRepository, resolveReviewTarget } from "./lib/git.mjs";
import { binaryAvailable, terminateProcessTree } from "./lib/process.mjs";
import { loadPromptTemplate, interpolateTemplate } from "./lib/prompts.mjs";
Expand Down Expand Up @@ -79,7 +80,7 @@ function printUsage() {
" node scripts/codex-companion.mjs setup [--enable-review-gate|--disable-review-gate] [--json]",
" node scripts/codex-companion.mjs review [--wait|--background] [--base <ref>] [--scope <auto|working-tree|branch>]",
" node scripts/codex-companion.mjs adversarial-review [--wait|--background] [--base <ref>] [--scope <auto|working-tree|branch>] [focus text]",
" node scripts/codex-companion.mjs task [--background] [--write] [--resume-last|--resume|--fresh] [--model <model|spark>] [--effort <none|minimal|low|medium|high|xhigh>] [prompt]",
" node scripts/codex-companion.mjs task [--background] [--write] [--resume-last|--resume|--fresh] [--model <model|spark>] [--effort <none|minimal|low|medium|high|xhigh>] [--prompt-file <path> [--prompt-file-sha256 <hex>]] [prompt]",
" node scripts/codex-companion.mjs transfer [--source <claude-jsonl>] [--json]",
" node scripts/codex-companion.mjs status [job-id] [--all] [--json]",
" node scripts/codex-companion.mjs result [job-id] [--json]",
Expand Down Expand Up @@ -485,6 +486,7 @@ async function executeTaskRun(request) {
const result = await runAppServerTurn(workspaceRoot, {
resumeThreadId,
prompt: request.prompt,
preservePromptWhitespace: request.promptSource === "file",
defaultPrompt: resumeThreadId ? DEFAULT_CONTINUE_PROMPT : "",
model: request.model,
effort: request.effort,
Expand Down Expand Up @@ -513,7 +515,8 @@ async function executeTaskRun(request) {
threadId: result.threadId,
rawOutput,
touchedFiles: result.touchedFiles,
reasoningSummary: result.reasoningSummary
reasoningSummary: result.reasoningSummary,
...(request.promptFileSha256 ? { promptFileSha256: request.promptFileSha256 } : {})
};

return {
Expand Down Expand Up @@ -601,12 +604,14 @@ function buildTaskJob(workspaceRoot, taskMetadata, write) {
});
}

function buildTaskRequest({ cwd, model, effort, prompt, write, resumeLast, jobId }) {
function buildTaskRequest({ cwd, model, effort, prompt, promptSource, promptFileSha256 = null, write, resumeLast, jobId }) {
return {
cwd,
model,
effort,
prompt,
promptSource,
...(promptFileSha256 ? { promptFileSha256 } : {}),
write,
resumeLast,
jobId
Expand Down Expand Up @@ -640,15 +645,6 @@ async function executeTransfer(cwd, options = {}) {
};
}

function readTaskPrompt(cwd, options, positionals) {
if (options["prompt-file"]) {
return fs.readFileSync(path.resolve(cwd, options["prompt-file"]), "utf8");
}

const positionalPrompt = positionals.join(" ");
return positionalPrompt || readStdinIfPiped();
}

function requireTaskRequest(prompt, resumeLast) {
if (!prompt && !resumeLast) {
throw new Error("Provide a prompt, a prompt file, piped stdin, or use --resume-last.");
Expand Down Expand Up @@ -761,7 +757,7 @@ async function handleReview(argv) {

async function handleTask(argv) {
const { options, positionals } = parseCommandInput(argv, {
valueOptions: ["model", "effort", "cwd", "prompt-file"],
valueOptions: ["model", "effort", "cwd", "prompt-file", "prompt-file-sha256"],
booleanOptions: ["json", "write", "resume-last", "resume", "fresh", "background"],
aliasMap: {
m: "model"
Expand All @@ -772,7 +768,8 @@ async function handleTask(argv) {
const workspaceRoot = resolveCommandWorkspace(options);
const model = normalizeRequestedModel(options.model);
const effort = normalizeReasoningEffort(options.effort);
const prompt = readTaskPrompt(cwd, options, positionals);
const promptInput = readTaskPromptInput(cwd, options, positionals, readStdinIfPiped);
const prompt = promptInput.text;

const resumeLast = Boolean(options["resume-last"] || options.resume);
const fresh = Boolean(options.fresh);
Expand All @@ -795,6 +792,8 @@ async function handleTask(argv) {
model,
effort,
prompt,
promptSource: promptInput.source,
promptFileSha256: promptInput.sha256,
write,
resumeLast,
jobId: job.id
Expand All @@ -813,6 +812,8 @@ async function handleTask(argv) {
model,
effort,
prompt,
promptSource: promptInput.source,
promptFileSha256: promptInput.sha256,
write,
resumeLast,
jobId: job.id,
Expand Down
9 changes: 8 additions & 1 deletion plugins/codex/scripts/lib/codex.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1124,7 +1124,14 @@ export async function runAppServerTurn(cwd, options = {}) {
threadId
});

const prompt = options.prompt?.trim() || options.defaultPrompt || "";
const suppliedPrompt = typeof options.prompt === "string" ? options.prompt : "";
const normalizedPrompt = suppliedPrompt.trim();
if (options.preservePromptWhitespace && !normalizedPrompt) {
throw new Error("A prompt is required for this Codex run.");
}
const prompt = options.preservePromptWhitespace
? suppliedPrompt
: normalizedPrompt || options.defaultPrompt || "";
if (!prompt) {
throw new Error("A prompt is required for this Codex run.");
}
Expand Down
58 changes: 58 additions & 0 deletions plugins/codex/scripts/lib/task-prompt.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";

const SHA256_PATTERN = /^[a-f0-9]{64}$/i;

function normalizeExpectedSha256(value) {
if (value == null) {
return null;
}
const normalized = String(value).trim().toLowerCase();
if (!SHA256_PATTERN.test(normalized)) {
throw new Error("`--prompt-file-sha256` must be exactly 64 hexadecimal characters.");
}
return normalized;
}

function digestsEqual(leftHex, rightHex) {
const left = Buffer.from(leftHex, "hex");
const right = Buffer.from(rightHex, "hex");
return left.length === right.length && crypto.timingSafeEqual(left, right);
}

export function readTaskPromptInput(cwd, options, positionals, readStdin) {
const expectedSha256 = normalizeExpectedSha256(options["prompt-file-sha256"]);
const promptFile = options["prompt-file"];
if (expectedSha256 && !promptFile) {
throw new Error("`--prompt-file-sha256` requires `--prompt-file <path>`.");
}

if (promptFile) {
const resolvedPath = path.resolve(cwd, promptFile);
const bytes = fs.readFileSync(resolvedPath);
const sha256 = crypto.createHash("sha256").update(bytes).digest("hex");
Comment thread
ALV0612 marked this conversation as resolved.
if (expectedSha256 && !digestsEqual(expectedSha256, sha256)) {
throw new Error(
`Prompt file SHA-256 mismatch for ${resolvedPath}: expected ${expectedSha256}, received ${sha256}.`
);
}
return {
text: bytes.toString("utf8"),
source: "file",
sha256,
filePath: resolvedPath
};
}

const positionalPrompt = positionals.join(" ");
if (positionalPrompt) {
return { text: positionalPrompt, source: "positional", sha256: null, filePath: null };
}
return {
text: readStdin(),
source: "stdin",
sha256: null,
filePath: null
};
}
1 change: 1 addition & 0 deletions plugins/codex/skills/codex-cli-runtime/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ Command selection:
- `--resume`: always use `task --resume-last`, even if the request text is ambiguous.
- `--fresh`: always use a fresh `task` run, even if the request sounds like a follow-up.
- `--effort`: accepted values are `none`, `minimal`, `low`, `medium`, `high`, `xhigh`.
- `--prompt-file-sha256 <hex>`: when using `--prompt-file`, pass the caller-supplied SHA-256 to bind the approved file bytes to the verbatim decoded text Codex receives. The JSON receipt is `promptFileSha256`. Never invent or recompute an expected digest on the caller's behalf after handoff.
- `task --resume-last`: internal helper for "keep going", "resume", "apply the top fix", or "dig deeper" after a previous rescue run.

Safety rules:
Expand Down
3 changes: 3 additions & 0 deletions tests/commands.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,9 @@ test("rescue command absorbs continue semantics", () => {
assert.match(runtimeSkill, /If the forwarded request includes `--background` or `--wait`, treat that as Claude-side execution control only/i);
assert.match(runtimeSkill, /Strip it before calling `task`/i);
assert.match(runtimeSkill, /`--effort`: accepted values are `none`, `minimal`, `low`, `medium`, `high`, `xhigh`/i);
assert.match(runtimeSkill, /`--prompt-file-sha256 <hex>`/i);
assert.match(runtimeSkill, /bind the approved file bytes to the verbatim decoded text Codex receives/i);
assert.match(runtimeSkill, /JSON receipt is `promptFileSha256`/i);
assert.match(runtimeSkill, /Do not inspect the repository, read files, grep, monitor progress, poll status, fetch results, cancel jobs, summarize output, or do any follow-up work of your own/i);
assert.match(runtimeSkill, /If the Bash call fails or Codex cannot be invoked, return nothing/i);
assert.match(readme, /`codex:codex-rescue` subagent/i);
Expand Down
124 changes: 124 additions & 0 deletions tests/runtime.test.mjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import test from "node:test";
Expand Down Expand Up @@ -2257,3 +2258,126 @@ test("setup and status honor --cwd when reading shared session runtime", () => {
assert.equal(payload.sessionRuntime.mode, "shared");
assert.equal(payload.sessionRuntime.endpoint, "unix:/tmp/fake-broker.sock");
});


test("task verifies prompt-file bytes and sends their decoded text verbatim", () => {
const repo = makeTempDir();
const binDir = 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 prompt = " Inspect $HOME, `backticks`, and the exact newline. \n";
const promptFile = path.join(repo, "prompt.txt");
fs.writeFileSync(promptFile, prompt, "utf8");
const digest = crypto.createHash("sha256").update(Buffer.from(prompt, "utf8")).digest("hex");

const result = run(
"node",
[SCRIPT, "task", "--json", "--prompt-file", promptFile, "--prompt-file-sha256", digest],
{ cwd: repo, env: buildEnv(binDir) }
);

assert.equal(result.status, 0, result.stderr);
const payload = JSON.parse(result.stdout);
assert.equal(payload.promptFileSha256, digest);
const fakeState = JSON.parse(fs.readFileSync(path.join(binDir, "fake-codex-state.json"), "utf8"));
assert.equal(fakeState.lastTurnStart.prompt, prompt);
const stateDir = resolveStateDir(repo);
const state = JSON.parse(fs.readFileSync(path.join(stateDir, "state.json"), "utf8"));
const stored = JSON.parse(fs.readFileSync(path.join(stateDir, "jobs", `${state.jobs[0].id}.json`), "utf8"));
assert.equal(stored.result.promptFileSha256, digest);
});

test("task keeps stdin prompt normalization separate from verbatim prompt files", () => {
const repo = makeTempDir();
const binDir = makeTempDir();
installFakeCodex(binDir);
initGitRepo(repo);

const result = run("node", [SCRIPT, "task", "--json"], {
cwd: repo,
env: buildEnv(binDir),
input: " stdin prompt with boundary whitespace \n"
});

assert.equal(result.status, 0, result.stderr);
const fakeState = JSON.parse(fs.readFileSync(path.join(binDir, "fake-codex-state.json"), "utf8"));
assert.equal(fakeState.lastTurnStart.prompt, "stdin prompt with boundary whitespace");
});

test("task rejects a prompt-file digest mismatch before creating a job", () => {
const repo = makeTempDir();
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 approved = Buffer.from("approved prompt", "utf8");
const promptFile = path.join(repo, "prompt.txt");
fs.writeFileSync(promptFile, "substituted prompt", "utf8");
const digest = crypto.createHash("sha256").update(approved).digest("hex");
const stateDir = resolveStateDir(repo);

const result = run(
"node",
[SCRIPT, "task", "--json", "--prompt-file", promptFile, "--prompt-file-sha256", digest],
{ cwd: repo }
);

assert.notEqual(result.status, 0);
assert.match(result.stderr, /Prompt file SHA-256 mismatch/);
assert.equal(fs.existsSync(path.join(stateDir, "state.json")), false);
assert.equal(fs.existsSync(path.join(stateDir, "jobs")), false);
});

test("background prompt-file task persists the actual SHA-256 and exact prompt", async () => {
const repo = makeTempDir();
const binDir = makeTempDir();
installFakeCodex(binDir, "slow-task");
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 prompt = " Background prompt with $ and `literal` bytes. \n";
const promptFile = path.join(repo, "prompt.txt");
fs.writeFileSync(promptFile, prompt, "utf8");
const digest = crypto.createHash("sha256").update(Buffer.from(prompt, "utf8")).digest("hex");
const env = buildEnv(binDir);

const launched = run(
"node",
[SCRIPT, "task", "--background", "--json", "--prompt-file", promptFile],
{ cwd: repo, env }
);
assert.equal(launched.status, 0, launched.stderr);
const jobId = JSON.parse(launched.stdout).jobId;
const stateDir = resolveStateDir(repo);

const stored = await waitFor(() => {
const jobFile = path.join(stateDir, "jobs", `${jobId}.json`);
if (!fs.existsSync(jobFile)) return null;
const value = JSON.parse(fs.readFileSync(jobFile, "utf8"));
return value.request?.promptFileSha256 ? value : null;
});
assert.equal(stored.request.promptFileSha256, digest);
assert.equal(stored.request.prompt, prompt);
assert.equal(stored.request.promptSource, "file");

const waited = run(
"node",
[SCRIPT, "status", jobId, "--wait", "--timeout-ms", "15000", "--json"],
{ cwd: repo, env }
);
assert.equal(waited.status, 0, waited.stderr);
assert.equal(JSON.parse(waited.stdout).job.status, "completed");
const fakeState = JSON.parse(fs.readFileSync(path.join(binDir, "fake-codex-state.json"), "utf8"));
assert.equal(fakeState.lastTurnStart.prompt, prompt);

const result = run("node", [SCRIPT, "result", jobId, "--json"], { cwd: repo, env });
assert.equal(result.status, 0, result.stderr);
assert.equal(JSON.parse(result.stdout).storedJob.result.promptFileSha256, digest);
});
Loading