feat: attribute turn diffs so git-only changes stop polluting changed files #4249
Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 4 commits into
main fromfeat/attribution-aware-turn-diffsopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
- apps/server/src/checkpointing/Diffs.ts line 113Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -25,3 +25,16 @@25252626 return files.toSorted((left, right) => left.path.localeCompare(right.path));2727 }28+29+function stripGitPathQuoting(value: string): string {30+ return value.startsWith('"') && value.endsWith('"') && value.length >= 231+ ? value.slice(1, -1)32+ : value;33+}34+35+/**36+ * Extract the post-image path of one `diff --git` section, preferring the37+ * `+++ b/` line and falling back to `--- a/` for deletions. Returns null when38+ * the section is unparseable; callers should keep such sections.39+ */40+function resolveDiffSectionPath(section: string): string | null {apps/server/src/vcs/GitVcsDriver.ts line 993Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -850,0 +958,21 @@958+ return null;959+ }960+961+ const headRangeResult = yield* execute({962+ operation,963+ cwd: input.cwd,964+ args: [965+ "log",966+ "--format=%H %at %p",967+ `${fromMetadata.headOid}..${toMetadata.headOid}`,968+ "--",969+ ],970+ allowNonZeroExit: true,971+ maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,972+ });973+ if (headRangeResult.exitCode !== 0 || headRangeResult.stdoutTruncated) {974+ return null;975+ }976+977+ const turnAuthoredCommits: Array<{ readonly oid: string; readonly isMerge: boolean }> = [];978+ for (const line of headRangeResult.stdout.split("\n")) {apps/web/src/components/DiffPanel.tsx line 336Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -311,13 +312,20 @@311312 : null,312313 [selectedCheckpointTurnCount],313314 );315+ // Number of files in the selected turn whose change came from pre-existing316+ // git history rather than agent work; drives the hidden-changes banner.317+ const selectedTurnGitFileCount = useMemo(318+ () => selectedTurn?.files.filter((file) => file.origin === "git").length ?? 0,319+ [selectedTurn],320+ );314321 const activeCheckpointDiff = useCheckpointDiff(315322 {316323 environmentId: activeThread?.environmentId ?? null,317324 threadId: activeThreadId,318325 fromTurnCount: selectedCheckpointRange?.fromTurnCount ?? null,319326 toTurnCount: selectedCheckpointRange?.toTurnCount ?? null,320327 ignoreWhitespace: diffIgnoreWhitespace,328+ includeGitChanges,321329 cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : null,322330 },323331 { enabled: isGitRepo && selectedTurn !== undefined },apps/web/src/components/chat/MessagesTimeline.tsx lines 1252 to 1257Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1243,5 +1244,8 @@12431244 onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;12441245 }) {12451246 if (!turnSummary) return null;1246- const checkpointFiles = turnSummary.files;1247- if (checkpointFiles.length === 0) return null;1247+ if (turnSummary.files.length === 0) return null;1248+ // Changes explained by pre-existing git history (pull, checkout,1249+ // cherry-pick, rebase) collapse into a single summary row instead of1250+ // being listed as agent work.1251+ const { agentFiles, gitFiles } = partitionTurnDiffFiles(turnSummary.files);apps/server/src/vcs/GitVcsDriver.ts line 1101Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -850,0 +980,21 @@980+ if (!oid || !authorTime) {981+ continue;982+ }983+ const authoredAt = Number(authorTime);984+ if (Number.isFinite(authoredAt) && authoredAt >= fromCommitTime) {985+ turnAuthoredCommits.push({ oid, isMerge: parents.length > 1 });986+ }987+ }988+ // A pathological number of turn-authored commits (e.g. clock skew989+ // misclassifying a pulled range) would mean one diff-tree call per990+ // commit; skip attribution instead — the diff renders unfiltered.991+ if (turnAuthoredCommits.length > 100) {992+ return null;993+ }994+995+ const turnAuthoredPaths = new Set<string>();996+ for (const commit of turnAuthoredCommits) {997+ const pathsResult = yield* execute({998+ operation,999+ cwd: input.cwd,1000+ args: [
- apps/server/src/checkpointing/Diffs.ts line 141Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -27,0 +35,21 @@35+/**36+ * Extract the post-image path of one `diff --git` section, preferring the37+ * `+++ b/` line and falling back to `--- a/` for deletions. Returns null when38+ * the section is unparseable; callers should keep such sections.39+ */40+function resolveDiffSectionPath(section: string): string | null {41+ for (const line of section.split("\n")) {42+ if (line.startsWith("+++ ")) {43+ const target = stripGitPathQuoting(line.slice(4).trim());44+ if (target !== "/dev/null") {45+ return target.startsWith("b/") ? target.slice(2) : target;46+ }47+ } else if (line.startsWith("--- ")) {48+ const source = stripGitPathQuoting(line.slice(4).trim());49+ if (source !== "/dev/null" && source.startsWith("a/")) {50+ return source.slice(2);51+ }52+ }53+ }54+ return null;55+}apps/server/src/vcs/GitVcsDriver.ts line 1008Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -850,0 +966,21 @@966+ "--format=%H %at %p",967+ `${fromMetadata.headOid}..${toMetadata.headOid}`,968+ "--",969+ ],970+ allowNonZeroExit: true,971+ maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,972+ });973+ if (headRangeResult.exitCode !== 0 || headRangeResult.stdoutTruncated) {974+ return null;975+ }976+977+ const turnAuthoredCommits: Array<{ readonly oid: string; readonly isMerge: boolean }> = [];978+ for (const line of headRangeResult.stdout.split("\n")) {979+ const [oid, authorTime, ...parents] = line.trim().split(" ");980+ if (!oid || !authorTime) {981+ continue;982+ }983+ const authoredAt = Number(authorTime);984+ if (Number.isFinite(authoredAt) && authoredAt >= fromCommitTime) {985+ turnAuthoredCommits.push({ oid, isMerge: parents.length > 1 });986+ }
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/vcs/GitVcsDriver.ts line 1035OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -850,0 +1015,21 @@1015+ // affected rewritten commits as agent work (shown).1016+ const patchIdsForCommits = (oids: ReadonlyArray<string>) =>1017+ Effect.gen(function* () {1018+ if (oids.length === 0) {1019+ return new Map<string, string>();1020+ }1021+ const patches = yield* execute({1022+ operation,1023+ cwd: input.cwd,1024+ args: ["diff-tree", "--stdin", "-p", "--no-renames", "--root"],1025+ stdin: `${oids.join("\n")}\n`,1026+ allowNonZeroExit: true,1027+ maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,1028+ });1029+ if (patches.exitCode !== 0 || patches.stdoutTruncated) {1030+ return new Map<string, string>();1031+ }1032+ const ids = yield* execute({1033+ operation,1034+ cwd: input.cwd,1035+ args: ["patch-id", "--stable"],
- apps/server/src/vcs/GitVcsDriver.ts line 1085Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -850,0 +1063,21 @@1063+ "--remotes",1064+ "--reflog",1065+ "--not",1066+ toMetadata.headOid,1067+ ],1068+ allowNonZeroExit: true,1069+ maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,1070+ });1071+ const candidateOids =1072+ candidatesResult.exitCode === 0 && !candidatesResult.stdoutTruncated1073+ ? candidatesResult.stdout.split("\n").filter((line) => line.length > 0)1074+ : [];1075+ const candidatePatchIds = new Set((yield* patchIdsForCommits(candidateOids)).values());1076+ const rewrittenPatchIds = yield* patchIdsForCommits(1077+ rewrittenCommits.map((commit) => commit.oid),1078+ );1079+ for (const commit of rewrittenCommits) {1080+ const patchId = rewrittenPatchIds.get(commit.oid);1081+ if (patchId === undefined || !candidatePatchIds.has(patchId)) {1082+ turnAuthoredCommits.push(commit);1083+ }
- apps/server/src/checkpointing/CheckpointDiffQuery.ts lines 115 to 120Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -81,0 +96,21 @@96+ readonly includeGitChanges: boolean;97+ }): Effect.fn.Return<{ readonly diff: string; readonly gitFileCount: number | undefined }> {98+ if (input.diff.trim().length === 0) {99+ return { diff: input.diff, gitFileCount: undefined };100+ }101+ const attribution = yield* checkpointStore102+ .attributeCheckpointDiff({103+ cwd: input.cwd,104+ fromCheckpointRef: input.fromCheckpointRef,105+ toCheckpointRef: input.toCheckpointRef,106+ })107+ .pipe(Effect.catch(() => Effect.succeed(null)));108+ if (attribution === null) {109+ return { diff: input.diff, gitFileCount: undefined };110+ }111+ let gitFileCount = 0;112+ for (const origin of attribution.values()) {113+ if (origin === "git") {114+ gitFileCount += 1;115+ }116+ }apps/server/src/checkpointing/Diffs.ts line 34OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -25,3 +25,10 @@25252626 return files.toSorted((left, right) => left.path.localeCompare(right.path));2727 }28+29+function stripGitPathQuoting(value: string): string {30+ if (!(value.startsWith('"') && value.endsWith('"') && value.length >= 2)) {31+ return value;32+ }33+ // Git C-style quoting: decode the escapes it emits for unusual paths.34+ return value.slice(1, -1).replace(/\\([\\"abfnrtv]|[0-7]{1,3})/g, (_, escape: string) => {
- apps/server/src/checkpointing/Diffs.ts line 57OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -27,0 +37,21 @@37+ return "\\";38+ case '"':39+ return '"';40+ case "a":41+ return "\x07";42+ case "b":43+ return "\b";44+ case "f":45+ return "\f";46+ case "n":47+ return "\n";48+ case "r":49+ return "\r";50+ case "t":51+ return "\t";52+ case "v":53+ return "\v";54+ default:55+ return String.fromCharCode(parseInt(escape, 8));56+ }57+ });apps/server/src/checkpointing/CheckpointDiffQuery.ts line 120Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -81,0 +96,21 @@96+ readonly includeGitChanges: boolean;97+ }): Effect.fn.Return<{ readonly diff: string; readonly gitFileCount: number | undefined }> {98+ if (input.diff.trim().length === 0) {99+ return { diff: input.diff, gitFileCount: undefined };100+ }101+ const attribution = yield* checkpointStore102+ .attributeCheckpointDiff({103+ cwd: input.cwd,104+ fromCheckpointRef: input.fromCheckpointRef,105+ toCheckpointRef: input.toCheckpointRef,106+ })107+ .pipe(Effect.catch(() => Effect.succeed(null)));108+ if (attribution === null) {109+ return { diff: input.diff, gitFileCount: undefined };110+ }111+ let gitFileCount = 0;112+ for (const origin of attribution.values()) {113+ if (origin === "git") {114+ gitFileCount += 1;115+ }116+ }
- @@ -850,0 +888,21 @@888+ allowNonZeroExit: true,889+ }).pipe(Effect.map((result) => (result.exitCode === 0 ? result.stdout.trimEnd() : null)));890+891+ const fromMessage = yield* readCommitField(`${input.fromCheckpointRef}^{commit}`, "%B");892+ const toMessage = yield* readCommitField(`${input.toCheckpointRef}^{commit}`, "%B");893+ if (fromMessage === null || toMessage === null) {894+ return null;895+ }896+ const fromMetadata = parseCheckpointCommitMessage(fromMessage);897+ const toMetadata = parseCheckpointCommitMessage(toMessage);898+ // Checkpoints captured before attribution metadata existed: unavailable.899+ if (fromMetadata === null || toMetadata === null) {900+ return null;901+ }902+903+ // HEAD did not move during the turn (or the repo has no commits):904+ // every tree change is agent-authored. An empty map means "classified,905+ // no git-origin paths".906+ if (fromMetadata.headOid === toMetadata.headOid || fromMetadata.headOid === null) {907+ return new Map<string, "agent" | "git">();908+ }@@ -850,0 +988,21 @@988+ readonly oid: string;989+ readonly isMerge: boolean;990+ }991+ const turnAuthoredCommits: Array<RangeCommit> = [];992+ const rewrittenCommits: Array<RangeCommit> = [];993+ for (const line of headRangeResult.stdout.split("\n")) {994+ const [oid, authorTime, commitTime, ...parents] = line.trim().split(" ");995+ if (!oid || !authorTime || !commitTime) {996+ continue;997+ }998+ const authoredAt = Number(authorTime);999+ const committedAt = Number(commitTime);1000+ if (!Number.isFinite(authoredAt) || !Number.isFinite(committedAt)) {1001+ continue;1002+ }1003+ const commit: RangeCommit = { oid, isMerge: parents.length > 1 };1004+ if (authoredAt >= fromCommitTime) {1005+ turnAuthoredCommits.push(commit);1006+ } else if (committedAt >= fromCommitTime) {1007+ rewrittenCommits.push(commit);1008+ }@@ -173,3 +221,9 @@173221 ignoreWhitespace,174222 })175223 .pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints"));224+ const filtered = yield* applyAttributionFilter({225+ cwd: workspaceCwd,226+ fromCheckpointRef,227+ toCheckpointRef,228+ diff: rawDiff,229+ includeGitChanges: input.includeGitChanges ?? false,
juliusmarminge closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID:
133e6086-1c6f-453c-a2e4-e240e58ce87aYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.