Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
25 changes: 11 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 @@ -513,7 +514,8 @@ async function executeTaskRun(request) {
threadId: result.threadId,
rawOutput,
touchedFiles: result.touchedFiles,
reasoningSummary: result.reasoningSummary
reasoningSummary: result.reasoningSummary,
...(request.promptSha256 ? { promptSha256: request.promptSha256 } : {})
};

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

function buildTaskRequest({ cwd, model, effort, prompt, write, resumeLast, jobId }) {
function buildTaskRequest({ cwd, model, effort, prompt, promptSha256 = null, write, resumeLast, jobId }) {
return {
cwd,
model,
effort,
prompt,
...(promptSha256 ? { promptSha256 } : {}),
write,
resumeLast,
jobId
Expand Down Expand Up @@ -640,15 +643,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 +755,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 +766,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 +790,7 @@ async function handleTask(argv) {
model,
effort,
prompt,
promptSha256: promptInput.sha256,
write,
resumeLast,
jobId: job.id
Expand All @@ -813,6 +809,7 @@ async function handleTask(argv) {
model,
effort,
prompt,
promptSha256: promptInput.sha256,
write,
resumeLast,
jobId: job.id,
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 bytes to the prompt that Codex receives. 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
2 changes: 2 additions & 0 deletions tests/commands.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,8 @@ 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 bytes to the prompt that Codex receives/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
104 changes: 104 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,106 @@ 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 returns their SHA-256 receipt", () => {
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.promptSha256, digest);
const fakeState = JSON.parse(fs.readFileSync(path.join(binDir, "fake-codex-state.json"), "utf8"));
assert.equal(fakeState.lastTurnStart.prompt, prompt.trim());
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.promptSha256, digest);
});

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?.promptSha256 ? value : null;
});
assert.equal(stored.request.promptSha256, digest);
assert.equal(stored.request.prompt, prompt);

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 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.promptSha256, digest);
});
102 changes: 102 additions & 0 deletions tests/task-prompt.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import test from "node:test";
import assert from "node:assert/strict";

import { readTaskPromptInput } from "../plugins/codex/scripts/lib/task-prompt.mjs";
import { makeTempDir } from "./helpers.mjs";

function sha256(bytes) {
return crypto.createHash("sha256").update(bytes).digest("hex");
}

test("readTaskPromptInput verifies and decodes the same prompt-file bytes", () => {
const cwd = makeTempDir();
const bytes = Buffer.from("review $HOME and `ticks`\n", "utf8");
fs.writeFileSync(path.join(cwd, "prompt.txt"), bytes);

const input = readTaskPromptInput(
cwd,
{ "prompt-file": "prompt.txt", "prompt-file-sha256": sha256(bytes).toUpperCase() },
[],
() => "unused"
);

assert.equal(input.text, bytes.toString("utf8"));
assert.equal(input.source, "file");
assert.equal(input.sha256, sha256(bytes));
assert.equal(input.filePath, path.join(cwd, "prompt.txt"));
});

test("readTaskPromptInput rejects changed prompt-file bytes", () => {
const cwd = makeTempDir();
const approved = Buffer.from("approved prompt", "utf8");
fs.writeFileSync(path.join(cwd, "prompt.txt"), "substituted prompt", "utf8");

assert.throws(
() =>
readTaskPromptInput(
cwd,
{ "prompt-file": "prompt.txt", "prompt-file-sha256": sha256(approved) },
[],
() => "unused"
),
/Prompt file SHA-256 mismatch.*expected.*received/
);
});

for (const digest of ["abc", "g".repeat(64), "a".repeat(63), "a".repeat(65)]) {
test(`readTaskPromptInput rejects malformed digest ${digest.slice(0, 8)}`, () => {
const cwd = makeTempDir();
fs.writeFileSync(path.join(cwd, "prompt.txt"), "prompt", "utf8");
assert.throws(
() =>
readTaskPromptInput(
cwd,
{ "prompt-file": "prompt.txt", "prompt-file-sha256": digest },
[],
() => "unused"
),
/exactly 64 hexadecimal characters/
);
});
}

test("readTaskPromptInput rejects digest without prompt-file", () => {
assert.throws(
() =>
readTaskPromptInput(
makeTempDir(),
{ "prompt-file-sha256": "a".repeat(64) },
["do", "not", "leak"],
() => "unused"
),
/requires `--prompt-file/
);
});

test("readTaskPromptInput records a receipt without enforcing a digest", () => {
const cwd = makeTempDir();
const bytes = Buffer.from("compatible prompt", "utf8");
fs.writeFileSync(path.join(cwd, "prompt.txt"), bytes);

const input = readTaskPromptInput(cwd, { "prompt-file": "prompt.txt" }, [], () => "unused");
assert.equal(input.text, "compatible prompt");
assert.equal(input.sha256, sha256(bytes));
});

test("readTaskPromptInput preserves positional and stdin transports", () => {
assert.deepEqual(readTaskPromptInput(makeTempDir(), {}, ["hello", "world"], () => "unused"), {
text: "hello world",
source: "positional",
sha256: null,
filePath: null
});
assert.deepEqual(readTaskPromptInput(makeTempDir(), {}, [], () => "stdin prompt"), {
text: "stdin prompt",
source: "stdin",
sha256: null,
filePath: null
});
});
1 change: 1 addition & 0 deletions tsconfig.app-server.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"plugins/codex/scripts/lib/codex.mjs",
"plugins/codex/scripts/lib/fs.mjs",
"plugins/codex/scripts/lib/process.mjs",
"plugins/codex/scripts/lib/task-prompt.mjs",
"plugins/codex/scripts/lib/app-server-protocol.d.ts",
"plugins/codex/.generated/app-server-types/**/*.ts"
]
Expand Down