Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bcebb793b0 | ||
|
|
0dd887c3e9 | ||
|
|
6f07f6853b | ||
|
|
fc3a695383 |
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(
|
||||
@@ -301,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");
|
||||
@@ -328,6 +427,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 +481,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, listUnifiedDiffPaths } from "./Diffs.ts";
|
||||
import * as CheckpointStore from "./CheckpointStore.ts";
|
||||
|
||||
/** Service tag for checkpoint diff queries. */
|
||||
@@ -66,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 } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -79,6 +82,51 @@ 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. 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;
|
||||
}): 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({
|
||||
cwd: input.cwd,
|
||||
fromCheckpointRef: input.fromCheckpointRef,
|
||||
toCheckpointRef: input.toCheckpointRef,
|
||||
})
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
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 path of listUnifiedDiffPaths(input.diff)) {
|
||||
if (attribution.get(path) === "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")(
|
||||
function* (input) {
|
||||
const operation = "CheckpointDiffQuery.getTurnDiff";
|
||||
@@ -164,7 +212,7 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const diff = yield* checkpointStore
|
||||
const rawDiff = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef,
|
||||
@@ -173,8 +221,15 @@ export const make = Effect.gen(function* () {
|
||||
ignoreWhitespace,
|
||||
})
|
||||
.pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints"));
|
||||
const filtered = yield* applyAttributionFilter({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
diff: rawDiff,
|
||||
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,
|
||||
@@ -254,15 +309,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 filtered = yield* applyAttributionFilter({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
diff: rawDiff,
|
||||
includeGitChanges: input.includeGitChanges ?? false,
|
||||
});
|
||||
|
||||
const turnDiff = buildTurnDiffResult(
|
||||
{
|
||||
@@ -270,7 +334,8 @@ export const make = Effect.gen(function* () {
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: input.toTurnCount,
|
||||
},
|
||||
diff,
|
||||
filtered.diff,
|
||||
filtered.gitFileCount,
|
||||
);
|
||||
if (!isTurnDiffResult(turnDiff)) {
|
||||
return yield* new CheckpointDiffResultInvalidError({
|
||||
|
||||
@@ -55,6 +55,7 @@ function writeTextFile(
|
||||
function git(
|
||||
cwd: string,
|
||||
args: ReadonlyArray<string>,
|
||||
env?: NodeJS.ProcessEnv,
|
||||
): Effect.Effect<string, VcsError, VcsProcess.VcsProcess> {
|
||||
return Effect.gen(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
@@ -63,12 +64,19 @@ function git(
|
||||
command: "git",
|
||||
cwd,
|
||||
args,
|
||||
...(env ? { env: { ...global.process.env, ...env } } : {}),
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
return result.stdout.trim();
|
||||
});
|
||||
}
|
||||
|
||||
/** Author and committer dates both in the past: a genuinely pre-existing commit. */
|
||||
const PRE_EXISTING_COMMIT_ENV: NodeJS.ProcessEnv = {
|
||||
GIT_AUTHOR_DATE: "2020-01-01T00:00:00Z",
|
||||
GIT_COMMITTER_DATE: "2020-01-01T00:00:00Z",
|
||||
};
|
||||
|
||||
function initRepoWithCommit(
|
||||
cwd: string,
|
||||
): Effect.Effect<
|
||||
@@ -222,4 +230,237 @@ 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", "."]);
|
||||
yield* git(tmp, ["commit", "-m", "feature work"], PRE_EXISTING_COMMIT_ENV);
|
||||
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",
|
||||
],
|
||||
PRE_EXISTING_COMMIT_ENV,
|
||||
);
|
||||
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("keeps an amend of a pre-turn commit as agent work", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
// Pre-turn commit with an old author date, as amend preserves it.
|
||||
yield* writeTextFile(NodePath.join(tmp, "amended.ts"), "export const value = 1;\n");
|
||||
yield* git(tmp, ["add", "."]);
|
||||
yield* git(tmp, ["commit", "-m", "pre-turn work", "--date", "2020-01-01T00:00:00Z"]);
|
||||
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-attr-amend");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
|
||||
// The "turn": edit the file and amend it into the pre-turn commit.
|
||||
// The author date stays 2020, but the content is new agent work.
|
||||
yield* writeTextFile(NodePath.join(tmp, "amended.ts"), "export const value = 2;\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("amended.ts")).toBe("agent");
|
||||
}),
|
||||
);
|
||||
|
||||
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();
|
||||
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,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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,159 @@ 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("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);
|
||||
});
|
||||
|
||||
it("returns empty diff unchanged", () => {
|
||||
expect(filterUnifiedDiffFiles("", () => false)).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDiffSectionPath via renames", () => {
|
||||
it("filters rename sections by the post-image path", () => {
|
||||
const renameDiff = [
|
||||
"diff --git a/old/name.ts b/new/name.ts",
|
||||
"similarity index 90%",
|
||||
"rename from old/name.ts",
|
||||
"rename to new/name.ts",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/old/name.ts",
|
||||
"+++ b/new/name.ts",
|
||||
"@@ -1,1 +1,1 @@",
|
||||
"-before",
|
||||
"+after",
|
||||
"",
|
||||
].join("\n");
|
||||
// The attribution map is keyed by post-image paths; a filter that only
|
||||
// knows the new path must still match this section.
|
||||
expect(filterUnifiedDiffFiles(renameDiff, (path) => path !== "new/name.ts").trim()).toBe("");
|
||||
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 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", () => {
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -25,3 +25,179 @@ 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: 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));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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. 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());
|
||||
if (target !== "/dev/null") {
|
||||
return target.startsWith("b/") ? target.slice(2) : target;
|
||||
}
|
||||
} else if (line.startsWith("--- ") && fallbackSource === null) {
|
||||
const source = stripGitPathQuoting(line.slice(4).trim());
|
||||
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 ?? renameTarget ?? headerPath;
|
||||
}
|
||||
|
||||
function splitUnifiedDiffSections(diff: string): ReadonlyArray<string> {
|
||||
const normalized = diff.replace(/\r\n/g, "\n");
|
||||
if (normalized.trim().length === 0) {
|
||||
return [];
|
||||
}
|
||||
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);
|
||||
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;
|
||||
}
|
||||
|
||||
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.
@@ -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,262 @@ 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 split three ways:
|
||||
// - authored at/after turn start: made during the turn → agent work.
|
||||
// - authored before AND committed before: pre-existing content that
|
||||
// moved into the range wholesale (pull, checkout, merge fast path).
|
||||
// - authored before but COMMITTED during the turn: rewritten by a
|
||||
// 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 (--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",
|
||||
);
|
||||
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 %ct %p",
|
||||
`${fromMetadata.headOid}..${toMetadata.headOid}`,
|
||||
"--",
|
||||
],
|
||||
allowNonZeroExit: true,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
if (headRangeResult.exitCode !== 0 || headRangeResult.stdoutTruncated) {
|
||||
return null;
|
||||
}
|
||||
|
||||
interface RangeCommit {
|
||||
readonly oid: string;
|
||||
readonly isMerge: boolean;
|
||||
}
|
||||
const turnAuthoredCommits: Array<RangeCommit> = [];
|
||||
const rewrittenCommits: Array<RangeCommit> = [];
|
||||
for (const line of headRangeResult.stdout.split("\n")) {
|
||||
const [oid, authorTime, commitTime, ...parents] = line.trim().split(" ");
|
||||
if (!oid || !authorTime || !commitTime) {
|
||||
continue;
|
||||
}
|
||||
const authoredAt = Number(authorTime);
|
||||
const committedAt = Number(commitTime);
|
||||
if (!Number.isFinite(authoredAt) || !Number.isFinite(committedAt)) {
|
||||
continue;
|
||||
}
|
||||
const commit: RangeCommit = { oid, isMerge: parents.length > 1 };
|
||||
if (authoredAt >= fromCommitTime) {
|
||||
turnAuthoredCommits.push(commit);
|
||||
} else if (committedAt >= fromCommitTime) {
|
||||
rewrittenCommits.push(commit);
|
||||
}
|
||||
}
|
||||
if (rewrittenCommits.length > 100) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Batch patch-id computation: diff-tree --stdin -p streams every
|
||||
// commit's patch prefixed by its oid, which `git patch-id` consumes
|
||||
// directly. Failures degrade to an empty map, which classifies the
|
||||
// affected rewritten commits as agent work (shown).
|
||||
const patchIdsForCommits = (oids: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
if (oids.length === 0) {
|
||||
return new Map<string, string>();
|
||||
}
|
||||
const patches = yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["diff-tree", "--stdin", "-p", "--no-renames", "--root"],
|
||||
stdin: `${oids.join("\n")}\n`,
|
||||
allowNonZeroExit: true,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
if (patches.exitCode !== 0 || patches.stdoutTruncated) {
|
||||
return new Map<string, string>();
|
||||
}
|
||||
const ids = yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["patch-id", "--verbatim"],
|
||||
stdin: patches.stdout,
|
||||
allowNonZeroExit: true,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
if (ids.exitCode !== 0 || ids.stdoutTruncated) {
|
||||
return new Map<string, string>();
|
||||
}
|
||||
const byCommit = new Map<string, string>();
|
||||
for (const line of ids.stdout.split("\n")) {
|
||||
const [patchId, commitId] = line.trim().split(" ");
|
||||
if (patchId && commitId) {
|
||||
byCommit.set(commitId, patchId);
|
||||
}
|
||||
}
|
||||
return byCommit;
|
||||
});
|
||||
|
||||
if (rewrittenCommits.length > 0) {
|
||||
const candidatesResult = yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"rev-list",
|
||||
"-n",
|
||||
"500",
|
||||
"--branches",
|
||||
"--tags",
|
||||
"--remotes",
|
||||
"--reflog",
|
||||
"--not",
|
||||
toMetadata.headOid,
|
||||
],
|
||||
allowNonZeroExit: true,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
const candidateOids =
|
||||
candidatesResult.exitCode === 0 && !candidatesResult.stdoutTruncated
|
||||
? candidatesResult.stdout.split("\n").filter((line) => line.length > 0)
|
||||
: [];
|
||||
const candidatePatchIds = new Set((yield* patchIdsForCommits(candidateOids)).values());
|
||||
const rewrittenPatchIds = yield* patchIdsForCommits(
|
||||
rewrittenCommits.map((commit) => commit.oid),
|
||||
);
|
||||
for (const commit of rewrittenCommits) {
|
||||
const patchId = rewrittenPatchIds.get(commit.oid);
|
||||
if (patchId === undefined || !candidatePatchIds.has(patchId)) {
|
||||
turnAuthoredCommits.push(commit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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",
|
||||
// Root commits (orphan branches) have no parent; without
|
||||
// --root they would list no paths and their agent-authored
|
||||
// content would be misattributed to history.
|
||||
"--root",
|
||||
// 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 {
|
||||
|
||||
@@ -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<
|
||||
|
||||
@@ -194,6 +194,12 @@ export default function DiffPanel({
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const [wordWrap, setWordWrap] = useState(settings.wordWrap);
|
||||
const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
|
||||
// Scoped per turn selection so revealing git changes on one turn doesn't
|
||||
// leak into other turns or threads.
|
||||
const [includeGitChangesState, setIncludeGitChangesState] = useState<{
|
||||
scopeKey: string | null;
|
||||
value: boolean;
|
||||
}>(() => ({ scopeKey: null, value: false }));
|
||||
const [baseRefQuery, setBaseRefQuery] = useState("");
|
||||
const [collapsedDiffFiles, setCollapsedDiffFiles] = useState<CollapsedDiffFilesState>(() => ({
|
||||
scopeKey: null,
|
||||
@@ -311,6 +317,12 @@ export default function DiffPanel({
|
||||
: null,
|
||||
[selectedCheckpointTurnCount],
|
||||
);
|
||||
const includeGitChanges =
|
||||
includeGitChangesState.scopeKey === collapseScopeKey && includeGitChangesState.value;
|
||||
const setIncludeGitChanges = useCallback(
|
||||
(value: boolean) => setIncludeGitChangesState({ scopeKey: collapseScopeKey, value }),
|
||||
[collapseScopeKey],
|
||||
);
|
||||
const activeCheckpointDiff = useCheckpointDiff(
|
||||
{
|
||||
environmentId: activeThread?.environmentId ?? null,
|
||||
@@ -318,10 +330,17 @@ 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 },
|
||||
);
|
||||
// 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({
|
||||
@@ -783,6 +802,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,77 +1290,107 @@ function AssistantChangedFilesSectionInner({
|
||||
);
|
||||
const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);
|
||||
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
|
||||
const gitSummaryStat = summarizeTurnDiffStats(gitFiles);
|
||||
// A git-only turn renders as a compact card with just the git summary row:
|
||||
// the "N changed files" header, expand/collapse, and View diff controls all
|
||||
// operate on agent files and would be dead weight.
|
||||
const hasAgentFiles = checkpointFiles.length > 0;
|
||||
|
||||
return (
|
||||
<div className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 pt-4 dark:border-transparent dark:bg-input/32">
|
||||
<div className="sticky top-2 z-10 mb-3 flex items-center justify-between gap-2 bg-secondary px-2 before:absolute before:inset-x-0 before:-top-4 before:h-4 before:bg-secondary before:content-[''] dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))] dark:before:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]">
|
||||
<p className="flex items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
|
||||
<span>
|
||||
{checkpointFiles.length} changed file{checkpointFiles.length === 1 ? "" : "s"}
|
||||
</span>
|
||||
{hasNonZeroStat(summaryStat) && (
|
||||
<DiffStatLabel
|
||||
additions={summaryStat.additions}
|
||||
className="text-xs leading-4"
|
||||
deletions={summaryStat.deletions}
|
||||
layout="inline"
|
||||
/>
|
||||
)}
|
||||
</p>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
className="!size-[22px]"
|
||||
aria-label={allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
data-scroll-anchor-ignore
|
||||
onClick={() =>
|
||||
setExpanded(routeThreadKey, turnSummary.turnId, !allDirectoriesExpanded)
|
||||
}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{allDirectoriesExpanded ? (
|
||||
<ChevronsDownUpIcon className="size-3" />
|
||||
) : (
|
||||
<ChevronsUpDownIcon className="size-3" />
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
className="!size-[22px]"
|
||||
aria-label="View diff"
|
||||
onClick={() => onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<FileDiffIcon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">View diff</TooltipPopup>
|
||||
</Tooltip>
|
||||
<div
|
||||
className={cn(
|
||||
"mt-4 rounded-2xl border border-border/70 bg-secondary p-2 dark:border-transparent dark:bg-input/32",
|
||||
hasAgentFiles && "pt-4",
|
||||
)}
|
||||
>
|
||||
{hasAgentFiles && (
|
||||
<div className="sticky top-2 z-10 mb-3 flex items-center justify-between gap-2 bg-secondary px-2 before:absolute before:inset-x-0 before:-top-4 before:h-4 before:bg-secondary before:content-[''] dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))] dark:before:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]">
|
||||
<p className="flex items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
|
||||
<span>
|
||||
{checkpointFiles.length} changed file{checkpointFiles.length === 1 ? "" : "s"}
|
||||
</span>
|
||||
{hasNonZeroStat(summaryStat) && (
|
||||
<DiffStatLabel
|
||||
additions={summaryStat.additions}
|
||||
className="text-xs leading-4"
|
||||
deletions={summaryStat.deletions}
|
||||
layout="inline"
|
||||
/>
|
||||
)}
|
||||
</p>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
className="!size-[22px]"
|
||||
aria-label={allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
data-scroll-anchor-ignore
|
||||
onClick={() =>
|
||||
setExpanded(routeThreadKey, turnSummary.turnId, !allDirectoriesExpanded)
|
||||
}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{allDirectoriesExpanded ? (
|
||||
<ChevronsDownUpIcon className="size-3" />
|
||||
) : (
|
||||
<ChevronsUpDownIcon className="size-3" />
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
className="!size-[22px]"
|
||||
aria-label="View diff"
|
||||
onClick={() => onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<FileDiffIcon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">View diff</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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"]);
|
||||
});
|
||||
});
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -1236,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 },
|
||||
);
|
||||
@@ -1283,6 +1303,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 +1321,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;
|
||||
|
||||
|
||||
Reference in new issue
Block a user