Compare commits

..

11 Commits

Author SHA1 Message Date
bryane-oai db52e28f4d Remove shell expansion for git commands (#447)
* Remove shell expansion for git commands

* Version bump
2026-07-07 17:17:00 -07:00
Dominik Kundel 80c31f9957 fix: bump plugin version to 1.0.5 (#398) 2026-06-23 10:36:15 -07:00
stefanstokic-oai 430e2a8630 feat: add Claude session transfer command (#374) 2026-06-23 10:26:06 -07:00
Dominik Kundel 807e03ac9d fix: bump plugin version to 1.0.4 (#244) 2026-04-18 13:41:53 -07:00
Friende bb38412a67 fix: route /codex:rescue through the Agent tool to stop Skill recursion (#234) (#235)
* fix: route /codex:rescue through the Agent tool to stop Skill recursion (#234)

`/codex:rescue` previously combined two things that together caused a hang:

- `context: fork` in the frontmatter, which spawns a `general-purpose`
  subagent for the command body.
- Body prose "Route this request to the `codex:codex-rescue` subagent."
  without naming the transport.

When the main agent called `Skill(codex:rescue)` programmatically, the
fork resolved the ambiguous prose by trying `Skill(codex:codex-rescue)`
(unknown skill) and then falling back to `Skill(codex:rescue)`, which
re-entered this command and hung the session until the user cancelled.
No Codex job was ever created.

Naming the transport as `Agent(codex:codex-rescue)` alone is not enough:
forked general-purpose subagents do not expose the `Agent` tool, so the
forked runner cannot reach the subagent that way either. The minimal fix
is therefore two coordinated changes:

- Drop `context: fork` so the command body runs inline in the calling
  agent's context, where `Agent` is in scope.
- Say explicitly "use the `Agent` tool with `subagent_type:
  "codex:codex-rescue"`", and call out that `Skill(codex:codex-rescue)`
  and `Skill(codex:rescue)` are not valid routing paths. Add `Agent`
  to `allowed-tools` so the call does not prompt for permission.

Everything else in rescue.md (resume-candidate check, flag handling,
background/foreground semantics, operating rules) is unchanged. The
`codex:codex-rescue` subagent itself is unchanged.

Tests pin the new allow-list, the explicit `subagent_type`, the ban on
`Skill(codex:codex-rescue)`, and the absence of `context: fork`. The
existing "run the `codex:codex-rescue` subagent in the background"
assertion continues to hold since that sentence still reads correctly
with the Agent-tool transport.

Fixes openai/codex-plugin-cc#234

* test: match quoted result and cancel command arguments

---------

Co-authored-by: Dominik Kundel <dkundel@openai.com>
2026-04-18 13:38:45 -07:00
xiaolai 6a5c2ba53b fix: quote \$ARGUMENTS in cancel, result, and status commands (#168)
Unquoted \$ARGUMENTS in the ! shell commands allowed shell metacharacters
in user-supplied job IDs to be expanded before Node received them (e.g.,
`task-123; malicious-cmd` would execute the trailing command). This is
inconsistent with review.md and adversarial-review.md, which both wrap
"$ARGUMENTS" in double quotes.

Co-authored-by: claude[bot] <claude-bot@anthropic.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-04-08 14:48:50 -07:00
Manav Agarwal 8e9a38cdfe fix: correct invalid 'xhigh' reasoning effort in README (#99)
Closes #77

Updated README to replace unsupported 'xhigh' value with 'high' to prevent configuration errors.
2026-04-08 14:29:32 -07:00
xiaolai b1156235e0 fix: declare model in codex-rescue agent frontmatter (#169)
* fix: declare model in codex-rescue agent frontmatter

The codex-rescue agent had no model field, leaving Claude Code to assign
whatever default it chooses. As a thin forwarding wrapper that issues a
single Bash call, this agent is well-suited to the haiku tier; declaring
it explicitly ensures a predictable cost profile and tier guarantee.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* Update codex-rescue.md

---------

Co-authored-by: claude[bot] <claude-bot@anthropic.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
Co-authored-by: Dominik Kundel <dkundel@openai.com>
2026-04-08 14:28:45 -07:00
VOIDXAI c24afe8404 codex: honor --cwd when reporting session runtime (#35)
* codex: honor --cwd when reporting session runtime

* codex: keep session runtime lookup scoped to callers

---------

Co-authored-by: VOIDXAI <VOIDXAI@users.noreply.github.com>
2026-04-08 14:27:04 -07:00
Dominik Kundel 11a720b7db bump: update plugin version to 1.0.3 (#180) 2026-04-07 22:11:51 -07:00
Dominik Kundel bc8fa661a5 fix: avoid embedding large adversarial review diffs (#179)
* fix: avoid embedding large adversarial review diffs

* fix: preserve untracked content in lightweight review

* address comments

* fix: handle ENOBUFS type check in git diff sizing
2026-04-07 22:04:40 -07:00
26 changed files with 824 additions and 61 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.3"
"version": "1.0.6"
},
"plugins": [
{
"name": "codex",
"description": "Use Codex from Claude Code to review code or delegate tasks.",
"version": "1.0.3",
"version": "1.0.6",
"author": {
"name": "OpenAI"
},
+17 -2
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:status`, `/codex:result`, and `/codex:cancel` to delegate work and manage background jobs
- `/codex:rescue`, `/codex:transfer`, `/codex:status`, `/codex:result`, and `/codex:cancel` to delegate work, hand off sessions, and manage background jobs
## Requirements
@@ -162,6 +162,21 @@ 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.
@@ -259,7 +274,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 = "xhigh"
model_reasoning_effort = "high"
```
Your configuration will be picked up based on:
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@openai/codex-plugin-cc",
"version": "1.0.3",
"version": "1.0.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@openai/codex-plugin-cc",
"version": "1.0.3",
"version": "1.0.6",
"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.3",
"version": "1.0.6",
"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.3",
"version": "1.0.6",
"description": "Use Codex from Claude Code to review code or delegate tasks.",
"author": {
"name": "OpenAI"
+1
View File
@@ -1,6 +1,7 @@
---
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]"
context: fork
allowed-tools: Bash(node:*), AskUserQuestion
allowed-tools: Bash(node:*), AskUserQuestion, Agent
---
Route this request to the `codex:codex-rescue` subagent.
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.
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
@@ -0,0 +1,10 @@
---
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,6 +32,7 @@ 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>
+48 -1
View File
@@ -14,12 +14,14 @@ 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";
@@ -78,6 +80,7 @@ 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]"
@@ -202,7 +205,7 @@ async function buildSetupReport(cwd, actionsTaken = []) {
npm: npmStatus,
codex: codexStatus,
auth: authStatus,
sessionRuntime: getSessionRuntimeStatus(),
sessionRuntime: getSessionRuntimeStatus(process.env, workspaceRoot),
reviewGateEnabled: Boolean(config.stopReviewGate),
actionsTaken,
nextSteps
@@ -241,6 +244,7 @@ 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
});
}
@@ -609,6 +613,33 @@ 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");
@@ -791,6 +822,19 @@ 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"]
@@ -999,6 +1043,9 @@ 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,6 +6,8 @@ import type {
ServerNotification
} from "../../.generated/app-server-types/index.js";
import type {
ExternalAgentConfigImportParams,
ExternalAgentConfigImportResponse,
ReviewStartParams,
ReviewStartResponse,
ReviewTarget,
@@ -56,6 +58,7 @@ 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 };
+5 -1
View File
@@ -32,6 +32,7 @@ const DEFAULT_CLIENT_INFO = {
/** @type {InitializeCapabilities} */
const DEFAULT_CAPABILITIES = {
experimentalApi: false,
requestAttestation: false,
optOutNotificationMethods: [
"item/agentMessage/delta",
"item/reasoning/summaryTextDelta",
@@ -206,10 +207,13 @@ 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}`}).`);
: createProtocolError(
`codex app-server exited unexpectedly (${signal ? `signal ${signal}` : `exit ${code}`}).${stderr ? `\n${stderr}` : ""}`
);
this.handleExit(detail);
});
@@ -0,0 +1,44 @@
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;
}
+133 -2
View File
@@ -34,6 +34,11 @@
* 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";
@@ -43,6 +48,8 @@ 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
@@ -60,8 +67,7 @@ function buildThreadParams(cwd, options = {}) {
approvalPolicy: options.approvalPolicy ?? "never",
sandbox: options.sandbox ?? "read-only",
serviceName: SERVICE_NAME,
ephemeral: options.ephemeral ?? true,
experimentalRawEvents: false
ephemeral: options.ephemeral ?? true
};
}
@@ -635,6 +641,94 @@ 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;
@@ -961,6 +1055,43 @@ 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) {
+157 -32
View File
@@ -2,16 +2,77 @@ import fs from "node:fs";
import path from "node:path";
import { isProbablyText } from "./fs.mjs";
import { runCommand, runCommandChecked } from "./process.mjs";
import { formatCommandFailure, 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 });
return runCommand("git", args, { cwd, ...options, shell: false });
}
function gitChecked(cwd, args, options = {}) {
return runCommandChecked("git", args, { cwd, ...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`
};
}
export function ensureGitRepository(cwd) {
@@ -161,55 +222,115 @@ function formatUntrackedFile(cwd, relativePath) {
return [`### ${relativePath}`, "```", buffer.toString("utf8").trimEnd(), "```"].join("\n");
}
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");
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);
const parts = [
formatSection("Git Status", status),
formatSection("Staged Diff", stagedDiff),
formatSection("Unstaged Diff", unstagedDiff),
formatSection("Untracked Files", untrackedBody)
];
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)
];
}
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")
content: parts.join("\n"),
changedFiles
};
}
function collectBranchContext(cwd, baseRef) {
const mergeBase = gitChecked(cwd, ["merge-base", "HEAD", baseRef]).stdout.trim();
const commitRange = `${mergeBase}..HEAD`;
function collectBranchContext(cwd, baseRef, options = {}) {
const includeDiff = options.includeDiff !== false;
const comparison = options.comparison ?? buildBranchComparison(cwd, baseRef);
const currentBranch = getCurrentBranch(cwd);
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;
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();
return {
mode: "branch",
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")
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
};
}
export function collectReviewContext(cwd, target) {
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 = {}) {
const repoRoot = getRepoRoot(cwd);
const state = getWorkingTreeState(cwd);
const currentBranch = getCurrentBranch(cwd);
const currentBranch = getCurrentBranch(repoRoot);
const maxInlineFiles = normalizeMaxInlineFiles(options.maxInlineFiles);
const maxInlineDiffBytes = normalizeMaxInlineDiffBytes(options.maxInlineDiffBytes);
let details;
let includeDiff;
let diffBytes;
if (target.mode === "working-tree") {
details = collectWorkingTreeContext(repoRoot, state);
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 });
} else {
details = collectBranchContext(repoRoot, target.baseRef);
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 });
}
return {
@@ -217,6 +338,10 @@ export function collectReviewContext(cwd, target) {
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),
sessionRuntime: getSessionRuntimeStatus(options.env, workspaceRoot),
running,
latestFinished,
recent,
+2 -1
View File
@@ -7,8 +7,9 @@ export function runCommand(command, args = [], options = {}) {
env: options.env,
encoding: "utf8",
input: options.input,
maxBuffer: options.maxBuffer,
stdio: options.stdio ?? "pipe",
shell: process.platform === "win32" ? (process.env.SHELL || true) : false,
shell: options.shell ?? (process.platform === "win32" ? (process.env.SHELL || true) : false),
windowsHide: true
});
@@ -14,6 +14,7 @@ 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";
@@ -75,6 +76,7 @@ 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]);
}
+20 -5
View File
@@ -79,7 +79,8 @@ test("continue is not exposed as a user-facing command", () => {
"result.md",
"review.md",
"setup.md",
"status.md"
"status.md",
"transfer.md"
]);
});
@@ -90,7 +91,16 @@ 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/);
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, /--background\|--wait/);
assert.match(rescue, /--resume\|--fresh/);
assert.match(rescue, /--model <model\|spark>/);
@@ -154,20 +164,25 @@ 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("result and cancel commands are exposed as deterministic runtime entrypoints", () => {
test("transfer, result, and cancel commands are exposed as deterministic runtime entrypoints", () => {
const transfer = read("commands/transfer.md");
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,6 +9,7 @@ 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");
@@ -144,6 +145,21 @@ 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) } });
@@ -335,6 +351,59 @@ 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,6 +38,35 @@ 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);
@@ -69,6 +98,23 @@ 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);
@@ -101,3 +147,66 @@ 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: process.platform === "win32" && !path.isAbsolute(command),
shell: options.shell ?? (process.platform === "win32" && !path.isAbsolute(command)),
windowsHide: true
});
}
+189 -3
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 } from "../plugins/codex/scripts/lib/broker-lifecycle.mjs";
import { loadBrokerSession, saveBrokerSession } 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,6 +193,140 @@ 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();
@@ -273,6 +407,33 @@ 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();
@@ -508,11 +669,12 @@ 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 and plugin data dir for later commands", () => {
test("session start hook exports the Claude session id, transcript path, and plugin data dir", () => {
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,
@@ -524,6 +686,7 @@ test("session start hook exports the Claude session id and plugin data dir for l
input: JSON.stringify({
hook_event_name: "SessionStart",
session_id: "sess-current",
transcript_path: transcriptPath,
cwd: repo
})
});
@@ -531,7 +694,7 @@ test("session start hook exports the Claude session id and plugin data dir for l
assert.equal(result.status, 0, result.stderr);
assert.equal(
fs.readFileSync(envFile, "utf8"),
`export CODEX_COMPANION_SESSION_ID='sess-current'\nexport CLAUDE_PLUGIN_DATA='${pluginDataDir}'\n`
`export CODEX_COMPANION_SESSION_ID='sess-current'\nexport CODEX_COMPANION_TRANSCRIPT_PATH='${transcriptPath}'\nexport CLAUDE_PLUGIN_DATA='${pluginDataDir}'\n`
);
});
@@ -2071,3 +2234,26 @@ 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");
});