diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.ts index c75fe99a79..a58369d50e 100644 --- a/apps/server/src/checkpointing/CheckpointDiffQuery.ts +++ b/apps/server/src/checkpointing/CheckpointDiffQuery.ts @@ -67,12 +67,14 @@ function buildTurnDiffResult( readonly toTurnCount: number; }, diff: string, + gitFileCount?: number, ): OrchestrationGetTurnDiffResultType { return { threadId: input.threadId, fromTurnCount: input.fromTurnCount, toTurnCount: input.toTurnCount, diff, + ...(gitFileCount !== undefined ? { gitFileCount } : {}), }; } @@ -82,16 +84,19 @@ export const make = Effect.gen(function* () { // Drop file sections attributed to pre-existing git history from a patch // unless the caller opted in. Attribution failures degrade to the - // unfiltered patch — never block the diff on attribution. + // unfiltered patch — never block the diff on attribution. The returned + // gitFileCount comes from the SAME attribution pass that produced the + // patch, so UI driven by it always agrees with what is rendered; + // undefined means attribution was unavailable and nothing was filtered. const applyAttributionFilter = Effect.fn("applyAttributionFilter")(function* (input: { readonly cwd: string; readonly fromCheckpointRef: CheckpointRef; readonly toCheckpointRef: CheckpointRef; readonly diff: string; readonly includeGitChanges: boolean; - }) { - if (input.includeGitChanges || input.diff.trim().length === 0) { - return input.diff; + }): Effect.fn.Return<{ readonly diff: string; readonly gitFileCount: number | undefined }> { + if (input.diff.trim().length === 0) { + return { diff: input.diff, gitFileCount: undefined }; } const attribution = yield* checkpointStore .attributeCheckpointDiff({ @@ -101,9 +106,21 @@ export const make = Effect.gen(function* () { }) .pipe(Effect.catch(() => Effect.succeed(null))); if (attribution === null) { - return input.diff; + return { diff: input.diff, gitFileCount: undefined }; } - return filterUnifiedDiffFiles(input.diff, (path) => attribution.get(path) !== "git"); + let gitFileCount = 0; + for (const origin of attribution.values()) { + if (origin === "git") { + gitFileCount += 1; + } + } + if (input.includeGitChanges || gitFileCount === 0) { + return { diff: input.diff, gitFileCount }; + } + return { + diff: filterUnifiedDiffFiles(input.diff, (path) => attribution.get(path) !== "git"), + gitFileCount, + }; }); const getTurnDiff: CheckpointDiffQuery["Service"]["getTurnDiff"] = Effect.fn("getTurnDiff")( @@ -200,7 +217,7 @@ export const make = Effect.gen(function* () { ignoreWhitespace, }) .pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints")); - const diff = yield* applyAttributionFilter({ + const filtered = yield* applyAttributionFilter({ cwd: workspaceCwd, fromCheckpointRef, toCheckpointRef, @@ -208,7 +225,7 @@ export const make = Effect.gen(function* () { includeGitChanges: input.includeGitChanges ?? false, }); - const turnDiff = buildTurnDiffResult(input, diff); + const turnDiff = buildTurnDiffResult(input, filtered.diff, filtered.gitFileCount); if (!isTurnDiffResult(turnDiff)) { return yield* new CheckpointDiffResultInvalidError({ operation, @@ -299,7 +316,7 @@ export const make = Effect.gen(function* () { ignoreWhitespace, }) .pipe(Effect.withSpan("checkpoint.fullThread.diffCheckpoints")); - const diff = yield* applyAttributionFilter({ + const filtered = yield* applyAttributionFilter({ cwd: workspaceCwd, fromCheckpointRef, toCheckpointRef, @@ -313,7 +330,8 @@ export const make = Effect.gen(function* () { fromTurnCount: 0, toTurnCount: input.toTurnCount, }, - diff, + filtered.diff, + filtered.gitFileCount, ); if (!isTurnDiffResult(turnDiff)) { return yield* new CheckpointDiffResultInvalidError({ diff --git a/apps/server/src/checkpointing/CheckpointStore.test.ts b/apps/server/src/checkpointing/CheckpointStore.test.ts index fc5b409df9..f3516206da 100644 --- a/apps/server/src/checkpointing/CheckpointStore.test.ts +++ b/apps/server/src/checkpointing/CheckpointStore.test.ts @@ -396,6 +396,41 @@ it.layer(TestLayer)("CheckpointStore.layer", (it) => { }), ); + it.effect("keeps a whitespace-only amend of a pre-turn commit as agent work", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + // Pre-turn commit; its pre-amend state stays reachable via reflog, + // which is exactly the patch-id collision candidate. + yield* writeTextFile(NodePath.join(tmp, "style.ts"), "export const x = 1;\n"); + yield* git(tmp, ["add", "."]); + yield* git(tmp, ["commit", "-m", "pre-turn work"], PRE_EXISTING_COMMIT_ENV); + + const checkpointStore = yield* CheckpointStore.CheckpointStore; + const threadId = ThreadId.make("thread-attr-ws-amend"); + const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0); + const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1); + + yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef }); + // The "turn": whitespace-only reformat amended into the pre-turn + // commit. `git patch-id --stable` would hash this identically to the + // original (it strips whitespace); --verbatim must not. + yield* writeTextFile(NodePath.join(tmp, "style.ts"), "export const x = 1;\n"); + yield* git(tmp, ["add", "."]); + yield* git(tmp, ["commit", "--amend", "--no-edit"]); + yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef }); + + const attribution = yield* checkpointStore.attributeCheckpointDiff({ + cwd: tmp, + fromCheckpointRef, + toCheckpointRef, + }); + + expect(attribution).not.toBe(null); + expect(attribution!.get("style.ts")).toBe("agent"); + }), + ); + it.effect("returns null for legacy checkpoints without head metadata", () => Effect.gen(function* () { const tmp = yield* makeTmpDir(); diff --git a/apps/server/src/checkpointing/Diffs.test.ts b/apps/server/src/checkpointing/Diffs.test.ts index 51356ec48a..d4e779eb6e 100644 --- a/apps/server/src/checkpointing/Diffs.test.ts +++ b/apps/server/src/checkpointing/Diffs.test.ts @@ -113,8 +113,13 @@ describe("filterUnifiedDiffFiles", () => { expect(filterUnifiedDiffFiles(deletionDiff, (path) => path !== "removed.ts").trim()).toBe(""); }); - it("keeps unparseable sections", () => { + it("filters simple header-only sections via the diff --git header", () => { const oddDiff = ["diff --git a/x b/x", "Binary files differ", ""].join("\n"); + expect(filterUnifiedDiffFiles(oddDiff, (path) => path !== "x").trim()).toBe(""); + }); + + it("keeps unparseable sections", () => { + const oddDiff = ["diff --git malformed-header", "Binary files differ", ""].join("\n"); expect(filterUnifiedDiffFiles(oddDiff, () => false)).toBe(oddDiff); }); @@ -144,3 +149,77 @@ describe("resolveDiffSectionPath via renames", () => { expect(filterUnifiedDiffFiles(renameDiff, (path) => path !== "old/name.ts")).toBe(renameDiff); }); }); + +describe("filterUnifiedDiffFiles fallback paths", () => { + it("filters binary sections via the diff --git header", () => { + const binaryDiff = [ + "diff --git a/assets/logo.png b/assets/logo.png", + "index 1111111..2222222 100644", + "Binary files a/assets/logo.png and b/assets/logo.png differ", + "", + ].join("\n"); + expect(filterUnifiedDiffFiles(binaryDiff, (path) => path !== "assets/logo.png").trim()).toBe( + "", + ); + expect(filterUnifiedDiffFiles(binaryDiff, () => true)).toBe(binaryDiff); + }); + + it("filters mode-only sections via the diff --git header", () => { + const modeDiff = [ + "diff --git a/scripts/run.sh b/scripts/run.sh", + "old mode 100644", + "new mode 100755", + "", + ].join("\n"); + expect(filterUnifiedDiffFiles(modeDiff, (path) => path !== "scripts/run.sh").trim()).toBe(""); + }); + + it("filters binary sections with spaces in the path", () => { + const binaryDiff = [ + "diff --git a/my assets/logo file.png b/my assets/logo file.png", + "Binary files differ", + "", + ].join("\n"); + expect( + filterUnifiedDiffFiles(binaryDiff, (path) => path !== "my assets/logo file.png").trim(), + ).toBe(""); + }); + + it("decodes git C-style quoted paths", () => { + const quotedDiff = [ + 'diff --git "a/sp\\303\\244ce.ts" "b/sp\\303\\244ce.ts"', + "index 1111111..2222222 100644", + '--- "a/sp\\303\\244ce.ts"', + '+++ "b/sp\\303\\244ce.ts"', + "@@ -1,1 +1,1 @@", + "-old", + "+new", + "", + ].join("\n"); + // git octal-escapes UTF-8 bytes; our decoder maps each escaped byte to a + // char code, so the filter key uses the same byte-per-char convention. + const decodedPath = "späce.ts"; + expect(filterUnifiedDiffFiles(quotedDiff, (path) => path !== decodedPath).trim()).toBe(""); + }); + + it("filters rename-only sections without hunks via rename metadata", () => { + const renameOnlyDiff = [ + "diff --git a/old.ts b/new.ts", + "similarity index 100%", + "rename from old.ts", + "rename to new.ts", + "", + ].join("\n"); + expect(filterUnifiedDiffFiles(renameOnlyDiff, (path) => path !== "new.ts").trim()).toBe(""); + expect(filterUnifiedDiffFiles(renameOnlyDiff, (path) => path !== "old.ts")).toBe( + renameOnlyDiff, + ); + }); + + it("keeps ambiguous unquoted rename headers", () => { + // Rename of a space-containing path is ambiguous in the header when git + // does not quote; with no other metadata the section must be kept. + const ambiguous = ["diff --git a/x y b/y z", "Binary files differ", ""].join("\n"); + expect(filterUnifiedDiffFiles(ambiguous, () => false)).toBe(ambiguous); + }); +}); diff --git a/apps/server/src/checkpointing/Diffs.ts b/apps/server/src/checkpointing/Diffs.ts index 0e54cfd4b7..45e737cf62 100644 --- a/apps/server/src/checkpointing/Diffs.ts +++ b/apps/server/src/checkpointing/Diffs.ts @@ -27,21 +27,80 @@ export function parseTurnDiffFilesFromUnifiedDiff( } function stripGitPathQuoting(value: string): string { - return value.startsWith('"') && value.endsWith('"') && value.length >= 2 - ? value.slice(1, -1) - : value; + if (!(value.startsWith('"') && value.endsWith('"') && value.length >= 2)) { + return value; + } + // Git C-style quoting: decode the escapes it emits for unusual paths. + return value.slice(1, -1).replace(/\\([\\"abfnrtv]|[0-7]{1,3})/g, (_, escape: string) => { + switch (escape) { + case "\\": + return "\\"; + case '"': + return '"'; + case "a": + return "\x07"; + case "b": + return "\b"; + case "f": + return "\f"; + case "n": + return "\n"; + case "r": + return "\r"; + case "t": + return "\t"; + case "v": + return "\v"; + default: + return String.fromCharCode(parseInt(escape, 8)); + } + }); +} + +/** + * Parse the post-image path out of a `diff --git a/ b/` header. + * + * Only trustworthy when both paths are quoted or the two paths are equal + * (no rename): for unquoted renamed paths containing spaces the split is + * ambiguous, so return null and let the caller keep the section. + */ +function resolveDiffGitHeaderPath(headerLine: string): string | null { + const spec = headerLine.slice("diff --git ".length).trim(); + const quotedMatch = /^("(?:[^"\\]|\\.)*"|\S+) ("(?:[^"\\]|\\.)*"|\S+)$/.exec(spec); + if (quotedMatch) { + const source = stripGitPathQuoting(quotedMatch[1]!); + const target = stripGitPathQuoting(quotedMatch[2]!); + if (source.startsWith("a/") && target.startsWith("b/")) { + return target.slice(2); + } + } + // Paths with spaces are unquoted in this header; recover the symmetric + // a/X b/X form (covers everything but renames of space-containing paths). + if (spec.length % 2 === 1) { + const midpoint = (spec.length - 1) / 2; + const source = spec.slice(0, midpoint); + const target = spec.slice(midpoint + 1); + if (source.startsWith("a/") && target.startsWith("b/") && source.slice(2) === target.slice(2)) { + return target.slice(2); + } + } + return null; } /** * Extract the post-image path of one `diff --git` section, preferring the - * `+++ b/` line and falling back to `--- a/` for deletions. Returns null when - * the section is unparseable; callers should keep such sections. + * `+++ b/` line and falling back to `--- a/` for deletions. Binary and + * mode-only sections have neither, so fall back to rename/copy metadata and + * finally the `diff --git` header itself. Returns null when the section is + * unparseable; callers should keep such sections. */ function resolveDiffSectionPath(section: string): string | null { // `--- a/` precedes `+++ b/` in a section, so resolve the post-image path // in a full pass before falling back — for renames the two differ, and the // attribution map is keyed by the post-image path. let fallbackSource: string | null = null; + let renameTarget: string | null = null; + let headerPath: string | null = null; for (const line of section.split("\n")) { if (line.startsWith("+++ ")) { const target = stripGitPathQuoting(line.slice(4).trim()); @@ -53,9 +112,16 @@ function resolveDiffSectionPath(section: string): string | null { if (source !== "/dev/null" && source.startsWith("a/")) { fallbackSource = source.slice(2); } + } else if ( + (line.startsWith("rename to ") || line.startsWith("copy to ")) && + renameTarget === null + ) { + renameTarget = stripGitPathQuoting(line.slice(line.indexOf(" to ") + 4)); + } else if (line.startsWith("diff --git ") && headerPath === null) { + headerPath = resolveDiffGitHeaderPath(line); } } - return fallbackSource; + return fallbackSource ?? renameTarget ?? headerPath; } /** diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 8fa048fc09..33db06125e 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -953,10 +953,12 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( // history-editing command. Cherry-pick and rebase preserve author // dates while re-committing, and so does `commit --amend` — but an // amend carries NEW agent content while a replay carries old - // content. Disambiguated below by patch-id: a rewritten commit - // whose exact patch exists elsewhere in the repo (branches, - // remotes, or reflog — the latter catches pre-rebase originals) is - // a replay → demote; otherwise treat as agent work → show. + // content. Disambiguated below by patch-id (--verbatim, so + // whitespace-only amends don't collide with their pre-amend + // original): a rewritten commit whose byte-exact patch exists + // elsewhere in the repo (branches, remotes, or reflog — the + // latter catches pre-rebase originals) is a replay → demote; + // otherwise treat as agent work → show. const fromCommitTimeRaw = yield* readCommitField( `${input.fromCheckpointRef}^{commit}`, "%ct", @@ -1032,7 +1034,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( const ids = yield* execute({ operation, cwd: input.cwd, - args: ["patch-id", "--stable"], + args: ["patch-id", "--verbatim"], stdin: patches.stdout, allowNonZeroExit: true, maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES, diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index f196a6090f..8933100a2b 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -317,12 +317,6 @@ export default function DiffPanel({ : null, [selectedCheckpointTurnCount], ); - // Number of files in the selected turn whose change came from pre-existing - // git history rather than agent work; drives the hidden-changes banner. - const selectedTurnGitFileCount = useMemo( - () => selectedTurn?.files.filter((file) => file.origin === "git").length ?? 0, - [selectedTurn], - ); const includeGitChanges = includeGitChangesState.scopeKey === collapseScopeKey && includeGitChangesState.value; const setIncludeGitChanges = useCallback( @@ -341,6 +335,12 @@ export default function DiffPanel({ }, { enabled: isGitRepo && selectedTurn !== undefined }, ); + // Number of files in the selected turn whose change came from pre-existing + // git history; drives the hidden-changes banner. Comes from the diff + // response so it reflects the same attribution pass that produced (or + // deliberately kept) the rendered patch — the turn summary's origin tags + // are computed by a separate pass and could disagree after failures. + const selectedTurnGitFileCount = activeCheckpointDiff.data?.gitFileCount ?? 0; const primaryBranchDiffPreview = useEnvironmentQuery( selectedTurnId === null && activeThread && activeCwd ? reviewEnvironment.diffPreview({ diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 5a89cbc89d..82499112f9 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -1248,6 +1248,14 @@ export const ThreadTurnDiff = TurnCountRange.mapFields( Struct.assign({ threadId: ThreadId, diff: Schema.String, + /** + * Number of files in this range whose change is attributed to + * pre-existing git history. Reflects the same attribution pass that + * filtered (or, with includeGitChanges, deliberately kept) the patch in + * `diff`, so banners driven by it always agree with the rendered patch. + * Absent when attribution was unavailable. + */ + gitFileCount: Schema.optionalKey(NonNegativeInt), }), { unsafePreserveChecks: true }, );