feat: attribute turn diffs so git-only changes stop polluting changed files

The changed-files card and per-turn inline diff are derived from full-tree
checkpoint snapshots, so any tree-rewriting git command the agent runs
(pull, checkout, cherry-pick, rebase) shows up as hundreds of "changed
files" the agent never authored.

This adds a read-side attribution layer on top of the existing checkpoint
mechanism (capture, storage, and revert are untouched):

- Checkpoint commits now record the HEAD oid and branch in their commit
  message. Legacy checkpoints without metadata degrade to today's behavior.
- attributeCheckpointDiff classifies each path in a checkpoint tree delta:
  a path is "git" only when its exact blob transition also appears in the
  HEAD-movement delta for the turn and no commit authored during the turn
  touched it. Every ambiguity resolves to "agent" (shown), so
  misclassification can add noise but never hide agent work. Merge commits
  use the combined diff so only conflict resolutions count as agent work.
- The checkpoint reactor tags each file with an origin; attribution
  failures degrade to unattributed files and never block the pipeline.
- getTurnDiff/getFullThreadDiff drop git-attributed file sections from the
  patch unless the new includeGitChanges input is set.
- The changed-files card lists agent files only, with a muted
  "Updated via git — N files" row for demoted changes. The diff panel
  shows a banner with a show/hide toggle so the full tree delta stays one
  click away.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 committed 2026-07-23 13:43:20 -07:00
1 parent 88c69ffff6
commit fc3a695383
18 files changed
+903 -21

No files matched your search

@@ -69,6 +69,7 @@ describe("CheckpointDiffQuery.layer", () => {
return "full thread diff patch";
}),
deleteCheckpointRefs: () => Effect.void,
attributeCheckpointDiff: () => Effect.succeed(null),
};
const layer = CheckpointDiffQuery.layer.pipe(
@@ -177,6 +178,7 @@ describe("CheckpointDiffQuery.layer", () => {
return "diff patch";
}),
deleteCheckpointRefs: () => Effect.void,
attributeCheckpointDiff: () => Effect.succeed(null),
};
const layer = CheckpointDiffQuery.layer.pipe(
@@ -260,6 +262,7 @@ describe("CheckpointDiffQuery.layer", () => {
return "diff patch";
}),
deleteCheckpointRefs: () => Effect.void,
attributeCheckpointDiff: () => Effect.succeed(null),
};
const layer = CheckpointDiffQuery.layer.pipe(
@@ -328,6 +331,7 @@ describe("CheckpointDiffQuery.layer", () => {
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: () => Effect.succeed("diff patch"),
deleteCheckpointRefs: () => Effect.void,
attributeCheckpointDiff: () => Effect.succeed(null),
};
const layer = CheckpointDiffQuery.layer.pipe(
@@ -381,6 +385,7 @@ describe("CheckpointDiffQuery.layer", () => {
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: () => Effect.succeed(""),
deleteCheckpointRefs: () => Effect.void,
attributeCheckpointDiff: () => Effect.succeed(null),
};
const layer = CheckpointDiffQuery.layer.pipe(
@@ -31,6 +31,7 @@ import {
} from "./Errors.ts";
import type { CheckpointServiceError } from "./Errors.ts";
import { checkpointRefForThreadTurn } from "./Utils.ts";
import { filterUnifiedDiffFiles } from "./Diffs.ts";
import * as CheckpointStore from "./CheckpointStore.ts";
/** Service tag for checkpoint diff queries. */
@@ -79,6 +80,32 @@ export const make = Effect.gen(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const checkpointStore = yield* CheckpointStore.CheckpointStore;
// 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.
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;
}
const attribution = yield* checkpointStore
.attributeCheckpointDiff({
cwd: input.cwd,
fromCheckpointRef: input.fromCheckpointRef,
toCheckpointRef: input.toCheckpointRef,
})
.pipe(Effect.catch(() => Effect.succeed(null)));
if (attribution === null) {
return input.diff;
}
return filterUnifiedDiffFiles(input.diff, (path) => attribution.get(path) !== "git");
});
const getTurnDiff: CheckpointDiffQuery["Service"]["getTurnDiff"] = Effect.fn("getTurnDiff")(
function* (input) {
const operation = "CheckpointDiffQuery.getTurnDiff";
@@ -164,7 +191,7 @@ export const make = Effect.gen(function* () {
});
}
const diff = yield* checkpointStore
const rawDiff = yield* checkpointStore
.diffCheckpoints({
cwd: workspaceCwd,
fromCheckpointRef,
@@ -173,6 +200,13 @@ export const make = Effect.gen(function* () {
ignoreWhitespace,
})
.pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints"));
const diff = yield* applyAttributionFilter({
cwd: workspaceCwd,
fromCheckpointRef,
toCheckpointRef,
diff: rawDiff,
includeGitChanges: input.includeGitChanges ?? false,
});
const turnDiff = buildTurnDiffResult(input, diff);
if (!isTurnDiffResult(turnDiff)) {
@@ -254,15 +288,24 @@ export const make = Effect.gen(function* () {
});
}
const diff = yield* checkpointStore
const fromCheckpointRef = checkpointRefForThreadTurn(input.threadId, 0);
const toCheckpointRef = threadContext.value.toCheckpointRef as CheckpointRef;
const rawDiff = yield* checkpointStore
.diffCheckpoints({
cwd: workspaceCwd,
fromCheckpointRef: checkpointRefForThreadTurn(input.threadId, 0),
toCheckpointRef: threadContext.value.toCheckpointRef as CheckpointRef,
fromCheckpointRef,
toCheckpointRef,
fallbackFromToHead: false,
ignoreWhitespace,
})
.pipe(Effect.withSpan("checkpoint.fullThread.diffCheckpoints"));
const diff = yield* applyAttributionFilter({
cwd: workspaceCwd,
fromCheckpointRef,
toCheckpointRef,
diff: rawDiff,
includeGitChanges: input.includeGitChanges ?? false,
});
const turnDiff = buildTurnDiffResult(
{
@@ -222,4 +222,169 @@ it.layer(TestLayer)("CheckpointStore.layer", (it) => {
}),
);
});
describe("attributeCheckpointDiff", () => {
it.effect("returns an empty map when HEAD did not move", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const checkpointStore = yield* CheckpointStore.CheckpointStore;
const threadId = ThreadId.make("thread-attr-no-head-move");
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
yield* writeTextFile(NodePath.join(tmp, "edited.ts"), "export const edited = true;\n");
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
const attribution = yield* checkpointStore.attributeCheckpointDiff({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
});
expect(attribution).not.toBe(null);
expect(attribution!.size).toBe(0);
}),
);
it.effect("attributes a branch switch to git while keeping tool edits as agent work", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const defaultBranch = yield* git(tmp, ["rev-parse", "--abbrev-ref", "HEAD"]);
// A second branch with a pre-existing commit, created before the turn.
yield* git(tmp, ["checkout", "-b", "feature"]);
yield* writeTextFile(NodePath.join(tmp, "feature.ts"), "export const feature = 1;\n");
yield* git(tmp, ["add", "."]);
// Author date in the past: pre-existing commits are authored before
// the turn starts (timestamps here have 1s granularity).
yield* git(tmp, ["commit", "-m", "feature work", "--date", "2020-01-01T00:00:00Z"]);
yield* git(tmp, ["checkout", defaultBranch]);
const checkpointStore = yield* CheckpointStore.CheckpointStore;
const threadId = ThreadId.make("thread-attr-branch-switch");
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
// The "turn": switch branches (history-driven) and also edit a file.
yield* git(tmp, ["checkout", "feature"]);
yield* writeTextFile(NodePath.join(tmp, "edited.ts"), "export const edited = true;\n");
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
const attribution = yield* checkpointStore.attributeCheckpointDiff({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
});
expect(attribution).not.toBe(null);
expect(attribution!.get("feature.ts")).toBe("git");
expect(attribution!.get("edited.ts")).toBe("agent");
}),
);
it.effect("keeps files committed during the turn as agent work", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const checkpointStore = yield* CheckpointStore.CheckpointStore;
const threadId = ThreadId.make("thread-attr-own-commit");
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
// The "turn": edit and commit — HEAD moves, but by a turn-authored commit.
yield* writeTextFile(NodePath.join(tmp, "committed.ts"), "export const done = true;\n");
yield* git(tmp, ["add", "."]);
yield* git(tmp, ["commit", "-m", "agent commit"]);
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
const attribution = yield* checkpointStore.attributeCheckpointDiff({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
});
expect(attribution).not.toBe(null);
expect(attribution!.get("committed.ts")).toBe("agent");
}),
);
it.effect("attributes a cherry-pick of a pre-existing commit to git", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const defaultBranch = yield* git(tmp, ["rev-parse", "--abbrev-ref", "HEAD"]);
// Pre-existing commit on another branch, authored before the turn.
yield* git(tmp, ["checkout", "-b", "source"]);
yield* writeTextFile(NodePath.join(tmp, "picked.ts"), "export const picked = 1;\n");
yield* git(tmp, ["add", "."]);
yield* git(tmp, [
"-c",
"[email protected]",
"-c",
"user.name=Other",
"commit",
"-m",
"source work",
"--date",
"2020-01-01T00:00:00Z",
]);
const pickedOid = yield* git(tmp, ["rev-parse", "HEAD"]);
yield* git(tmp, ["checkout", defaultBranch]);
const checkpointStore = yield* CheckpointStore.CheckpointStore;
const threadId = ThreadId.make("thread-attr-cherry-pick");
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
yield* git(tmp, ["cherry-pick", pickedOid]);
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
const attribution = yield* checkpointStore.attributeCheckpointDiff({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
});
expect(attribution).not.toBe(null);
expect(attribution!.get("picked.ts")).toBe("git");
}),
);
it.effect("returns null for legacy checkpoints without head metadata", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const checkpointStore = yield* CheckpointStore.CheckpointStore;
const threadId = ThreadId.make("thread-attr-legacy");
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
// Simulate a pre-attribution checkpoint: commit the tree with the old
// single-line message format.
const treeOid = yield* git(tmp, ["write-tree"]);
const legacyCommit = yield* git(tmp, [
"commit-tree",
treeOid,
"-m",
`t3 checkpoint ref=${fromCheckpointRef}`,
]);
yield* git(tmp, ["update-ref", fromCheckpointRef, legacyCommit]);
yield* writeTextFile(NodePath.join(tmp, "edited.ts"), "export const edited = true;\n");
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
const attribution = yield* checkpointStore.attributeCheckpointDiff({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
});
expect(attribution).toBe(null);
}),
);
});
});
@@ -46,6 +46,18 @@ export interface DeleteCheckpointRefsInput {
readonly checkpointRefs: ReadonlyArray<CheckpointRef>;
}
export interface AttributeCheckpointDiffInput {
readonly cwd: string;
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
}
/**
* Per-path origin classification of a checkpoint tree delta, or null when
* attribution is unavailable (see VcsCheckpointAttribution).
*/
export type CheckpointAttribution = ReadonlyMap<string, "agent" | "git"> | null;
/** Service tag for checkpoint persistence and restore operations. */
export class CheckpointStore extends Context.Service<
CheckpointStore,
@@ -93,6 +105,17 @@ export class CheckpointStore extends Context.Service<
readonly deleteCheckpointRefs: (
input: DeleteCheckpointRefsInput,
) => Effect.Effect<void, CheckpointStoreError>;
/**
* Classify each path in a checkpoint-to-checkpoint tree delta as
* agent-authored or explained by pre-existing git history.
*
* Returns null when attribution is unavailable (legacy checkpoints
* without HEAD metadata, or truncated git output).
*/
readonly attributeCheckpointDiff: (
input: AttributeCheckpointDiffInput,
) => Effect.Effect<CheckpointAttribution, CheckpointStoreError>;
}
>()("t3/checkpointing/CheckpointStore") {}
@@ -157,6 +180,16 @@ export const make = Effect.gen(function* () {
return yield* checkpoints.deleteCheckpointRefs(input);
});
const attributeCheckpointDiff: CheckpointStore["Service"]["attributeCheckpointDiff"] = Effect.fn(
"attributeCheckpointDiff",
)(function* (input) {
const checkpoints = yield* resolveCheckpoints(
"CheckpointStore.attributeCheckpointDiff",
input.cwd,
);
return yield* checkpoints.attributeCheckpointDiff(input);
});
return CheckpointStore.of({
isGitRepository,
captureCheckpoint,
@@ -164,6 +197,7 @@ export const make = Effect.gen(function* () {
restoreCheckpoint,
diffCheckpoints,
deleteCheckpointRefs,
attributeCheckpointDiff,
});
});
+57 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import { parseTurnDiffFilesFromUnifiedDiff } from "./Diffs.ts";
import { filterUnifiedDiffFiles, parseTurnDiffFilesFromUnifiedDiff } from "./Diffs.ts";
describe("parseTurnDiffFilesFromUnifiedDiff", () => {
it("returns empty list for empty diff", () => {
@@ -66,3 +66,59 @@ describe("parseTurnDiffFilesFromUnifiedDiff", () => {
]);
});
});
describe("filterUnifiedDiffFiles", () => {
const twoFileDiff = [
"diff --git a/kept.ts b/kept.ts",
"index 1111111..2222222 100644",
"--- a/kept.ts",
"+++ b/kept.ts",
"@@ -1,1 +1,1 @@",
"-old",
"+new",
"diff --git a/dropped.ts b/dropped.ts",
"index 3333333..4444444 100644",
"--- a/dropped.ts",
"+++ b/dropped.ts",
"@@ -1,1 +1,1 @@",
"-before",
"+after",
"",
].join("\n");
it("removes sections whose path is rejected", () => {
const filtered = filterUnifiedDiffFiles(twoFileDiff, (path) => path !== "dropped.ts");
expect(filtered).toContain("kept.ts");
expect(filtered).not.toContain("dropped.ts");
expect(parseTurnDiffFilesFromUnifiedDiff(filtered)).toEqual([
{ path: "kept.ts", additions: 1, deletions: 1 },
]);
});
it("returns the diff unchanged when everything is kept", () => {
expect(filterUnifiedDiffFiles(twoFileDiff, () => true)).toBe(twoFileDiff);
});
it("filters deleted files via the --- a/ path", () => {
const deletionDiff = [
"diff --git a/removed.ts b/removed.ts",
"deleted file mode 100644",
"index 1111111..0000000",
"--- a/removed.ts",
"+++ /dev/null",
"@@ -1,1 +0,0 @@",
"-gone",
"",
].join("\n");
expect(filterUnifiedDiffFiles(deletionDiff, (path) => path !== "removed.ts").trim()).toBe("");
});
it("keeps unparseable sections", () => {
const oddDiff = ["diff --git a/x b/x", "Binary files differ", ""].join("\n");
expect(filterUnifiedDiffFiles(oddDiff, () => false)).toBe(oddDiff);
});
it("returns empty diff unchanged", () => {
expect(filterUnifiedDiffFiles("", () => false)).toBe("");
});
});
+71
View File
@@ -25,3 +25,74 @@ export function parseTurnDiffFilesFromUnifiedDiff(
return files.toSorted((left, right) => left.path.localeCompare(right.path));
}
function stripGitPathQuoting(value: string): string {
return value.startsWith('"') && value.endsWith('"') && value.length >= 2
? value.slice(1, -1)
: value;
}
/**
* 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.
*/
function resolveDiffSectionPath(section: string): string | null {
for (const line of section.split("\n")) {
if (line.startsWith("+++ ")) {
const target = stripGitPathQuoting(line.slice(4).trim());
if (target !== "/dev/null") {
return target.startsWith("b/") ? target.slice(2) : target;
}
} else if (line.startsWith("--- ")) {
const source = stripGitPathQuoting(line.slice(4).trim());
if (source !== "/dev/null" && source.startsWith("a/")) {
return source.slice(2);
}
}
}
return null;
}
/**
* 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 normalized = diff.replace(/\r\n/g, "\n");
if (normalized.trim().length === 0) {
return diff;
}
const sections: Array<string> = [];
let currentStart = -1;
const lines = normalized.split("\n");
const flush = (endExclusive: number) => {
if (currentStart >= 0) {
sections.push(lines.slice(currentStart, endExclusive).join("\n"));
}
};
for (let index = 0; index < lines.length; index += 1) {
if (lines[index]!.startsWith("diff --git ")) {
flush(index);
currentStart = index;
}
}
flush(lines.length);
if (sections.length === 0) {
return diff;
}
const kept = sections.filter((section) => {
const path = resolveDiffSectionPath(section);
return path === null || shouldKeepPath(path);
});
if (kept.length === sections.length) {
return diff;
}
return kept.join("\n");
}
@@ -256,6 +256,27 @@ const make = Effect.gen(function* () {
// reflects files created or deleted during this turn.
yield* workspaceEntries.refresh(input.cwd);
// Best-effort per-path attribution: paths whose change is fully explained
// by pre-existing history moving through HEAD (pull, checkout,
// cherry-pick, rebase) are tagged origin "git" so the UI can demote them.
// Attribution must never block the checkpoint pipeline — any failure
// degrades to unattributed files (all shown as agent work).
const attribution = yield* checkpointStore
.attributeCheckpointDiff({
cwd: input.cwd,
fromCheckpointRef,
toCheckpointRef: targetCheckpointRef,
})
.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to attribute checkpoint diff", {
threadId: input.threadId,
turnId: input.turnId,
detail: error.message,
}).pipe(Effect.as(null)),
),
);
const files = yield* checkpointStore
.diffCheckpoints({
cwd: input.cwd,
@@ -271,6 +292,7 @@ const make = Effect.gen(function* () {
kind: "modified" as const,
additions: file.additions,
deletions: file.deletions,
...(attribution ? { origin: attribution.get(file.path) ?? "agent" } : {}),
})),
),
Effect.tapError((error) =>
@@ -0,0 +1,152 @@
import { describe, expect, it } from "vite-plus/test";
import {
classifyCheckpointPaths,
formatCheckpointCommitMessage,
parseCheckpointCommitMessage,
parseRawDiffEntries,
type RawDiffEntry,
} from "./CheckpointAttribution.ts";
const ZERO_OID = "0".repeat(40);
function entry(overrides: Partial<RawDiffEntry> & { path: string }): RawDiffEntry {
return {
srcMode: "100644",
dstMode: "100644",
srcOid: "a".repeat(40),
dstOid: "b".repeat(40),
status: "M",
...overrides,
};
}
describe("checkpoint commit message metadata", () => {
it("round-trips head and branch", () => {
const message = formatCheckpointCommitMessage({
checkpointRef: "refs/t3/checkpoints/x/turn/3",
headOid: "c".repeat(40),
branch: "feature/attribution",
});
expect(parseCheckpointCommitMessage(message)).toEqual({
headOid: "c".repeat(40),
branch: "feature/attribution",
});
});
it("round-trips null head (unborn HEAD)", () => {
const message = formatCheckpointCommitMessage({
checkpointRef: "refs/t3/checkpoints/x/turn/0",
headOid: null,
branch: null,
});
expect(parseCheckpointCommitMessage(message)).toEqual({ headOid: null, branch: null });
});
it("returns null for legacy messages without metadata", () => {
expect(parseCheckpointCommitMessage("t3 checkpoint ref=refs/t3/checkpoints/x/turn/1")).toBe(
null,
);
});
});
describe("parseRawDiffEntries", () => {
it("parses NUL-separated raw records", () => {
const src = "a".repeat(40);
const dst = "b".repeat(40);
const output = `:100644 100644 ${src} ${dst} M\0src/index.ts\0:000000 100644 ${ZERO_OID} ${dst} A\0new file.ts\0`;
expect(parseRawDiffEntries(output)).toEqual([
{
srcMode: "100644",
dstMode: "100644",
srcOid: src,
dstOid: dst,
status: "M",
path: "src/index.ts",
},
{
srcMode: "000000",
dstMode: "100644",
srcOid: ZERO_OID,
dstOid: dst,
status: "A",
path: "new file.ts",
},
]);
});
it("returns empty for empty output", () => {
expect(parseRawDiffEntries("")).toEqual([]);
});
});
describe("classifyCheckpointPaths", () => {
it("attributes a pull-only change to git", () => {
const pulled = entry({ path: "upstream.ts" });
const origins = classifyCheckpointPaths({
treeDelta: [pulled],
historyDelta: [pulled],
turnAuthoredPaths: new Set(),
});
expect(origins.get("upstream.ts")).toBe("git");
});
it("attributes tool edits to agent (no history match)", () => {
const origins = classifyCheckpointPaths({
treeDelta: [entry({ path: "edited.ts" })],
historyDelta: [],
turnAuthoredPaths: new Set(),
});
expect(origins.get("edited.ts")).toBe("agent");
});
it("keeps a file the agent committed during the turn as agent work", () => {
const committed = entry({ path: "committed.ts" });
const origins = classifyCheckpointPaths({
treeDelta: [committed],
historyDelta: [committed],
turnAuthoredPaths: new Set(["committed.ts"]),
});
expect(origins.get("committed.ts")).toBe("agent");
});
it("attributes a pulled-then-edited file to agent (blob transition differs)", () => {
const origins = classifyCheckpointPaths({
treeDelta: [entry({ path: "both.ts", dstOid: "d".repeat(40) })],
historyDelta: [entry({ path: "both.ts", dstOid: "e".repeat(40) })],
turnAuthoredPaths: new Set(),
});
expect(origins.get("both.ts")).toBe("agent");
});
it("attributes mode-only mismatches to agent", () => {
const origins = classifyCheckpointPaths({
treeDelta: [entry({ path: "script.sh", dstMode: "100755" })],
historyDelta: [entry({ path: "script.sh", dstMode: "100644" })],
turnAuthoredPaths: new Set(),
});
expect(origins.get("script.sh")).toBe("agent");
});
it("attributes checkout deletions and additions to git", () => {
const removed = entry({
path: "only-on-old-branch.ts",
dstMode: "000000",
dstOid: ZERO_OID,
status: "D",
});
const added = entry({
path: "only-on-new-branch.ts",
srcMode: "000000",
srcOid: ZERO_OID,
status: "A",
});
const origins = classifyCheckpointPaths({
treeDelta: [removed, added],
historyDelta: [removed, added],
turnAuthoredPaths: new Set(),
});
expect(origins.get("only-on-old-branch.ts")).toBe("git");
expect(origins.get("only-on-new-branch.ts")).toBe("git");
});
});
Binary file not shown.
+181 -3
View File
@@ -29,6 +29,12 @@ import {
type VcsStatusResult,
} from "@t3tools/contracts";
import { makeGitVcsDriverCore } from "./GitVcsDriverCore.ts";
import {
classifyCheckpointPaths,
formatCheckpointCommitMessage,
parseCheckpointCommitMessage,
parseRawDiffEntries,
} from "./CheckpointAttribution.ts";
import * as VcsDriver from "./VcsDriver.ts";
import * as VcsProcess from "./VcsProcess.ts";
@@ -636,6 +642,22 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
}),
);
const resolveHeadBranch = (cwd: string) =>
execute({
operation: "GitVcsDriver.checkpoints.resolveHeadBranch",
cwd,
args: ["symbolic-ref", "--short", "--quiet", "HEAD"],
allowNonZeroExit: true,
}).pipe(
Effect.map((result) => {
if (result.exitCode !== 0) {
return null;
}
const branch = result.stdout.trim();
return branch.length > 0 ? branch : null;
}),
);
const resolveGitCommonDir = (cwd: string) =>
Effect.gen(function* () {
const result = yield* execute({
@@ -669,8 +691,9 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
.pipe(Effect.ignore);
yield* Effect.gen(function* () {
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
const headCommit = yield* resolveHeadCommit(input.cwd);
const headBranch = yield* resolveHeadBranch(input.cwd);
if (headCommit) {
yield* execute({
operation,
cwd: input.cwd,
@@ -703,7 +726,11 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
});
}
const message = `t3 checkpoint ref=${input.checkpointRef}`;
const message = formatCheckpointCommitMessage({
checkpointRef: input.checkpointRef,
headOid: headCommit,
branch: headBranch,
});
const commitTreeResult = yield* execute({
operation,
cwd: input.cwd,
@@ -848,6 +875,157 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
);
},
),
attributeCheckpointDiff: Effect.fn("GitVcsDriver.checkpoints.attributeCheckpointDiff")(
function* (input) {
const operation = "GitVcsDriver.checkpoints.attributeCheckpointDiff";
const readCommitField = (revision: string, format: string) =>
execute({
operation,
cwd: input.cwd,
args: ["log", "-1", `--format=${format}`, revision, "--"],
allowNonZeroExit: true,
}).pipe(Effect.map((result) => (result.exitCode === 0 ? result.stdout.trimEnd() : null)));
const fromMessage = yield* readCommitField(`${input.fromCheckpointRef}^{commit}`, "%B");
const toMessage = yield* readCommitField(`${input.toCheckpointRef}^{commit}`, "%B");
if (fromMessage === null || toMessage === null) {
return null;
}
const fromMetadata = parseCheckpointCommitMessage(fromMessage);
const toMetadata = parseCheckpointCommitMessage(toMessage);
// Checkpoints captured before attribution metadata existed: unavailable.
if (fromMetadata === null || toMetadata === null) {
return null;
}
// HEAD did not move during the turn (or the repo has no commits):
// every tree change is agent-authored. An empty map means "classified,
// no git-origin paths".
if (fromMetadata.headOid === toMetadata.headOid || fromMetadata.headOid === null) {
return new Map<string, "agent" | "git">();
}
if (toMetadata.headOid === null) {
// HEAD disappeared mid-turn (e.g. re-init); fail toward "agent".
return new Map<string, "agent" | "git">();
}
const rawDiff = (fromRevision: string, toRevision: string) =>
execute({
operation,
cwd: input.cwd,
args: [
"diff-tree",
"-r",
"-z",
"--no-abbrev",
"--no-renames",
fromRevision,
toRevision,
],
allowNonZeroExit: true,
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
}).pipe(
Effect.map((result) =>
result.exitCode === 0 && !result.stdoutTruncated
? parseRawDiffEntries(result.stdout)
: null,
),
);
const treeDelta = yield* rawDiff(
`${input.fromCheckpointRef}^{commit}`,
`${input.toCheckpointRef}^{commit}`,
);
const historyDelta = yield* rawDiff(fromMetadata.headOid, toMetadata.headOid);
if (treeDelta === null || historyDelta === null) {
return null;
}
// The baseline checkpoint commit is created at turn start, so its
// committer timestamp is the turn-start time. Commits in the HEAD
// range authored at or after it were made during the turn and count
// as agent work; commits authored before it carried pre-existing
// content (pull, checkout — and, because cherry-pick and rebase
// preserve author dates, replayed foreign commits too).
const fromCommitTimeRaw = yield* readCommitField(
`${input.fromCheckpointRef}^{commit}`,
"%ct",
);
const fromCommitTime = fromCommitTimeRaw === null ? NaN : Number(fromCommitTimeRaw);
if (!Number.isFinite(fromCommitTime)) {
return null;
}
const headRangeResult = yield* execute({
operation,
cwd: input.cwd,
args: [
"log",
"--format=%H %at %p",
`${fromMetadata.headOid}..${toMetadata.headOid}`,
"--",
],
allowNonZeroExit: true,
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
});
if (headRangeResult.exitCode !== 0 || headRangeResult.stdoutTruncated) {
return null;
}
const turnAuthoredCommits: Array<{ readonly oid: string; readonly isMerge: boolean }> = [];
for (const line of headRangeResult.stdout.split("\n")) {
const [oid, authorTime, ...parents] = line.trim().split(" ");
if (!oid || !authorTime) {
continue;
}
const authoredAt = Number(authorTime);
if (Number.isFinite(authoredAt) && authoredAt >= fromCommitTime) {
turnAuthoredCommits.push({ oid, isMerge: parents.length > 1 });
}
}
// A pathological number of turn-authored commits (e.g. clock skew
// misclassifying a pulled range) would mean one diff-tree call per
// commit; skip attribution instead — the diff renders unfiltered.
if (turnAuthoredCommits.length > 100) {
return null;
}
const turnAuthoredPaths = new Set<string>();
for (const commit of turnAuthoredCommits) {
const pathsResult = yield* execute({
operation,
cwd: input.cwd,
args: [
"diff-tree",
"-r",
"-z",
"--no-commit-id",
"--name-only",
// For merges, the combined diff lists only paths whose result
// differs from every parent — i.e. conflict resolutions the
// agent authored. Paths taken wholesale from one side are
// pre-existing content and stay attributable to history.
...(commit.isMerge ? ["-c"] : []),
commit.oid,
],
allowNonZeroExit: true,
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
});
if (pathsResult.exitCode !== 0 || pathsResult.stdoutTruncated) {
return null;
}
for (const pathValue of pathsResult.stdout.split("\0")) {
if (pathValue.length > 0) {
turnAuthoredPaths.add(pathValue);
}
}
}
return classifyCheckpointPaths({ treeDelta, historyDelta, turnAuthoredPaths });
},
),
};
return {
+21
View File
@@ -38,6 +38,24 @@ export interface VcsDeleteCheckpointRefsInput {
readonly checkpointRefs: ReadonlyArray<CheckpointRef>;
}
export interface VcsAttributeCheckpointDiffInput {
readonly cwd: string;
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
}
/**
* Per-path attribution of a checkpoint-to-checkpoint tree delta.
*
* Paths mapped to "git" are byte-for-byte explained by pre-existing commits
* that moved through HEAD during the turn (pull, checkout, cherry-pick,
* rebase). Paths mapped to "agent" — and paths absent from the map — were
* authored during the turn. `null` means attribution is unavailable (HEAD
* metadata missing on either snapshot); callers must treat every path as
* agent-authored.
*/
export type VcsCheckpointAttribution = ReadonlyMap<string, "agent" | "git"> | null;
export interface VcsCheckpointOps {
readonly captureCheckpoint: (input: VcsCaptureCheckpointInput) => Effect.Effect<void, VcsError>;
readonly hasCheckpointRef: (
@@ -50,6 +68,9 @@ export interface VcsCheckpointOps {
readonly deleteCheckpointRefs: (
input: VcsDeleteCheckpointRefsInput,
) => Effect.Effect<void, VcsError>;
readonly attributeCheckpointDiff: (
input: VcsAttributeCheckpointDiffInput,
) => Effect.Effect<VcsCheckpointAttribution, VcsError>;
}
export class VcsDriver extends Context.Service<
+38
View File
@@ -194,6 +194,7 @@ export default function DiffPanel({
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
const [wordWrap, setWordWrap] = useState(settings.wordWrap);
const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
const [includeGitChanges, setIncludeGitChanges] = useState(false);
const [baseRefQuery, setBaseRefQuery] = useState("");
const [collapsedDiffFiles, setCollapsedDiffFiles] = useState<CollapsedDiffFilesState>(() => ({
scopeKey: null,
@@ -311,6 +312,12 @@ 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 activeCheckpointDiff = useCheckpointDiff(
{
environmentId: activeThread?.environmentId ?? null,
@@ -318,6 +325,7 @@ export default function DiffPanel({
fromTurnCount: selectedCheckpointRange?.fromTurnCount ?? null,
toTurnCount: selectedCheckpointRange?.toTurnCount ?? null,
ignoreWhitespace: diffIgnoreWhitespace,
includeGitChanges,
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : null,
},
{ enabled: isGitRepo && selectedTurn !== undefined },
@@ -783,6 +791,36 @@ export default function DiffPanel({
incomplete.
</p>
)}
{selectedTurn && selectedTurnGitFileCount > 0 && (
<p className="shrink-0 border-b border-border/70 bg-muted/40 px-3 py-1.5 text-[11px] text-muted-foreground">
{includeGitChanges ? (
<>
Showing {selectedTurnGitFileCount} file
{selectedTurnGitFileCount === 1 ? "" : "s"} changed via git (pull, checkout,
rebase, …).{" "}
<button
type="button"
className="cursor-pointer underline underline-offset-2 hover:text-foreground"
onClick={() => setIncludeGitChanges(false)}
>
Hide them
</button>
</>
) : (
<>
{selectedTurnGitFileCount} file{selectedTurnGitFileCount === 1 ? "" : "s"}{" "}
changed via git (pull, checkout, rebase, …) are hidden.{" "}
<button
type="button"
className="cursor-pointer underline underline-offset-2 hover:text-foreground"
onClick={() => setIncludeGitChanges(true)}
>
Show them
</button>
</>
)}
</p>
)}
{selectedPatchError && !renderablePatch && (
<div className="px-3">
<p className="mb-2 text-[11px] text-red-500/80">{selectedPatchError}</p>
@@ -32,7 +32,7 @@ import {
workLogEntryIsToolLike,
} from "../../session-logic";
import { type TurnDiffSummary } from "../../types";
import { summarizeTurnDiffStats } from "../../lib/turnDiffTree";
import { partitionTurnDiffFiles, summarizeTurnDiffStats } from "../../lib/turnDiffTree";
import {
getRenderablePatch,
resolveDiffThemeName,
@@ -49,6 +49,7 @@ import {
CircleAlertIcon,
EyeIcon,
FileDiffIcon,
GitBranchIcon,
GlobeIcon,
HammerIcon,
MessageCircleIcon,
@@ -1249,13 +1250,17 @@ const AssistantChangedFilesSection = memo(function AssistantChangedFilesSection(
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
}) {
if (!turnSummary) return null;
const checkpointFiles = turnSummary.files;
if (checkpointFiles.length === 0) return null;
if (turnSummary.files.length === 0) return null;
// Changes explained by pre-existing git history (pull, checkout,
// cherry-pick, rebase) collapse into a single summary row instead of
// being listed as agent work.
const { agentFiles, gitFiles } = partitionTurnDiffFiles(turnSummary.files);
return (
<AssistantChangedFilesSectionInner
turnSummary={turnSummary}
checkpointFiles={checkpointFiles}
checkpointFiles={agentFiles}
gitFiles={gitFiles}
routeThreadKey={routeThreadKey}
resolvedTheme={resolvedTheme}
onOpenTurnDiff={onOpenTurnDiff}
@@ -1268,12 +1273,14 @@ const AssistantChangedFilesSection = memo(function AssistantChangedFilesSection(
function AssistantChangedFilesSectionInner({
turnSummary,
checkpointFiles,
gitFiles,
routeThreadKey,
resolvedTheme,
onOpenTurnDiff,
}: {
turnSummary: TurnDiffSummary;
checkpointFiles: TurnDiffSummary["files"];
gitFiles: TurnDiffSummary["files"];
routeThreadKey: string;
resolvedTheme: "light" | "dark";
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
@@ -1283,6 +1290,7 @@ function AssistantChangedFilesSectionInner({
);
const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
const gitSummaryStat = summarizeTurnDiffStats(gitFiles);
return (
<div className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 pt-4 dark:border-transparent dark:bg-input/32">
@@ -1346,14 +1354,32 @@ function AssistantChangedFilesSectionInner({
</Tooltip>
</div>
</div>
<ChangedFilesTree
key={`changed-files-tree:${turnSummary.turnId}`}
turnId={turnSummary.turnId}
files={checkpointFiles}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onOpenTurnDiff={onOpenTurnDiff}
/>
{checkpointFiles.length > 0 && (
<ChangedFilesTree
key={`changed-files-tree:${turnSummary.turnId}`}
turnId={turnSummary.turnId}
files={checkpointFiles}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onOpenTurnDiff={onOpenTurnDiff}
/>
)}
{gitFiles.length > 0 && (
<div className="flex items-center gap-1.5 rounded-xl px-2 py-1 text-muted-foreground/80">
<GitBranchIcon aria-hidden="true" className="size-3.5 shrink-0" />
<span className="truncate font-mono text-[11px]">
Updated via git — {gitFiles.length} file{gitFiles.length === 1 ? "" : "s"}
</span>
{hasNonZeroStat(gitSummaryStat) && (
<span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
<DiffStatLabel
additions={gitSummaryStat.additions}
deletions={gitSummaryStat.deletions}
/>
</span>
)}
</div>
)}
</div>
);
}
+31 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import { buildTurnDiffTree, summarizeTurnDiffStats } from "./turnDiffTree";
import { buildTurnDiffTree, partitionTurnDiffFiles, summarizeTurnDiffStats } from "./turnDiffTree";
describe("summarizeTurnDiffStats", () => {
it("sums only files with numeric additions/deletions", () => {
@@ -166,3 +166,33 @@ describe("buildTurnDiffTree", () => {
expect(directoryNodes.map((node) => node.path).toSorted()).toEqual([" a", "a"]);
});
});
describe("partitionTurnDiffFiles", () => {
it("splits files by origin, defaulting missing origin to agent", () => {
const agentEdit = { path: "edited.ts", kind: "modified", additions: 1, deletions: 0 } as const;
const legacy = { path: "legacy.ts", kind: "modified", additions: 2, deletions: 0 } as const;
const pulled = {
path: "pulled.ts",
kind: "modified",
additions: 3,
deletions: 1,
origin: "git",
} as const;
const explicitAgent = {
path: "explicit.ts",
kind: "modified",
additions: 4,
deletions: 0,
origin: "agent",
} as const;
const { agentFiles, gitFiles } = partitionTurnDiffFiles([
agentEdit,
legacy,
pulled,
explicitAgent,
]);
expect(agentFiles.map((file) => file.path)).toEqual(["edited.ts", "legacy.ts", "explicit.ts"]);
expect(gitFiles.map((file) => file.path)).toEqual(["pulled.ts"]);
});
});
+18
View File
@@ -96,6 +96,24 @@ function toTreeNodes(directory: MutableDirectoryNode): TurnDiffTreeNode[] {
return [...subdirectories, ...files];
}
/**
* Split a turn's changed files into agent-authored work and changes that
* arrived via pre-existing git history (pull, checkout, cherry-pick, rebase).
* Files without an origin (captured before attribution shipped) count as
* agent work.
*/
export function partitionTurnDiffFiles(files: ReadonlyArray<TurnDiffFileChange>): {
agentFiles: ReadonlyArray<TurnDiffFileChange>;
gitFiles: ReadonlyArray<TurnDiffFileChange>;
} {
const agentFiles: TurnDiffFileChange[] = [];
const gitFiles: TurnDiffFileChange[] = [];
for (const file of files) {
(file.origin === "git" ? gitFiles : agentFiles).push(file);
}
return { agentFiles, gitFiles };
}
export function summarizeTurnDiffStats(files: ReadonlyArray<TurnDiffFileChange>): TurnDiffStat {
return files.reduce(
(acc, file) => {
+2
View File
@@ -232,6 +232,7 @@ export function useCheckpointDiff(
threadId: target.threadId!,
toTurnCount: target.toTurnCount!,
ignoreWhitespace: target.ignoreWhitespace,
includeGitChanges: target.includeGitChanges ?? false,
},
}
: null;
@@ -244,6 +245,7 @@ export function useCheckpointDiff(
fromTurnCount: target.fromTurnCount!,
toTurnCount: target.toTurnCount!,
ignoreWhitespace: target.ignoreWhitespace,
includeGitChanges: target.includeGitChanges ?? false,
},
}
: null;
@@ -21,5 +21,6 @@ export interface CheckpointDiffTarget {
readonly fromTurnCount: number | null;
readonly toTurnCount: number | null;
readonly ignoreWhitespace: boolean;
readonly includeGitChanges?: boolean;
readonly cacheScope?: string | null;
}
+20
View File
@@ -281,11 +281,23 @@ export const OrchestrationSession = Schema.Struct({
});
export type OrchestrationSession = typeof OrchestrationSession.Type;
/**
* Attribution of a checkpoint file change. "agent" means the content was
* authored during the turn (tool edits, command side effects, commits made in
* the turn). "git" means the byte-for-byte change is fully explained by
* pre-existing git history moving through the working tree (pull, checkout,
* cherry-pick, rebase). Absent on checkpoints captured before attribution
* shipped; treat absent as "agent".
*/
export const OrchestrationCheckpointFileOrigin = Schema.Literals(["agent", "git"]);
export type OrchestrationCheckpointFileOrigin = typeof OrchestrationCheckpointFileOrigin.Type;
export const OrchestrationCheckpointFile = Schema.Struct({
path: TrimmedNonEmptyString,
kind: TrimmedNonEmptyString,
additions: NonNegativeInt,
deletions: NonNegativeInt,
origin: Schema.optional(OrchestrationCheckpointFileOrigin),
});
export type OrchestrationCheckpointFile = typeof OrchestrationCheckpointFile.Type;
@@ -1283,6 +1295,12 @@ export const OrchestrationGetTurnDiffInput = TurnCountRange.mapFields(
Struct.assign({
threadId: ThreadId,
ignoreWhitespace: Schema.optionalKey(Schema.Boolean),
/**
* Include changes attributed to pre-existing git history (pull, checkout,
* cherry-pick, rebase). Defaults to false: history-driven file sections
* are removed from the patch so it shows agent-authored work only.
*/
includeGitChanges: Schema.optionalKey(Schema.Boolean),
}),
{ unsafePreserveChecks: true },
);
@@ -1295,6 +1313,8 @@ export const OrchestrationGetFullThreadDiffInput = Schema.Struct({
threadId: ThreadId,
toTurnCount: NonNegativeInt,
ignoreWhitespace: Schema.optionalKey(Schema.Boolean),
/** See OrchestrationGetTurnDiffInput.includeGitChanges. */
includeGitChanges: Schema.optionalKey(Schema.Boolean),
});
export type OrchestrationGetFullThreadDiffInput = typeof OrchestrationGetFullThreadDiffInput.Type;