Skip to content

Commit 5748958

Browse files
axisrowclaude
andcommitted
fix(worktree): spawn-failure status + byte-preserving binary patch
Cycle-2 review of PR #11 (Codex found two more fail-open paths; Claude subagent verified the cycle-1 fixes clean but missed these). Both confirmed empirically. 1. process.mjs runCommand still normalized a spawn failure to status:0. The cycle-1 fix covered `signal !== null` but not `error` (ENOENT/EAGAIN/ maxBuffer — spawnSync returns status:null, signal:null, error:set). A missing/failed git op still read as success (status ?? 0 → 0), so worktree cleanup could destroy the only copy. Now: `failed = signal != null || error`; failed => status 1. (Codex critical) 2. git.mjs applyWorktreePatch round-tripped the patch through a JS string. runCommand decodes stdout as UTF-8, replacing invalid bytes (0xff, NUL, legacy encodings) with U+FFFD; git apply then applied the corrupted patch as "success" and the source worktree was destroyed — silent data loss for any binary or non-UTF-8 file Codex touched. Now byte-preserving: write the patch via `git diff --cached --binary --output=<file>` (git→file, no JS string), detect empty by file size, apply. (Codex critical) Regression tests: - process.test.mjs: ENOENT spawn failure => non-zero status. - worktree.test.mjs: keep round-trips a raw 0xff byte without U+FFFD corruption. Verified: worktree 14/14, process 5/5, git 11/11 green; full npm test 157 pass / 4 pre-existing (unchanged, unrelated). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_0189cGaohsYdpkB4otKZnpAt
1 parent 4d57e1c commit 5748958

4 files changed

Lines changed: 57 additions & 13 deletions

File tree

‎plugins/codex/scripts/lib/git.mjs‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -364,19 +364,21 @@ export function getWorktreeDiff(worktreePath, baseCommit) {
364364

365365
export function applyWorktreePatch(repoRoot, worktreePath, baseCommit) {
366366
gitChecked(worktreePath, ["add", "-A"]);
367-
const patchResult = git(worktreePath, ["diff", "--cached", baseCommit]);
368-
if (patchResult.status !== 0) {
369-
throw new Error(`Failed to snapshot worktree changes: ${patchResult.stderr.trim()}`);
370-
}
371-
if (!patchResult.stdout.trim()) {
372-
return { applied: false, detail: "No changes to apply." };
373-
}
374367
const patchPath = path.join(
375368
repoRoot,
376369
".codex-worktree-" + Date.now() + "-" + Math.random().toString(16).slice(2) + ".patch"
377370
);
378371
try {
379-
fs.writeFileSync(patchPath, patchResult.stdout, "utf8");
372+
// Write the patch via `git diff --output=<file>` so the bytes flow directly
373+
// git→file, never through a JS string. runCommand decodes stdout as UTF-8,
374+
// which would replace invalid bytes (0xff, NUL, legacy encodings) with
375+
// U+FFFD and then apply a corrupted patch as "success" — destroying the
376+
// only correct copy in the worktree. Detect empty via file size instead.
377+
const diffResult = gitChecked(worktreePath, ["diff", "--cached", "--binary", baseCommit, "--output", patchPath]);
378+
void diffResult;
379+
if (!fs.existsSync(patchPath) || fs.statSync(patchPath).size === 0) {
380+
return { applied: false, detail: "No changes to apply." };
381+
}
380382
const applyResult = git(repoRoot, ["apply", "--index", patchPath]);
381383
if (applyResult.status !== 0) {
382384
return { applied: false, detail: applyResult.stderr.trim() || "Patch apply failed (conflicts?)." };

‎plugins/codex/scripts/lib/process.mjs‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,14 @@ export function runCommand(command, args = [], options = {}) {
1313
windowsHide: true
1414
});
1515

16-
const succeeded = result.status === 0 && result.signal === null;
17-
// A child killed by signal has status: null. Treat that as a non-zero exit
18-
// (not a success) so callers that check status===0 don't mistake a
19-
// signal-terminated process (e.g. git apply killed mid-run) for success.
20-
const status = result.signal !== null ? 1 : result.status ?? 0;
16+
const succeeded = result.status === 0 && result.signal === null && !result.error;
17+
// A child that was killed by a signal OR failed to spawn (ENOENT, EAGAIN,
18+
// maxBuffer) returns status:null. Treat any of those as a non-zero exit so
19+
// callers that check status===0 don't mistake an abnormal git op (killed
20+
// mid-run, missing binary) for success — for worktree cleanup that would mean
21+
// deleting the only copy of unapplied changes.
22+
const failed = result.signal !== null || result.error;
23+
const status = failed ? 1 : result.status ?? 0;
2124

2225
return {
2326
command,

‎tests/process.test.mjs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,3 +96,14 @@ test("runCommand reports a signal-terminated child as failed (non-zero status)",
9696
assert.ok(result.signal !== null, `expected a signal, got signal=${result.signal}`);
9797
assert.notEqual(result.status, 0, `signal-terminated child must not report status 0, got ${result.status}`);
9898
});
99+
100+
// Regression: a child that fails to spawn (ENOENT — missing binary) returns
101+
// status:null, signal:null, error:ENOENT from spawnSync. runCommand must NOT
102+
// normalize that to status:0 — callers checking status===0 would mistake a
103+
// missing/failed git op for success, which for worktree cleanup destroys the
104+
// only copy of unapplied changes (openai#137 cycle-2 review finding).
105+
test("runCommand reports a spawn failure (ENOENT) as failed (non-zero status)", () => {
106+
const result = runCommand("/nonexistent-codex-binary-xyz", []);
107+
assert.ok(result.error, `expected an error, got ${result.error}`);
108+
assert.notEqual(result.status, 0, `spawn failure must not report status 0, got ${result.status}`);
109+
});

‎tests/worktree.test.mjs‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,3 +261,31 @@ test("removeWorktree is a no-op (no throw) when the worktree is already removed"
261261
removeWorktree(repoRoot, session.worktreePath);
262262
assert.doesNotThrow(() => removeWorktree(repoRoot, session.worktreePath));
263263
});
264+
265+
// Regression: the keep patch path must be byte-preserving. runCommand decodes
266+
// stdout as UTF-8, which corrupts invalid bytes (0xff, NUL, legacy encodings)
267+
// into U+FFFD. applyWorktreePatch now writes the patch via `git diff --output`
268+
// (git→file, no JS string), so binary/non-UTF-8 changes round-trip exactly —
269+
// otherwise keep would apply a corrupted patch as "success" then destroy the
270+
// only correct copy in the worktree (openai#137 cycle-2 review finding).
271+
test("cleanupWorktreeSession keep round-trips a non-UTF-8 byte (0xff) without corruption", () => {
272+
const { repoRoot } = createRepoWithInitialCommit();
273+
const session = createWorktreeSession(repoRoot);
274+
275+
try {
276+
// Write a file containing a raw 0xff byte in the worktree.
277+
fs.writeFileSync(path.join(session.worktreePath, "binary.bin"), Buffer.from([0xff, 0x00, 0x41, 0xff]));
278+
279+
const result = cleanupWorktreeSession(session, { keep: true });
280+
assert.equal(result.applied, true);
281+
282+
const applied = fs.readFileSync(path.join(repoRoot, "binary.bin"));
283+
assert.deepEqual(
284+
Array.from(applied),
285+
[0xff, 0x00, 0x41, 0xff],
286+
`binary bytes must round-trip exactly; got ${Array.from(applied)} (U+FFFD corruption would show 0xEF 0xBF 0xBD)`
287+
);
288+
} finally {
289+
cleanupSession(session);
290+
}
291+
});

0 commit comments

Comments
 (0)