fix: address review findings on turn diff attribution

- resolveDiffSectionPath scanned line-by-line and returned the `--- a/`
  source path before ever seeing `+++ b/`, so rename sections resolved to
  the pre-image path and could be mis-filtered (macroscope, bugbot). Now
  resolves the post-image path in a full pass with the source as fallback,
  plus a rename filtering test.
- `commit --amend` of a pre-turn commit preserved the old author date, so
  amended agent content was misattributed to history and hidden — the one
  invariant violation both bots flagged. Commits authored before the turn
  but committed during it are now disambiguated by patch-id: an identical
  patch elsewhere in the repo (branches/remotes/reflog — reflog catches
  pre-rebase originals) means replayed pre-existing content (demote);
  otherwise it's an amend (show). Integration test included.
- Per-commit diff-tree now passes --root so agent-authored root commits on
  orphan branches contribute their paths (macroscope).
- includeGitChanges is scoped to the diff panel selection key so revealing
  git changes on one turn no longer leaks into other turns/threads
  (macroscope).
- Git-only turns render a compact card with just the "Updated via git" row
  instead of a "0 changed files" header with dead controls (macroscope).

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 committed 2026-07-23 13:44:17 -07:00
1 parent fc3a695383
commit 6f07f6853b
6 files changed
+280 -88

No files matched your search

@@ -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<
@@ -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",
"[email protected]",
"-c",
"user.name=Other",
"commit",
"-m",
"source work",
"--date",
"2020-01-01T00:00:00Z",
]);
yield* git(
tmp,
[
"-c",
"user.[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]);
@@ -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();
@@ -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);
});
});
+7 -3
View File
@@ -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;
}
/**
+113 -10
View File
@@ -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<RangeCommit> = [];
const rewrittenCommits: Array<RangeCommit> = [];
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<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", "--stable"],
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.
@@ -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
+12 -1
View File
@@ -194,7 +194,12 @@ export default function DiffPanel({
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
const [wordWrap, setWordWrap] = useState(settings.wordWrap);
const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
const [includeGitChanges, setIncludeGitChanges] = useState(false);
// 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,
@@ -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,
@@ -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 (
<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>
)}
{checkpointFiles.length > 0 && (
<ChangedFilesTree
key={`changed-files-tree:${turnSummary.turnId}`}