fix: harden attribution against whitespace amends, binary/mode-only filtering, and banner drift
- patch-id --stable strips whitespace, so a whitespace-only amend collided with its pre-amend reflog original and was demoted as a replay — hiding agent work (macroscope, bugbot, codex). Switched to --verbatim and added an integration test amending a whitespace-only change. - Binary and mode-only sections have no ---/+++ lines, so they always survived filtering even when git-attributed (codex). resolveDiffSectionPath now falls back to rename/copy metadata and then the `diff --git` header (with C-style quoted-path decoding); genuinely ambiguous headers are still kept. Tests for binary, mode-only, quoted, spaced, rename-only, and ambiguous sections. - The diff panel banner was driven by the turn summary's origin tags while the patch was filtered by an independent attribution pass, so the two could disagree after partial failures (codex). getTurnDiff and getFullThreadDiff now return gitFileCount from the same pass that filtered the patch, and the banner uses that. Codex also flagged attribution cost (re-running per diff-query variant); deferred — all calls are plumbing on OIDs, the fast path covers turns without HEAD movement, and caching by checkpoint pair can come later if real-world latency shows up. Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
6f07f6853b
commit
0dd887c3e9
7 files changed
+236
-28
No files matched your search
@@ -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({
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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/<path> b/<path>` 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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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 },
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user