@devries-cameron20 / t3code-1 / commits / 7bd9134824
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): turn diffs follow branch switches (#36343)

Julius Marminge committed Nov 13, 2026 at 12:21 UTC 7bd9134824dde380e76e38b589a98f0865c8a2b6
6 files changed +345 -14
apps/server/src/checkpointing/CheckpointStore.test.ts
+66
@@ -546,6 +546,72 @@ it.layer(layerTest)("CheckpointStore.layer", (it) => {
546 }),
547 );
548
549 + it.effect.each([{ committed: "before the turn" }, { committed: "during the turn" }])(
550 + "starts a turn that switched branches from the branch it landed on (committed $committed)",
551 + ({ committed }) =>
552 + Effect.gen(function* () {
553 + const tmp = yield* makeTmpDir();
554 + yield* initRepoWithCommit(tmp);
555 + const checkpointStore = yield* CheckpointStore.CheckpointStore;
556 + const threadId = ThreadId.make("checkpoint-branch-switch");
557 + const [first, second, third] = [0, 1, 2].map((turn) =>
558 + checkpointRefForThreadTurn(threadId, turn),
559 + ) as [CheckpointRef, CheckpointRef, CheckpointRef];
560 + const changedSince = (fromCheckpointRef: CheckpointRef, toCheckpointRef: CheckpointRef) =>
561 + Effect.gen(function* () {
562 + const refs = { cwd: tmp, fromCheckpointRef, toCheckpointRef };
563 + return {
564 + patch: yield* checkpointStore.diffCheckpoints({ ...refs, ignoreWhitespace: false }),
565 + authored: yield* checkpointStore.listAuthoredPaths(refs),
566 + };
567 + });
568 + const commitOnA = git(tmp, ["commit", "-am", "work on a"]);
569 +
570 + yield* git(tmp, ["branch", "b"]);
571 + yield* git(tmp, ["checkout", "-b", "a"]);
572 + yield* writeTextFile(NodePath.join(tmp, "a.txt"), "a\n");
573 + yield* writeTextFile(NodePath.join(tmp, "README.md"), "# on a\n");
574 + yield* git(tmp, ["add", "."]);
575 + if (committed === "before the turn") yield* commitOnA;
576 + yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: first });
577 +
578 + if (committed === "during the turn") yield* commitOnA;
579 + yield* git(tmp, ["checkout", "b"]);
580 + yield* writeTextFile(NodePath.join(tmp, "README.md"), "# on b\n");
581 + yield* writeTextFile(NodePath.join(tmp, "b.txt"), "b\n");
582 + yield* checkpointStore.captureCheckpoint({
583 + cwd: tmp,
584 + checkpointRef: second,
585 + previousCheckpointRef: first,
586 + });
587 +
588 + const switched = yield* changedSince(first, second);
589 + expect(switched.patch).not.toContain("a.txt");
590 + expect(switched.patch).toContain("-# test\n+# on b\n");
591 + expect(switched.patch).toContain("b/b.txt");
592 + expect(switched.authored).toBeNull();
593 +
594 + // A reset also moves HEAD off a commit, and what it removed is the turn's doing.
595 + yield* git(tmp, ["add", "."]);
596 + yield* git(tmp, ["commit", "-m", "work on b"]);
597 + yield* checkpointStore.captureCheckpoint({
598 + cwd: tmp,
599 + checkpointRef: second,
600 + previousCheckpointRef: first,
601 + });
602 + yield* git(tmp, ["reset", "--hard", "HEAD~1"]);
603 + yield* checkpointStore.captureCheckpoint({
604 + cwd: tmp,
605 + checkpointRef: third,
606 + previousCheckpointRef: second,
607 + });
608 +
609 + const reset = yield* changedSince(second, third);
610 + expect(reset.patch).toContain("--- a/b.txt\n+++ /dev/null");
611 + expect(reset.authored).toEqual(new Set(["README.md", "b.txt"]));
612 + }),
613 + );
614 +
615 it.effect("keeps paths from signed commits under log.showSignature", () =>
616 Effect.gen(function* () {
617 const tmp = yield* makeTmpDir();
apps/server/src/checkpointing/CheckpointStore.ts
+2
@@ -10,6 +10,8 @@ import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
10 export interface CaptureCheckpointInput {
11 readonly cwd: string;
12 readonly checkpointRef: CheckpointRef;
13 + /** The checkpoint this one follows, so a turn that switched branches starts where it landed. */
14 + readonly previousCheckpointRef?: CheckpointRef;
15 }
16
17 export interface RestoreCheckpointInput {
apps/server/src/orchestration-v2/CheckpointService.ts
+1
@@ -410,6 +410,7 @@ export const layer: Layer.Layer<
410 .captureCheckpoint({
411 cwd: input.scope.cwd,
412 checkpointRef,
413 + ...(input.ordinalWithinScope > 0 ? { previousCheckpointRef } : {}),
414 })
415 .pipe(
416 Effect.as("ready" as const),
apps/server/src/vcs/GitVcsDriver.test.ts
+58
@@ -861,6 +861,63 @@ it.effect.each([1_700_000_000, 1_700_000_000.9999])(
861 }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
862 );
863
864 +it.effect("a branch switch landing after the snapshot belongs to the next checkpoint", () =>
865 + Effect.gen(function* () {
866 + const fileSystem = yield* FileSystem.FileSystem;
867 + const path = yield* Path.Path;
868 + const liveProcess = yield* VcsProcess.VcsProcess;
869 + const driver = yield* GitVcsDriver.makeVcsDriverShape();
870 + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-switch-race-" });
871 + const git = (args: ReadonlyArray<string>) =>
872 + driver.execute({ operation: "checkpoint-test", cwd, args });
873 + yield* git(["init"]);
874 + yield* git(["config", "user.name", "Test"]);
875 + yield* git(["config", "user.email", "test@test.com"]);
876 + yield* fileSystem.writeFileString(path.join(cwd, "f.txt"), "A\n");
877 + yield* git(["add", "."]);
878 + yield* git(["commit", "-m", "a"]);
879 + yield* git(["checkout", "-b", "b"]);
880 + yield* fileSystem.writeFileString(path.join(cwd, "f.txt"), "B\n");
881 + yield* git(["commit", "-am", "b"]);
882 + yield* git(["checkout", "-"]);
883 + const [first, second, third] = ["1", "2", "3"].map((turn) =>
884 + CheckpointRef.make(`refs/t3/checkpoints/switch-race/${turn}`),
885 + ) as [CheckpointRef, CheckpointRef, CheckpointRef];
886 + const racedDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
887 + Effect.provideService(VcsProcess.VcsProcess, {
888 + run: Effect.fn(function* (input: VcsProcess.VcsProcessInput) {
889 + const result = yield* liveProcess.run(input);
890 + if (input.args.includes("write-tree")) yield* git(["checkout", "b"]).pipe(Effect.orDie);
891 + return result;
892 + }),
893 + }),
894 + );
895 + const changedSince = (fromCheckpointRef: CheckpointRef, toCheckpointRef: CheckpointRef) =>
896 + Effect.gen(function* () {
897 + const refs = { cwd, fromCheckpointRef, toCheckpointRef };
898 + return {
899 + patch: yield* driver.checkpoints.diffCheckpoints({ ...refs, ignoreWhitespace: false }),
900 + authored: yield* driver.checkpoints.listAuthoredPaths(refs),
901 + };
902 + });
903 +
904 + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef: first });
905 + yield* racedDriver.checkpoints.captureCheckpoint({
906 + cwd,
907 + checkpointRef: second,
908 + previousCheckpointRef: first,
909 + });
910 + yield* driver.checkpoints.captureCheckpoint({
911 + cwd,
912 + checkpointRef: third,
913 + previousCheckpointRef: second,
914 + });
915 +
916 + assert.deepEqual(yield* changedSince(first, second), { patch: "", authored: null });
917 + assert.deepEqual(yield* changedSince(second, third), { patch: "", authored: null });
918 + }).pipe(Effect.scoped, Effect.provide(layerGitContract)),
919 +);
920 +
921 it.effect("checkpoint capture preserves racy edits made after resetting the index", () =>
922 Effect.gen(function* () {
923 const fileSystem = yield* FileSystem.FileSystem;
@@ -1051,6 +1108,7 @@ it.effect.each(["committed", "unborn"] as const)(
1108
1109 assert.deepStrictEqual(commands, [
1110 "rev-parse",
1111 + ...(head === "committed" ? ["log"] : []),
1112 "config",
1113 ...(head === "committed" ? ["read-tree", "ls-files"] : []),
1114 "add",
apps/server/src/vcs/GitVcsDriver.ts
+216 -14
@@ -585,6 +585,10 @@ const gitCommand = Effect.fn("GitVcsDriver.gitCommand")(
585 }),
586 );
587
588 +const HEAD_MOVES_SCAN_LIMIT = 512;
589 +const HEAD_MARK_TRAILER = "T3-Head-Moved-At";
590 +const HEAD_MARK_TRAILER_PATTERN = new RegExp(`^${HEAD_MARK_TRAILER}: (\\d+) (\\d+)$`, "m");
591 +
592 export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () {
593 const fileSystem = yield* FileSystem.FileSystem;
594 const path = yield* Path.Path;
@@ -922,13 +926,14 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
926 const headExists = result.exitCode === 0;
927 const headChecked = headExists || result.exitCode === 1;
928 const lines = result.stdout.split("\n");
925 - const [gitCommonDir = "", indexPath = "", prefix = ""] = lines;
929 + const [gitCommonDir = "", indexPath = "", prefix = "", head = ""] = lines;
930 if (headChecked && lines.length === (headExists ? 5 : 4) && lines.at(-1) === "") {
931 return {
932 gitCommonDir: gitCommonDir.trim(),
933 indexPath: indexPath.trim(),
934 prefix,
935 headExists,
936 + head: headExists ? head : undefined,
937 };
938 }
939 // Git before 2.31 echoes --path-format, and a path containing a newline spans lines.
@@ -944,6 +949,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
949 indexPath: undefined,
950 prefix: prefixResult.stdout.replace(/\n$/, ""),
951 headExists: headChecked ? headExists : yield* hasHeadCommit(cwd),
952 + head: undefined,
953 };
954 });
955
@@ -965,6 +971,64 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
971 // core.longpaths is disabled in the user's Git configuration.
972 const longPaths = hostPlatform === "win32" ? ["-c", "core.longpaths=true"] : [];
973
974 + // Newest first: the commit each HEAD move landed on, when, and Git's reason for it.
975 + const readHeadMoves = (cwd: string) =>
976 + execute({
977 + operation: VcsProcess.CHECKPOINT_CAPTURE_OPERATION,
978 + cwd,
979 + args: [
980 + "-c",
981 + "log.showSignature=false",
982 + "log",
983 + "--walk-reflogs",
984 + "-n",
985 + String(HEAD_MOVES_SCAN_LIMIT),
986 + "--date=unix",
987 + "--format=%H %gd %gs",
988 + "HEAD",
989 + "--",
990 + ],
991 + allowNonZeroExit: true,
992 + }).pipe(
993 + Effect.map((result) =>
994 + result.exitCode !== 0
995 + ? []
996 + : result.stdout.split("\n").flatMap((line) => {
997 + const [, to, at, reason] = /^([0-9a-f]+) HEAD@\{(\d+)\} (.*)$/.exec(line) ?? [];
998 + return to === undefined || at === undefined || reason === undefined
999 + ? []
1000 + : [{ to, at, reason }];
1001 + }),
1002 + ),
1003 + Effect.orElseSucceed(() => []),
1004 + );
1005 +
1006 + // A checkpoint taken after a branch switch has a second parent: the checkpoint before it with
1007 + // the switch applied, which is where that turn started. Other ranges start at `from` itself.
1008 + const resolveTurnStart = (input: VcsDriver.VcsListAuthoredPathsInput) =>
1009 + execute({
1010 + operation: "GitVcsDriver.checkpoints.resolveTurnStart",
1011 + cwd: input.cwd,
1012 + args: [
1013 + "-c",
1014 + "log.showSignature=false",
1015 + "log",
1016 + "--no-walk=unsorted",
1017 + "--format=%H %P",
1018 + `${input.fromCheckpointRef}^{commit}`,
1019 + `${input.toCheckpointRef}^2`,
1020 + ],
1021 + allowNonZeroExit: true,
1022 + }).pipe(
1023 + Effect.map((result): string => {
1024 + const [fromLine = "", startLine = ""] = result.stdout.trimEnd().split("\n");
1025 + const [start = "", , startedFrom] = startLine.split(" ");
1026 + return result.exitCode === 0 && startedFrom === fromLine.split(" ")[0]
1027 + ? start
1028 + : input.fromCheckpointRef;
1029 + }),
1030 + );
1031 +
1032 const checkpoints: VcsDriver.VcsCheckpointOps = {
1033 captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) {
1034 const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION;
@@ -979,9 +1043,18 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
1043 "-c",
1044 "splitIndex.sharedIndexExpire=never",
1045 ];
982 - const { gitCommonDir, indexPath, prefix, headExists } = yield* resolveCaptureRepository(
1046 + const { gitCommonDir, indexPath, prefix, headExists, head } = yield* resolveCaptureRepository(
1047 input.cwd,
1048 );
1049 + // Read before the snapshot and pinned to the same HEAD: a switch that lands while files are
1050 + // being staged then belongs to the next checkpoint instead of being applied to this one.
1051 + const headMoves = head === undefined ? [] : yield* readHeadMoves(input.cwd);
1052 + const lastMove = headMoves.at(0);
1053 + // Moves share a second, so the mark also counts how many of that second it has seen.
1054 + const headMark =
1055 + lastMove !== undefined && lastMove.to === head
1056 + ? `${lastMove.at} ${headMoves.filter((move) => move.at === lastMove.at).length}`
1057 + : undefined;
1058 const indexId = yield* random.uuidV4();
1059 const tempIndexPath = path.join(gitCommonDir, `t3-checkpoint-index-${indexId}`);
1060 const hostEnv = yield* HostProcess.Environment;
@@ -1331,8 +1404,137 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
1404 });
1405 }
1406
1334 - const message = `t3 checkpoint ref=${input.checkpointRef}`;
1335 - // HEAD is the parent so listAuthoredPaths can see how HEAD moved between checkpoints.
1407 + // Switching branches rewrites files the turn never wrote, and only HEAD's reflog tells a
1408 + // switch from a reset. The trailer marks where that reflog stood for the next checkpoint.
1409 + const turnStart =
1410 + headMark === undefined || input.previousCheckpointRef === undefined
1411 + ? null
1412 + : yield* Effect.gen(function* () {
1413 + const previous = yield* execute({
1414 + operation,
1415 + cwd: input.cwd,
1416 + args: [
1417 + "-c",
1418 + "log.showSignature=false",
1419 + "log",
1420 + "--no-walk",
1421 + "--format=%H %T %ct %P%n%B",
1422 + `${input.previousCheckpointRef}^{commit}`,
1423 + ],
1424 + allowNonZeroExit: true,
1425 + });
1426 + if (previous.exitCode !== 0) return null;
1427 + const [commit = "", tree = "", capturedAt = "", previousHead = ""] = previous.stdout
1428 + .slice(0, previous.stdout.indexOf("\n"))
1429 + .split(" ");
1430 + const [, markedAt, markedCount] =
1431 + HEAD_MARK_TRAILER_PATTERN.exec(previous.stdout) ?? [];
1432 + const oldestMarked = headMoves.findLastIndex((move) => move.at === markedAt);
1433 + // -1 when the scan ended inside the marked second, so the count cannot be placed.
1434 + const since =
1435 + oldestMarked === HEAD_MOVES_SCAN_LIMIT - 1
1436 + ? -1
1437 + : oldestMarked - Number(markedCount) + 1;
1438 + if (headMoves[since]?.to !== previousHead) return null;
1439 + const switches = headMoves
1440 + .slice(0, since)
1441 + .map((move, index) => ({ ...move, from: headMoves[index + 1]!.to }))
1442 + .filter(
1443 + (move) =>
1444 + move.reason.startsWith("checkout: moving from ") && move.from !== move.to,
1445 + )
1446 + .toReversed();
1447 + const landedOn = switches.at(-1)?.to;
1448 + if (landedOn === undefined) return null;
1449 +
1450 + yield* execute({
1451 + operation,
1452 + cwd: input.cwd,
1453 + args: [...indexConfig, "-c", "index.sparse=false", "read-tree", tree],
1454 + env: commitEnv,
1455 + });
1456 + for (const { from, to } of switches) {
1457 + const changes = yield* execute({
1458 + operation,
1459 + cwd: input.cwd,
1460 + args: [
1461 + "-c",
1462 + "core.quotePath=true",
1463 + "diff-tree",
1464 + "-r",
1465 + "--no-renames",
1466 + from,
1467 + to,
1468 + ],
1469 + maxOutputBytes: VcsDriver.CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
1470 + outputMode: "error",
1471 + });
1472 + // A switch succeeds only where the files it replaces were unmodified, so each
1473 + // changed path takes the destination's version. Mode 000000 drops the path.
1474 + const entries = changes.stdout
1475 + .split("\n")
1476 + // A switch leaves a submodule's own checkout where it was.
1477 + .filter((line) => line !== "" && !/^:(?:160000 |[0-7]{6} 160000 )/.test(line))
1478 + .map((line) =>
1479 + line.replace(
1480 + /^:[0-7]{6} ([0-7]{6}) [0-9a-f]+ ([0-9a-f]+) [A-Z]\t/,
1481 + "$1 $2\t",
1482 + ),
1483 + );
1484 + if (entries.length === 0) continue;
1485 + yield* execute({
1486 + operation,
1487 + cwd: input.cwd,
1488 + args: [
1489 + ...indexConfig,
1490 + "-c",
1491 + "index.sparse=false",
1492 + "update-index",
1493 + "--index-info",
1494 + ],
1495 + stdin: `${entries.join("\n")}\n`,
1496 + env: commitEnv,
1497 + });
1498 + }
1499 + const startTree = (yield* execute({
1500 + operation,
1501 + cwd: input.cwd,
1502 + args: [...indexConfig, ...durableWrite, "write-tree"],
1503 + env: commitEnv,
1504 + })).stdout.trim();
1505 + if (startTree === "" || startTree === tree) return null;
1506 + const startCommit = yield* execute({
1507 + operation,
1508 + cwd: input.cwd,
1509 + args: [
1510 + ...durableWrite,
1511 + "commit-tree",
1512 + startTree,
1513 + "-p",
1514 + landedOn,
1515 + "-p",
1516 + commit,
1517 + "-m",
1518 + `t3 checkpoint turn start ref=${input.checkpointRef}`,
1519 + ],
1520 + // listAuthoredPaths reads commits newer than the start as the turn's own.
1521 + env: { ...commitEnv, GIT_COMMITTER_DATE: `${capturedAt} +0000` },
1522 + });
1523 + return startCommit.stdout.trim() || null;
1524 + }).pipe(
1525 + Effect.catch((cause) =>
1526 + Effect.logWarning("checkpoint branch switch turn start failed", {
1527 + cwd: input.cwd,
1528 + checkpointRef: input.checkpointRef,
1529 + cause: String(cause),
1530 + }).pipe(Effect.as(null)),
1531 + ),
1532 + );
1533 +
1534 + const message = `t3 checkpoint ref=${input.checkpointRef}${
1535 + headMark === undefined ? "" : `\n\n${HEAD_MARK_TRAILER}: ${headMark}`
1536 + }`;
1537 + // HEAD is the first parent so listAuthoredPaths can see how HEAD moved between checkpoints.
1538 const commitTreeResult = yield* execute({
1539 operation,
1540 cwd: input.cwd,
@@ -1340,7 +1542,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
1542 ...durableWrite,
1543 "commit-tree",
1544 treeOid,
1343 - ...(headExists ? ["-p", "HEAD"] : []),
1545 + ...(headExists ? ["-p", head ?? "HEAD"] : []),
1546 + ...(turnStart === null ? [] : ["-p", turnStart]),
1547 "-m",
1548 message,
1549 ],
@@ -1571,15 +1774,13 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
1774 "checkpoint.fallback_from_to_head": input.fallbackFromToHead,
1775 });
1776
1574 - let fromRevision: string = input.fromCheckpointRef;
1777 + let fromRevision = yield* resolveTurnStart(input);
1778 if (input.fallbackFromToHead === true) {
1779 const resolvedFromCommit = yield* resolveCheckpointCommit(
1780 input.cwd,
1781 input.fromCheckpointRef,
1782 );
1580 - if (resolvedFromCommit) {
1581 - fromRevision = resolvedFromCommit;
1582 - } else {
1783 + if (!resolvedFromCommit) {
1784 const headCommit = yield* resolveHeadCommit(input.cwd);
1785 if (!headCommit) {
1786 return yield* new VcsProcessExitError({
@@ -1638,20 +1839,21 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
1839
1840 listAuthoredPaths: Effect.fn("GitVcsDriver.checkpoints.listAuthoredPaths")(function* (input) {
1841 const operation = "GitVcsDriver.checkpoints.listAuthoredPaths";
1842 + const turnStart = yield* resolveTurnStart(input);
1843 const heads = yield* execute({
1844 operation,
1845 cwd: input.cwd,
1846 args: [
1847 "log",
1848 "--no-walk=unsorted",
1647 - "--format=%P %ct",
1648 - `${input.fromCheckpointRef}^{commit}`,
1849 + "--format=%ct %P",
1850 + `${turnStart}^{commit}`,
1851 `${input.toCheckpointRef}^{commit}`,
1852 ],
1853 });
1854 const [fromLine = "", toLine = ""] = heads.stdout.trimEnd().split("\n");
1653 - const [startHead = "", capturedAt = ""] = fromLine.split(" ");
1654 - const [endHead = ""] = toLine.split(" ");
1855 + const [capturedAt = "", startHead = ""] = fromLine.split(" ");
1856 + const [, endHead = ""] = toLine.split(" ");
1857 if (startHead === "" || endHead === "" || startHead === endHead) {
1858 return null;
1859 }
@@ -1678,7 +1880,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
1880 // Remerge diffs retain merge conflict fixes while excluding clean upstream changes.
1881 const pathLists = yield* Effect.all(
1882 [
1681 - listPaths(["diff", startHead, `${input.fromCheckpointRef}^{commit}`]),
1883 + listPaths(["diff", startHead, `${turnStart}^{commit}`]),
1884 listPaths(["diff", endHead, `${input.toCheckpointRef}^{commit}`]),
1885 listPaths(["log", "--format=", "--diff-merges=remerge", `${endHead}..${startHead}`]),
1886 listPaths([
apps/server/src/vcs/VcsDriver.ts
+2
@@ -14,6 +14,8 @@ import * as VcsProcess from "./VcsProcess.ts";
14 export interface VcsCaptureCheckpointInput {
15 readonly cwd: string;
16 readonly checkpointRef: CheckpointRef;
17 + /** The checkpoint this one follows, so a turn that switched branches starts where it landed. */
18 + readonly previousCheckpointRef?: CheckpointRef;
19 }
20
21 export interface VcsRestoreCheckpointInput {