Compare commits

..

1 Commits

Author SHA1 Message Date
Dominik Kundel b5938a651e bump: update plugin version to 1.0.3 2026-04-07 22:09:46 -07:00
26 changed files with 61 additions and 824 deletions
+2 -2
View File
@@ -5,13 +5,13 @@
},
"metadata": {
"description": "Codex plugins to use in Claude Code for delegation and code review.",
"version": "1.0.6"
"version": "1.0.3"
},
"plugins": [
{
"name": "codex",
"description": "Use Codex from Claude Code to review code or delegate tasks.",
"version": "1.0.6",
"version": "1.0.3",
"author": {
"name": "OpenAI"
},
+2 -17
View File
@@ -11,7 +11,7 @@ they already have.
- `/codex:review` for a normal read-only Codex review
- `/codex:adversarial-review` for a steerable challenge review
- `/codex:rescue`, `/codex:transfer`, `/codex:status`, `/codex:result`, and `/codex:cancel` to delegate work, hand off sessions, and manage background jobs
- `/codex:rescue`, `/codex:status`, `/codex:result`, and `/codex:cancel` to delegate work and manage background jobs
## Requirements
@@ -162,21 +162,6 @@ Ask Codex to redesign the database connection to be more resilient.
- if you say `spark`, the plugin maps that to `gpt-5.3-codex-spark`
- follow-up rescue requests can continue the latest Codex task in the repo
### `/codex:transfer`
Creates a persistent Codex thread from the current Claude Code session and prints a `codex resume <session-id>` command.
Use it when you started a debugging or implementation conversation in Claude Code and want to continue that same context directly in Codex.
Examples:
```bash
/codex:transfer
/codex:transfer --source ~/.claude/projects/-Users-me-repo/<session-id>.jsonl
```
The plugin's existing `SessionStart` hook supplies the current transcript path automatically; `--source` is available as a manual override. The transfer uses Codex's external-agent session importer, so it follows the same conversion rules as importing Claude history in the Codex App and creates visible turns that can be continued in the App or TUI. The source must be under `~/.claude/projects`, and older Codex versions that do not expose session import must be upgraded before using this command.
### `/codex:status`
Shows running and recent Codex jobs for the current repository.
@@ -274,7 +259,7 @@ If you want to change the default reasoning effort or the default model that get
```toml
model = "gpt-5.4-mini"
model_reasoning_effort = "high"
model_reasoning_effort = "xhigh"
```
Your configuration will be picked up based on:
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@openai/codex-plugin-cc",
"version": "1.0.6",
"version": "1.0.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@openai/codex-plugin-cc",
"version": "1.0.6",
"version": "1.0.3",
"license": "Apache-2.0",
"devDependencies": {
"@types/node": "^25.5.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@openai/codex-plugin-cc",
"version": "1.0.6",
"version": "1.0.3",
"private": true,
"type": "module",
"description": "Use Codex from Claude Code to review code or delegate tasks.",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "codex",
"version": "1.0.6",
"version": "1.0.3",
"description": "Use Codex from Claude Code to review code or delegate tasks.",
"author": {
"name": "OpenAI"
-1
View File
@@ -1,7 +1,6 @@
---
name: codex-rescue
description: Proactively use when Claude Code is stuck, wants a second implementation or diagnosis pass, needs a deeper root-cause investigation, or should hand a substantial coding task to Codex through the shared runtime
model: sonnet
tools: Bash
skills:
- codex-cli-runtime
+1 -1
View File
@@ -5,4 +5,4 @@ disable-model-invocation: true
allowed-tools: Bash(node:*)
---
!`node "${CLAUDE_PLUGIN_ROOT}/scripts/codex-companion.mjs" cancel "$ARGUMENTS"`
!`node "${CLAUDE_PLUGIN_ROOT}/scripts/codex-companion.mjs" cancel $ARGUMENTS`
+3 -3
View File
@@ -1,11 +1,11 @@
---
description: Delegate investigation, an explicit fix request, or follow-up rescue work to the Codex rescue subagent
argument-hint: "[--background|--wait] [--resume|--fresh] [--model <model|spark>] [--effort <none|minimal|low|medium|high|xhigh>] [what Codex should investigate, solve, or continue]"
allowed-tools: Bash(node:*), AskUserQuestion, Agent
context: fork
allowed-tools: Bash(node:*), AskUserQuestion
---
Invoke the `codex:codex-rescue` subagent via the `Agent` tool (`subagent_type: "codex:codex-rescue"`), forwarding the raw user request as the prompt.
`codex:codex-rescue` is a subagent, not a skill — do not call `Skill(codex:codex-rescue)` (no such skill) or `Skill(codex:rescue)` (that re-enters this command and hangs the session). The command runs inline so the `Agent` tool stays in scope; forked general-purpose subagents do not expose it.
Route this request to the `codex:codex-rescue` subagent.
The final user-visible response must be Codex's output verbatim.
Raw user request:
+1 -1
View File
@@ -5,7 +5,7 @@ disable-model-invocation: true
allowed-tools: Bash(node:*)
---
!`node "${CLAUDE_PLUGIN_ROOT}/scripts/codex-companion.mjs" result "$ARGUMENTS"`
!`node "${CLAUDE_PLUGIN_ROOT}/scripts/codex-companion.mjs" result $ARGUMENTS`
Present the full command output to the user. Do not summarize or condense it. Preserve all details including:
- Job ID and status
+1 -1
View File
@@ -5,7 +5,7 @@ disable-model-invocation: true
allowed-tools: Bash(node:*)
---
!`node "${CLAUDE_PLUGIN_ROOT}/scripts/codex-companion.mjs" status "$ARGUMENTS"`
!`node "${CLAUDE_PLUGIN_ROOT}/scripts/codex-companion.mjs" status $ARGUMENTS`
If the user did not pass a job ID:
- Render the command output as a single Markdown table for the current and past runs in this session.
-10
View File
@@ -1,10 +0,0 @@
---
description: Transfer the current Claude Code session into a resumable Codex thread
argument-hint: "[--source <claude-jsonl>]"
disable-model-invocation: true
allowed-tools: Bash(node:*)
---
!`node "${CLAUDE_PLUGIN_ROOT}/scripts/codex-companion.mjs" transfer "$ARGUMENTS"`
Present the command output to the user exactly as returned. Preserve the Codex session ID and the `codex resume <session-id>` command.
@@ -32,7 +32,6 @@ Actively try to disprove the change.
Look for violated invariants, missing guards, unhandled failure paths, and assumptions that stop being true under stress.
Trace how bad inputs, retries, concurrent actions, or partially completed operations move through the code.
If the user supplied a focus area, weight it heavily, but still report any other material issue you can defend.
{{REVIEW_COLLECTION_GUIDANCE}}
</review_method>
<finding_bar>
+1 -48
View File
@@ -14,14 +14,12 @@ import {
getCodexAuthStatus,
getCodexAvailability,
getSessionRuntimeStatus,
importExternalAgentSession,
interruptAppServerTurn,
parseStructuredOutput,
readOutputSchema,
runAppServerReview,
runAppServerTurn
} from "./lib/codex.mjs";
import { resolveClaudeSessionPath } from "./lib/claude-session-transfer.mjs";
import { readStdinIfPiped } from "./lib/fs.mjs";
import { collectReviewContext, ensureGitRepository, resolveReviewTarget } from "./lib/git.mjs";
import { binaryAvailable, terminateProcessTree } from "./lib/process.mjs";
@@ -80,7 +78,6 @@ function printUsage() {
" 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 transfer [--source <claude-jsonl>] [--json]",
" node scripts/codex-companion.mjs status [job-id] [--all] [--json]",
" node scripts/codex-companion.mjs result [job-id] [--json]",
" node scripts/codex-companion.mjs cancel [job-id] [--json]"
@@ -205,7 +202,7 @@ async function buildSetupReport(cwd, actionsTaken = []) {
npm: npmStatus,
codex: codexStatus,
auth: authStatus,
sessionRuntime: getSessionRuntimeStatus(process.env, workspaceRoot),
sessionRuntime: getSessionRuntimeStatus(),
reviewGateEnabled: Boolean(config.stopReviewGate),
actionsTaken,
nextSteps
@@ -244,7 +241,6 @@ function buildAdversarialReviewPrompt(context, focusText) {
REVIEW_KIND: "Adversarial Review",
TARGET_LABEL: context.target.label,
USER_FOCUS: focusText || "No extra focus provided.",
REVIEW_COLLECTION_GUIDANCE: context.collectionGuidance,
REVIEW_INPUT: context.content
});
}
@@ -613,33 +609,6 @@ function buildTaskRequest({ cwd, model, effort, prompt, write, resumeLast, jobId
};
}
function renderTransferResult(payload) {
const lines = [
"Transferred the Claude session into a Codex thread with visible turn history.",
`Codex session ID: ${payload.threadId}`,
`Resume in Codex: ${payload.resumeCommand}`
];
return `${lines.join("\n")}\n`;
}
async function executeTransfer(cwd, options = {}) {
const sourcePath = resolveClaudeSessionPath(cwd, {
source: options.source
});
const result = await importExternalAgentSession(cwd, { sourcePath });
const payload = {
threadId: result.threadId,
resumeCommand: `codex resume ${result.threadId}`,
sourcePath,
sessionId: path.basename(sourcePath, ".jsonl")
};
return {
payload,
rendered: renderTransferResult(payload)
};
}
function readTaskPrompt(cwd, options, positionals) {
if (options["prompt-file"]) {
return fs.readFileSync(path.resolve(cwd, options["prompt-file"]), "utf8");
@@ -822,19 +791,6 @@ async function handleTask(argv) {
);
}
async function handleTransfer(argv) {
const { options } = parseCommandInput(argv, {
valueOptions: ["cwd", "source"],
booleanOptions: ["json"]
});
const cwd = resolveCommandCwd(options);
const { payload, rendered } = await executeTransfer(cwd, {
source: options.source
});
outputCommandResult(payload, rendered, options.json);
}
async function handleTaskWorker(argv) {
const { options } = parseCommandInput(argv, {
valueOptions: ["cwd", "job-id"]
@@ -1043,9 +999,6 @@ async function main() {
case "task":
await handleTask(argv);
break;
case "transfer":
await handleTransfer(argv);
break;
case "task-worker":
await handleTaskWorker(argv);
break;
-3
View File
@@ -6,8 +6,6 @@ import type {
ServerNotification
} from "../../.generated/app-server-types/index.js";
import type {
ExternalAgentConfigImportParams,
ExternalAgentConfigImportResponse,
ReviewStartParams,
ReviewStartResponse,
ReviewTarget,
@@ -58,7 +56,6 @@ export interface CodexAppServerClientOptions {
export interface AppServerMethodMap {
initialize: { params: InitializeParams; result: InitializeResponse };
"externalAgentConfig/import": { params: ExternalAgentConfigImportParams; result: ExternalAgentConfigImportResponse };
"thread/start": { params: ThreadStartParams; result: ThreadStartResponse };
"thread/resume": { params: ThreadResumeParams; result: ThreadResumeResponse };
"thread/name/set": { params: ThreadSetNameParams; result: ThreadSetNameResponse };
+1 -5
View File
@@ -32,7 +32,6 @@ const DEFAULT_CLIENT_INFO = {
/** @type {InitializeCapabilities} */
const DEFAULT_CAPABILITIES = {
experimentalApi: false,
requestAttestation: false,
optOutNotificationMethods: [
"item/agentMessage/delta",
"item/reasoning/summaryTextDelta",
@@ -207,13 +206,10 @@ class SpawnedCodexAppServerClient extends AppServerClientBase {
});
this.proc.on("exit", (code, signal) => {
const stderr = this.stderr.trim();
const detail =
code === 0
? null
: createProtocolError(
`codex app-server exited unexpectedly (${signal ? `signal ${signal}` : `exit ${code}`}).${stderr ? `\n${stderr}` : ""}`
);
: createProtocolError(`codex app-server exited unexpectedly (${signal ? `signal ${signal}` : `exit ${code}`}).`);
this.handleExit(detail);
});
@@ -1,44 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { ensureAbsolutePath } from "./fs.mjs";
export const TRANSCRIPT_PATH_ENV = "CODEX_COMPANION_TRANSCRIPT_PATH";
const CLAUDE_PROJECTS_DIR = path.join(os.homedir(), ".claude", "projects");
function resolveUserPath(cwd, value) {
if (value === "~") {
return os.homedir();
}
if (String(value).startsWith("~/")) {
return path.join(os.homedir(), String(value).slice(2));
}
return ensureAbsolutePath(cwd, value);
}
export function resolveClaudeSessionPath(cwd, options = {}) {
const requestedPath = options.source || process.env[TRANSCRIPT_PATH_ENV];
if (!requestedPath) {
throw new Error("Could not identify the current Claude transcript. Retry with --source <path-to-claude-jsonl>.");
}
const sourcePath = resolveUserPath(cwd, requestedPath);
if (path.extname(sourcePath) !== ".jsonl") {
throw new Error(`Claude session source must be a JSONL file: ${sourcePath}`);
}
let source;
let projects;
try {
source = fs.realpathSync(sourcePath);
projects = fs.realpathSync(CLAUDE_PROJECTS_DIR);
} catch {
throw new Error(`Claude session file not found: ${sourcePath}`);
}
const relative = path.relative(projects, source);
if (relative === "" || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
throw new Error(`Codex can import Claude sessions only from ${CLAUDE_PROJECTS_DIR}: ${source}`);
}
return source;
}
+2 -133
View File
@@ -34,11 +34,6 @@
* onProgress: ProgressReporter | null
* }} TurnCaptureState
*/
import crypto from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { readJsonFile } from "./fs.mjs";
import { BROKER_BUSY_RPC_CODE, BROKER_ENDPOINT_ENV, CodexAppServerClient } from "./app-server.mjs";
import { loadBrokerSession } from "./broker-lifecycle.mjs";
@@ -48,8 +43,6 @@ const SERVICE_NAME = "claude_code_codex_plugin";
const TASK_THREAD_PREFIX = "Codex Companion Task";
const DEFAULT_CONTINUE_PROMPT =
"Continue from the current thread state. Pick the next highest-value step and follow through until the task is resolved.";
const EXTERNAL_AGENT_IMPORT_COMPLETED = "externalAgentConfig/import/completed";
const EXTERNAL_AGENT_IMPORT_TIMEOUT_MS = 2 * 60 * 1000;
function cleanCodexStderr(stderr) {
return stderr
@@ -67,7 +60,8 @@ function buildThreadParams(cwd, options = {}) {
approvalPolicy: options.approvalPolicy ?? "never",
sandbox: options.sandbox ?? "read-only",
serviceName: SERVICE_NAME,
ephemeral: options.ephemeral ?? true
ephemeral: options.ephemeral ?? true,
experimentalRawEvents: false
};
}
@@ -641,94 +635,6 @@ async function withAppServer(cwd, fn) {
}
}
async function withDirectAppServer(cwd, fn) {
const client = await CodexAppServerClient.connect(cwd, { disableBroker: true });
try {
return await fn(client);
} finally {
await client.close();
}
}
function resolveCodexHome() {
return path.resolve(process.env.CODEX_HOME || path.join(os.homedir(), ".codex"));
}
function sourceContentSha256(sourcePath) {
return crypto.createHash("sha256").update(fs.readFileSync(sourcePath)).digest("hex");
}
function importedThreadIdForSource(sourcePath) {
const ledgerPath = path.join(resolveCodexHome(), "external_agent_session_imports.json");
if (!fs.existsSync(ledgerPath)) {
return null;
}
const ledger = readJsonFile(ledgerPath);
const canonicalSource = fs.realpathSync(sourcePath);
const contentSha256 = sourceContentSha256(canonicalSource);
const records = Array.isArray(ledger?.records) ? ledger.records : [];
const match = records
.filter(
(record) =>
record?.source_path === canonicalSource &&
record?.content_sha256 === contentSha256 &&
typeof record?.imported_thread_id === "string"
)
.at(-1);
return match?.imported_thread_id ?? null;
}
function externalAgentSessionMigration(sourcePath, cwd) {
return {
migrationItems: [
{
itemType: "SESSIONS",
description: `Transfer Claude session ${path.basename(sourcePath)}`,
cwd: null,
details: {
plugins: [],
sessions: [{ path: sourcePath, cwd, title: null }],
mcpServers: [],
hooks: [],
subagents: [],
commands: []
}
}
]
};
}
async function requestExternalAgentSessionImport(client, params) {
const previousHandler = client.notificationHandler;
let timeout = null;
let resolveCompleted;
let rejectCompleted;
const completed = new Promise((resolve, reject) => {
resolveCompleted = resolve;
rejectCompleted = reject;
});
void completed.catch(() => {});
client.setNotificationHandler((message) => {
if (message.method === EXTERNAL_AGENT_IMPORT_COMPLETED) {
resolveCompleted();
return;
}
previousHandler?.(message);
});
timeout = setTimeout(() => {
rejectCompleted(new Error("Timed out waiting for Codex to finish importing the Claude session."));
}, EXTERNAL_AGENT_IMPORT_TIMEOUT_MS);
try {
await client.request("externalAgentConfig/import", params);
await completed;
} finally {
clearTimeout(timeout);
client.setNotificationHandler(previousHandler ?? null);
}
}
async function startThread(client, cwd, options = {}) {
const response = await client.request("thread/start", buildThreadParams(cwd, options));
const threadId = response.thread.id;
@@ -1055,43 +961,6 @@ export async function runAppServerReview(cwd, options = {}) {
});
}
export async function importExternalAgentSession(cwd, options = {}) {
const availability = getCodexAvailability(cwd);
if (!availability.available) {
throw new Error("Codex CLI is not installed or is missing required runtime support. Install it with `npm install -g @openai/codex`, then rerun `/codex:setup`.");
}
if (!options.sourcePath) {
throw new Error("A Claude session source path is required.");
}
return withDirectAppServer(cwd, async (client) => {
emitProgress(options.onProgress, "Importing Claude session into Codex.", "transferring");
try {
await requestExternalAgentSessionImport(client, externalAgentSessionMigration(options.sourcePath, cwd));
} catch (error) {
if (error?.rpcCode === -32601) {
throw new Error(
"This Codex version does not support Claude session transfer. Update Codex with `npm install -g @openai/codex@latest`, then retry.",
{ cause: error }
);
}
throw error;
}
const threadId = importedThreadIdForSource(options.sourcePath);
if (!threadId) {
const stderr = cleanCodexStderr(client.stderr);
throw new Error(
`Codex reported that the Claude import completed, but did not record an imported thread.${stderr ? `\n${stderr}` : " Check the Codex app-server logs for the underlying import error."}`
);
}
emitProgress(options.onProgress, `Claude session imported (${threadId}).`, "completed", { threadId });
return {
threadId,
stderr: cleanCodexStderr(client.stderr)
};
});
}
export async function runAppServerTurn(cwd, options = {}) {
const availability = getCodexAvailability(cwd);
if (!availability.available) {
+32 -157
View File
@@ -2,77 +2,16 @@ import fs from "node:fs";
import path from "node:path";
import { isProbablyText } from "./fs.mjs";
import { formatCommandFailure, runCommand, runCommandChecked } from "./process.mjs";
import { runCommand, runCommandChecked } from "./process.mjs";
const MAX_UNTRACKED_BYTES = 24 * 1024;
const DEFAULT_INLINE_DIFF_MAX_FILES = 2;
const DEFAULT_INLINE_DIFF_MAX_BYTES = 256 * 1024;
// Git is directly executable on Windows. Repository-derived arguments must never pass through a shell.
function git(cwd, args, options = {}) {
return runCommand("git", args, { cwd, ...options, shell: false });
return runCommand("git", args, { cwd, ...options });
}
function gitChecked(cwd, args, options = {}) {
return runCommandChecked("git", args, { cwd, ...options, shell: false });
}
function listUniqueFiles(...groups) {
return [...new Set(groups.flat().filter(Boolean))].sort();
}
function normalizeMaxInlineFiles(value) {
const parsed = Number(value);
if (!Number.isFinite(parsed) || parsed < 0) {
return DEFAULT_INLINE_DIFF_MAX_FILES;
}
return Math.floor(parsed);
}
function normalizeMaxInlineDiffBytes(value) {
const parsed = Number(value);
if (!Number.isFinite(parsed) || parsed < 0) {
return DEFAULT_INLINE_DIFF_MAX_BYTES;
}
return Math.floor(parsed);
}
function measureGitOutputBytes(cwd, args, maxBytes) {
const result = git(cwd, args, { maxBuffer: maxBytes + 1 });
if (result.error && /** @type {NodeJS.ErrnoException} */ (result.error).code === "ENOBUFS") {
return maxBytes + 1;
}
if (result.error) {
throw result.error;
}
if (result.status !== 0) {
throw new Error(formatCommandFailure(result));
}
return Buffer.byteLength(result.stdout, "utf8");
}
function measureCombinedGitOutputBytes(cwd, argSets, maxBytes) {
let totalBytes = 0;
for (const args of argSets) {
const remainingBytes = maxBytes - totalBytes;
if (remainingBytes < 0) {
return maxBytes + 1;
}
totalBytes += measureGitOutputBytes(cwd, args, remainingBytes);
if (totalBytes > maxBytes) {
return totalBytes;
}
}
return totalBytes;
}
function buildBranchComparison(cwd, baseRef) {
const mergeBase = gitChecked(cwd, ["merge-base", "HEAD", baseRef]).stdout.trim();
return {
mergeBase,
commitRange: `${mergeBase}..HEAD`,
reviewRange: `${baseRef}...HEAD`
};
return runCommandChecked("git", args, { cwd, ...options });
}
export function ensureGitRepository(cwd) {
@@ -222,115 +161,55 @@ function formatUntrackedFile(cwd, relativePath) {
return [`### ${relativePath}`, "```", buffer.toString("utf8").trimEnd(), "```"].join("\n");
}
function collectWorkingTreeContext(cwd, state, options = {}) {
const includeDiff = options.includeDiff !== false;
const status = gitChecked(cwd, ["status", "--short", "--untracked-files=all"]).stdout.trim();
const changedFiles = listUniqueFiles(state.staged, state.unstaged, state.untracked);
function collectWorkingTreeContext(cwd, state) {
const status = gitChecked(cwd, ["status", "--short"]).stdout.trim();
const stagedDiff = gitChecked(cwd, ["diff", "--cached", "--binary", "--no-ext-diff", "--submodule=diff"]).stdout;
const unstagedDiff = gitChecked(cwd, ["diff", "--binary", "--no-ext-diff", "--submodule=diff"]).stdout;
const untrackedBody = state.untracked.map((file) => formatUntrackedFile(cwd, file)).join("\n\n");
let parts;
if (includeDiff) {
const stagedDiff = gitChecked(cwd, ["diff", "--cached", "--binary", "--no-ext-diff", "--submodule=diff"]).stdout;
const unstagedDiff = gitChecked(cwd, ["diff", "--binary", "--no-ext-diff", "--submodule=diff"]).stdout;
const untrackedBody = state.untracked.map((file) => formatUntrackedFile(cwd, file)).join("\n\n");
parts = [
formatSection("Git Status", status),
formatSection("Staged Diff", stagedDiff),
formatSection("Unstaged Diff", unstagedDiff),
formatSection("Untracked Files", untrackedBody)
];
} else {
const stagedStat = gitChecked(cwd, ["diff", "--shortstat", "--cached"]).stdout.trim();
const unstagedStat = gitChecked(cwd, ["diff", "--shortstat"]).stdout.trim();
const untrackedBody = state.untracked.map((file) => formatUntrackedFile(cwd, file)).join("\n\n");
parts = [
formatSection("Git Status", status),
formatSection("Staged Diff Stat", stagedStat),
formatSection("Unstaged Diff Stat", unstagedStat),
formatSection("Changed Files", changedFiles.join("\n")),
formatSection("Untracked Files", untrackedBody)
];
}
const parts = [
formatSection("Git Status", status),
formatSection("Staged Diff", stagedDiff),
formatSection("Unstaged Diff", unstagedDiff),
formatSection("Untracked Files", untrackedBody)
];
return {
mode: "working-tree",
summary: `Reviewing ${state.staged.length} staged, ${state.unstaged.length} unstaged, and ${state.untracked.length} untracked file(s).`,
content: parts.join("\n"),
changedFiles
content: parts.join("\n")
};
}
function collectBranchContext(cwd, baseRef, options = {}) {
const includeDiff = options.includeDiff !== false;
const comparison = options.comparison ?? buildBranchComparison(cwd, baseRef);
function collectBranchContext(cwd, baseRef) {
const mergeBase = gitChecked(cwd, ["merge-base", "HEAD", baseRef]).stdout.trim();
const commitRange = `${mergeBase}..HEAD`;
const currentBranch = getCurrentBranch(cwd);
const changedFiles = gitChecked(cwd, ["diff", "--name-only", comparison.commitRange]).stdout.trim().split("\n").filter(Boolean);
const logOutput = gitChecked(cwd, ["log", "--oneline", "--decorate", comparison.commitRange]).stdout.trim();
const diffStat = gitChecked(cwd, ["diff", "--stat", comparison.commitRange]).stdout.trim();
const logOutput = gitChecked(cwd, ["log", "--oneline", "--decorate", commitRange]).stdout.trim();
const diffStat = gitChecked(cwd, ["diff", "--stat", commitRange]).stdout.trim();
const diff = gitChecked(cwd, ["diff", "--binary", "--no-ext-diff", "--submodule=diff", commitRange]).stdout;
return {
mode: "branch",
summary: `Reviewing branch ${currentBranch} against ${baseRef} from merge-base ${comparison.mergeBase}.`,
content: includeDiff
? [
formatSection("Commit Log", logOutput),
formatSection("Diff Stat", diffStat),
formatSection(
"Branch Diff",
gitChecked(cwd, ["diff", "--binary", "--no-ext-diff", "--submodule=diff", comparison.commitRange]).stdout
)
].join("\n")
: [
formatSection("Commit Log", logOutput),
formatSection("Diff Stat", diffStat),
formatSection("Changed Files", changedFiles.join("\n"))
].join("\n"),
changedFiles,
comparison
summary: `Reviewing branch ${currentBranch} against ${baseRef} from merge-base ${mergeBase}.`,
content: [
formatSection("Commit Log", logOutput),
formatSection("Diff Stat", diffStat),
formatSection("Branch Diff", diff)
].join("\n")
};
}
function buildAdversarialCollectionGuidance(options = {}) {
if (options.includeDiff !== false) {
return "Use the repository context below as primary evidence.";
}
return "The repository context below is a lightweight summary. Inspect the target diff yourself with read-only git commands before finalizing findings.";
}
export function collectReviewContext(cwd, target, options = {}) {
export function collectReviewContext(cwd, target) {
const repoRoot = getRepoRoot(cwd);
const currentBranch = getCurrentBranch(repoRoot);
const maxInlineFiles = normalizeMaxInlineFiles(options.maxInlineFiles);
const maxInlineDiffBytes = normalizeMaxInlineDiffBytes(options.maxInlineDiffBytes);
const state = getWorkingTreeState(cwd);
const currentBranch = getCurrentBranch(cwd);
let details;
let includeDiff;
let diffBytes;
if (target.mode === "working-tree") {
const state = getWorkingTreeState(repoRoot);
diffBytes = measureCombinedGitOutputBytes(
repoRoot,
[
["diff", "--cached", "--binary", "--no-ext-diff", "--submodule=diff"],
["diff", "--binary", "--no-ext-diff", "--submodule=diff"]
],
maxInlineDiffBytes
);
includeDiff =
options.includeDiff ??
(listUniqueFiles(state.staged, state.unstaged, state.untracked).length <= maxInlineFiles &&
diffBytes <= maxInlineDiffBytes);
details = collectWorkingTreeContext(repoRoot, state, { includeDiff });
details = collectWorkingTreeContext(repoRoot, state);
} else {
const comparison = buildBranchComparison(repoRoot, target.baseRef);
const fileCount = gitChecked(repoRoot, ["diff", "--name-only", comparison.commitRange]).stdout.trim().split("\n").filter(Boolean).length;
diffBytes = measureGitOutputBytes(
repoRoot,
["diff", "--binary", "--no-ext-diff", "--submodule=diff", comparison.commitRange],
maxInlineDiffBytes
);
includeDiff = options.includeDiff ?? (fileCount <= maxInlineFiles && diffBytes <= maxInlineDiffBytes);
details = collectBranchContext(repoRoot, target.baseRef, { includeDiff, comparison });
details = collectBranchContext(repoRoot, target.baseRef);
}
return {
@@ -338,10 +217,6 @@ export function collectReviewContext(cwd, target, options = {}) {
repoRoot,
branch: currentBranch,
target,
fileCount: details.changedFiles.length,
diffBytes,
inputMode: includeDiff ? "inline-diff" : "self-collect",
collectionGuidance: buildAdversarialCollectionGuidance({ includeDiff }),
...details
};
}
+1 -1
View File
@@ -231,7 +231,7 @@ export function buildStatusSnapshot(cwd, options = {}) {
return {
workspaceRoot,
config,
sessionRuntime: getSessionRuntimeStatus(options.env, workspaceRoot),
sessionRuntime: getSessionRuntimeStatus(options.env),
running,
latestFinished,
recent,
+1 -2
View File
@@ -7,9 +7,8 @@ export function runCommand(command, args = [], options = {}) {
env: options.env,
encoding: "utf8",
input: options.input,
maxBuffer: options.maxBuffer,
stdio: options.stdio ?? "pipe",
shell: options.shell ?? (process.platform === "win32" ? (process.env.SHELL || true) : false),
shell: process.platform === "win32" ? (process.env.SHELL || true) : false,
windowsHide: true
});
@@ -14,7 +14,6 @@ import {
teardownBrokerSession
} from "./lib/broker-lifecycle.mjs";
import { loadState, resolveStateFile, saveState } from "./lib/state.mjs";
import { TRANSCRIPT_PATH_ENV } from "./lib/claude-session-transfer.mjs";
import { resolveWorkspaceRoot } from "./lib/workspace.mjs";
export const SESSION_ID_ENV = "CODEX_COMPANION_SESSION_ID";
@@ -76,7 +75,6 @@ function cleanupSessionJobs(cwd, sessionId) {
function handleSessionStart(input) {
appendEnvVar(SESSION_ID_ENV, input.session_id);
appendEnvVar(TRANSCRIPT_PATH_ENV, input.transcript_path);
appendEnvVar(PLUGIN_DATA_ENV, process.env[PLUGIN_DATA_ENV]);
}
+5 -20
View File
@@ -79,8 +79,7 @@ test("continue is not exposed as a user-facing command", () => {
"result.md",
"review.md",
"setup.md",
"status.md",
"transfer.md"
"status.md"
]);
});
@@ -91,16 +90,7 @@ test("rescue command absorbs continue semantics", () => {
const runtimeSkill = read("skills/codex-cli-runtime/SKILL.md");
assert.match(rescue, /The final user-visible response must be Codex's output verbatim/i);
assert.match(rescue, /allowed-tools:\s*Bash\(node:\*\),\s*AskUserQuestion,\s*Agent/);
// Regression for #234: `Skill(codex:rescue)` from the main agent recursed
// because rescue.md named the routing with ambiguous prose ("Route this
// request to the `codex:codex-rescue` subagent") while running under
// `context: fork` — forked general-purpose subagents do not expose the
// `Agent` tool, so the fork fell back to `Skill` and re-entered this
// command. Pin the explicit transport and the inline (no-fork) execution.
assert.match(rescue, /subagent_type: "codex:codex-rescue"/);
assert.match(rescue, /do not call `Skill\(codex:codex-rescue\)`/i);
assert.doesNotMatch(rescue, /^context:\s*fork\b/m);
assert.match(rescue, /allowed-tools:\s*Bash\(node:\*\),\s*AskUserQuestion/);
assert.match(rescue, /--background\|--wait/);
assert.match(rescue, /--resume\|--fresh/);
assert.match(rescue, /--model <model\|spark>/);
@@ -164,25 +154,20 @@ test("rescue command absorbs continue semantics", () => {
assert.match(readme, /uses the same review target selection as `\/codex:review`/i);
assert.match(readme, /--base main challenge whether this was the right caching and retry design/);
assert.match(readme, /### `\/codex:rescue`/);
assert.match(readme, /### `\/codex:transfer`/);
assert.match(readme, /### `\/codex:status`/);
assert.match(readme, /### `\/codex:result`/);
assert.match(readme, /### `\/codex:cancel`/);
});
test("transfer, result, and cancel commands are exposed as deterministic runtime entrypoints", () => {
const transfer = read("commands/transfer.md");
test("result and cancel commands are exposed as deterministic runtime entrypoints", () => {
const result = read("commands/result.md");
const cancel = read("commands/cancel.md");
const resultHandling = read("skills/codex-result-handling/SKILL.md");
assert.match(transfer, /disable-model-invocation:\s*true/);
assert.match(transfer, /codex-companion\.mjs" transfer "\$ARGUMENTS"/);
assert.match(transfer, /codex resume <session-id>/);
assert.match(result, /disable-model-invocation:\s*true/);
assert.match(result, /codex-companion\.mjs" result "\$ARGUMENTS"/);
assert.match(result, /codex-companion\.mjs" result \$ARGUMENTS/);
assert.match(cancel, /disable-model-invocation:\s*true/);
assert.match(cancel, /codex-companion\.mjs" cancel "\$ARGUMENTS"/);
assert.match(cancel, /codex-companion\.mjs" cancel \$ARGUMENTS/);
assert.match(resultHandling, /do not turn a failed or incomplete Codex run into a Claude-side implementation attempt/i);
assert.match(resultHandling, /if Codex was never successfully invoked, do not generate a substitute answer at all/i);
});
-69
View File
@@ -9,7 +9,6 @@ export function installFakeCodex(binDir, behavior = "review-ok") {
const scriptPath = path.join(binDir, "codex");
const source = `#!/usr/bin/env node
const fs = require("node:fs");
const crypto = require("node:crypto");
const path = require("node:path");
const readline = require("node:readline");
@@ -145,21 +144,6 @@ function nextTurnId(state) {
return turnId;
}
function importLedgerPath() {
return path.join(process.env.CODEX_HOME || path.join(process.env.HOME, ".codex"), "external_agent_session_imports.json");
}
function loadImportLedger() {
const ledgerPath = importLedgerPath();
return fs.existsSync(ledgerPath) ? JSON.parse(fs.readFileSync(ledgerPath, "utf8")) : { records: [] };
}
function saveImportLedger(ledger) {
const ledgerPath = importLedgerPath();
fs.mkdirSync(path.dirname(ledgerPath), { recursive: true });
fs.writeFileSync(ledgerPath, JSON.stringify(ledger, null, 2));
}
function emitTurnCompleted(threadId, turnId, item) {
const items = Array.isArray(item) ? item : [item];
send({ method: "turn/started", params: { threadId, turn: buildTurn(turnId) } });
@@ -351,59 +335,6 @@ rl.on("line", (line) => {
break;
}
case "externalAgentConfig/import": {
if (BEHAVIOR === "external-import-unsupported") {
send({ id: message.id, error: { code: -32601, message: "Unsupported method: externalAgentConfig/import" } });
break;
}
if (BEHAVIOR === "external-import-fails") {
send({ id: message.id, result: {} });
send({ method: "externalAgentConfig/import/completed", params: {} });
break;
}
const sessions = (message.params.migrationItems || [])
.flatMap((item) => item.details && Array.isArray(item.details.sessions) ? item.details.sessions : []);
const session = sessions[0];
if (!session) {
throw new Error("missing external session migration");
}
const sourcePath = fs.realpathSync(session.path);
const contents = fs.readFileSync(sourcePath, "utf8");
const contentSha256 = crypto.createHash("sha256").update(contents).digest("hex");
const ledger = loadImportLedger();
let record = ledger.records.find(
(candidate) => candidate.source_path === sourcePath && candidate.content_sha256 === contentSha256
);
let thread;
if (record) {
thread = ensureThread(state, record.imported_thread_id);
} else {
const records = contents.split(/\\r?\\n/).filter(Boolean).map((line) => JSON.parse(line));
const title = records.find((entry) => entry.type === "custom-title")?.customTitle || null;
const messages = records
.filter((entry) => entry.type === "user" || entry.type === "assistant")
.map((entry) => ({ role: entry.type, text: entry.message?.content || "" }));
thread = nextThread(state, session.cwd, false);
thread.name = title;
thread.preview = messages.find((entry) => entry.role === "user")?.text || "";
thread.visibleMessages = messages;
state.lastExternalAgentImport = { sourcePath, threadId: thread.id, messages };
record = {
source_path: sourcePath,
content_sha256: contentSha256,
imported_thread_id: thread.id,
imported_at: now(),
source_modified_at: null
};
ledger.records.push(record);
saveState(state);
saveImportLedger(ledger);
}
send({ id: message.id, result: {} });
send({ method: "externalAgentConfig/import/completed", params: {} });
break;
}
case "review/start": {
const thread = ensureThread(state, message.params.threadId);
let reviewThread = thread;
-109
View File
@@ -38,35 +38,6 @@ test("resolveReviewTarget falls back to branch diff when repo is clean", () => {
assert.match(context.content, /Branch Diff/);
});
test("default branch names with special characters are passed to git literally", () => {
const cwd = makeTempDir();
const branchName = "main&branch-helper&x";
const helperOutputPath = path.join(cwd, "branch-helper-output");
initGitRepo(cwd);
fs.writeFileSync(path.join(cwd, "branch-helper.cmd"), "@echo branch-helper>branch-helper-output\r\n");
fs.writeFileSync(path.join(cwd, "app.js"), "console.log('base');\n");
run("git", ["add", "app.js", "branch-helper.cmd"], { cwd });
run("git", ["commit", "-m", "base"], { cwd });
run("git", ["branch", "-m", branchName], { cwd, shell: false });
run("git", ["update-ref", `refs/remotes/origin/${branchName}`, branchName], { cwd, shell: false });
run("git", ["symbolic-ref", "refs/remotes/origin/HEAD", `refs/remotes/origin/${branchName}`], {
cwd,
shell: false
});
run("git", ["checkout", "-b", "feature/test"], { cwd });
fs.writeFileSync(path.join(cwd, "app.js"), "console.log('feature');\n");
run("git", ["add", "app.js"], { cwd });
run("git", ["commit", "-m", "feature"], { cwd });
const target = resolveReviewTarget(cwd, {});
const context = collectReviewContext(cwd, target);
assert.equal(target.mode, "branch");
assert.equal(target.baseRef, branchName);
assert.match(context.content, /Branch Diff/);
assert.equal(fs.existsSync(helperOutputPath), false);
});
test("resolveReviewTarget honors explicit base overrides", () => {
const cwd = makeTempDir();
initGitRepo(cwd);
@@ -98,23 +69,6 @@ test("resolveReviewTarget requires an explicit base when no default branch can b
);
});
test("collectReviewContext keeps inline diffs for tiny adversarial reviews", () => {
const cwd = makeTempDir();
initGitRepo(cwd);
fs.writeFileSync(path.join(cwd, "app.js"), "console.log('v1');\n");
run("git", ["add", "app.js"], { cwd });
run("git", ["commit", "-m", "init"], { cwd });
fs.writeFileSync(path.join(cwd, "app.js"), "console.log('INLINE_MARKER');\n");
const target = resolveReviewTarget(cwd, {});
const context = collectReviewContext(cwd, target);
assert.equal(context.inputMode, "inline-diff");
assert.equal(context.fileCount, 1);
assert.match(context.collectionGuidance, /primary evidence/i);
assert.match(context.content, /INLINE_MARKER/);
});
test("collectReviewContext skips untracked directories in working tree review", () => {
const cwd = makeTempDir();
initGitRepo(cwd);
@@ -147,66 +101,3 @@ test("collectReviewContext skips broken untracked symlinks instead of crashing",
assert.match(context.content, /### broken-link/);
assert.match(context.content, /skipped: broken symlink or unreadable file/i);
});
test("collectReviewContext falls back to lightweight context for larger adversarial reviews", () => {
const cwd = makeTempDir();
initGitRepo(cwd);
for (const name of ["a.js", "b.js", "c.js"]) {
fs.writeFileSync(path.join(cwd, name), `export const value = "${name}-v1";\n`);
}
run("git", ["add", "a.js", "b.js", "c.js"], { cwd });
run("git", ["commit", "-m", "init"], { cwd });
fs.writeFileSync(path.join(cwd, "a.js"), 'export const value = "SELF_COLLECT_MARKER_A";\n');
fs.writeFileSync(path.join(cwd, "b.js"), 'export const value = "SELF_COLLECT_MARKER_B";\n');
fs.writeFileSync(path.join(cwd, "c.js"), 'export const value = "SELF_COLLECT_MARKER_C";\n');
const target = resolveReviewTarget(cwd, {});
const context = collectReviewContext(cwd, target);
assert.equal(context.inputMode, "self-collect");
assert.equal(context.fileCount, 3);
assert.match(context.collectionGuidance, /lightweight summary/i);
assert.match(context.collectionGuidance, /read-only git commands/i);
assert.doesNotMatch(context.content, /SELF_COLLECT_MARKER_[ABC]/);
assert.match(context.content, /## Changed Files/);
});
test("collectReviewContext falls back to lightweight context for oversized single-file diffs", () => {
const cwd = makeTempDir();
initGitRepo(cwd);
fs.writeFileSync(path.join(cwd, "app.js"), "export const value = 'v1';\n");
run("git", ["add", "app.js"], { cwd });
run("git", ["commit", "-m", "init"], { cwd });
fs.writeFileSync(path.join(cwd, "app.js"), `export const value = '${"x".repeat(512)}';\n`);
const target = resolveReviewTarget(cwd, {});
const context = collectReviewContext(cwd, target, { maxInlineDiffBytes: 128 });
assert.equal(context.fileCount, 1);
assert.equal(context.inputMode, "self-collect");
assert.ok(context.diffBytes > 128);
assert.doesNotMatch(context.content, /xxx/);
assert.match(context.content, /## Changed Files/);
});
test("collectReviewContext keeps untracked file content in lightweight working tree context", () => {
const cwd = makeTempDir();
initGitRepo(cwd);
for (const name of ["a.js", "b.js"]) {
fs.writeFileSync(path.join(cwd, name), `export const value = "${name}-v1";\n`);
}
run("git", ["add", "a.js", "b.js"], { cwd });
run("git", ["commit", "-m", "init"], { cwd });
fs.writeFileSync(path.join(cwd, "a.js"), 'export const value = "TRACKED_MARKER_A";\n');
fs.writeFileSync(path.join(cwd, "b.js"), 'export const value = "TRACKED_MARKER_B";\n');
fs.writeFileSync(path.join(cwd, "new-risk.js"), 'export const value = "UNTRACKED_RISK_MARKER";\n');
const target = resolveReviewTarget(cwd, {});
const context = collectReviewContext(cwd, target);
assert.equal(context.inputMode, "self-collect");
assert.equal(context.fileCount, 3);
assert.doesNotMatch(context.content, /TRACKED_MARKER_[AB]/);
assert.match(context.content, /## Untracked Files/);
assert.match(context.content, /UNTRACKED_RISK_MARKER/);
});
+1 -1
View File
@@ -18,7 +18,7 @@ export function run(command, args, options = {}) {
env: options.env,
encoding: "utf8",
input: options.input,
shell: options.shell ?? (process.platform === "win32" && !path.isAbsolute(command)),
shell: process.platform === "win32" && !path.isAbsolute(command),
windowsHide: true
});
}
+3 -189
View File
@@ -7,7 +7,7 @@ import { fileURLToPath } from "node:url";
import { buildEnv, installFakeCodex } from "./fake-codex-fixture.mjs";
import { initGitRepo, makeTempDir, run } from "./helpers.mjs";
import { loadBrokerSession, saveBrokerSession } from "../plugins/codex/scripts/lib/broker-lifecycle.mjs";
import { loadBrokerSession } from "../plugins/codex/scripts/lib/broker-lifecycle.mjs";
import { resolveStateDir } from "../plugins/codex/scripts/lib/state.mjs";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
@@ -193,140 +193,6 @@ test("task runs without auth preflight so Codex can refresh an expired session",
assert.match(result.stdout, /Handled the requested task/);
});
test("transfer delegates the current Claude session directly to native import", () => {
const home = makeTempDir();
const repo = path.join(home, "repo");
const binDir = makeTempDir();
const sessionId = "sess-native-transfer";
fs.mkdirSync(repo, { recursive: true });
const projectDir = path.join(home, ".claude", "projects", "-repo");
const sourcePath = path.join(projectDir, `${sessionId}.jsonl`);
fs.mkdirSync(projectDir, { recursive: true });
installFakeCodex(binDir);
initGitRepo(repo);
fs.writeFileSync(
sourcePath,
[
{ type: "custom-title", customTitle: "Native transfer" },
{ type: "user", cwd: repo, message: { role: "user", content: "Initial request" } },
{ type: "assistant", cwd: repo, message: { role: "assistant", content: "Initial answer" } },
{ type: "user", cwd: repo, message: { role: "user", content: "/codex:transfer" } }
].map((entry) => JSON.stringify(entry)).join("\n") + "\n",
"utf8"
);
const result = run("node", [SCRIPT, "transfer", "--json"], {
cwd: repo,
env: {
...buildEnv(binDir),
HOME: home,
CODEX_HOME: path.join(home, ".codex"),
CODEX_COMPANION_TRANSCRIPT_PATH: sourcePath
}
});
assert.equal(result.status, 0, result.stderr);
const payload = JSON.parse(result.stdout);
const canonicalSourcePath = fs.realpathSync(sourcePath);
assert.equal(payload.threadId, "thr_1");
assert.equal(payload.resumeCommand, "codex resume thr_1");
assert.equal(payload.sourcePath, canonicalSourcePath);
assert.equal(payload.sessionId, sessionId);
const fakeState = JSON.parse(fs.readFileSync(path.join(binDir, "fake-codex-state.json"), "utf8"));
assert.equal(fakeState.threads.length, 1);
assert.equal(fakeState.threads[0].ephemeral, false);
assert.equal(fakeState.threads[0].name, "Native transfer");
assert.equal(fakeState.lastExternalAgentImport.sourcePath, canonicalSourcePath);
assert.deepEqual(
fakeState.threads[0].visibleMessages.map((message) => message.text),
["Initial request", "Initial answer", "/codex:transfer"]
);
});
test("transfer reports an actionable upgrade error when native import is unsupported", () => {
const home = makeTempDir();
const repo = path.join(home, "repo");
const binDir = makeTempDir();
const projectDir = path.join(home, ".claude", "projects", "-repo");
const sourcePath = path.join(projectDir, "session.jsonl");
fs.mkdirSync(repo, { recursive: true });
fs.mkdirSync(projectDir, { recursive: true });
installFakeCodex(binDir, "external-import-unsupported");
initGitRepo(repo);
fs.writeFileSync(
sourcePath,
`${JSON.stringify({ type: "user", cwd: repo, message: { role: "user", content: "Continue this work." } })}\n`,
"utf8"
);
const result = run("node", [SCRIPT, "transfer", "--source", sourcePath, "--json"], {
cwd: repo,
env: {
...buildEnv(binDir),
HOME: home,
CODEX_HOME: path.join(home, ".codex")
}
});
assert.notEqual(result.status, 0);
assert.match(result.stderr, /does not support Claude session transfer/);
assert.match(result.stderr, /@openai\/codex@latest/);
});
test("transfer fails visibly when native import completes without a ledger record", () => {
const home = makeTempDir();
const repo = path.join(home, "repo");
const binDir = makeTempDir();
const projectDir = path.join(home, ".claude", "projects", "-repo");
const sourcePath = path.join(projectDir, "session.jsonl");
fs.mkdirSync(repo, { recursive: true });
fs.mkdirSync(projectDir, { recursive: true });
installFakeCodex(binDir, "external-import-fails");
initGitRepo(repo);
fs.writeFileSync(
sourcePath,
`${JSON.stringify({ type: "user", cwd: repo, message: { role: "user", content: "Do not lose this request." } })}\n`,
"utf8"
);
const result = run("node", [SCRIPT, "transfer", "--source", sourcePath], {
cwd: repo,
env: {
...buildEnv(binDir),
HOME: home,
CODEX_HOME: path.join(home, ".codex")
}
});
assert.notEqual(result.status, 0);
assert.match(result.stderr, /did not record an imported thread/);
});
test("transfer rejects sources outside the Claude projects directory", () => {
const home = makeTempDir();
const repo = path.join(home, "repo");
const binDir = makeTempDir();
const sourcePath = path.join(home, "session.jsonl");
fs.mkdirSync(repo, { recursive: true });
fs.mkdirSync(path.join(home, ".claude", "projects"), { recursive: true });
installFakeCodex(binDir);
initGitRepo(repo);
fs.writeFileSync(
sourcePath,
`${JSON.stringify({ type: "user", cwd: repo, message: { role: "user", content: "Outside source." } })}\n`,
"utf8"
);
const result = run("node", [SCRIPT, "transfer", "--source", sourcePath], {
cwd: repo,
env: { ...buildEnv(binDir), HOME: home }
});
assert.notEqual(result.status, 0);
assert.match(result.stderr, /only from .*\.claude.*projects/);
});
test("task reports the actual Codex auth error when the run is rejected", () => {
const repo = makeTempDir();
const binDir = makeTempDir();
@@ -407,33 +273,6 @@ test("adversarial review accepts the same base-branch targeting as review", () =
assert.match(result.stdout, /Missing empty-state guard/);
});
test("adversarial review asks Codex to inspect larger diffs itself", () => {
const repo = makeTempDir();
const binDir = makeTempDir();
installFakeCodex(binDir);
initGitRepo(repo);
fs.mkdirSync(path.join(repo, "src"));
for (const name of ["a.js", "b.js", "c.js"]) {
fs.writeFileSync(path.join(repo, "src", name), `export const value = "${name}-v1";\n`);
}
run("git", ["add", "src/a.js", "src/b.js", "src/c.js"], { cwd: repo });
run("git", ["commit", "-m", "init"], { cwd: repo });
fs.writeFileSync(path.join(repo, "src", "a.js"), 'export const value = "PROMPT_SELF_COLLECT_A";\n');
fs.writeFileSync(path.join(repo, "src", "b.js"), 'export const value = "PROMPT_SELF_COLLECT_B";\n');
fs.writeFileSync(path.join(repo, "src", "c.js"), 'export const value = "PROMPT_SELF_COLLECT_C";\n');
const result = run("node", [SCRIPT, "adversarial-review"], {
cwd: repo,
env: buildEnv(binDir)
});
assert.equal(result.status, 0, result.stderr);
const state = JSON.parse(fs.readFileSync(path.join(binDir, "fake-codex-state.json"), "utf8"));
assert.match(state.lastTurnStart.prompt, /lightweight summary/i);
assert.match(state.lastTurnStart.prompt, /read-only git commands/i);
assert.doesNotMatch(state.lastTurnStart.prompt, /PROMPT_SELF_COLLECT_[ABC]/);
});
test("review includes reasoning output when the app server returns it", () => {
const repo = makeTempDir();
const binDir = makeTempDir();
@@ -669,12 +508,11 @@ test("task --resume-last ignores running tasks from other Claude sessions", () =
assert.match(resume.stderr, /No previous Codex task thread was found for this repository\./);
});
test("session start hook exports the Claude session id, transcript path, and plugin data dir", () => {
test("session start hook exports the Claude session id and plugin data dir for later commands", () => {
const repo = makeTempDir();
const envFile = path.join(makeTempDir(), "claude-env.sh");
fs.writeFileSync(envFile, "", "utf8");
const pluginDataDir = makeTempDir();
const transcriptPath = path.join(repo, "session.jsonl");
const result = run("node", [SESSION_HOOK, "SessionStart"], {
cwd: repo,
@@ -686,7 +524,6 @@ test("session start hook exports the Claude session id, transcript path, and plu
input: JSON.stringify({
hook_event_name: "SessionStart",
session_id: "sess-current",
transcript_path: transcriptPath,
cwd: repo
})
});
@@ -694,7 +531,7 @@ test("session start hook exports the Claude session id, transcript path, and plu
assert.equal(result.status, 0, result.stderr);
assert.equal(
fs.readFileSync(envFile, "utf8"),
`export CODEX_COMPANION_SESSION_ID='sess-current'\nexport CODEX_COMPANION_TRANSCRIPT_PATH='${transcriptPath}'\nexport CLAUDE_PLUGIN_DATA='${pluginDataDir}'\n`
`export CODEX_COMPANION_SESSION_ID='sess-current'\nexport CLAUDE_PLUGIN_DATA='${pluginDataDir}'\n`
);
});
@@ -2234,26 +2071,3 @@ test("status reports shared session runtime when a lazy broker is active", () =>
assert.equal(result.status, 0, result.stderr);
assert.match(result.stdout, /Session runtime: shared session/);
});
test("setup and status honor --cwd when reading shared session runtime", () => {
const targetWorkspace = makeTempDir();
const invocationWorkspace = makeTempDir();
saveBrokerSession(targetWorkspace, {
endpoint: "unix:/tmp/fake-broker.sock"
});
const status = run("node", [SCRIPT, "status", "--cwd", targetWorkspace], {
cwd: invocationWorkspace
});
assert.equal(status.status, 0, status.stderr);
assert.match(status.stdout, /Session runtime: shared session/);
const setup = run("node", [SCRIPT, "setup", "--cwd", targetWorkspace, "--json"], {
cwd: invocationWorkspace
});
assert.equal(setup.status, 0, setup.stderr);
const payload = JSON.parse(setup.stdout);
assert.equal(payload.sessionRuntime.mode, "shared");
assert.equal(payload.sessionRuntime.endpoint, "unix:/tmp/fake-broker.sock");
});