Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(codex): record file edit payload for patch_apply events (#6158)

Multica Eve999e9f93c769
diff --git a/packages/views/agents/agents-i18n-parity.test.ts b/packages/views/agents/agents-i18n-parity.test.ts
index ae60471590..d67a06c5e9 100644
--- a/packages/views/agents/agents-i18n-parity.test.ts
+++ b/packages/views/agents/agents-i18n-parity.test.ts
@@ -64,3 +64,52 @@ describe("access-scope i18n parity across all 4 locales", () => {
}
});
});
+
+/**
+ * The transcript's multi-file patch summary is handed the number of files
+ * *beyond* the named one. A translation that phrases this as a total silently
+ * under-reports by one — "a.go 等 2 个文件" reads as two files including a.go
+ * when three changed. English hides the distinction ("+2 more"), so it has to
+ * be pinned per locale.
+ */
+describe("transcript patch summary i18n", () => {
+ const KEY = "transcript.patch_summary_more";
+
+ const read = (loc: object): unknown =>
+ KEY.split(".").reduce<unknown>(
+ (node, part) =>
+ node !== null && typeof node === "object"
+ ? (node as Record<string, unknown>)[part]
+ : undefined,
+ loc,
+ );
+
+ const phraseOf = (loc: object): string => {
+ const node = read(loc);
+ return typeof node === "string" ? node : "";
+ };
+
+ it("is present in all 4 locales", () => {
+ for (const [name, loc] of Object.entries(LOCALES)) {
+ expect(typeof read(loc), `${name}: ${KEY} missing`).toBe("string");
+ expect(phraseOf(loc).length > 0, `${name}: ${KEY} is empty`).toBe(true);
+ }
+ });
+
+ it("interpolates {{path}} and {{extra}} in every locale", () => {
+ for (const [name, loc] of Object.entries(LOCALES)) {
+ const phrase = phraseOf(loc);
+ expect(phrase.includes("{{path}}"), `${name}: ${KEY} lost {{path}}`).toBe(true);
+ expect(phrase.includes("{{extra}}"), `${name}: ${KEY} lost {{extra}}`).toBe(true);
+ }
+ });
+
+ // `count` is i18next's plural selector — this namespace already uses it that
+ // way for events_one/events_other. Reusing it here for a plain number ties
+ // the string to plural resolution it does not want.
+ it("does not use the reserved {{count}} token", () => {
+ for (const [name, loc] of Object.entries(LOCALES)) {
+ expect(phraseOf(loc).includes("{{count}}"), `${name}: ${KEY} must use {{extra}}`).toBe(false);
+ }
+ });
+});
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
index 542283ecbc..d4fdebadc7 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
@@ -65,7 +65,7 @@ import {
traceEventSummary,
traceEventSummaryIsMono,
} from "./trace-event-presenter";
-import type { TraceDiffLine } from "./trace-event-presenter";
+import type { TraceDiffLine, TracePatchFile, TraceSummaryLabels } from "./trace-event-presenter";
import { highlightBlock, highlightToLines, languageForPath } from "./diff-highlight";
import { useT } from "../../i18n";
import "../../editor/styles/code.css";
@@ -1102,7 +1102,17 @@ const TranscriptEventRow = ({
const kind = traceEventKind(item);
const color = getEventColor(item);
const label = traceEventLabel(item);
- const summary = traceEventSummary(item);
+ // The presenter stays i18n-free, so the localizable phrasing is injected.
+ // `extra` counts files beyond the named one, and is deliberately not called
+ // `count`: i18next reads `count` as a plural selector.
+ const summaryLabels = useMemo<TraceSummaryLabels>(
+ () => ({
+ morePaths: (path, extraCount) =>
+ t(($) => $.transcript.patch_summary_more, { path, extra: extraCount }),
+ }),
+ [t],
+ );
+ const summary = traceEventSummary(item, summaryLabels);
const date = useMemo(
() => (item.created_at ? new Date(item.created_at) : null),
[item.created_at],
@@ -1221,6 +1231,8 @@ const TranscriptEventRow = ({
<div className="ml-[72px] rounded-md bg-muted/40">
{detail.kind === "diff" ? (
<DiffDetailSurface lines={detail.lines} path={detail.path} />
+ ) : detail.kind === "patch" ? (
+ <PatchDetailSurface files={detail.files} truncated={detail.truncated} />
) : detail.kind === "file" ? (
<FileWriteSurface text={detail.text} lineCount={detail.lineCount} path={detail.path} />
) : (
@@ -1329,6 +1341,73 @@ function FileWriteSurface({
);
}
+/**
+ * A multi-file patch: one section per file, each reusing the single-file
+ * surfaces. Codex's `patch_apply` routinely touches several files in one call,
+ * so collapsing them into a single body would lose which change belongs where.
+ */
+function PatchDetailSurface({
+ files,
+ truncated,
+}: {
+ files: TracePatchFile[];
+ truncated: boolean;
+}) {
+ const { t } = useT("agents");
+ return (
+ <div className="divide-y divide-border/40">
+ {files.map((file, index) => (
+ // Transcript events are immutable once persisted, so index is stable.
+ <div key={`${file.path}:${index}`}>
+ <div className="flex items-center gap-2 px-3 pt-2 font-mono text-micro">
+ {file.changeKind && (
+ <span
+ className={cn(
+ "shrink-0 uppercase",
+ file.changeKind === "add" && "text-success",
+ file.changeKind === "delete" && "text-destructive",
+ file.changeKind === "update" && "text-muted-foreground/70",
+ )}
+ >
+ {file.changeKind}
+ </span>
+ )}
+ <span className="truncate text-muted-foreground">{file.path}</span>
+ {file.movePath && (
+ <>
+ <span className="shrink-0 text-muted-foreground/50" aria-hidden>
+ →
+ </span>
+ <span className="truncate text-muted-foreground">{file.movePath}</span>
+ </>
+ )}
+ </div>
+ {file.body.kind === "diff" ? (
+ <DiffDetailSurface lines={file.body.lines} path={file.path} />
+ ) : file.body.kind === "file" ? (
+ <FileWriteSurface
+ text={file.body.text}
+ lineCount={file.body.lineCount}
+ path={file.path}
+ />
+ ) : (
+ <div className="px-3 pb-2 pt-1 font-mono text-micro text-muted-foreground/60">
+ {file.truncated
+ ? t(($) => $.transcript.patch_body_truncated)
+ : t(($) => $.transcript.patch_no_content)}
+ </div>
+ )}
+ </div>
+ ))}
+ {truncated && (
+ <div className="px-3 py-2 font-mono text-micro text-muted-foreground/60">
+ {t(($) => $.transcript.patch_truncated)}
+ </div>
+ )}
+ </div>
+ );
+}
+
/**
* A file change reads as a diff rather than two escaped string literals. Same
* fade/"show all" shell as the text surface so both bodies behave alike inside
diff --git a/packages/views/common/task-transcript/trace-event-presenter.test.ts b/packages/views/common/task-transcript/trace-event-presenter.test.ts
index c491e3efa8..68d7924fd9 100644
--- a/packages/views/common/task-transcript/trace-event-presenter.test.ts
+++ b/packages/views/common/task-transcript/trace-event-presenter.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import {
collapseDiffContext,
+ parseUnifiedDiff,
stripShellWrapper,
traceEventCopyText,
traceEventDefaultExpanded,
@@ -288,3 +289,282 @@ describe("collapseDiffContext", () => {
expect(collapseDiffContext(lines)).toEqual(lines);
});
});
+
+// --- Codex multi-file patch payload (GH #6157) -----------------------------
+//
+// The Codex adapter records a file edit as
+// `{ changes: [{ path, kind, diff?, content?, move_path? }], truncated? }`.
+// Before this the presenter only understood a top-level file_path plus
+// old_string/new_string, so a Codex edit fell through to pretty JSON.
+
+describe("parseUnifiedDiff", () => {
+ it("maps a ready-made unified diff onto diff rows", () => {
+ // Codex hands over a finished diff, so it is parsed rather than recomputed.
+ expect(parseUnifiedDiff("@@ -1,3 +1,3 @@\n ctx\n-old\n+new\n")).toEqual([
+ { kind: "gap", text: "@@ -1,3 +1,3 @@" },
+ { kind: "context", text: "ctx" },
+ { kind: "remove", text: "old" },
+ { kind: "add", text: "new" },
+ ]);
+ });
+
+ it("drops file headers ahead of the first hunk", () => {
+ const lines = parseUnifiedDiff(
+ "diff --git a/x b/x\nindex 111..222 100644\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b\n\\ No newline at end of file\n",
+ );
+ expect(lines).toEqual([
+ { kind: "gap", text: "@@ -1 +1 @@" },
+ { kind: "remove", text: "a" },
+ { kind: "add", text: "b" },
+ ]);
+ });
+
+ // Inside a hunk, "---"/"+++" are ordinary changed lines whose content starts
+ // with a dash or plus — a Markdown rule, a nested patch, a comment banner.
+ // Treating them as file headers anywhere silently deleted real content.
+ it("keeps header-like content lines once inside a hunk", () => {
+ expect(parseUnifiedDiff("@@ -1 +1 @@\n--- old markdown\n+++ new markdown\n")).toEqual([
+ { kind: "gap", text: "@@ -1 +1 @@" },
+ { kind: "remove", text: "-- old markdown" },
+ { kind: "add", text: "++ new markdown" },
+ ]);
+ });
+
+ it("keeps a removed line that is exactly a Markdown rule", () => {
+ expect(parseUnifiedDiff("@@ -1,2 +1,1 @@\n---\n ok\n")).toEqual([
+ { kind: "gap", text: "@@ -1,2 +1,1 @@" },
+ { kind: "remove", text: "--" },
+ { kind: "context", text: "ok" },
+ ]);
+ });
+
+ it("keeps an empty context line and does not invent a trailing one", () => {
+ // " " is a blank unchanged line; the phantom element left by the trailing
+ // newline is not.
+ expect(parseUnifiedDiff("@@ -1,2 +1,2 @@\n \n+x\n")).toEqual([
+ { kind: "gap", text: "@@ -1,2 +1,2 @@" },
+ { kind: "context", text: "" },
+ { kind: "add", text: "x" },
+ ]);
+ });
+});
+
+describe("traceEventDetail — Codex changes[]", () => {
+ it("renders a multi-file patch with one section per file", () => {
+ const detail = traceEventDetail({
+ type: "tool_use",
+ tool: "patch_apply",
+ input: {
+ changes: [
+ { path: "src/a.go", kind: "update", diff: "@@ -1 +1 @@\n-a\n+b\n" },
+ { path: "src/new.go", kind: "add", content: "package main\n" },
+ ],
+ },
+ });
+ expect(detail.kind).toBe("patch");
+ if (detail.kind !== "patch") return;
+ expect(detail.truncated).toBe(false);
+ expect(detail.files).toHaveLength(2);
+
+ const [update, added] = detail.files;
+ expect(update?.path).toBe("src/a.go");
+ expect(update?.changeKind).toBe("update");
+ expect(update?.body).toEqual({
+ kind: "diff",
+ lines: [
+ { kind: "gap", text: "@@ -1 +1 @@" },
+ { kind: "remove", text: "a" },
+ { kind: "add", text: "b" },
+ ],
+ });
+
+ // An added file has no before side, matching the whole-file write surface.
+ expect(added?.path).toBe("src/new.go");
+ expect(added?.body).toEqual({ kind: "file", text: "package main\n", lineCount: 2 });
+ });
+
+ it("renders a deletion as all-removals rather than a green whole-file write", () => {
+ // The legacy protocol reports a delete as the outgoing file's content; a
+ // "+N" gutter would state the opposite of what happened.
+ const detail = traceEventDetail({
+ type: "tool_use",
+ tool: "patch_apply",
+ input: { changes: [{ path: "gone.txt", kind: "delete", content: "one\ntwo" }] },
+ });
+ expect(detail.kind).toBe("patch");
+ if (detail.kind !== "patch") return;
+ expect(detail.files[0]?.body).toEqual({
+ kind: "diff",
+ lines: [
+ { kind: "remove", text: "one" },
+ { kind: "remove", text: "two" },
+ ],
+ });
+ });
+
+ it("surfaces a rename destination", () => {
+ const detail = traceEventDetail({
+ type: "tool_use",
+ tool: "patch_apply",
+ input: {
+ changes: [
+ { path: "old.go", kind: "update", move_path: "new.go", diff: "@@ -1 +1 @@\n-x\n+y\n" },
+ ],
+ },
+ });
+ if (detail.kind !== "patch") return expect(detail.kind).toBe("patch");
+ expect(detail.files[0]?.movePath).toBe("new.go");
+ });
+
+ it("keeps the path when the body was dropped by the size budget", () => {
+ const detail = traceEventDetail({
+ type: "tool_use",
+ tool: "patch_apply",
+ input: {
+ changes: [{ path: "big.txt", kind: "add", truncated: true }],
+ truncated: true,
+ },
+ });
+ expect(detail.kind).toBe("patch");
+ if (detail.kind !== "patch") return;
+ expect(detail.truncated).toBe(true);
+ expect(detail.files[0]).toEqual({
+ path: "big.txt",
+ changeKind: "add",
+ truncated: true,
+ body: { kind: "none" },
+ });
+ });
+
+ it("renders an empty added file as an empty body, not as a missing one", () => {
+ const detail = traceEventDetail({
+ type: "tool_use",
+ tool: "patch_apply",
+ input: { changes: [{ path: "empty.txt", kind: "add", content: "" }] },
+ });
+ if (detail.kind !== "patch") return expect(detail.kind).toBe("patch");
+ expect(detail.files[0]?.body).toEqual({ kind: "file", text: "", lineCount: 0 });
+ });
+
+ it("falls back to pretty JSON for an unrecognised shape", () => {
+ // Forward compatibility: a payload this presenter does not understand must
+ // still be readable rather than rendering as an empty patch.
+ const detail = traceEventDetail({
+ type: "tool_use",
+ tool: "patch_apply",
+ input: { changes: "not-an-array" },
+ });
+ expect(detail.kind).toBe("text");
+ if (detail.kind !== "text") return;
+ expect(detail.text).toContain("not-an-array");
+ });
+
+ it("falls back to pretty JSON when no change carries a path", () => {
+ const detail = traceEventDetail({
+ type: "tool_use",
+ tool: "patch_apply",
+ input: { changes: [42, null, { kind: "add" }] },
+ });
+ expect(detail.kind).toBe("text");
+ });
+});
+
+describe("traceToolArgSummary / traceEventHasDetail — Codex changes[]", () => {
+ it("summarises a single-file patch as its path", () => {
+ expect(
+ traceToolArgSummary({ changes: [{ path: "src/a.go", kind: "update", diff: "@@\n+x" }] }),
+ ).toBe("src/a.go");
+ });
+
+ it("summarises a multi-file patch as the first path plus a count", () => {
+ expect(
+ traceToolArgSummary({
+ changes: [
+ { path: "src/a.go", kind: "update", diff: "@@\n+x" },
+ { path: "src/b.go", kind: "add", content: "y" },
+ { path: "src/c.go", kind: "add", content: "z" },
+ ],
+ }),
+ ).toBe("src/a.go +2 more");
+ });
+
+ it("shortens a deep path in the summary", () => {
+ expect(
+ traceToolArgSummary({ changes: [{ path: "a/b/c/d/e.go", kind: "add", content: "x" }] }),
+ ).toBe(".../d/e.go");
+ });
+
+ // The presenter stays i18n-free, so the caller injects the phrasing; the
+ // English form is only the fallback.
+ it("uses injected phrasing for the multi-file count", () => {
+ expect(
+ traceToolArgSummary(
+ {
+ changes: [
+ { path: "src/a.go", kind: "update", diff: "@@\n+x" },
+ { path: "src/b.go", kind: "add", content: "y" },
+ ],
+ },
+ { morePaths: (path, extraCount) => `${path},另有 ${extraCount} 个文件` },
+ ),
+ ).toBe("src/a.go,另有 1 个文件");
+ });
+
+ // The injected number counts files *beyond* the named one. Phrasing it as a
+ // total under-reports by one, which is easy to miss in English ("+2 more")
+ // and obvious in a language that states the total outright.
+ it("passes the count of additional files, not the total", () => {
+ const seen: number[] = [];
+ traceToolArgSummary(
+ {
+ changes: [
+ { path: "a.go", kind: "add", content: "x" },
+ { path: "b.go", kind: "add", content: "y" },
+ { path: "c.go", kind: "add", content: "z" },
+ ],
+ },
+ {
+ morePaths: (path, extraCount) => {
+ seen.push(extraCount);
+ return path;
+ },
+ },
+ );
+ expect(seen).toEqual([2]);
+ });
+
+ it("does not consult the injected phrasing for a single file", () => {
+ expect(
+ traceToolArgSummary(
+ { changes: [{ path: "only.go", kind: "add", content: "x" }] },
+ {
+ morePaths: () => {
+ throw new Error("must not be called for a single-file patch");
+ },
+ },
+ ),
+ ).toBe("only.go");
+ });
+
+ it("makes a patch row expandable — the bug was two blank unexpandable rows", () => {
+ expect(
+ traceEventHasDetail({
+ type: "tool_use",
+ tool: "patch_apply",
+ input: { changes: [{ path: "a.go", kind: "add", content: "x" }] },
+ }),
+ ).toBe(true);
+ expect(
+ traceEventHasDetail({
+ type: "tool_result",
+ tool: "patch_apply",
+ output: "completed (1 file)",
+ }),
+ ).toBe(true);
+ // The regression itself: no payload means no expandable detail.
+ expect(traceEventHasDetail({ type: "tool_use", tool: "patch_apply", input: {} })).toBe(false);
+ expect(traceEventHasDetail({ type: "tool_result", tool: "patch_apply", output: "" })).toBe(
+ false,
+ );
+ });
+});
diff --git a/packages/views/common/task-transcript/trace-event-presenter.ts b/packages/views/common/task-transcript/trace-event-presenter.ts
index 42da3be608..f3c93752f9 100644
--- a/packages/views/common/task-transcript/trace-event-presenter.ts
+++ b/packages/views/common/task-transcript/trace-event-presenter.ts
@@ -95,15 +95,39 @@ function clip(value: string, max: number): string {
return value.length > max ? value.slice(0, max) + "..." : value;
}
+/**
+ * Localizable phrasing the presenter cannot produce on its own. This module
+ * stays free of React and i18n so it remains unit-testable in isolation, so the
+ * caller injects the wording instead. Omitting it falls back to English, which
+ * keeps the fallback safe rather than blank.
+ */
+export interface TraceSummaryLabels {
+ /**
+ * Phrase a multi-file patch, e.g. `src/a.go +2 more`.
+ *
+ * `extraCount` is the number of files *beyond* the named one, not the total.
+ * Translations must say "and N more", not "N files in total" — the two read
+ * almost the same in English and diverge in other languages.
+ */
+ morePaths?: (path: string, extraCount: number) => string;
+}
+
/**
* The single most informative argument of a tool call, as one line. Preference
* order matches what a reviewer scans for first, falling back to the first
* short string value.
*/
-export function traceToolArgSummary(input: Record<string, unknown> | undefined): string {
+export function traceToolArgSummary(
+ input: Record<string, unknown> | undefined,
+ labels?: TraceSummaryLabels,
+): string {
if (!input) return "";
const str = (v: unknown): string => (typeof v === "string" ? v : "");
if (str(input.query)) return str(input.query);
+ // A multi-file patch has no single path field; without this the row's
+ // summary would fall through to the generic scan and come back empty.
+ const patch = readPatchSummary(input, labels);
+ if (patch) return patch;
if (str(input.file_path)) return shortenTracePath(str(input.file_path));
if (str(input.path)) return shortenTracePath(str(input.path));
if (str(input.pattern)) return str(input.pattern);
@@ -131,12 +155,12 @@ function collapseWhitespace(value: string | undefined): string {
}
/** One-line summary for the collapsed row — never contains a newline. */
-export function traceEventSummary(event: TraceEvent): string {
+export function traceEventSummary(event: TraceEvent, labels?: TraceSummaryLabels): string {
switch (traceEventKind(event)) {
case "thinking":
return clip(firstLine(event.content), 200);
case "tool_use":
- return traceToolArgSummary(event.input);
+ return traceToolArgSummary(event.input, labels);
case "tool_result":
// Unwrap first: the collapsed row is the one people read without
// clicking, so it must not show transport escaping.
@@ -201,13 +225,33 @@ export interface TraceDiffLine {
/**
* Expanded-row body. A replacement reads as a diff; a whole-file write reads as
* plain content, because nothing was compared — marking all of it `+` adds
- * noise, not information. Everything else is text.
+ * noise, not information. A patch carries one entry per file, since a single
+ * Codex `patch_apply` routinely touches several. Everything else is text.
*/
export type TraceEventDetail =
| { kind: "diff"; path: string; lines: TraceDiffLine[] }
| { kind: "file"; path: string; text: string; lineCount: number }
+ | { kind: "patch"; files: TracePatchFile[]; truncated: boolean }
| { kind: "text"; text: string };
+/** Body of one file inside a multi-file patch. */
+export type TracePatchBody =
+ | { kind: "diff"; lines: TraceDiffLine[] }
+ | { kind: "file"; text: string; lineCount: number }
+ /** Path and kind are known but the body was dropped by the size budget. */
+ | { kind: "none" };
+
+export interface TracePatchFile {
+ path: string;
+ /** `add` | `delete` | `update`, verbatim from the provider when reported. */
+ changeKind?: string;
+ /** Rename destination, when the change moved the file. */
+ movePath?: string;
+ /** True when this file's body was trimmed to fit the payload budget. */
+ truncated?: boolean;
+ body: TracePatchBody;
+}
+
/** An empty body is zero lines, not one blank line — a pure deletion has no `+`. */
function toLines(value: string): string[] {
return value.length === 0 ? [] : value.split("\n");
@@ -316,6 +360,133 @@ type FileMutation =
| { mode: "replace"; path: string; before: string[]; after: string[] }
| { mode: "write"; path: string; content: string };
+/**
+ * Parse a ready-made unified diff into diff rows.
+ *
+ * Codex reports an updated file as a unified diff rather than a before/after
+ * pair, so there is nothing to compare — recomputing a diff would mean first
+ * reconstructing both sides from the diff itself. Hunk headers become `gap`
+ * rows, which is exactly what they denote: skipped, unchanged content.
+ */
+export function parseUnifiedDiff(diff: string): TraceDiffLine[] {
+ const raw = diff.split("\n");
+ // `split` on a trailing newline yields a phantom final element; a genuinely
+ // empty trailing context line would have been " ", not "".
+ if (raw.length > 0 && raw[raw.length - 1] === "") raw.pop();
+
+ const out: TraceDiffLine[] = [];
+ // File headers only exist ahead of the first hunk. Past that point every
+ // line belongs to the file, and "---"/"+++" are ordinary changed lines whose
+ // content happens to start with a dash or plus — a Markdown rule, a nested
+ // patch, a comment banner. Treating them as headers anywhere deleted real
+ // content from the diff.
+ let inHunk = false;
+ for (const line of raw) {
+ if (line.startsWith("@@")) {
+ inHunk = true;
+ out.push({ kind: "gap", text: line });
+ continue;
+ }
+ if (!inHunk) {
+ if (
+ line.startsWith("diff --git") ||
+ line.startsWith("index ") ||
+ line.startsWith("--- ") ||
+ line.startsWith("+++ ") ||
+ line === "---" ||
+ line === "+++"
+ ) {
+ continue;
+ }
+ }
+ // "\ No newline at end of file" is metadata, not a line of the file: a
+ // real line starting with a backslash carries a +/-/space prefix first.
+ if (line.startsWith("\\")) continue;
+ if (line.startsWith("+")) {
+ out.push({ kind: "add", text: line.slice(1) });
+ continue;
+ }
+ if (line.startsWith("-")) {
+ out.push({ kind: "remove", text: line.slice(1) });
+ continue;
+ }
+ if (line.startsWith(" ")) {
+ out.push({ kind: "context", text: line.slice(1) });
+ continue;
+ }
+ // Tolerate a context line that lost its leading space rather than dropping
+ // content on the floor.
+ out.push({ kind: "context", text: line });
+ }
+ return out;
+}
+
+/**
+ * Read the normalized multi-file patch payload that the Codex adapter records:
+ * `{ changes: [{ path, kind, diff?, content?, move_path? }], truncated? }`.
+ *
+ * Returns null for anything that is not this shape, so an unrecognised payload
+ * falls back to pretty JSON instead of rendering as an empty patch.
+ */
+function readPatchChanges(input: Record<string, unknown>): TracePatchFile[] | null {
+ if (!Array.isArray(input.changes)) return null;
+
+ const files: TracePatchFile[] = [];
+ for (const entry of input.changes) {
+ if (typeof entry !== "object" || entry === null) continue;
+ const rec = entry as Record<string, unknown>;
+ const path = typeof rec.path === "string" ? rec.path : "";
+ if (path.length === 0) continue;
+
+ const file: TracePatchFile = { path, body: { kind: "none" } };
+ if (typeof rec.kind === "string" && rec.kind.length > 0) file.changeKind = rec.kind;
+ if (typeof rec.move_path === "string" && rec.move_path.length > 0) {
+ file.movePath = rec.move_path;
+ }
+ if (rec.truncated === true) file.truncated = true;
+
+ if (typeof rec.diff === "string" && rec.diff.length > 0) {
+ file.body = { kind: "diff", lines: parseUnifiedDiff(rec.diff) };
+ } else if (typeof rec.content === "string") {
+ // An added file can legitimately be empty, so this keys on the field
+ // being present rather than on the content being non-empty.
+ if (file.changeKind === "delete") {
+ // The legacy protocol reports a deletion as the whole outgoing file.
+ // All-removals states that; a green "+N" would say the opposite.
+ file.body = {
+ kind: "diff",
+ lines: toLines(rec.content).map((text) => ({ kind: "remove" as const, text })),
+ };
+ } else {
+ file.body = {
+ kind: "file",
+ text: rec.content,
+ lineCount: toLines(rec.content).length,
+ };
+ }
+ }
+ files.push(file);
+ }
+
+ return files.length > 0 ? files : null;
+}
+
+/** First path plus a count, for the collapsed one-line summary. */
+function readPatchSummary(
+ input: Record<string, unknown> | undefined,
+ labels?: TraceSummaryLabels,
+): string {
+ if (!input) return "";
+ const files = readPatchChanges(input);
+ if (files === null) return "";
+ const first = files[0];
+ if (first === undefined) return "";
+ const head = shortenTracePath(first.path);
+ if (files.length === 1) return head;
+ const extraCount = files.length - 1;
+ return labels?.morePaths?.(head, extraCount) ?? `${head} +${extraCount} more`;
+}
+
function readFileMutation(input: Record<string, unknown>): FileMutation | null {
const str = (v: unknown): string | null => (typeof v === "string" ? v : null);
const path = str(input.file_path) ?? str(input.path);
@@ -345,6 +516,10 @@ export function traceEventDetail(event: TraceEvent): TraceEventDetail {
switch (traceEventKind(event)) {
case "tool_use": {
if (!event.input) return { kind: "text", text: "" };
+ const patch = readPatchChanges(event.input);
+ if (patch !== null) {
+ return { kind: "patch", files: patch, truncated: event.input.truncated === true };
+ }
const mutation = readFileMutation(event.input);
if (mutation?.mode === "replace") {
return {
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index bab6580f1a..a7671ec851 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -789,6 +789,10 @@
"density_collapsed_desc": "One line per event — the most compact scan",
"no_output": "No output",
"show_all": "Show all",
+ "patch_truncated": "... (truncated)",
+ "patch_body_truncated": "... (body truncated)",
+ "patch_no_content": "(no content reported)",
+ "patch_summary_more": "{{path}} +{{extra}} more",
"status_queued": "Queued",
"status_dispatched": "Dispatched",
"status_cancelled": "Cancelled",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index 8ce59251a1..2c548600cd 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -667,6 +667,10 @@
"density_collapsed_desc": "1 行 1 イベントの最もコンパクトな表示",
"no_output": "出力なし",
"show_all": "すべて表示",
+ "patch_truncated": "...(切り詰め済み)",
+ "patch_body_truncated": "...(本文を切り詰めました)",
+ "patch_no_content": "(内容の記録なし)",
+ "patch_summary_more": "{{path}} 他 {{extra}} 件",
"status_queued": "待機列",
"status_dispatched": "ディスパッチ済み",
"status_cancelled": "キャンセル",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 2b2e6821d5..e98031d0f6 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -675,6 +675,10 @@
"density_collapsed_desc": "이벤트당 한 줄, 가장 간결한 보기",
"no_output": "출력 없음",
"show_all": "모두 보기",
+ "patch_truncated": "...(잘림)",
+ "patch_body_truncated": "...(본문 잘림)",
+ "patch_no_content": "(기록된 내용 없음)",
+ "patch_summary_more": "{{path}} 외 {{extra}}개",
"status_queued": "대기열",
"status_dispatched": "디스패치됨",
"status_cancelled": "취소됨",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index 455ac8f0cf..c5691724d7 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -774,6 +774,10 @@
"density_collapsed_desc": "一行一事件,最紧凑的扫读视图",
"no_output": "无输出",
"show_all": "显示全部",
+ "patch_truncated": "...(已截断)",
+ "patch_body_truncated": "...(内容已截断)",
+ "patch_no_content": "(未记录内容)",
+ "patch_summary_more": "{{path}},另有 {{extra}} 个文件",
"status_queued": "排队中",
"status_dispatched": "已派发",
"status_cancelled": "已取消",
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 41699b4878..92f2a3e4ff 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -27,6 +27,7 @@ import (
"github.com/multica-ai/multica/server/internal/daemon/repocache"
"github.com/multica-ai/multica/server/internal/selfexec"
"github.com/multica-ai/multica/server/pkg/agent"
+ "github.com/multica-ai/multica/server/pkg/redact"
"github.com/multica-ai/multica/server/pkg/skillbundle"
"github.com/multica-ai/multica/server/pkg/taskfailure"
)
@@ -6017,10 +6018,19 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
s := msgSeq.Add(1)
mu.Lock()
batch = append(batch, TaskMessageData{
- Seq: int(s),
- Type: "tool_use",
- Tool: msg.Tool,
- Input: msg.Input,
+ Seq: int(s),
+ Type: "tool_use",
+ Tool: msg.Tool,
+ // Redact before the payload leaves this process, not
+ // only on arrival. The server redacts again in its
+ // ingest handler, but that is the *remote* side: a
+ // daemon that self-updated ahead of the server — or one
+ // talking to a server mid-rollout — would otherwise ship
+ // whole-file edit contents (a deleted .env, a patched
+ // credential) to a peer that does not scrub nested
+ // values yet. Deployment order is not a control we
+ // have, so this side has to be safe on its own.
+ Input: redact.InputMap(msg.Input),
})
mu.Unlock()
case agent.MessageToolResult:
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index ef2b6f13ab..fbe100a4e2 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -4620,3 +4620,86 @@ func TestConvertDisabledRuntimeSkillsForEnvScopesToClaimedRuntime(t *testing.T)
t.Fatalf("unexpected scoped runtime skill policy: %+v", got)
}
}
+
+// nestedPatchSecretBackend emits a Codex-shaped file-edit payload carrying a
+// credential nested inside changes[] — the legacy protocol reports a deletion
+// as the whole outgoing file, so deleting a .env puts its contents here.
+type nestedPatchSecretBackend struct{}
+
+func (nestedPatchSecretBackend) Execute(
+ _ context.Context,
+ _ string,
+ _ agent.ExecOptions,
+) (*agent.Session, error) {
+ msgCh := make(chan agent.Message, 2)
+ resCh := make(chan agent.Result, 1)
+
+ msgCh <- agent.Message{
+ Type: agent.MessageToolUse,
+ Tool: "patch_apply",
+ CallID: "patch-1",
+ Input: map[string]any{
+ "changes": []any{
+ map[string]any{
+ "path": ".env",
+ "kind": "delete",
+ "content": "GITHUB_TOKEN=ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmn\n",
+ },
+ },
+ },
+ }
+ close(msgCh)
+ resCh <- agent.Result{Status: "completed", Output: "done"}
+ close(resCh)
+
+ return &agent.Session{Messages: msgCh, Result: resCh}, nil
+}
+
+// TestExecuteAndDrain_RedactsNestedToolInputBeforeSending pins the daemon side
+// of the redaction contract. The server scrubs again on ingest, but that is the
+// remote end: a daemon that self-updated ahead of the server, or one talking to
+// a server mid-rollout, must not put whole-file edit contents on the wire in
+// cleartext. Deployment order is not a control we have, so this side has to be
+// safe on its own.
+func TestExecuteAndDrain_RedactsNestedToolInputBeforeSending(t *testing.T) {
+ t.Parallel()
+
+ d, rec := newTranscriptRecorder(t)
+
+ if _, _, err := d.executeAndDrain(
+ context.Background(),
+ nestedPatchSecretBackend{},
+ "p",
+ agent.ExecOptions{},
+ slog.Default(),
+ "task-redact",
+ "",
+ new(atomic.Int32),
+ ); err != nil {
+ t.Fatalf("executeAndDrain: %v", err)
+ }
+
+ msgs := rec.snapshot()
+ var toolUse *TaskMessageData
+ for i := range msgs {
+ if msgs[i].Type == "tool_use" {
+ toolUse = &msgs[i]
+ break
+ }
+ }
+ if toolUse == nil {
+ t.Fatalf("no tool_use message reported: %+v", msgs)
+ }
+
+ blob, err := json.Marshal(toolUse.Input)
+ if err != nil {
+ t.Fatalf("marshal reported input: %v", err)
+ }
+ if strings.Contains(string(blob), "ghp_ABCDEFGH") {
+ t.Fatalf("nested token left the daemon unredacted: %s", blob)
+ }
+ // The surrounding structure must survive, or the transcript loses the edit.
+ if !strings.Contains(string(blob), ".env") {
+ t.Fatalf("redaction destroyed the change metadata: %s", blob)
+ }
+}
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index 1a4bdd9c58..fc0546f5c9 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -19,6 +19,8 @@ import (
"sync/atomic"
"syscall"
"time"
+
+ "github.com/multica-ai/multica/server/pkg/redact"
)
// codexBlockedArgs are flags hardcoded by the daemon that must not be
@@ -2384,6 +2386,306 @@ func (c *codexClient) handleNotification(raw map[string]json.RawMessage) {
}
}
+// codexPatchInputMaxBytes bounds the total diff/content bytes recorded for a
+// single patch_apply event.
+//
+// The bound exists because the legacy protocol reports `add` and `delete` as
+// whole-file contents rather than diffs, so a single generated file can be
+// arbitrarily large. It is deliberately applied only to this new Codex payload:
+// other providers already stream tool inputs through unbounded, and clamping
+// them here would silently truncate transcripts that render correctly today.
+// Unifying the limit at the persistence boundary is a separate change.
+const codexPatchInputMaxBytes = 64 * 1024
+
+// codexNormalizeLegacyChanges converts a legacy `patch_apply_*` changes map
+// into the normalized change list.
+//
+// The legacy wire shape is map[path]FileChange, where FileChange is internally
+// tagged on `type` and carries *different* payload fields per variant:
+// add/delete carry whole-file `content`, while update carries `unified_diff`
+// plus an optional `move_path`. Nothing in that shape is a plain unified diff
+// for every case, which is why the normalized form keeps `diff` and `content`
+// as alternatives instead of one field.
+func codexNormalizeLegacyChanges(raw any) []any {
+ changes, ok := raw.(map[string]any)
+ if !ok || len(changes) == 0 {
+ return nil
+ }
+
+ // Go randomizes map iteration; sort so a replayed event yields a stable
+ // transcript instead of reshuffling the file list on every run.
+ paths := make([]string, 0, len(changes))
+ for path := range changes {
+ paths = append(paths, path)
+ }
+ sort.Strings(paths)
+
+ out := make([]any, 0, len(paths))
+ for _, path := range paths {
+ entry, ok := changes[path].(map[string]any)
+ if !ok {
+ continue
+ }
+ norm := map[string]any{"path": path}
+ if kind, _ := entry["type"].(string); kind != "" {
+ norm["kind"] = kind
+ }
+ if diff, _ := entry["unified_diff"].(string); diff != "" {
+ norm["diff"] = diff
+ }
+ // Presence, not non-emptiness: an added empty file has content "" and
+ // should still render as an empty body rather than a missing one.
+ if content, ok := entry["content"].(string); ok {
+ norm["content"] = content
+ }
+ if movePath, _ := entry["move_path"].(string); movePath != "" {
+ norm["move_path"] = movePath
+ }
+ out = append(out, norm)
+ }
+ if len(out) == 0 {
+ return nil
+ }
+ return out
+}
+
+// codexNormalizeRawChanges converts a v2 app-server `fileChange` item's
+// changes array into the normalized change list.
+//
+// Unlike the legacy shape this is an ordered array of
+// FileUpdateChange{path, kind, diff}, and `kind` is an *object*
+// ({type, move_path?}) rather than a string — reading it as a string yields ""
+// and silently loses the add/delete/update distinction.
+//
+// The `diff` field is misleadingly named: upstream's format_file_change_diff
+// only produces a unified diff for `update`. For `add` and `delete` it returns
+// the whole file's contents verbatim, and for a moved `update` it appends a
+// trailing "\n\nMoved to: <path>" line. Feeding an added file's contents to a
+// diff parser mislabels every line — and actively inverts the meaning of any
+// line that happens to begin with '+' or '-' — so the payload is routed by
+// `kind`, not by field name.
+func codexNormalizeRawChanges(raw any) []any {
+ changes, ok := raw.([]any)
+ if !ok || len(changes) == 0 {
+ return nil
+ }
+ out := make([]any, 0, len(changes))
+ for _, change := range changes {
+ entry, ok := change.(map[string]any)
+ if !ok {
+ continue
+ }
+ norm := map[string]any{}
+ if path, _ := entry["path"].(string); path != "" {
+ norm["path"] = path
+ }
+ kind := ""
+ movePath := ""
+ switch k := entry["kind"].(type) {
+ case map[string]any:
+ kind, _ = k["type"].(string)
+ movePath, _ = k["move_path"].(string)
+ case string:
+ // Tolerate a flattened form so a future protocol tweak degrades
+ // to a labelled change instead of an unlabelled one.
+ kind = k
+ }
+ if kind != "" {
+ norm["kind"] = kind
+ }
+ if movePath != "" {
+ norm["move_path"] = movePath
+ }
+
+ body, bodyPresent := entry["diff"].(string)
+ switch kind {
+ case "add", "delete":
+ // Whole-file contents, despite arriving under `diff`. Keyed on the
+ // field being present rather than non-empty so an empty added file
+ // still renders as an empty body instead of a missing one.
+ if bodyPresent {
+ norm["content"] = body
+ } else if content, ok := entry["content"].(string); ok {
+ norm["content"] = content
+ }
+ default:
+ if body != "" {
+ norm["diff"] = stripCodexMovedToSuffix(body, movePath)
+ } else if content, ok := entry["content"].(string); ok {
+ norm["content"] = content
+ }
+ }
+ if len(norm) == 0 {
+ continue
+ }
+ out = append(out, norm)
+ }
+ if len(out) == 0 {
+ return nil
+ }
+ return out
+}
+
+// stripCodexMovedToSuffix removes the trailing "Moved to: <path>" line that
+// upstream appends to a moved file's unified diff. The destination is already
+// carried as move_path, and leaving the sentence in would render as two stray
+// context lines at the end of the diff.
+func stripCodexMovedToSuffix(diff, movePath string) string {
+ if movePath == "" {
+ return diff
+ }
+ suffix := "\n\nMoved to: " + movePath
+ return strings.TrimSuffix(diff, suffix)
+}
+
+// codexPatchInput wraps normalized changes into the tool_use input, applying
+// the size bound. It returns nil when nothing could be normalized so a
+// malformed or unrecognised event degrades to the previous payload-less
+// behaviour rather than breaking the transcript.
+func codexPatchInput(changes []any) map[string]any {
+ if len(changes) == 0 {
+ return nil
+ }
+ // Measure before anything rewrites the bodies, so the figure reported to the
+ // reader is the size of the patch they actually produced.
+ originalBytes := codexPatchBodyBytes(changes)
+
+ // Redaction must run BEFORE the size budget, never after it. Several rules
+ // only match a credential as a whole — the PEM rule needs both the BEGIN
+ // and the END marker — so cutting a body at the budget can strand the
+ // opening half of a private key in text that no pattern will match again.
+ // The daemon and the server each redact further down the path, and neither
+ // can recover a secret that truncation has already made unrecognisable.
+ safe, ok := redact.InputMap(map[string]any{"changes": changes})["changes"].([]any)
+ if !ok {
+ safe = changes
+ }
+
+ input := map[string]any{"changes": safe}
+ // Budget the redacted bodies, since those are what gets stored. Redaction
+ // usually shrinks a body — a whole key collapses to a short placeholder —
+ // so this is also the measurement that decides whether trimming is needed
+ // at all.
+ if codexPatchBodyBytes(safe) > codexPatchInputMaxBytes {
+ applyCodexPatchBudget(safe)
+ input["truncated"] = true
+ input["original_bytes"] = originalBytes
+ }
+ return input
+}
+
+// codexPatchBodyBytes totals the diff/content payload carried by a change list.
+func codexPatchBodyBytes(changes []any) int {
+ total := 0
+ for _, change := range changes {
+ entry, ok := change.(map[string]any)
+ if !ok {
+ continue
+ }
+ for _, key := range []string{"diff", "content"} {
+ if body, _ := entry[key].(string); body != "" {
+ total += len(body)
+ }
+ }
+ }
+ return total
+}
+
+// applyCodexPatchBudget trims diff/content bodies in place until the payload
+// fits codexPatchInputMaxBytes. Paths and kinds are never dropped: they are
+// small and are the part a reviewer needs even when the body is gone.
+func applyCodexPatchBudget(changes []any) {
+ remaining := codexPatchInputMaxBytes
+ for _, change := range changes {
+ entry, ok := change.(map[string]any)
+ if !ok {
+ continue
+ }
+ for _, key := range []string{"diff", "content"} {
+ body, _ := entry[key].(string)
+ if body == "" {
+ continue
+ }
+ if len(body) <= remaining {
+ remaining -= len(body)
+ continue
+ }
+ if kept := truncateUTF8(body, remaining); kept != "" {
+ entry[key] = kept
+ } else {
+ delete(entry, key)
+ }
+ entry["truncated"] = true
+ remaining = 0
+ }
+ }
+}
+
+// truncateUTF8 cuts s to at most max bytes without leaving a split rune, so the
+// result still marshals as valid JSON.
+func truncateUTF8(s string, max int) string {
+ if max <= 0 {
+ return ""
+ }
+ if len(s) <= max {
+ return s
+ }
+ return strings.ToValidUTF8(s[:max], "")
+}
+
+// codexNormalizePatchStatus maps both protocols' status spellings onto one
+// snake_case vocabulary: the legacy enum is already snake_case
+// (completed/failed/declined) while the v2 enum is camelCase and adds
+// inProgress.
+func codexNormalizePatchStatus(status string) string {
+ switch status {
+ case "":
+ return ""
+ case "inProgress", "in_progress":
+ return "in_progress"
+ default:
+ return status
+ }
+}
+
+// codexPatchResultOutput renders the tool_result line for a finished patch.
+// It always produces a non-empty string when anything is known, because an
+// empty output renders as an unexpandable blank row in the transcript.
+func codexPatchResultOutput(status string, changes []any, stdout, stderr string) string {
+ segments := make([]string, 0, 3)
+
+ if headline := codexPatchHeadline(status, len(changes)); headline != "" {
+ segments = append(segments, headline)
+ }
+ if out := strings.TrimSpace(stdout); out != "" {
+ segments = append(segments, out)
+ }
+ if err := strings.TrimSpace(stderr); err != "" {
+ segments = append(segments, err)
+ }
+ return strings.Join(segments, "\n")
+}
+
+func codexPatchHeadline(status string, fileCount int) string {
+ switch {
+ case status == "" && fileCount == 0:
+ return ""
+ case status == "":
+ return fmt.Sprintf("%s changed", pluralizeFiles(fileCount))
+ case fileCount == 0:
+ return status
+ default:
+ return fmt.Sprintf("%s (%s)", status, pluralizeFiles(fileCount))
+ }
+}
+
+func pluralizeFiles(n int) string {
+ if n == 1 {
+ return "1 file"
+ }
+ return fmt.Sprintf("%d files", n)
+}
+
func (c *codexClient) handleEvent(msg map[string]any) {
msgType, _ := msg["type"].(string)
@@ -2427,15 +2729,32 @@ func (c *codexClient) handleEvent(msg map[string]any) {
Type: MessageToolUse,
Tool: "patch_apply",
CallID: callID,
+ Input: codexPatchInput(codexNormalizeLegacyChanges(msg["changes"])),
})
}
case "patch_apply_end":
callID, _ := msg["call_id"].(string)
+ stdout, _ := msg["stdout"].(string)
+ stderr, _ := msg["stderr"].(string)
+ status, _ := msg["status"].(string)
+ if status == "" {
+ // `status` postdates `success`; fall back so older builds still
+ // report an outcome rather than a bare file count.
+ if success, ok := msg["success"].(bool); ok {
+ if success {
+ status = "completed"
+ } else {
+ status = "failed"
+ }
+ }
+ }
+ changes := codexNormalizeLegacyChanges(msg["changes"])
if c.onMessage != nil {
c.onMessage(Message{
Type: MessageToolResult,
Tool: "patch_apply",
CallID: callID,
+ Output: codexPatchResultOutput(codexNormalizePatchStatus(status), changes, stdout, stderr),
})
}
case "task_complete":
@@ -2598,15 +2917,19 @@ func (c *codexClient) handleItemNotification(method string, params map[string]an
Type: MessageToolUse,
Tool: "patch_apply",
CallID: itemID,
+ Input: codexPatchInput(codexNormalizeRawChanges(item["changes"])),
})
}
case method == "item/completed" && itemType == "fileChange":
+ status, _ := item["status"].(string)
+ changes := codexNormalizeRawChanges(item["changes"])
if c.onMessage != nil {
c.onMessage(Message{
Type: MessageToolResult,
Tool: "patch_apply",
CallID: itemID,
+ Output: codexPatchResultOutput(codexNormalizePatchStatus(status), changes, "", ""),
})
}
diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.go
index 22bcff98ad..de52272f1f 100644
--- a/server/pkg/agent/codex_test.go
+++ b/server/pkg/agent/codex_test.go
@@ -16,6 +16,8 @@ import (
"testing"
"time"
"unicode/utf8"
+
+ "github.com/multica-ai/multica/server/pkg/redact"
)
func newTestCodexClient(t *testing.T) (*codexClient, *fakeStdin, []Message) {
@@ -4462,3 +4464,717 @@ func TestHasManagedCodexMcpConfig(t *testing.T) {
})
}
}
+
+// --- patch_apply payload capture (GH #6157) -------------------------------
+//
+// Both Codex protocols used to record a file edit as a bare call ID, leaving
+// the transcript with two unexpandable blank rows per edit. These tests pin the
+// payload on both paths, including the two shapes that differ between them:
+// legacy reports add/delete as whole-file content under a path-keyed map, while
+// v2 reports an ordered array whose `kind` is an object rather than a string.
+
+// codexTestChanges extracts the normalized change list from a tool_use input.
+func codexTestChanges(t *testing.T, msg Message) []map[string]any {
+ t.Helper()
+ if msg.Input == nil {
+ t.Fatalf("expected input on tool_use message, got nil: %+v", msg)
+ }
+ raw, ok := msg.Input["changes"].([]any)
+ if !ok {
+ t.Fatalf("expected changes slice, got %#v", msg.Input["changes"])
+ }
+ out := make([]map[string]any, 0, len(raw))
+ for _, entry := range raw {
+ m, ok := entry.(map[string]any)
+ if !ok {
+ t.Fatalf("expected change to be an object, got %#v", entry)
+ }
+ out = append(out, m)
+ }
+ return out
+}
+
+func TestCodexLegacyPatchApplyRecordsChanges(t *testing.T) {
+ t.Parallel()
+
+ c, _, _ := newTestCodexClient(t)
+ var messages []Message
+ c.onMessage = func(msg Message) { messages = append(messages, msg) }
+
+ c.handleLine(`{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"patch_apply_begin","call_id":"p1","auto_approved":true,"changes":{"src/b.go":{"type":"update","unified_diff":"@@ -1 +1 @@\n-old\n+new\n","move_path":"src/c.go"},"src/a.txt":{"type":"add","content":"hello"}}}}}`)
+ c.handleLine(`{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"patch_apply_end","call_id":"p1","stdout":"Success. Updated the following files:\nM src/b.go","stderr":"","success":true,"status":"completed","changes":{"src/b.go":{"type":"update","unified_diff":"@@ -1 +1 @@\n-old\n+new\n"},"src/a.txt":{"type":"add","content":"hello"}}}}}`)
+
+ if len(messages) != 2 {
+ t.Fatalf("expected 2 messages, got %d", len(messages))
+ }
+
+ begin := messages[0]
+ if begin.Type != MessageToolUse || begin.Tool != "patch_apply" || begin.CallID != "p1" {
+ t.Fatalf("unexpected begin message: %+v", begin)
+ }
+ changes := codexTestChanges(t, begin)
+ if len(changes) != 2 {
+ t.Fatalf("expected 2 changes, got %d: %#v", len(changes), changes)
+ }
+ // Sorted by path so a replayed event does not reshuffle the file list.
+ if changes[0]["path"] != "src/a.txt" || changes[1]["path"] != "src/b.go" {
+ t.Fatalf("changes not sorted by path: %#v", changes)
+ }
+ if changes[0]["kind"] != "add" || changes[0]["content"] != "hello" {
+ t.Fatalf("add change lost its whole-file content: %#v", changes[0])
+ }
+ if _, hasDiff := changes[0]["diff"]; hasDiff {
+ t.Fatalf("legacy add must not invent a diff: %#v", changes[0])
+ }
+ if changes[1]["kind"] != "update" {
+ t.Fatalf("expected update kind, got %#v", changes[1]["kind"])
+ }
+ if diff, _ := changes[1]["diff"].(string); !strings.Contains(diff, "-old") || !strings.Contains(diff, "+new") {
+ t.Fatalf("update change lost its unified diff: %#v", changes[1])
+ }
+ if changes[1]["move_path"] != "src/c.go" {
+ t.Fatalf("expected move_path to be preserved: %#v", changes[1])
+ }
+
+ end := messages[1]
+ if end.Type != MessageToolResult || end.CallID != "p1" {
+ t.Fatalf("unexpected end message: %+v", end)
+ }
+ if end.Output == "" {
+ t.Fatal("patch_apply_end output is empty, transcript row stays unexpandable")
+ }
+ if !strings.Contains(end.Output, "completed") {
+ t.Fatalf("expected status in output, got %q", end.Output)
+ }
+ if !strings.Contains(end.Output, "Success. Updated the following files:") {
+ t.Fatalf("expected apply_patch stdout in output, got %q", end.Output)
+ }
+}
+
+func TestCodexLegacyPatchApplyDeleteKeepsContent(t *testing.T) {
+ t.Parallel()
+
+ c, _, _ := newTestCodexClient(t)
+ var messages []Message
+ c.onMessage = func(msg Message) { messages = append(messages, msg) }
+
+ c.handleLine(`{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"patch_apply_begin","call_id":"p1","auto_approved":true,"changes":{"old.txt":{"type":"delete","content":"gone"}}}}}`)
+
+ changes := codexTestChanges(t, messages[0])
+ if len(changes) != 1 || changes[0]["kind"] != "delete" || changes[0]["content"] != "gone" {
+ t.Fatalf("delete change not captured: %#v", changes)
+ }
+}
+
+func TestCodexLegacyPatchApplyStatusFallsBackToSuccess(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ event string
+ wantSub string
+ }{
+ {
+ name: "success true without status",
+ event: `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"patch_apply_end","call_id":"p1","stdout":"","stderr":"","success":true,"changes":{"a.txt":{"type":"add","content":"x"}}}}}`,
+ wantSub: "completed",
+ },
+ {
+ name: "success false without status",
+ event: `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"patch_apply_end","call_id":"p1","stdout":"","stderr":"parse error","success":false,"changes":{"a.txt":{"type":"add","content":"x"}}}}}`,
+ wantSub: "failed",
+ },
+ {
+ name: "explicit declined status wins",
+ event: `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"patch_apply_end","call_id":"p1","stdout":"","stderr":"","success":false,"status":"declined","changes":{}}}}`,
+ wantSub: "declined",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ c, _, _ := newTestCodexClient(t)
+ var messages []Message
+ c.onMessage = func(msg Message) { messages = append(messages, msg) }
+
+ c.handleLine(tc.event)
+
+ if len(messages) != 1 {
+ t.Fatalf("expected 1 message, got %d", len(messages))
+ }
+ if !strings.Contains(messages[0].Output, tc.wantSub) {
+ t.Fatalf("expected output to contain %q, got %q", tc.wantSub, messages[0].Output)
+ }
+ })
+ }
+}
+
+func TestCodexLegacyPatchApplyStderrSurfaced(t *testing.T) {
+ t.Parallel()
+
+ c, _, _ := newTestCodexClient(t)
+ var messages []Message
+ c.onMessage = func(msg Message) { messages = append(messages, msg) }
+
+ c.handleLine(`{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"patch_apply_end","call_id":"p1","stdout":"","stderr":"apply_patch: could not parse hunk","success":false,"status":"failed","changes":{}}}}`)
+
+ if !strings.Contains(messages[0].Output, "could not parse hunk") {
+ t.Fatalf("expected stderr in output, got %q", messages[0].Output)
+ }
+}
+
+func TestCodexRawPatchApplyRecordsChanges(t *testing.T) {
+ t.Parallel()
+
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = "raw"
+ var messages []Message
+ c.onMessage = func(msg Message) { messages = append(messages, msg) }
+
+ // Fixtures follow upstream convert_patch_changes: `diff` holds a unified
+ // diff only for `update`. For `add` it is the whole file's contents.
+ c.handleLine(`{"jsonrpc":"2.0","method":"item/started","params":{"item":{"type":"fileChange","id":"patch-1","status":"inProgress","changes":[{"path":"src/a.go","kind":{"type":"update","move_path":null},"diff":"@@ -1 +1 @@\n-a\n+b\n"},{"path":"src/new.go","kind":{"type":"add"},"diff":"package main\n"}]}}}`)
+ c.handleLine(`{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"fileChange","id":"patch-1","status":"completed","changes":[{"path":"src/a.go","kind":{"type":"update"},"diff":"@@ -1 +1 @@\n-a\n+b\n"},{"path":"src/new.go","kind":{"type":"add"},"diff":"package main\n"}]}}}`)
+
+ if len(messages) != 2 {
+ t.Fatalf("expected 2 messages, got %d", len(messages))
+ }
+
+ begin := messages[0]
+ if begin.Type != MessageToolUse || begin.Tool != "patch_apply" || begin.CallID != "patch-1" {
+ t.Fatalf("unexpected start message: %+v", begin)
+ }
+ changes := codexTestChanges(t, begin)
+ if len(changes) != 2 {
+ t.Fatalf("expected 2 changes, got %d: %#v", len(changes), changes)
+ }
+ if changes[0]["path"] != "src/a.go" || changes[1]["path"] != "src/new.go" {
+ t.Fatalf("v2 change order not preserved: %#v", changes)
+ }
+ // `kind` arrives as an object; reading it as a string yields "" and loses
+ // the add/delete/update distinction.
+ if changes[0]["kind"] != "update" {
+ t.Fatalf("expected kind flattened to \"update\", got %#v", changes[0]["kind"])
+ }
+ if diff, _ := changes[0]["diff"].(string); !strings.Contains(diff, "+b") {
+ t.Fatalf("v2 update diff not captured: %#v", changes[0])
+ }
+ // The add's payload is file content, so it must NOT be labelled a diff:
+ // a diff parser would mislabel every line and invert any line starting
+ // with '+' or '-'.
+ if changes[1]["kind"] != "add" {
+ t.Fatalf("expected kind flattened to \"add\", got %#v", changes[1]["kind"])
+ }
+ if _, isDiff := changes[1]["diff"]; isDiff {
+ t.Fatalf("v2 add must not be recorded as a diff: %#v", changes[1])
+ }
+ if changes[1]["content"] != "package main\n" {
+ t.Fatalf("v2 add content not captured: %#v", changes[1])
+ }
+
+ end := messages[1]
+ if end.Type != MessageToolResult || end.CallID != "patch-1" {
+ t.Fatalf("unexpected complete message: %+v", end)
+ }
+ if end.Output == "" {
+ t.Fatal("fileChange completion output is empty, transcript row stays unexpandable")
+ }
+ if !strings.Contains(end.Output, "completed") || !strings.Contains(end.Output, "2 files") {
+ t.Fatalf("expected status and file count, got %q", end.Output)
+ }
+}
+
+// Upstream format_file_change_diff returns whole-file contents for add and
+// delete under the `diff` field. Treating that as a unified diff renders plain
+// lines as context, and inverts any line that begins with '+' or '-'.
+func TestCodexRawPatchApplyContentKindsAreNotDiffs(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ kind string
+ body string
+ }{
+ {name: "add", kind: "add", body: "package main\n"},
+ {name: "delete", kind: "delete", body: "goodbye\n"},
+ {
+ name: "add whose content looks like a diff",
+ kind: "add",
+ body: "--- not a header\n+++ also not\n-minus lead\n+plus lead\n",
+ },
+ {name: "empty add", kind: "add", body: ""},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = "raw"
+ var messages []Message
+ c.onMessage = func(msg Message) { messages = append(messages, msg) }
+
+ event, err := json.Marshal(map[string]any{
+ "jsonrpc": "2.0",
+ "method": "item/started",
+ "params": map[string]any{
+ "item": map[string]any{
+ "type": "fileChange", "id": "patch-1", "status": "inProgress",
+ "changes": []any{
+ map[string]any{
+ "path": "f.txt",
+ "kind": map[string]any{"type": tc.kind},
+ "diff": tc.body,
+ },
+ },
+ },
+ },
+ })
+ if err != nil {
+ t.Fatalf("marshal event: %v", err)
+ }
+ c.handleLine(string(event))
+
+ changes := codexTestChanges(t, messages[0])
+ if len(changes) != 1 {
+ t.Fatalf("expected 1 change, got %#v", changes)
+ }
+ if _, isDiff := changes[0]["diff"]; isDiff {
+ t.Fatalf("%s must be recorded as content, not diff: %#v", tc.kind, changes[0])
+ }
+ content, ok := changes[0]["content"].(string)
+ if !ok {
+ // Presence, not non-emptiness: an empty added file still has a
+ // body, and dropping it would render as "no content reported".
+ t.Fatalf("expected content to be present for %s: %#v", tc.kind, changes[0])
+ }
+ if content != tc.body {
+ t.Fatalf("content altered: got %q want %q", content, tc.body)
+ }
+ })
+ }
+}
+
+// A moved update has "\n\nMoved to: <path>" appended to its diff upstream. The
+// destination is already carried as move_path, and leaving the sentence in
+// renders as two stray context rows at the end of the diff.
+func TestCodexRawPatchApplyStripsMovedToSuffix(t *testing.T) {
+ t.Parallel()
+
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = "raw"
+ var messages []Message
+ c.onMessage = func(msg Message) { messages = append(messages, msg) }
+
+ c.handleLine(`{"jsonrpc":"2.0","method":"item/started","params":{"item":{"type":"fileChange","id":"patch-1","status":"inProgress","changes":[{"path":"old/name.go","kind":{"type":"update","move_path":"new/name.go"},"diff":"@@ -1 +1 @@\n-x\n+y\n\n\nMoved to: new/name.go"}]}}}`)
+
+ changes := codexTestChanges(t, messages[0])
+ if changes[0]["move_path"] != "new/name.go" {
+ t.Fatalf("expected move_path lifted out of kind, got %#v", changes[0])
+ }
+ diff, _ := changes[0]["diff"].(string)
+ if strings.Contains(diff, "Moved to:") {
+ t.Fatalf("Moved to: sentence should be stripped from the diff: %q", diff)
+ }
+ if !strings.Contains(diff, "+y") {
+ t.Fatalf("stripping removed real diff content: %q", diff)
+ }
+}
+
+func TestCodexRawPatchApplyMovePathFromKind(t *testing.T) {
+ t.Parallel()
+
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = "raw"
+ var messages []Message
+ c.onMessage = func(msg Message) { messages = append(messages, msg) }
+
+ c.handleLine(`{"jsonrpc":"2.0","method":"item/started","params":{"item":{"type":"fileChange","id":"patch-1","status":"inProgress","changes":[{"path":"old/name.go","kind":{"type":"update","move_path":"new/name.go"},"diff":"@@ -1 +1 @@\n-x\n+y\n"}]}}}`)
+
+ changes := codexTestChanges(t, messages[0])
+ if changes[0]["move_path"] != "new/name.go" {
+ t.Fatalf("expected move_path lifted out of kind, got %#v", changes[0])
+ }
+}
+
+func TestCodexLegacyPatchApplyKeepsEmptyAddedFile(t *testing.T) {
+ t.Parallel()
+
+ c, _, _ := newTestCodexClient(t)
+ var messages []Message
+ c.onMessage = func(msg Message) { messages = append(messages, msg) }
+
+ c.handleLine(`{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"patch_apply_begin","call_id":"p1","auto_approved":true,"changes":{"empty.txt":{"type":"add","content":""}}}}}`)
+
+ changes := codexTestChanges(t, messages[0])
+ content, ok := changes[0]["content"].(string)
+ if !ok || content != "" {
+ t.Fatalf("empty added file should keep an empty body: %#v", changes[0])
+ }
+}
+
+func TestCodexRawPatchApplyStatusNormalized(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct{ status, want string }{
+ {"inProgress", "in_progress"},
+ {"completed", "completed"},
+ {"failed", "failed"},
+ {"declined", "declined"},
+ }
+ for _, tc := range tests {
+ t.Run(tc.status, func(t *testing.T) {
+ t.Parallel()
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = "raw"
+ var messages []Message
+ c.onMessage = func(msg Message) { messages = append(messages, msg) }
+
+ c.handleLine(fmt.Sprintf(`{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"fileChange","id":"patch-1","status":%q,"changes":[{"path":"a.go","kind":{"type":"add"},"diff":"+x"}]}}}`, tc.status))
+
+ if len(messages) != 1 {
+ t.Fatalf("expected 1 message, got %d", len(messages))
+ }
+ if !strings.Contains(messages[0].Output, tc.want) {
+ t.Fatalf("status %q: expected output to contain %q, got %q", tc.status, tc.want, messages[0].Output)
+ }
+ })
+ }
+}
+
+// A missing or malformed `changes` must degrade to the previous payload-less
+// behaviour rather than panicking or emitting a broken payload.
+func TestCodexPatchApplyMalformedChangesDegrade(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ event string
+ raw bool
+ }{
+ {
+ name: "legacy changes absent",
+ event: `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"patch_apply_begin","call_id":"p1","auto_approved":true}}}`,
+ },
+ {
+ name: "legacy changes wrong type",
+ event: `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"patch_apply_begin","call_id":"p1","changes":"not-an-object"}}}`,
+ },
+ {
+ name: "legacy changes empty",
+ event: `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"patch_apply_begin","call_id":"p1","changes":{}}}}`,
+ },
+ {
+ name: "legacy change entry not an object",
+ event: `{"jsonrpc":"2.0","method":"codex/event","params":{"msg":{"type":"patch_apply_begin","call_id":"p1","changes":{"a.txt":42}}}}`,
+ },
+ {
+ name: "raw changes absent",
+ event: `{"jsonrpc":"2.0","method":"item/started","params":{"item":{"type":"fileChange","id":"patch-1"}}}`,
+ raw: true,
+ },
+ {
+ name: "raw changes wrong type",
+ event: `{"jsonrpc":"2.0","method":"item/started","params":{"item":{"type":"fileChange","id":"patch-1","changes":{"path":"a.go"}}}}`,
+ raw: true,
+ },
+ {
+ name: "raw change entries unusable",
+ event: `{"jsonrpc":"2.0","method":"item/started","params":{"item":{"type":"fileChange","id":"patch-1","changes":[42,null]}}}`,
+ raw: true,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ c, _, _ := newTestCodexClient(t)
+ if tc.raw {
+ c.notificationProtocol = "raw"
+ }
+ var messages []Message
+ c.onMessage = func(msg Message) { messages = append(messages, msg) }
+
+ c.handleLine(tc.event)
+
+ if len(messages) != 1 {
+ t.Fatalf("expected the tool_use message to still be emitted, got %d", len(messages))
+ }
+ if messages[0].Type != MessageToolUse || messages[0].Tool != "patch_apply" {
+ t.Fatalf("unexpected message: %+v", messages[0])
+ }
+ if messages[0].Input != nil {
+ t.Fatalf("expected nil input for unusable changes, got %#v", messages[0].Input)
+ }
+ })
+ }
+}
+
+func TestCodexPatchApplyTruncatesOversizePayload(t *testing.T) {
+ t.Parallel()
+
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = "raw"
+ var messages []Message
+ c.onMessage = func(msg Message) { messages = append(messages, msg) }
+
+ // Legacy add/delete report whole-file content, so a single generated file
+ // can dwarf the transcript budget.
+ huge := strings.Repeat("x", codexPatchInputMaxBytes+5000)
+ event, err := json.Marshal(map[string]any{
+ "jsonrpc": "2.0",
+ "method": "item/started",
+ "params": map[string]any{
+ "item": map[string]any{
+ "type": "fileChange",
+ "id": "patch-1",
+ "status": "inProgress",
+ "changes": []any{
+ map[string]any{"path": "big.txt", "kind": map[string]any{"type": "add"}, "diff": huge},
+ map[string]any{"path": "second.txt", "kind": map[string]any{"type": "add"}, "diff": "small"},
+ },
+ },
+ },
+ })
+ if err != nil {
+ t.Fatalf("marshal event: %v", err)
+ }
+ c.handleLine(string(event))
+
+ if len(messages) != 1 {
+ t.Fatalf("expected 1 message, got %d", len(messages))
+ }
+ input := messages[0].Input
+ if input["truncated"] != true {
+ t.Fatalf("expected truncated marker, got %#v", input["truncated"])
+ }
+ if input["original_bytes"] == nil {
+ t.Fatal("expected original_bytes to be recorded alongside truncation")
+ }
+
+ changes := codexTestChanges(t, messages[0])
+ total := 0
+ for _, change := range changes {
+ // An `add` is recorded as content, not diff, so both keys count
+ // toward the budget.
+ for _, key := range []string{"diff", "content"} {
+ body, ok := change[key].(string)
+ if !ok {
+ continue
+ }
+ total += len(body)
+ if !utf8.ValidString(body) {
+ t.Fatalf("truncation split a rune in %v", change["path"])
+ }
+ }
+ }
+ if total == 0 {
+ t.Fatal("expected some body to survive truncation")
+ }
+ if total > codexPatchInputMaxBytes {
+ t.Fatalf("payload %d bytes exceeds budget %d", total, codexPatchInputMaxBytes)
+ }
+ // The path survives even when its body is dropped: it is the part a
+ // reviewer still needs.
+ if changes[0]["path"] != "big.txt" || changes[1]["path"] != "second.txt" {
+ t.Fatalf("paths must survive truncation: %#v", changes)
+ }
+ if changes[0]["truncated"] != true {
+ t.Fatalf("expected per-change truncation marker: %#v", changes[0])
+ }
+}
+
+func TestCodexPatchApplyTruncationKeepsValidUTF8(t *testing.T) {
+ t.Parallel()
+
+ // Multi-byte runes straddling the cut must not leave an invalid string,
+ // or the payload fails to marshal into the JSONB column.
+ body := strings.Repeat("世", codexPatchInputMaxBytes)
+ changes := []any{
+ map[string]any{"path": "wide.txt", "kind": "add", "content": body},
+ }
+ input := codexPatchInput(changes)
+ if input["truncated"] != true {
+ t.Fatalf("expected truncation for %d-byte body", len(body))
+ }
+ for _, kept := range codexTestBodies(t, input) {
+ if !utf8.ValidString(kept) {
+ t.Fatal("truncated content is not valid UTF-8")
+ }
+ if len(kept) > codexPatchInputMaxBytes {
+ t.Fatalf("kept %d bytes, budget is %d", len(kept), codexPatchInputMaxBytes)
+ }
+ }
+ if _, err := json.Marshal(input); err != nil {
+ t.Fatalf("truncated payload does not marshal: %v", err)
+ }
+}
+
+func TestCodexPatchApplyUnderBudgetIsNotMarkedTruncated(t *testing.T) {
+ t.Parallel()
+
+ input := codexPatchInput([]any{
+ map[string]any{"path": "a.go", "kind": "update", "diff": "@@ -1 +1 @@\n-a\n+b\n"},
+ })
+ if _, marked := input["truncated"]; marked {
+ t.Fatalf("small payload must not be marked truncated: %#v", input)
+ }
+ if _, marked := input["original_bytes"]; marked {
+ t.Fatalf("small payload must not carry original_bytes: %#v", input)
+ }
+}
+
+// codexTestBodies returns the diff/content bodies carried by a tool_use input.
+//
+// Read the *returned* payload, never the slice handed to codexPatchInput:
+// redaction copies before the budget trims, so the caller's originals stay
+// untouched and asserting on them would pass vacuously.
+func codexTestBodies(t *testing.T, input map[string]any) []string {
+ t.Helper()
+ raw, ok := input["changes"].([]any)
+ if !ok {
+ t.Fatalf("expected changes slice, got %#v", input["changes"])
+ }
+ var bodies []string
+ for _, change := range raw {
+ entry, ok := change.(map[string]any)
+ if !ok {
+ continue
+ }
+ for _, key := range []string{"diff", "content"} {
+ if body, ok := entry[key].(string); ok {
+ bodies = append(bodies, body)
+ }
+ }
+ }
+ return bodies
+}
+
+// Redaction has to happen before the size budget, not after it. Several rules
+// only match a credential as a whole: the PEM rule needs both the BEGIN and the
+// END marker. If a key straddles the budget, truncating first strands the
+// opening half — marker plus key material — in text that no later pass can
+// recognise, so both the daemon's and the server's redaction wave it through
+// and it lands in the database and the WebSocket broadcast.
+func TestCodexPatchApplyRedactsBeforeTruncating(t *testing.T) {
+ t.Parallel()
+
+ const keyChunk = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKg"
+ // BEGIN lands inside the budget; END lands well past it.
+ pem := "-----BEGIN PRIVATE KEY-----\n" +
+ strings.Repeat(keyChunk, 2000) +
+ "\n-----END PRIVATE KEY-----\n"
+ if len(pem) <= codexPatchInputMaxBytes {
+ t.Fatalf("fixture must exceed the budget to exercise the boundary: %d", len(pem))
+ }
+
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = "raw"
+ var messages []Message
+ c.onMessage = func(msg Message) { messages = append(messages, msg) }
+
+ event, err := json.Marshal(map[string]any{
+ "jsonrpc": "2.0",
+ "method": "item/started",
+ "params": map[string]any{
+ "item": map[string]any{
+ "type": "fileChange", "id": "patch-1", "status": "inProgress",
+ "changes": []any{
+ map[string]any{
+ "path": "id_rsa",
+ "kind": map[string]any{"type": "add"},
+ "diff": pem,
+ },
+ },
+ },
+ },
+ })
+ if err != nil {
+ t.Fatalf("marshal event: %v", err)
+ }
+ c.handleLine(string(event))
+
+ if len(messages) != 1 {
+ t.Fatalf("expected 1 message, got %d", len(messages))
+ }
+ bodies := codexTestBodies(t, messages[0].Input)
+ if len(bodies) == 0 {
+ t.Fatal("expected a recorded body")
+ }
+
+ total := 0
+ for _, body := range bodies {
+ total += len(body)
+ if strings.Contains(body, "BEGIN PRIVATE KEY") {
+ t.Errorf("PEM opening marker survived: %q", body[:min(len(body), 120)])
+ }
+ if strings.Contains(body, keyChunk) {
+ t.Error("private key material survived redaction")
+ }
+ if !strings.Contains(body, "[REDACTED PRIVATE KEY]") {
+ t.Errorf("expected the redaction placeholder, got %q", body[:min(len(body), 120)])
+ }
+ }
+ if total > codexPatchInputMaxBytes {
+ t.Fatalf("payload %d bytes exceeds budget %d", total, codexPatchInputMaxBytes)
+ }
+}
+
+// The daemon and the server redact again after the adapter. Those passes must
+// not corrupt an already-redacted payload, or the placeholder itself would be
+// rewritten on the way to the database.
+func TestCodexPatchApplyRedactionIsIdempotent(t *testing.T) {
+ t.Parallel()
+
+ input := codexPatchInput([]any{
+ map[string]any{
+ "path": ".env",
+ "kind": "delete",
+ "content": "GITHUB_TOKEN=ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmn\n",
+ },
+ })
+
+ first, err := json.Marshal(input)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ if strings.Contains(string(first), "ghp_ABCDEFGH") {
+ t.Fatalf("token survived the adapter: %s", first)
+ }
+
+ second, err := json.Marshal(redact.InputMap(input))
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ if string(first) != string(second) {
+ t.Fatalf("a second redaction pass changed the payload:\n first=%s\nsecond=%s", first, second)
+ }
+}
+
+// Redaction running first must not disable the budget for ordinary large
+// patches: a big generated file carries no secret to shrink.
+func TestCodexPatchApplyStillTruncatesNonSecretPayload(t *testing.T) {
+ t.Parallel()
+
+ body := strings.Repeat("x", codexPatchInputMaxBytes+5000)
+ changes := []any{map[string]any{"path": "big.txt", "kind": "add", "content": body}}
+ input := codexPatchInput(changes)
+
+ if input["truncated"] != true {
+ t.Fatalf("expected truncation for a %d-byte body: %#v", len(body), input["truncated"])
+ }
+ if got := input["original_bytes"]; got != len(body) {
+ t.Fatalf("original_bytes should report the pre-redaction size: got %v want %d", got, len(body))
+ }
+ total := 0
+ for _, kept := range codexTestBodies(t, input) {
+ total += len(kept)
+ }
+ if total > codexPatchInputMaxBytes {
+ t.Fatalf("kept %d bytes, budget is %d", total, codexPatchInputMaxBytes)
+ }
+ // The caller's slice is deliberately left alone: redaction copies first.
+ if original, _ := changes[0].(map[string]any)["content"].(string); len(original) != len(body) {
+ t.Fatalf("codexPatchInput must not mutate its argument: %d != %d", len(original), len(body))
+ }
+}
diff --git a/server/pkg/redact/redact.go b/server/pkg/redact/redact.go
index 63763a5c11..934ac721aa 100644
--- a/server/pkg/redact/redact.go
+++ b/server/pkg/redact/redact.go
@@ -74,23 +74,84 @@ var patterns = []secretPattern{
{regexp.MustCompile(`(?i)(?:API_KEY|API_SECRET|SECRET_KEY|SECRET|ACCESS_TOKEN|AUTH_TOKEN|PRIVATE_KEY|DATABASE_URL|DB_PASSWORD|DB_URL|REDIS_URL|PASSWORD|TOKEN)\s*[=:]\s*\S+`), "[REDACTED CREDENTIAL]"},
}
-// InputMap returns a copy of m with all string values passed through Text.
-// Non-string values are preserved as-is.
+// maxRedactDepth bounds the walk in redactValue. Tool inputs are decoded from
+// daemon-supplied JSON, so nesting depth is attacker-influenced; without a
+// bound a pathologically nested payload would recurse until the stack blows and
+// take the process down. Real tool inputs nest a handful of levels at most, so
+// this only ever trips on abuse.
+const maxRedactDepth = 32
+
+// depthLimitPlaceholder replaces anything below maxRedactDepth. Returning the
+// raw value there would hand back an unscrubbed string, which is exactly what
+// this package exists to prevent, so the fail-safe direction is to drop it.
+const depthLimitPlaceholder = "[REDACTED DEPTH LIMIT]"
+
+// InputMap returns a copy of m with every string value passed through Text,
+// including strings nested inside maps and slices.
+//
+// The nested walk is load-bearing, not defensive tidying: providers record
+// structured tool inputs, and Codex records a file edit as
+// changes[]{path, diff, content}. A top-level-only pass leaves a credential
+// inside a patch body — or the full contents of a deleted .env — untouched on
+// its way to the database and the WebSocket broadcast.
func InputMap(m map[string]any) map[string]any {
+ return redactMap(m, 0)
+}
+
+func redactMap(m map[string]any, depth int) map[string]any {
if m == nil {
return nil
}
+ if depth >= maxRedactDepth {
+ return map[string]any{"_": depthLimitPlaceholder}
+ }
out := make(map[string]any, len(m))
for k, v := range m {
- if s, ok := v.(string); ok {
- out[k] = Text(s)
- } else {
- out[k] = v
- }
+ out[k] = redactValue(v, depth+1)
}
return out
}
+// redactValue scrubs a single decoded JSON value, recursing through the
+// composite shapes json.Unmarshal produces plus []string, which providers use
+// for argv-style inputs.
+//
+// Composites are copied rather than scrubbed in place: the caller still holds
+// the original map and keeps using it after redaction (the daemon handler logs
+// and re-reads it), so mutating through the shared reference would be a
+// surprise at a distance.
+func redactValue(v any, depth int) any {
+ if depth >= maxRedactDepth {
+ return depthLimitPlaceholder
+ }
+ switch t := v.(type) {
+ case string:
+ return Text(t)
+ case map[string]any:
+ return redactMap(t, depth)
+ case []any:
+ out := make([]any, len(t))
+ for i, e := range t {
+ out[i] = redactValue(e, depth+1)
+ }
+ return out
+ case []string:
+ out := make([]string, len(t))
+ for i, e := range t {
+ out[i] = Text(e)
+ }
+ return out
+ case map[string]string:
+ out := make(map[string]string, len(t))
+ for k, e := range t {
+ out[k] = Text(e)
+ }
+ return out
+ default:
+ return v
+ }
+}
+
// homeDir is resolved once at init for path redaction.
var homeDir string
var username string
diff --git a/server/pkg/redact/redact_test.go b/server/pkg/redact/redact_test.go
index bf777ac523..d0e950c575 100644
--- a/server/pkg/redact/redact_test.go
+++ b/server/pkg/redact/redact_test.go
@@ -1,6 +1,9 @@
package redact
import (
+ "encoding/json"
+ "os"
+ "os/user"
"strings"
"testing"
)
@@ -303,6 +306,156 @@ func TestInputMapNil(t *testing.T) {
}
}
+// A Codex file edit arrives as changes[]{path, diff, content}. Before the
+// nested walk these strings bypassed redaction entirely and reached the DB.
+func TestInputMapRedactsNestedSliceOfMaps(t *testing.T) {
+ t.Parallel()
+ m := map[string]any{
+ "changes": []any{
+ map[string]any{
+ "path": "cfg.go",
+ "diff": "+api_key: sk-proj-abc123def456ghi789jkl012mno345",
+ },
+ map[string]any{
+ "path": ".env",
+ "content": "GITHUB_TOKEN=ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmn",
+ },
+ },
+ }
+ got := InputMap(m)
+
+ changes, ok := got["changes"].([]any)
+ if !ok || len(changes) != 2 {
+ t.Fatalf("changes not preserved as a 2-element slice: %#v", got["changes"])
+ }
+ first, _ := changes[0].(map[string]any)
+ if diff, _ := first["diff"].(string); strings.Contains(diff, "sk-proj") {
+ t.Fatalf("API key nested in changes[0].diff not redacted: %s", diff)
+ }
+ if first["path"] != "cfg.go" {
+ t.Fatalf("clean nested string altered: %v", first["path"])
+ }
+ second, _ := changes[1].(map[string]any)
+ if content, _ := second["content"].(string); strings.Contains(content, "ghp_ABCDEFGH") {
+ t.Fatalf("token nested in changes[1].content not redacted: %s", content)
+ }
+}
+
+func TestInputMapRedactsDeeplyNestedMaps(t *testing.T) {
+ t.Parallel()
+ m := map[string]any{
+ "a": map[string]any{
+ "b": map[string]any{
+ "c": []any{"leak sk-proj-abc123def456ghi789jkl012mno345"},
+ },
+ },
+ }
+ got := InputMap(m)
+ a, _ := got["a"].(map[string]any)
+ b, _ := a["b"].(map[string]any)
+ c, _ := b["c"].([]any)
+ if len(c) != 1 {
+ t.Fatalf("nested slice not preserved: %#v", b["c"])
+ }
+ if s, _ := c[0].(string); strings.Contains(s, "sk-proj") {
+ t.Fatalf("API key at depth 4 not redacted: %s", s)
+ }
+}
+
+func TestInputMapRedactsNestedHomePath(t *testing.T) {
+ t.Parallel()
+ home, err := os.UserHomeDir()
+ if err != nil || home == "" {
+ t.Skip("no home directory resolved in this environment")
+ }
+ u, err := user.Current()
+ if err != nil || u.Username == "" {
+ t.Skip("no current user resolved in this environment")
+ }
+ m := map[string]any{
+ "changes": []any{
+ map[string]any{"path": home + "/secret/app.go"},
+ },
+ }
+ got := InputMap(m)
+ changes, _ := got["changes"].([]any)
+ first, _ := changes[0].(map[string]any)
+ path, _ := first["path"].(string)
+ if strings.Contains(path, u.Username) {
+ t.Fatalf("username leaked from nested path: %s", path)
+ }
+}
+
+func TestInputMapRedactsStringSliceAndStringMap(t *testing.T) {
+ t.Parallel()
+ m := map[string]any{
+ "argv": []string{"curl", "-H", "Authorization: Bearer abc123def456"},
+ "env": map[string]string{"TOKEN": "ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmn"},
+ }
+ got := InputMap(m)
+
+ argv, ok := got["argv"].([]string)
+ if !ok || len(argv) != 3 {
+ t.Fatalf("argv not preserved as []string: %#v", got["argv"])
+ }
+ if strings.Contains(argv[2], "abc123def456") {
+ t.Fatalf("bearer token in []string not redacted: %s", argv[2])
+ }
+ env, ok := got["env"].(map[string]string)
+ if !ok {
+ t.Fatalf("env not preserved as map[string]string: %#v", got["env"])
+ }
+ if strings.Contains(env["TOKEN"], "ghp_ABCDEFGH") {
+ t.Fatalf("token in map[string]string not redacted: %s", env["TOKEN"])
+ }
+}
+
+// The caller keeps using the map it passed in, so redaction must not write
+// through the shared nested references.
+func TestInputMapDoesNotMutateInput(t *testing.T) {
+ t.Parallel()
+ secret := "sk-proj-abc123def456ghi789jkl012mno345"
+ inner := map[string]any{"diff": secret}
+ m := map[string]any{"changes": []any{inner}}
+
+ _ = InputMap(m)
+
+ if inner["diff"] != secret {
+ t.Fatalf("input map was mutated in place: %v", inner["diff"])
+ }
+}
+
+// Depth is attacker-influenced, so the walk must bottom out instead of
+// exhausting the stack — and must not hand back a raw string when it does.
+func TestInputMapBoundsRecursionDepth(t *testing.T) {
+ t.Parallel()
+ leaf := map[string]any{"leak": "sk-proj-abc123def456ghi789jkl012mno345"}
+ cur := leaf
+ for i := 0; i < 5000; i++ {
+ cur = map[string]any{"next": cur}
+ }
+
+ got := InputMap(cur) // must not stack overflow
+
+ blob, err := json.Marshal(got)
+ if err != nil {
+ t.Fatalf("marshal redacted map: %v", err)
+ }
+ if strings.Contains(string(blob), "sk-proj") {
+ t.Fatalf("secret past the depth limit was returned unredacted")
+ }
+ if !strings.Contains(string(blob), depthLimitPlaceholder) {
+ t.Fatalf("expected depth-limit placeholder in output: %s", truncateForLog(string(blob)))
+ }
+}
+
+func truncateForLog(s string) string {
+ if len(s) <= 200 {
+ return s
+ }
+ return s[:200] + "…"
+}
+
func TestRedactMultipleSecrets(t *testing.T) {
t.Parallel()
input := "Keys: AKIAIOSFODNN7EXAMPLE and ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmn"