diff --git a/apps/server/src/checkpointing/CheckpointStore.test.ts b/apps/server/src/checkpointing/CheckpointStore.test.ts index 26e3055524..fc5b409df9 100644 --- a/apps/server/src/checkpointing/CheckpointStore.test.ts +++ b/apps/server/src/checkpointing/CheckpointStore.test.ts @@ -55,6 +55,7 @@ function writeTextFile( function git( cwd: string, args: ReadonlyArray, + env?: NodeJS.ProcessEnv, ): Effect.Effect { 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< @@ -257,9 +265,7 @@ it.layer(TestLayer)("CheckpointStore.layer", (it) => { 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, ["commit", "-m", "feature work"], PRE_EXISTING_COMMIT_ENV); yield* git(tmp, ["checkout", defaultBranch]); const checkpointStore = yield* CheckpointStore.CheckpointStore; @@ -321,17 +327,19 @@ it.layer(TestLayer)("CheckpointStore.layer", (it) => { 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", - "user.email=other@test.com", - "-c", - "user.name=Other", - "commit", - "-m", - "source work", - "--date", - "2020-01-01T00:00:00Z", - ]); + yield* git( + tmp, + [ + "-c", + "user.email=other@test.com", + "-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]); @@ -355,6 +363,39 @@ it.layer(TestLayer)("CheckpointStore.layer", (it) => { }), ); + 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("returns null for legacy checkpoints without head metadata", () => Effect.gen(function* () { const tmp = yield* makeTmpDir(); diff --git a/apps/server/src/checkpointing/Diffs.test.ts b/apps/server/src/checkpointing/Diffs.test.ts index 76713e743c..51356ec48a 100644 --- a/apps/server/src/checkpointing/Diffs.test.ts +++ b/apps/server/src/checkpointing/Diffs.test.ts @@ -122,3 +122,25 @@ describe("filterUnifiedDiffFiles", () => { 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); + }); +}); diff --git a/apps/server/src/checkpointing/Diffs.ts b/apps/server/src/checkpointing/Diffs.ts index e81b9647d1..0e54cfd4b7 100644 --- a/apps/server/src/checkpointing/Diffs.ts +++ b/apps/server/src/checkpointing/Diffs.ts @@ -38,20 +38,24 @@ function stripGitPathQuoting(value: string): string { * 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; 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("--- ")) { + } else if (line.startsWith("--- ") && fallbackSource === null) { const source = stripGitPathQuoting(line.slice(4).trim()); if (source !== "/dev/null" && source.startsWith("a/")) { - return source.slice(2); + fallbackSource = source.slice(2); } } } - return null; + return fallbackSource; } /** diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 127e07e5ee..8fa048fc09 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -945,10 +945,18 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( // 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). + // 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: a rewritten commit + // whose exact patch exists elsewhere in the repo (branches, + // remotes, or reflog — the latter catches pre-rebase originals) is + // a replay → demote; otherwise treat as agent work → show. const fromCommitTimeRaw = yield* readCommitField( `${input.fromCheckpointRef}^{commit}`, "%ct", @@ -963,7 +971,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( cwd: input.cwd, args: [ "log", - "--format=%H %at %p", + "--format=%H %at %ct %p", `${fromMetadata.headOid}..${toMetadata.headOid}`, "--", ], @@ -974,17 +982,108 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( return null; } - const turnAuthoredCommits: Array<{ readonly oid: string; readonly isMerge: boolean }> = []; + interface RangeCommit { + readonly oid: string; + readonly isMerge: boolean; + } + const turnAuthoredCommits: Array = []; + const rewrittenCommits: Array = []; for (const line of headRangeResult.stdout.split("\n")) { - const [oid, authorTime, ...parents] = line.trim().split(" "); - if (!oid || !authorTime) { + const [oid, authorTime, commitTime, ...parents] = line.trim().split(" "); + if (!oid || !authorTime || !commitTime) { continue; } const authoredAt = Number(authorTime); - if (Number.isFinite(authoredAt) && authoredAt >= fromCommitTime) { - turnAuthoredCommits.push({ oid, isMerge: parents.length > 1 }); + 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) => + Effect.gen(function* () { + if (oids.length === 0) { + return new Map(); + } + 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(); + } + const ids = yield* execute({ + operation, + cwd: input.cwd, + args: ["patch-id", "--stable"], + stdin: patches.stdout, + allowNonZeroExit: true, + maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES, + }); + if (ids.exitCode !== 0 || ids.stdoutTruncated) { + return new Map(); + } + const byCommit = new Map(); + 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. @@ -1003,6 +1102,10 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( "-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 diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 40a0e66c37..f196a6090f 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -194,7 +194,12 @@ export default function DiffPanel({ const [diffRenderMode, setDiffRenderMode] = useState("stacked"); const [wordWrap, setWordWrap] = useState(settings.wordWrap); const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace); - const [includeGitChanges, setIncludeGitChanges] = useState(false); + // 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(() => ({ scopeKey: null, @@ -318,6 +323,12 @@ export default function DiffPanel({ () => selectedTurn?.files.filter((file) => file.origin === "git").length ?? 0, [selectedTurn], ); + const includeGitChanges = + includeGitChangesState.scopeKey === collapseScopeKey && includeGitChangesState.value; + const setIncludeGitChanges = useCallback( + (value: boolean) => setIncludeGitChangesState({ scopeKey: collapseScopeKey, value }), + [collapseScopeKey], + ); const activeCheckpointDiff = useCheckpointDiff( { environmentId: activeThread?.environmentId ?? null, diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 88f363387f..053505a192 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1291,69 +1291,80 @@ 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 ( -
-
-

- - {checkpointFiles.length} changed file{checkpointFiles.length === 1 ? "" : "s"} - - {hasNonZeroStat(summaryStat) && ( - - )} -

-
- - - setExpanded(routeThreadKey, turnSummary.turnId, !allDirectoriesExpanded) - } - /> - } - > - {allDirectoriesExpanded ? ( - - ) : ( - - )} - - - {allDirectoriesExpanded ? "Collapse all" : "Expand all"} - - - - onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)} - /> - } - > - - - View diff - +
+ {hasAgentFiles && ( +
+

+ + {checkpointFiles.length} changed file{checkpointFiles.length === 1 ? "" : "s"} + + {hasNonZeroStat(summaryStat) && ( + + )} +

+
+ + + setExpanded(routeThreadKey, turnSummary.turnId, !allDirectoriesExpanded) + } + /> + } + > + {allDirectoriesExpanded ? ( + + ) : ( + + )} + + + {allDirectoriesExpanded ? "Collapse all" : "Expand all"} + + + + onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)} + /> + } + > + + + View diff + +
-
+ )} {checkpointFiles.length > 0 && (