fix: decode quoted paths as UTF-8 and count hidden git files from patch sections

- Git C-style quoting octal-escapes raw UTF-8 bytes; decoding each escape
  with String.fromCharCode produced mojibake, so attribution lookups missed
  quoted non-ASCII paths and their sections were never filtered (macroscope,
  bugbot). stripGitPathQuoting now decodes into a byte buffer and UTF-8
  decodes the result.
- gitFileCount counted every git-attributed path in the attribution map,
  overstating hidden files when a path had no section in the patch (e.g.
  whitespace-only changes elided by ignoreWhitespace) and double-counting
  renames from the --no-renames map (macroscope, bugbot). It now counts
  git-attributed sections actually present in the patch, so the banner
  matches what the toggle can reveal.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 committed 2026-07-23 13:44:17 -07:00
1 parent 0dd887c3e9
commit bcebb793b0
4 files changed
+176 -42

No files matched your search

@@ -304,6 +304,102 @@ describe("CheckpointDiffQuery.layer", () => {
}),
);
it.effect("filters git-attributed sections and reports gitFileCount from patch sections", () =>
Effect.gen(function* () {
const projectId = ProjectId.make("project-attribution");
const threadId = ThreadId.make("thread-attribution");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
const patch = [
"diff --git a/agent.ts b/agent.ts",
"index 1111111..2222222 100644",
"--- a/agent.ts",
"+++ b/agent.ts",
"@@ -1,1 +1,1 @@",
"-old",
"+new",
"diff --git a/pulled.ts b/pulled.ts",
"index 3333333..4444444 100644",
"--- a/pulled.ts",
"+++ b/pulled.ts",
"@@ -1,1 +1,1 @@",
"-before",
"+after",
"",
].join("\n");
// Attribution also tags a path that has no section in this patch
// (e.g. whitespace-only change elided by ignoreWhitespace) — it must
// not count toward gitFileCount.
const attribution = new Map<string, "agent" | "git">([
["agent.ts", "agent"],
["pulled.ts", "git"],
["whitespace-only.ts", "git"],
]);
const threadCheckpointContext = makeThreadCheckpointContext({
projectId,
threadId,
workspaceRoot: "/tmp/workspace",
worktreePath: null,
checkpointTurnCount: 1,
checkpointRef: toCheckpointRef,
});
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: () => Effect.succeed(true),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: () => Effect.succeed(patch),
deleteCheckpointRefs: () => Effect.void,
attributeCheckpointDiff: () => Effect.succeed(attribution),
};
const layer = CheckpointDiffQuery.layer.pipe(
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
),
);
const { filtered, revealed } = yield* Effect.gen(function* () {
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
const filtered = yield* query.getTurnDiff({
threadId,
fromTurnCount: 0,
toTurnCount: 1,
});
const revealed = yield* query.getTurnDiff({
threadId,
fromTurnCount: 0,
toTurnCount: 1,
includeGitChanges: true,
});
return { filtered, revealed };
}).pipe(Effect.provide(layer));
expect(filtered.diff).toContain("agent.ts");
expect(filtered.diff).not.toContain("pulled.ts");
expect(filtered.gitFileCount).toBe(1);
expect(revealed.diff).toBe(patch);
expect(revealed.gitFileCount).toBe(1);
}),
);
it.effect("does not preflight checkpoint refs before diffing", () =>
Effect.gen(function* () {
const projectId = ProjectId.make("project-no-preflight");
@@ -31,7 +31,7 @@ import {
} from "./Errors.ts";
import type { CheckpointServiceError } from "./Errors.ts";
import { checkpointRefForThreadTurn } from "./Utils.ts";
import { filterUnifiedDiffFiles } from "./Diffs.ts";
import { filterUnifiedDiffFiles, listUnifiedDiffPaths } from "./Diffs.ts";
import * as CheckpointStore from "./CheckpointStore.ts";
/** Service tag for checkpoint diff queries. */
@@ -108,9 +108,13 @@ export const make = Effect.gen(function* () {
if (attribution === null) {
return { diff: input.diff, gitFileCount: undefined };
}
// Count only git-attributed paths with a section in THIS patch. The
// attribution map can include paths absent from the patch (e.g.
// whitespace-only changes elided by ignoreWhitespace) — counting those
// would advertise hidden files the toggle can never reveal.
let gitFileCount = 0;
for (const origin of attribution.values()) {
if (origin === "git") {
for (const path of listUnifiedDiffPaths(input.diff)) {
if (attribution.get(path) === "git") {
gitFileCount += 1;
}
}
+3 -4
View File
@@ -196,10 +196,9 @@ describe("filterUnifiedDiffFiles fallback paths", () => {
"+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("");
// git octal-escapes the raw UTF-8 bytes (`ä` = \303\244); the decoder
// must reassemble them into the real character, not per-byte mojibake.
expect(filterUnifiedDiffFiles(quotedDiff, (path) => path !== "späce.ts").trim()).toBe("");
});
it("filters rename-only sections without hunks via rename metadata", () => {
+70 -35
View File
@@ -26,35 +26,51 @@ export function parseTurnDiffFilesFromUnifiedDiff(
return files.toSorted((left, right) => left.path.localeCompare(right.path));
}
const SIMPLE_ESCAPES: Record<string, number> = {
"\\": 0x5c,
'"': 0x22,
a: 0x07,
b: 0x08,
f: 0x0c,
n: 0x0a,
r: 0x0d,
t: 0x09,
v: 0x0b,
};
function stripGitPathQuoting(value: string): string {
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));
// Git C-style quoting: octal escapes are raw UTF-8 BYTES (e.g. `ä` is
// `\303\244`), so decode into a byte buffer first and UTF-8-decode the
// whole path at the end — per-escape String.fromCharCode would yield
// mojibake that never matches attribution map keys.
const inner = value.slice(1, -1);
const bytes: Array<number> = [];
const encoder = new TextEncoder();
for (let index = 0; index < inner.length; index += 1) {
const char = inner[index]!;
if (char !== "\\" || index === inner.length - 1) {
bytes.push(...encoder.encode(char));
continue;
}
});
const next = inner[index + 1]!;
const simple = SIMPLE_ESCAPES[next];
if (simple !== undefined) {
bytes.push(simple);
index += 1;
continue;
}
const octal = /^[0-7]{1,3}/.exec(inner.slice(index + 1))?.[0];
if (octal) {
bytes.push(parseInt(octal, 8) & 0xff);
index += octal.length;
continue;
}
bytes.push(...encoder.encode(char));
}
return new TextDecoder("utf-8", { fatal: false }).decode(new Uint8Array(bytes));
}
/**
@@ -124,20 +140,11 @@ function resolveDiffSectionPath(section: string): string | null {
return fallbackSource ?? renameTarget ?? headerPath;
}
/**
* Remove file sections from a unified diff by path.
*
* Sections whose path cannot be determined are kept (fail toward showing).
*/
export function filterUnifiedDiffFiles(
diff: string,
shouldKeepPath: (path: string) => boolean,
): string {
function splitUnifiedDiffSections(diff: string): ReadonlyArray<string> {
const normalized = diff.replace(/\r\n/g, "\n");
if (normalized.trim().length === 0) {
return diff;
return [];
}
const sections: Array<string> = [];
let currentStart = -1;
const lines = normalized.split("\n");
@@ -153,6 +160,34 @@ export function filterUnifiedDiffFiles(
}
}
flush(lines.length);
return sections;
}
/**
* List the resolvable post-image paths of a unified diff's file sections.
* Unparseable sections are omitted.
*/
export function listUnifiedDiffPaths(diff: string): ReadonlyArray<string> {
const paths: Array<string> = [];
for (const section of splitUnifiedDiffSections(diff)) {
const path = resolveDiffSectionPath(section);
if (path !== null) {
paths.push(path);
}
}
return paths;
}
/**
* Remove file sections from a unified diff by path.
*
* Sections whose path cannot be determined are kept (fail toward showing).
*/
export function filterUnifiedDiffFiles(
diff: string,
shouldKeepPath: (path: string) => boolean,
): string {
const sections = splitUnifiedDiffSections(diff);
if (sections.length === 0) {
return diff;
}