Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

fix(server): capture complete turn checkpoints after edits finish (#220)

Leo59f57730faf8
diff --git a/apps/server/package.json b/apps/server/package.json
index 5c02bb4ba..e25fbca59 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -44,7 +44,6 @@
"@mastra/telegram": "0.1.0",
"@opencode-ai/sdk": "^1.3.15",
"@photon-ai/chat-adapter-imessage": "3.2.0",
- "@pierre/diffs": "catalog:",
"@upstash/box": "0.5.3",
"@vercel/sandbox": "^2.5.0",
"chat": "4.39.0",
diff --git a/apps/server/src/checkpointing/CheckpointStore.test.ts b/apps/server/src/checkpointing/CheckpointStore.test.ts
index bf332d20d..b9792c70e 100644
--- a/apps/server/src/checkpointing/CheckpointStore.test.ts
+++ b/apps/server/src/checkpointing/CheckpointStore.test.ts
@@ -4,6 +4,7 @@ import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { ThreadId, type VcsError } from "@t3tools/contracts";
+import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -12,6 +13,7 @@ import * as Scope from "effect/Scope";
import { describe, expect } from "vite-plus/test";
import { checkpointRefForThreadTurn } from "./Utils.ts";
+import { parseTurnDiffFilesFromNumstat } from "./Diffs.ts";
import * as CheckpointStore from "./CheckpointStore.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
@@ -219,6 +221,227 @@ it.layer(TestLayer)("CheckpointStore.layer", (it) => {
expect(whitespaceIgnoredDiff).toContain("+ <div>");
expect(whitespaceIgnoredDiff).not.toContain("- <h1>Title</h1>");
expect(whitespaceIgnoredDiff).not.toContain("+ <h1>Title</h1>");
+
+ for (const ignoreWhitespace of [false, true]) {
+ const numstat = yield* checkpointStore.diffCheckpoints({
+ cwd: tmp,
+ fromCheckpointRef,
+ toCheckpointRef,
+ ignoreWhitespace,
+ format: "numstat",
+ });
+ expect(parseTurnDiffFilesFromNumstat(numstat)).toEqual([
+ {
+ path: "Component.tsx",
+ additions: ignoreWhitespace ? 4 : 6,
+ deletions: ignoreWhitespace ? 0 : 2,
+ },
+ ]);
+ }
+ }),
+ );
+ });
+
+ describe("checkpoint file summaries", () => {
+ it.effect("counts changes whose full patch exceeds the output limit", () =>
+ Effect.gen(function* () {
+ const tmp = yield* makeTmpDir();
+ yield* initRepoWithCommit(tmp);
+ const checkpointStore = yield* CheckpointStore.CheckpointStore;
+ const threadId = ThreadId.make("large-checkpoint-summary");
+ const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
+ const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
+ const filePath = NodePath.join(tmp, "README.md");
+ const lineCount = 20_000;
+ yield* writeTextFile(filePath, `${"before".repeat(50)}\n`.repeat(lineCount));
+ yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
+ yield* writeTextFile(filePath, `${"after".repeat(60)}\n`.repeat(lineCount));
+ yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
+
+ const numstat = yield* checkpointStore.diffCheckpoints({
+ cwd: tmp,
+ fromCheckpointRef,
+ toCheckpointRef,
+ ignoreWhitespace: false,
+ format: "numstat",
+ });
+
+ expect(parseTurnDiffFilesFromNumstat(numstat)).toEqual([
+ { path: "README.md", additions: lineCount, deletions: lineCount },
+ ]);
+ expect(numstat.length).toBeLessThan(100);
+ }),
+ );
+
+ it.effect("scopes nested workspace numstat away from sibling parent commits", () =>
+ Effect.gen(function* () {
+ const tmp = yield* makeTmpDir();
+ yield* initRepoWithCommit(tmp);
+ const fileSystem = yield* FileSystem.FileSystem;
+ const workspace = NodePath.join(tmp, "apps", "server");
+ const sibling = NodePath.join(tmp, "apps", "web");
+ yield* fileSystem.makeDirectory(workspace, { recursive: true });
+ yield* fileSystem.makeDirectory(sibling, { recursive: true });
+ yield* writeTextFile(NodePath.join(workspace, "index.ts"), "export const value = 1;\n");
+ yield* writeTextFile(NodePath.join(sibling, "page.ts"), "export const page = 1;\n");
+ yield* git(tmp, ["add", "."]);
+ yield* git(tmp, ["commit", "-m", "add workspaces"]);
+
+ const checkpointStore = yield* CheckpointStore.CheckpointStore;
+ const threadId = ThreadId.make("nested-workspace-summary");
+ const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
+ const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
+
+ yield* checkpointStore.captureCheckpoint({
+ cwd: workspace,
+ checkpointRef: fromCheckpointRef,
+ });
+ yield* writeTextFile(NodePath.join(workspace, "index.ts"), "export const value = 2;\n");
+ yield* writeTextFile(NodePath.join(sibling, "page.ts"), "export const page = 2;\n");
+ yield* git(tmp, ["add", "apps/web/page.ts"]);
+ yield* git(tmp, ["commit", "-m", "sibling commit"]);
+ yield* checkpointStore.captureCheckpoint({
+ cwd: workspace,
+ checkpointRef: toCheckpointRef,
+ });
+
+ const numstat = yield* checkpointStore.diffCheckpoints({
+ cwd: workspace,
+ fromCheckpointRef,
+ toCheckpointRef,
+ ignoreWhitespace: false,
+ format: "numstat",
+ });
+ expect(parseTurnDiffFilesFromNumstat(numstat)).toEqual([
+ { path: "apps/server/index.ts", additions: 1, deletions: 1 },
+ ]);
+ }),
+ );
+
+ it.effect("preserves file paths and turn ranges without changing the user index", () =>
+ Effect.gen(function* () {
+ const tmp = yield* makeTmpDir();
+ yield* initRepoWithCommit(tmp);
+ yield* git(tmp, ["config", "diff.renames", "copies"]);
+ const fileSystem = yield* FileSystem.FileSystem;
+ const checkpointStore = yield* CheckpointStore.CheckpointStore;
+ const threadId = ThreadId.make("checkpoint-summary-paths");
+ const baseline = checkpointRefForThreadTurn(threadId, 0);
+ const firstTurn = checkpointRefForThreadTurn(threadId, 1);
+ const secondTurn = checkpointRefForThreadTurn(threadId, 2);
+ const copiedText = Array.from({ length: 20 }, (_, index) => `copy line ${index}\n`).join(
+ "",
+ );
+ const platform = yield* HostProcessPlatform;
+ const renamedPath = platform === "win32" ? "renamed café.txt" : "renamed\tcafé\nname.txt";
+ const addedPath = platform === "win32" ? "new café.txt" : "new\tfile\n名.txt";
+ for (const [path, contents] of Object.entries({
+ "copy-source.txt": copiedText,
+ "deleted.txt": "delete me\n",
+ "rename-old.txt": "before\nkeep one\nkeep two\nkeep three\n",
+ "binary.bin": "\0before",
+ })) {
+ yield* writeTextFile(NodePath.join(tmp, path), contents);
+ }
+ yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: baseline });
+
+ yield* fileSystem.rename(
+ NodePath.join(tmp, "rename-old.txt"),
+ NodePath.join(tmp, renamedPath),
+ );
+ yield* fileSystem.remove(NodePath.join(tmp, "deleted.txt"));
+ for (const [path, contents] of Object.entries({
+ "copy-source.txt": `${copiedText}one more\n`,
+ "copied.txt": copiedText,
+ [renamedPath]: "after\nkeep one\nkeep two\nkeep three\n",
+ "binary.bin": "\0after",
+ "empty.txt": "",
+ [addedPath]: "first\nsecond\n",
+ })) {
+ yield* writeTextFile(NodePath.join(tmp, path), contents);
+ }
+ yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: firstTurn });
+ const userIndex = yield* fileSystem.readFile(NodePath.join(tmp, ".git/index"));
+ const input = {
+ cwd: tmp,
+ fromCheckpointRef: baseline,
+ toCheckpointRef: firstTurn,
+ ignoreWhitespace: false,
+ format: "numstat" as const,
+ };
+ const firstSummary = parseTurnDiffFilesFromNumstat(
+ yield* checkpointStore.diffCheckpoints(input),
+ );
+ const expectedFiles = [
+ { path: "binary.bin", additions: 0, deletions: 0 },
+ { path: "copied.txt", additions: 0, deletions: 0 },
+ { path: "copy-source.txt", additions: 1, deletions: 0 },
+ { path: "deleted.txt", additions: 0, deletions: 1 },
+ { path: "empty.txt", additions: 0, deletions: 0 },
+ { path: addedPath, additions: 2, deletions: 0 },
+ { path: renamedPath, additions: 1, deletions: 1 },
+ ].toSorted((left, right) => left.path.localeCompare(right.path));
+ expect(firstSummary).toEqual(expectedFiles);
+
+ yield* fileSystem.remove(NodePath.join(tmp, "empty.txt"));
+ yield* writeTextFile(NodePath.join(tmp, "copy-source.txt"), "replacement\n");
+ yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: secondTurn });
+ const secondSummary = parseTurnDiffFilesFromNumstat(
+ yield* checkpointStore.diffCheckpoints({
+ ...input,
+ fromCheckpointRef: firstTurn,
+ toCheckpointRef: secondTurn,
+ }),
+ );
+ expect(secondSummary).toEqual([
+ { path: "copy-source.txt", additions: 1, deletions: 21 },
+ { path: "empty.txt", additions: 0, deletions: 0 },
+ ]);
+
+ const inclusiveSummary = parseTurnDiffFilesFromNumstat(
+ yield* checkpointStore.diffCheckpoints({ ...input, toCheckpointRef: secondTurn }),
+ );
+ expect(inclusiveSummary).toEqual(
+ expectedFiles
+ .filter((file) => file.path !== "empty.txt")
+ .map((file) =>
+ file.path === "copy-source.txt" ? { ...file, additions: 1, deletions: 20 } : file,
+ ),
+ );
+ expect(
+ yield* checkpointStore.diffCheckpoints({ ...input, toCheckpointRef: baseline }),
+ ).toBe("");
+ expect(yield* fileSystem.readFile(NodePath.join(tmp, ".git/index"))).toEqual(userIndex);
+ }),
+ );
+
+ it.effect("uses HEAD for a missing baseline only when requested", () =>
+ Effect.gen(function* () {
+ const tmp = yield* makeTmpDir();
+ yield* initRepoWithCommit(tmp);
+ const checkpointStore = yield* CheckpointStore.CheckpointStore;
+ const threadId = ThreadId.make("checkpoint-summary-fallback");
+ const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
+ const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
+ yield* writeTextFile(NodePath.join(tmp, "README.md"), "changed\n");
+ yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
+ const input = {
+ cwd: tmp,
+ fromCheckpointRef,
+ toCheckpointRef,
+ ignoreWhitespace: false,
+ format: "numstat" as const,
+ };
+
+ const error = yield* Effect.flip(checkpointStore.diffCheckpoints(input));
+ expect(error._tag).toBe("VcsProcessExitError");
+ const numstat = yield* checkpointStore.diffCheckpoints({
+ ...input,
+ fallbackFromToHead: true,
+ });
+ expect(parseTurnDiffFilesFromNumstat(numstat)).toEqual([
+ { path: "README.md", additions: 1, deletions: 1 },
+ ]);
}),
);
});
diff --git a/apps/server/src/checkpointing/CheckpointStore.ts b/apps/server/src/checkpointing/CheckpointStore.ts
index 5614c9e37..e894b29f3 100644
--- a/apps/server/src/checkpointing/CheckpointStore.ts
+++ b/apps/server/src/checkpointing/CheckpointStore.ts
@@ -39,6 +39,7 @@ export interface DiffCheckpointsInput {
readonly toCheckpointRef: CheckpointRef;
readonly fallbackFromToHead?: boolean;
readonly ignoreWhitespace: boolean;
+ readonly format?: "patch" | "numstat";
}
export interface DeleteCheckpointRefsInput {
@@ -77,8 +78,9 @@ export class CheckpointStore extends Context.Service<
) => Effect.Effect<boolean, CheckpointStoreError>;
/**
- * Compute a patch diff between two checkpoint refs.
+ * Compute a diff between two checkpoint refs. Defaults to a full patch.
*
+ * Numstat output has NUL-delimited paths for file summaries.
* Can optionally treat a missing "from" ref as `HEAD`.
*/
readonly diffCheckpoints: (
diff --git a/apps/server/src/checkpointing/Diffs.test.ts b/apps/server/src/checkpointing/Diffs.test.ts
index f27f5ecb8..6b7f1a875 100644
--- a/apps/server/src/checkpointing/Diffs.test.ts
+++ b/apps/server/src/checkpointing/Diffs.test.ts
@@ -1,68 +1,54 @@
import { describe, expect, it } from "vite-plus/test";
-import { parseTurnDiffFilesFromUnifiedDiff } from "./Diffs.ts";
+import { parseTurnDiffFilesFromNumstat } from "./Diffs.ts";
-describe("parseTurnDiffFilesFromUnifiedDiff", () => {
- it("returns empty list for empty diff", () => {
- expect(parseTurnDiffFilesFromUnifiedDiff("")).toEqual([]);
+describe("parseTurnDiffFilesFromNumstat", () => {
+ it("returns an empty list when no files changed", () => {
+ expect(parseTurnDiffFilesFromNumstat("")).toEqual([]);
});
- it("parses per-file additions and deletions", () => {
- const diff = [
- "diff --git a/a.txt b/a.txt",
- "index 1111111..2222222 100644",
- "--- a/a.txt",
- "+++ b/a.txt",
- "@@ -1,2 +1,3 @@",
- " one",
- "-two",
- "+two updated",
- "+three",
- "diff --git a/src/b.ts b/src/b.ts",
- "index 3333333..4444444 100644",
- "--- a/src/b.ts",
- "+++ b/src/b.ts",
- "@@ -3,2 +3,0 @@",
- "-old",
- "-stale",
- "",
- ].join("\n");
-
- expect(parseTurnDiffFilesFromUnifiedDiff(diff)).toEqual([
+ it("sorts files and preserves addition and deletion counts", () => {
+ const numstat = ["0\t2\tsrc/b.ts", "2\t1\ta.txt", ""].join("\0");
+ expect(parseTurnDiffFilesFromNumstat(numstat)).toEqual([
{ path: "a.txt", additions: 2, deletions: 1 },
{ path: "src/b.ts", additions: 0, deletions: 2 },
]);
});
- it("parses rename-only diffs with zero line changes", () => {
- const diff = [
- "diff --git a/src/old.ts b/src/new.ts",
- "similarity index 100%",
- "rename from src/old.ts",
- "rename to src/new.ts",
+ it("uses destination paths for renames and copies", () => {
+ const numstat = [
+ "0\t0\t",
+ "src/old.ts",
+ "src/new.ts",
+ "2\t1\t",
+ "src/source.ts",
+ "src/copied.ts",
+ "1\t0\tother.ts",
"",
- ].join("\n");
+ ].join("\0");
- expect(parseTurnDiffFilesFromUnifiedDiff(diff)).toEqual([
+ expect(parseTurnDiffFilesFromNumstat(numstat)).toEqual([
+ { path: "other.ts", additions: 1, deletions: 0 },
+ { path: "src/copied.ts", additions: 2, deletions: 1 },
{ path: "src/new.ts", additions: 0, deletions: 0 },
]);
});
- it("normalizes CRLF input before parsing", () => {
- const diff = [
- "diff --git a/a.txt b/a.txt",
- "index 1111111..2222222 100644",
- "--- a/a.txt",
- "+++ b/a.txt",
- "@@ -1 +1,2 @@",
- "-one",
- "+one updated",
- "+two",
- "",
- ].join("\r\n");
+ it("keeps binary files and empty files with zero line changes", () => {
+ const numstat = ["-\t-\timage.png", "0\t0\tempty.txt", ""].join("\0");
+ expect(parseTurnDiffFilesFromNumstat(numstat)).toEqual([
+ { path: "empty.txt", additions: 0, deletions: 0 },
+ { path: "image.png", additions: 0, deletions: 0 },
+ ]);
+ });
- expect(parseTurnDiffFilesFromUnifiedDiff(diff)).toEqual([
- { path: "a.txt", additions: 2, deletions: 1 },
+ it("preserves Unicode, tabs, line endings, and spaces in paths", () => {
+ const path = " café\tline\r\nname.txt ";
+ const numstat = `3\t2\t\0old\tname\n.txt\0${path}\0`;
+
+ expect(parseTurnDiffFilesFromNumstat(numstat)).toEqual([{ path, additions: 3, deletions: 2 }]);
+ expect(parseTurnDiffFilesFromNumstat(`1\t0\t${path}\0`)).toEqual([
+ { path, additions: 1, deletions: 0 },
]);
});
});
diff --git a/apps/server/src/checkpointing/Diffs.ts b/apps/server/src/checkpointing/Diffs.ts
index 0eeee1b6f..b79510091 100644
--- a/apps/server/src/checkpointing/Diffs.ts
+++ b/apps/server/src/checkpointing/Diffs.ts
@@ -1,27 +1,33 @@
-import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
-
export interface TurnDiffFileSummary {
readonly path: string;
readonly additions: number;
readonly deletions: number;
}
-export function parseTurnDiffFilesFromUnifiedDiff(
- diff: string,
-): ReadonlyArray<TurnDiffFileSummary> {
- const normalized = diff.replace(/\r\n/g, "\n").trim();
- if (normalized.length === 0) {
- return [];
- }
+/** Reads Git's NUL-delimited numstat output without decoding display paths. */
+export function parseTurnDiffFilesFromNumstat(numstat: string): ReadonlyArray<TurnDiffFileSummary> {
+ const records = numstat.split("\0");
+ const files: TurnDiffFileSummary[] = [];
+
+ for (let index = 0; index < records.length; index += 1) {
+ const record = records[index]!;
+ const counts = /^(\d+|-)\t(\d+|-)\t/.exec(record);
+ if (!counts) continue;
- const parsedPatches = parsePatchFiles(normalized);
- const files = parsedPatches.flatMap((patch) =>
- patch.files.map((file) => ({
- path: file.name,
- additions: file.hunks.reduce((total, hunk) => total + hunk.additionLines, 0),
- deletions: file.hunks.reduce((total, hunk) => total + hunk.deletionLines, 0),
- })),
- );
+ let path = record.slice(counts[0].length);
+ if (path.length === 0) {
+ // Renames and copies use two more records: the source and destination.
+ path = records[index + 2] ?? "";
+ index += 2;
+ }
+ if (path.length === 0) continue;
+
+ files.push({
+ path,
+ additions: counts[1] === "-" ? 0 : Number(counts[1]),
+ deletions: counts[2] === "-" ? 0 : Number(counts[2]),
+ });
+ }
return files.toSorted((left, right) => left.path.localeCompare(right.path));
}
diff --git a/apps/server/src/git/Utils.ts b/apps/server/src/git/Utils.ts
deleted file mode 100644
index e4a703f44..000000000
--- a/apps/server/src/git/Utils.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-// @effect-diagnostics nodeBuiltinImport:off
-import * as NodeFS from "node:fs";
-import * as NodePath from "node:path";
-
-export function isGitRepository(cwd: string): boolean {
- return NodeFS.existsSync(NodePath.join(cwd, ".git"));
-}
diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts
index 76aa535ed..56366271a 100644
--- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts
+++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts
@@ -12,6 +12,7 @@ import {
} from "@t3tools/contracts";
import {
CommandId,
+ CheckpointRef,
DEFAULT_PROVIDER_INTERACTION_MODE,
EventId,
MessageId,
@@ -20,12 +21,15 @@ import {
TurnId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
+import { it as effectIt } from "@effect/vitest";
import * as Clock from "effect/Clock";
+import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
import * as PubSub from "effect/PubSub";
+import * as Queue from "effect/Queue";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
@@ -41,7 +45,11 @@ import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import * as ThreadPlanProgress from "../ThreadPlanProgress.ts";
-import { RuntimeReceiptBusLive } from "./RuntimeReceiptBus.ts";
+import { RuntimeReceiptBusTest } from "./RuntimeReceiptBus.ts";
+import {
+ RuntimeReceiptBus,
+ type OrchestrationRuntimeReceipt,
+} from "../Services/RuntimeReceiptBus.ts";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
@@ -243,7 +251,8 @@ describe("CheckpointReactor", () => {
| OrchestrationEngineService
| CheckpointReactor
| CheckpointStore.CheckpointStore
- | ProjectionSnapshotQuery,
+ | ProjectionSnapshotQuery
+ | RuntimeReceiptBus,
unknown
> | null = null;
let scope: Scope.Closeable | null = null;
@@ -269,6 +278,7 @@ describe("CheckpointReactor", () => {
async function createHarness(options?: {
readonly hasSession?: boolean;
readonly seedFilesystemCheckpoints?: boolean;
+ readonly initializeGit?: boolean;
readonly projectWorkspaceRoot?: string;
readonly threadWorktreePath?: string | null;
readonly threadBranch?: string | null;
@@ -277,8 +287,12 @@ describe("CheckpointReactor", () => {
readonly providerSessionCwd?: string;
readonly providerName?: ProviderDriverKind;
readonly gitStatusRefreshCalls?: Array<string>;
+ readonly gitStatusRefresh?: Effect.Effect<void>;
}) {
const cwd = createGitRepository();
+ if (options?.initializeGit === false) {
+ NodeFS.rmSync(NodePath.join(cwd, ".git"), { recursive: true });
+ }
tempDirs.push(cwd);
const provider = createAgentControllerHarness(
cwd,
@@ -312,6 +326,7 @@ describe("CheckpointReactor", () => {
Effect.sync(() => {
options?.gitStatusRefreshCalls?.push(cwd);
}).pipe(
+ Effect.andThen(options?.gitStatusRefresh ?? Effect.void),
Effect.as({
isRepo: true,
hasPrimaryRemote: false,
@@ -329,7 +344,7 @@ describe("CheckpointReactor", () => {
const layer = CheckpointReactorLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(projectionSnapshotLayer),
- Layer.provideMerge(RuntimeReceiptBusLive),
+ Layer.provideMerge(RuntimeReceiptBusTest),
Layer.provideMerge(Layer.succeed(AgentController, provider.service)),
Layer.provideMerge(vcsStatusBroadcasterLayer),
Layer.provideMerge(CheckpointStore.layer.pipe(Layer.provide(VcsDriverRegistry.layer))),
@@ -352,9 +367,21 @@ describe("CheckpointReactor", () => {
const checkpointStore = await runtime.runPromise(
Effect.service(CheckpointStore.CheckpointStore),
);
- scope = await Effect.runPromise(Scope.make("sequential"));
- await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
+ const receiptBus = await runtime.runPromise(Effect.service(RuntimeReceiptBus));
+ const testScope = await Effect.runPromise(Scope.make("sequential"));
+ scope = testScope;
+ const receipts = await Effect.runPromise(
+ Effect.gen(function* () {
+ const receipts = yield* Queue.unbounded<OrchestrationRuntimeReceipt>();
+ yield* Stream.runForEach(receiptBus.streamEventsForTest, (receipt) =>
+ Queue.offer(receipts, receipt),
+ ).pipe(Effect.forkIn(testScope));
+ yield* reactor.start().pipe(Scope.provide(testScope));
+ return receipts;
+ }),
+ );
const drain = () => Effect.runPromise(reactor.drain);
+ const nextReceipt = Queue.take(receipts);
const createdAt = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
@@ -442,6 +469,7 @@ describe("CheckpointReactor", () => {
provider,
cwd,
drain,
+ nextReceipt,
};
}
@@ -543,6 +571,47 @@ describe("CheckpointReactor", () => {
expect(gitStatusRefreshCalls).toEqual([harness.cwd]);
});
+ effectIt.effect("captures files while git status refresh is still pending", () =>
+ Effect.gen(function* () {
+ const lookupStarted = yield* Deferred.make<void>();
+ const finishLookup = yield* Deferred.make<void>();
+ const harness = yield* Effect.promise(() =>
+ createHarness({
+ seedFilesystemCheckpoints: false,
+ gitStatusRefresh: Deferred.succeed(lookupStarted, undefined).pipe(
+ Effect.andThen(Deferred.await(finishLookup)),
+ ),
+ }),
+ );
+ NodeFS.writeFileSync(NodePath.join(harness.cwd, "README.md"), "completed turn\n");
+ harness.provider.emit({
+ type: "turn.completed",
+ eventId: EventId.make("evt-turn-completed-slow-status"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt: "2026-01-01T00:00:00.000Z",
+ threadId: ThreadId.make("thread-1"),
+ turnId: asTurnId("turn-slow-status"),
+ payload: { state: "completed" },
+ });
+
+ yield* Deferred.await(lookupStarted);
+ yield* Effect.gen(function* () {
+ expect(yield* harness.nextReceipt).toMatchObject({
+ type: "checkpoint.diff.finalized",
+ turnId: "turn-slow-status",
+ });
+ expect(
+ gitShowFileAtRef(
+ harness.cwd,
+ checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
+ "README.md",
+ ),
+ ).toBe("completed turn\n");
+ }).pipe(Effect.ensuring(Deferred.succeed(finishLookup, undefined)));
+ yield* Effect.promise(harness.drain);
+ }),
+ );
+
it("adopts a drifted checkout as the thread branch on a dedicated worktree", async () => {
const harness = await createHarness({
seedFilesystemCheckpoints: false,
@@ -756,53 +825,455 @@ describe("CheckpointReactor", () => {
).toBe(true);
});
- it("appends capture failure activity when turn diff summary cannot be derived", async () => {
- const harness = await createHarness({ seedFilesystemCheckpoints: false });
- const createdAt = "2026-01-01T00:00:00.000Z";
-
- await Effect.runPromise(
- harness.engine.dispatch({
- type: "thread.session.set",
- commandId: CommandId.make("cmd-session-set-missing-baseline-diff"),
- threadId: ThreadId.make("thread-1"),
- session: {
- threadId: ThreadId.make("thread-1"),
- status: "ready",
- providerName: "codex",
- runtimeMode: "approval-required",
- activeTurnId: null,
- lastError: null,
- updatedAt: createdAt,
- },
- createdAt,
+ effectIt.effect.each(["turn.completed", "turn.aborted"] as const)(
+ "captures every edit after a mid-turn diff update on %s",
+ (terminalEventType) =>
+ Effect.gen(function* () {
+ const harness = yield* Effect.promise(() =>
+ createHarness({ seedFilesystemCheckpoints: false }),
+ );
+ const threadId = ThreadId.make("thread-1");
+ const turnId = asTurnId("turn-1");
+ const assistantMessageId = MessageId.make("assistant:mid-turn");
+ const createdAt = "2026-01-01T00:00:00.000Z";
+ yield* harness.engine.dispatch({
+ type: "thread.session.set",
+ commandId: CommandId.make("cmd-mid-turn-running"),
+ threadId,
+ session: {
+ threadId,
+ status: "running",
+ providerName: "codex",
+ runtimeMode: "approval-required",
+ activeTurnId: turnId,
+ lastError: null,
+ updatedAt: createdAt,
+ },
+ createdAt,
+ });
+ harness.provider.emit({
+ type: "turn.started",
+ eventId: EventId.make("evt-mid-turn-start"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt,
+ threadId,
+ turnId,
+ });
+ expect(yield* harness.nextReceipt).toMatchObject({
+ type: "checkpoint.baseline.captured",
+ });
+
+ NodeFS.writeFileSync(NodePath.join(harness.cwd, "early.ts"), "export const early = 1;\n");
+ yield* harness.engine.dispatch({
+ type: "thread.turn.diff.complete",
+ commandId: CommandId.make("cmd-mid-turn-diff"),
+ threadId,
+ turnId,
+ completedAt: createdAt,
+ checkpointRef: CheckpointRef.make("provider-diff:mid-turn"),
+ assistantMessageId,
+ status: "missing",
+ files: [],
+ checkpointTurnCount: 1,
+ createdAt,
+ });
+ yield* Effect.promise(harness.drain);
+
+ NodeFS.writeFileSync(NodePath.join(harness.cwd, "late.ts"), "export const late = 2;\n");
+ yield* harness.engine.dispatch({
+ type: "thread.session.set",
+ commandId: CommandId.make("cmd-mid-turn-settled"),
+ threadId,
+ session: {
+ threadId,
+ status: terminalEventType === "turn.aborted" ? "interrupted" : "ready",
+ providerName: "codex",
+ runtimeMode: "approval-required",
+ activeTurnId: null,
+ lastError: null,
+ updatedAt: createdAt,
+ },
+ createdAt,
+ });
+ harness.provider.emit({
+ eventId: EventId.make("evt-mid-turn-complete"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt,
+ threadId,
+ turnId,
+ ...(terminalEventType === "turn.completed"
+ ? { type: "turn.completed", payload: { state: "completed" } }
+ : { type: "turn.aborted", payload: { reason: "Interrupted by user." } }),
+ });
+ yield* Effect.promise(harness.drain);
+ expect(gitRefExists(harness.cwd, checkpointRefForThreadTurn(threadId, 1))).toBe(true);
+ expect(yield* harness.nextReceipt).toMatchObject({
+ type: "checkpoint.diff.finalized",
+ turnId,
+ checkpointTurnCount: 1,
+ });
+ expect(yield* harness.nextReceipt).toMatchObject({
+ type: "turn.processing.quiesced",
+ turnId,
+ });
+ yield* Effect.promise(harness.drain);
+ const thread = (yield* Effect.promise(harness.readModel)).threads.find(
+ (entry) => entry.id === threadId,
+ );
+ expect(thread?.checkpoints).toHaveLength(1);
+ expect(thread?.checkpoints[0]?.status).toBe("ready");
+ expect(thread?.latestTurn?.state).toBe(
+ terminalEventType === "turn.aborted" ? "interrupted" : "completed",
+ );
+ expect(thread?.checkpoints[0]?.assistantMessageId).toBe(assistantMessageId);
+ expect(thread?.checkpoints[0]?.files.map((file) => file.path)).toEqual([
+ "early.ts",
+ "late.ts",
+ ]);
+ expect(
+ gitShowFileAtRef(harness.cwd, checkpointRefForThreadTurn(threadId, 1), "late.ts"),
+ ).toBe("export const late = 2;\n");
+
+ const followUpTurnId = asTurnId("turn-2");
+ harness.provider.emit({
+ type: "turn.started",
+ eventId: EventId.make("evt-follow-up-start"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt,
+ threadId,
+ turnId: followUpTurnId,
+ });
+ harness.provider.emit({
+ type: "turn.completed",
+ eventId: EventId.make("evt-follow-up-complete"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt,
+ threadId,
+ turnId: followUpTurnId,
+ payload: { state: "completed" },
+ });
+ expect(yield* harness.nextReceipt).toMatchObject({
+ type: "checkpoint.diff.finalized",
+ turnId: followUpTurnId,
+ checkpointTurnCount: 2,
+ });
+ const followUp = (yield* Effect.promise(harness.readModel)).threads.find(
+ (entry) => entry.id === threadId,
+ );
+ expect(
+ followUp?.checkpoints.find((checkpoint) => checkpoint.turnId === followUpTurnId),
+ ).toMatchObject({ checkpointTurnCount: 2, files: [] });
}),
- );
+ );
+ it("does not capture an aborted turn without a matching start or active session", async () => {
+ const harness = await createHarness({ seedFilesystemCheckpoints: false });
harness.provider.emit({
- type: "turn.completed",
- eventId: EventId.make("evt-turn-completed-missing-baseline"),
+ type: "turn.aborted",
+ eventId: EventId.make("evt-untracked-abort"),
provider: ProviderDriverKind.make("codex"),
-
createdAt: "2026-01-01T00:00:00.000Z",
threadId: ThreadId.make("thread-1"),
- turnId: asTurnId("turn-missing-baseline"),
- payload: { state: "completed" },
+ turnId: asTurnId("turn-untracked"),
+ payload: { reason: "Interrupted before the turn started." },
});
+ await harness.drain();
- await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
- const thread = await waitForThread(
- harness.readModel,
- (entry) =>
- entry.checkpoints.length === 1 &&
- entry.activities.some((activity) => activity.kind === "checkpoint.capture.failed"),
- );
-
- expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
+ const thread = (await harness.readModel()).threads.find((entry) => entry.id === "thread-1");
+ expect(thread?.checkpoints).toEqual([]);
expect(
- thread.activities.some((activity) => activity.kind === "checkpoint.capture.failed"),
- ).toBe(true);
+ gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)),
+ ).toBe(false);
});
+ effectIt.effect("captures a checkpoint without a summary when the baseline is missing", () =>
+ Effect.gen(function* () {
+ const harness = yield* Effect.promise(() =>
+ createHarness({ seedFilesystemCheckpoints: false }),
+ );
+ harness.provider.emit({
+ type: "turn.completed",
+ eventId: EventId.make("evt-turn-completed-missing-baseline"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt: "2026-01-01T00:00:00.000Z",
+ threadId: ThreadId.make("thread-1"),
+ turnId: asTurnId("turn-missing-baseline"),
+ payload: { state: "completed" },
+ });
+ expect(yield* harness.nextReceipt).toMatchObject({
+ type: "checkpoint.diff.finalized",
+ checkpointTurnCount: 1,
+ });
+ yield* Effect.promise(harness.drain);
+ const thread = (yield* Effect.promise(harness.readModel)).threads[0];
+ expect(thread?.checkpoints[0]).toMatchObject({
+ status: "ready",
+ checkpointTurnCount: 1,
+ files: [],
+ });
+ expect(
+ gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)),
+ ).toBe(true);
+ expect(
+ thread?.activities.some((activity) => activity.kind === "checkpoint.capture.failed"),
+ ).toBe(false);
+ }),
+ );
+
+ effectIt.effect.each([
+ { timing: "between turns", commit: false },
+ { timing: "between turns", commit: true },
+ { timing: "during a turn", commit: false },
+ { timing: "during a turn", commit: true },
+ ])("resumes checkpointing after git init $timing (commit: $commit)", ({ timing, commit }) =>
+ Effect.gen(function* () {
+ const harness = yield* Effect.promise(() =>
+ createHarness({ initializeGit: false, seedFilesystemCheckpoints: false }),
+ );
+ const threadId = ThreadId.make("thread-1");
+ const createdAt = "2026-01-01T00:00:00.000Z";
+ const emit = (type: "turn.started" | "turn.completed", turn: number) =>
+ harness.provider.emit({
+ type,
+ eventId: EventId.make(`${type}-${turn}`),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt,
+ threadId,
+ turnId: asTurnId(`turn-${turn}`),
+ ...(type === "turn.completed" ? { payload: { state: "completed" } } : {}),
+ });
+ emit("turn.started", 1);
+ yield* Effect.promise(harness.drain);
+ NodeFS.writeFileSync(NodePath.join(harness.cwd, "README.md"), "before git\n");
+ emit("turn.completed", 1);
+ yield* Effect.promise(harness.drain);
+ expect((yield* Effect.promise(harness.readModel)).threads[0]?.checkpoints).toEqual([]);
+
+ if (timing === "during a turn") {
+ emit("turn.started", 2);
+ yield* Effect.promise(harness.drain);
+ }
+ runGit(harness.cwd, ["init", "--initial-branch=main"]);
+ if (commit) {
+ runGit(harness.cwd, ["add", "."]);
+ runGit(harness.cwd, [
+ "-c",
+ "user.name=Test",
+ "-c",
+ "commit",
+ "-m",
+ "Initial",
+ ]);
+ }
+ if (timing === "between turns") {
+ yield* harness.engine.dispatch({
+ type: "thread.turn.start",
+ commandId: CommandId.make("cmd-after-git-init"),
+ threadId,
+ message: {
+ messageId: MessageId.make("message-after-git-init"),
+ role: "user",
+ text: "continue",
+ attachments: [],
+ },
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ runtimeMode: "approval-required",
+ createdAt,
+ });
+ expect(yield* harness.nextReceipt).toMatchObject({
+ type: "checkpoint.baseline.captured",
+ checkpointTurnCount: 0,
+ });
+ emit("turn.started", 2);
+ yield* Effect.promise(harness.drain);
+ }
+ NodeFS.writeFileSync(NodePath.join(harness.cwd, "README.md"), "after git\n");
+ emit("turn.completed", 2);
+ expect(yield* harness.nextReceipt).toMatchObject({
+ type: "checkpoint.diff.finalized",
+ checkpointTurnCount: 1,
+ });
+ expect(yield* harness.nextReceipt).toMatchObject({ type: "turn.processing.quiesced" });
+ yield* Effect.promise(harness.drain);
+ const firstCheckpoint = (yield* Effect.promise(harness.readModel)).threads[0]?.checkpoints[0];
+ expect(firstCheckpoint?.files).toEqual(
+ timing === "between turns"
+ ? [{ path: "README.md", kind: "modified", additions: 1, deletions: 1 }]
+ : [],
+ );
+ expect(
+ gitShowFileAtRef(harness.cwd, checkpointRefForThreadTurn(threadId, 1), "README.md"),
+ ).toBe("after git\n");
+ expect(gitRefExists(harness.cwd, checkpointRefForThreadTurn(threadId, 0))).toBe(
+ timing === "between turns",
+ );
+
+ emit("turn.started", 3);
+ yield* Effect.promise(harness.drain);
+ NodeFS.writeFileSync(NodePath.join(harness.cwd, "README.md"), "next turn\n");
+ emit("turn.completed", 3);
+ expect(yield* harness.nextReceipt).toMatchObject({
+ type: "checkpoint.diff.finalized",
+ checkpointTurnCount: 2,
+ });
+ yield* Effect.promise(harness.drain);
+ const thread = (yield* Effect.promise(harness.readModel)).threads[0];
+ expect(thread?.checkpoints[1]?.files).toEqual([
+ { path: "README.md", kind: "modified", additions: 1, deletions: 1 },
+ ]);
+ expect(
+ thread?.activities.some((activity) => activity.kind === "checkpoint.capture.failed"),
+ ).toBe(false);
+ }),
+ );
+
+ effectIt.effect("captures and reverts checkpoints from a nested Git workspace", () =>
+ Effect.gen(function* () {
+ const repositoryRoot = createGitRepository();
+ tempDirs.push(repositoryRoot);
+ const workspaceRoot = NodePath.join(repositoryRoot, "apps", "server");
+ NodeFS.mkdirSync(workspaceRoot, { recursive: true });
+ const filePath = NodePath.join(workspaceRoot, "index.ts");
+ NodeFS.writeFileSync(filePath, "export const value = 1;\n");
+ runGit(repositoryRoot, ["add", "."]);
+ runGit(repositoryRoot, ["commit", "-m", "Add nested workspace"]);
+ const harness = yield* Effect.promise(() =>
+ createHarness({
+ seedFilesystemCheckpoints: false,
+ projectWorkspaceRoot: workspaceRoot,
+ threadWorktreePath: workspaceRoot,
+ providerSessionCwd: workspaceRoot,
+ }),
+ );
+ const threadId = ThreadId.make("thread-1");
+ const turnId = asTurnId("turn-nested");
+ const createdAt = "2026-01-01T00:00:00.000Z";
+ harness.provider.emit({
+ type: "turn.started",
+ eventId: EventId.make("evt-nested-start"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt,
+ threadId,
+ turnId,
+ });
+ yield* Effect.promise(harness.drain);
+ expect(gitRefExists(repositoryRoot, checkpointRefForThreadTurn(threadId, 0))).toBe(true);
+ expect(yield* harness.nextReceipt).toMatchObject({
+ type: "checkpoint.baseline.captured",
+ });
+
+ NodeFS.writeFileSync(filePath, "export const value = 2;\n");
+ harness.provider.emit({
+ type: "turn.completed",
+ eventId: EventId.make("evt-nested-complete"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt,
+ threadId,
+ turnId,
+ payload: { state: "completed" },
+ });
+ yield* Effect.promise(harness.drain);
+ const thread = (yield* Effect.promise(harness.readModel)).threads.find(
+ (entry) => entry.id === threadId,
+ );
+ expect(thread?.checkpoints[0]).toMatchObject({
+ status: "ready",
+ files: [{ path: "apps/server/index.ts", additions: 1, deletions: 1 }],
+ });
+ expect(yield* harness.nextReceipt).toMatchObject({
+ type: "checkpoint.diff.finalized",
+ turnId,
+ });
+ expect(yield* harness.nextReceipt).toMatchObject({ type: "turn.processing.quiesced" });
+
+ yield* harness.engine.dispatch({
+ type: "thread.checkpoint.revert",
+ commandId: CommandId.make("cmd-nested-revert"),
+ threadId,
+ turnCount: 0,
+ createdAt,
+ });
+ yield* Effect.promise(harness.drain);
+ expect(NodeFS.readFileSync(filePath, "utf8")).toBe("export const value = 1;\n");
+ expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({ threadId, numTurns: 1 });
+ expect(gitRefExists(repositoryRoot, checkpointRefForThreadTurn(threadId, 1))).toBe(false);
+ const reverted = (yield* Effect.promise(harness.readModel)).threads.find(
+ (entry) => entry.id === threadId,
+ );
+ expect(reverted?.checkpoints).toEqual([]);
+ }),
+ );
+
+ effectIt.effect("keeps nested workspace summaries free of sibling parent commits", () =>
+ Effect.gen(function* () {
+ const repositoryRoot = createGitRepository();
+ tempDirs.push(repositoryRoot);
+ const workspaceRoot = NodePath.join(repositoryRoot, "apps", "server");
+ const siblingRoot = NodePath.join(repositoryRoot, "apps", "web");
+ NodeFS.mkdirSync(workspaceRoot, { recursive: true });
+ NodeFS.mkdirSync(siblingRoot, { recursive: true });
+ const filePath = NodePath.join(workspaceRoot, "index.ts");
+ NodeFS.writeFileSync(filePath, "export const value = 1;\n");
+ NodeFS.writeFileSync(NodePath.join(siblingRoot, "page.ts"), "export const page = 1;\n");
+ runGit(repositoryRoot, ["add", "."]);
+ runGit(repositoryRoot, ["commit", "-m", "Add nested workspaces"]);
+ const harness = yield* Effect.promise(() =>
+ createHarness({
+ seedFilesystemCheckpoints: false,
+ projectWorkspaceRoot: workspaceRoot,
+ threadWorktreePath: workspaceRoot,
+ providerSessionCwd: workspaceRoot,
+ }),
+ );
+ const threadId = ThreadId.make("thread-1");
+ const turnId = asTurnId("turn-nested-sibling");
+ const createdAt = "2026-01-01T00:00:00.000Z";
+ harness.provider.emit({
+ type: "turn.started",
+ eventId: EventId.make("evt-nested-sibling-start"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt,
+ threadId,
+ turnId,
+ });
+ yield* Effect.promise(harness.drain);
+ expect(yield* harness.nextReceipt).toMatchObject({
+ type: "checkpoint.baseline.captured",
+ });
+
+ NodeFS.writeFileSync(filePath, "export const value = 2;\n");
+ NodeFS.writeFileSync(NodePath.join(siblingRoot, "page.ts"), "export const page = 2;\n");
+ runGit(repositoryRoot, ["add", "apps/web/page.ts"]);
+ runGit(repositoryRoot, ["commit", "-m", "Sibling commit"]);
+ harness.provider.emit({
+ type: "turn.completed",
+ eventId: EventId.make("evt-nested-sibling-complete"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt,
+ threadId,
+ turnId,
+ payload: { state: "completed" },
+ });
+ yield* Effect.promise(harness.drain);
+ const thread = (yield* Effect.promise(harness.readModel)).threads.find(
+ (entry) => entry.id === threadId,
+ );
+ expect(thread?.checkpoints[0]).toMatchObject({
+ status: "ready",
+ files: [{ path: "apps/server/index.ts", additions: 1, deletions: 1 }],
+ });
+ expect(thread?.checkpoints[0]?.files.some((file) => file.path.includes("apps/web"))).toBe(
+ false,
+ );
+ expect(yield* harness.nextReceipt).toMatchObject({
+ type: "checkpoint.diff.finalized",
+ turnId,
+ });
+ expect(yield* harness.nextReceipt).toMatchObject({ type: "turn.processing.quiesced" });
+ }),
+ );
+
it("captures pre-turn baseline from project workspace root when thread worktree is unset", async () => {
const harness = await createHarness({
hasSession: false,
diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts
index 251ce7512..1ffebe906 100644
--- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts
+++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts
@@ -21,7 +21,7 @@ import * as Stream from "effect/Stream";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
-import { parseTurnDiffFilesFromUnifiedDiff } from "../../checkpointing/Diffs.ts";
+import { parseTurnDiffFilesFromNumstat } from "../../checkpointing/Diffs.ts";
import {
checkpointRefForThreadTurn,
resolveThreadWorkspaceCwd,
@@ -35,7 +35,6 @@ import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"
import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
import type { CheckpointStoreError } from "../../checkpointing/Errors.ts";
import type { OrchestrationDispatchError } from "../Errors.ts";
-import { isGitRepository } from "../../git/Utils.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import * as WorkspaceEntries from "../../workspace/WorkspaceEntries.ts";
@@ -88,6 +87,8 @@ const make = Effect.gen(function* () {
const receiptBus = yield* RuntimeReceiptBus;
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
+ const startedTurns = new Map<ThreadId, TurnId>();
+ const pending = new Set<ThreadId>();
const appendRevertFailureActivity = (input: {
readonly threadId: ThreadId;
@@ -177,8 +178,6 @@ const make = Effect.gen(function* () {
return project ? [project] : [];
});
- const isGitWorkspace = (cwd: string) => isGitRepository(cwd);
-
// Resolves the workspace CWD for checkpoint operations, preferring the
// active provider session CWD and falling back to the thread/project config.
// Returns undefined when no CWD can be determined or the workspace is not
@@ -188,7 +187,7 @@ const make = Effect.gen(function* () {
readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null };
readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>;
readonly preferSessionRuntime: boolean;
- }): Effect.fn.Return<string | undefined> {
+ }): Effect.fn.Return<string | undefined, CheckpointStoreError> {
const fromSession = yield* resolveSessionRuntimeForThread(input.threadId);
const fromThread = resolveThreadWorkspaceCwd({
thread: input.thread,
@@ -209,7 +208,7 @@ const make = Effect.gen(function* () {
if (!cwd) {
return undefined;
}
- if (!isGitWorkspace(cwd)) {
+ if (!(yield* checkpointStore.isGitRepository(cwd))) {
return undefined;
}
return cwd;
@@ -259,40 +258,46 @@ const make = Effect.gen(function* () {
// reflects files created or deleted during this turn.
yield* workspaceEntries.refresh(input.cwd);
- const files = yield* checkpointStore
- .diffCheckpoints({
- cwd: input.cwd,
- fromCheckpointRef,
- toCheckpointRef: targetCheckpointRef,
- fallbackFromToHead: false,
- ignoreWhitespace: false,
- })
- .pipe(
- Effect.map((diff) =>
- parseTurnDiffFilesFromUnifiedDiff(diff).map((file) => ({
- path: file.path,
- kind: "modified" as const,
- additions: file.additions,
- deletions: file.deletions,
- })),
- ),
- Effect.tapError((error) =>
- appendCaptureFailureActivity({
- threadId: input.threadId,
- turnId: input.turnId,
- detail: `Checkpoint captured, but turn diff summary is unavailable: ${error.message}`,
- createdAt: input.createdAt,
- }),
- ),
- Effect.catch((error) =>
- Effect.logWarning("failed to derive checkpoint file summary", {
- threadId: input.threadId,
- turnId: input.turnId,
- turnCount: input.turnCount,
- detail: error.message,
- }).pipe(Effect.as([])),
- ),
- );
+ // Git may have been initialized during this turn, leaving no pre-turn
+ // snapshot. Keep the completion checkpoint for future turns, but do not
+ // invent a baseline or attempt a diff against a ref that does not exist.
+ const files = yield* (
+ fromCheckpointExists
+ ? checkpointStore.diffCheckpoints({
+ cwd: input.cwd,
+ fromCheckpointRef,
+ toCheckpointRef: targetCheckpointRef,
+ fallbackFromToHead: false,
+ ignoreWhitespace: false,
+ format: "numstat",
+ })
+ : Effect.succeed("")
+ ).pipe(
+ Effect.map((diff) =>
+ parseTurnDiffFilesFromNumstat(diff).map((file) => ({
+ path: file.path,
+ kind: "modified" as const,
+ additions: file.additions,
+ deletions: file.deletions,
+ })),
+ ),
+ Effect.tapError((error) =>
+ appendCaptureFailureActivity({
+ threadId: input.threadId,
+ turnId: input.turnId,
+ detail: `Checkpoint captured, but turn diff summary is unavailable: ${error.message}`,
+ createdAt: input.createdAt,
+ }),
+ ),
+ Effect.catch((error) =>
+ Effect.logWarning("failed to derive checkpoint file summary", {
+ threadId: input.threadId,
+ turnId: input.turnId,
+ turnCount: input.turnCount,
+ detail: error.message,
+ }).pipe(Effect.as([])),
+ ),
+ );
const assistantMessageId =
input.assistantMessageId ??
@@ -351,9 +356,9 @@ const make = Effect.gen(function* () {
});
});
- // Captures a real git checkpoint when a turn completes via a runtime event.
+ // Capture the files left by a completed or interrupted turn.
const captureCheckpointFromTurnCompletion = Effect.fn("captureCheckpointFromTurnCompletion")(
- function* (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>) {
+ function* (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" | "turn.aborted" }>) {
const turnId = toTurnId(event.turnId);
if (!turnId) {
return;
@@ -410,75 +415,16 @@ const make = Effect.gen(function* () {
thread,
cwd: checkpointCwd,
turnCount: nextTurnCount,
- status: checkpointStatusFromRuntime(event.payload.state),
- assistantMessageId: undefined,
+ status:
+ event.type === "turn.aborted"
+ ? "ready"
+ : checkpointStatusFromRuntime(event.payload.state),
+ assistantMessageId: existingPlaceholder?.assistantMessageId ?? undefined,
createdAt: event.createdAt,
});
},
);
- // Captures a real git checkpoint when a placeholder checkpoint (status "missing")
- // is detected via a domain event. This replaces the placeholder with a real
- // git-ref-based checkpoint.
- //
- // ProviderRuntimeIngestion creates placeholder checkpoints on turn.diff.updated
- // events from the Codex runtime. This handler fires when the corresponding
- // domain event arrives, allowing the reactor to capture the actual filesystem
- // state into a git ref and dispatch a replacement checkpoint.
- const captureCheckpointFromPlaceholder = Effect.fn("captureCheckpointFromPlaceholder")(function* (
- event: Extract<OrchestrationEvent, { type: "thread.turn-diff-completed" }>,
- ) {
- const { threadId, turnId, checkpointTurnCount, status } = event.payload;
-
- // Only replace placeholders; skip events from our own real captures.
- if (status !== "missing") {
- return;
- }
-
- const thread = yield* resolveThreadDetail(threadId);
- if (!thread) {
- yield* Effect.logWarning("checkpoint capture from placeholder skipped: thread not found", {
- threadId,
- });
- return;
- }
-
- // If a real checkpoint already exists for this turn, skip.
- if (
- thread.checkpoints.some(
- (checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
- )
- ) {
- yield* Effect.logDebug(
- "checkpoint capture from placeholder skipped: real checkpoint already exists",
- { threadId, turnId },
- );
- return;
- }
-
- const projects = yield* resolveThreadProjects(thread.projectId);
- const checkpointCwd = yield* resolveCheckpointCwd({
- threadId,
- thread,
- projects,
- preferSessionRuntime: true,
- });
- if (!checkpointCwd) {
- return;
- }
-
- yield* captureAndDispatchCheckpoint({
- threadId,
- turnId,
- thread,
- cwd: checkpointCwd,
- turnCount: checkpointTurnCount,
- status: "ready",
- assistantMessageId: event.payload.assistantMessageId ?? undefined,
- createdAt: event.payload.completedAt,
- });
- });
-
const ensurePreTurnBaselineFromTurnStart = Effect.fn("ensurePreTurnBaselineFromTurnStart")(
function* (event: Extract<ProviderRuntimeEvent, { type: "turn.started" }>) {
const turnId = toTurnId(event.turnId);
@@ -626,6 +572,23 @@ const make = Effect.gen(function* () {
);
});
+ // Refreshing git status can wait on remote lookups under the vcs status
+ // write lock. Run it on its own worker so file capture for this turn (and
+ // checkpoints for other threads) never wait behind that work.
+ const statusRefreshWorker = yield* makeDrainableWorker(
+ (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>) =>
+ refreshLocalGitStatusFromTurnCompletion(event).pipe(
+ Effect.catchCause((cause) =>
+ Cause.hasInterruptsOnly(cause)
+ ? Effect.failCause(cause)
+ : Effect.logWarning("failed to refresh git status after turn completion", {
+ threadId: event.threadId,
+ cause: Cause.pretty(cause),
+ }),
+ ),
+ ),
+ );
+
const ensurePreTurnBaselineFromDomainTurnStart = Effect.fn(
"ensurePreTurnBaselineFromDomainTurnStart",
)(function* (
@@ -714,7 +677,7 @@ const make = Effect.gen(function* () {
}).pipe(Effect.catch(() => Effect.void));
return;
}
- if (!isGitWorkspace(sessionRuntime.value.cwd)) {
+ if (!(yield* checkpointStore.isGitRepository(sessionRuntime.value.cwd))) {
yield* appendRevertFailureActivity({
threadId: event.payload.threadId,
turnCount: event.payload.turnCount,
@@ -820,6 +783,7 @@ const make = Effect.gen(function* () {
const processDomainEvent = Effect.fn("processDomainEvent")(function* (event: OrchestrationEvent) {
if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") {
+ if (event.type === "thread.turn-start-requested") pending.add(event.payload.threadId);
yield* ensurePreTurnBaselineFromDomainTurnStart(event);
return;
}
@@ -837,41 +801,51 @@ const make = Effect.gen(function* () {
),
),
);
- return;
- }
-
- // When ProviderRuntimeIngestion creates a placeholder checkpoint (status "missing")
- // from a turn.diff.updated runtime event, capture the real git checkpoint to
- // replace it. The AgentController stream does not reliably deliver
- // turn.completed runtime events to this reactor (shared subscription), so
- // reacting to the domain event is the reliable path.
- if (event.type === "thread.turn-diff-completed") {
- yield* captureCheckpointFromPlaceholder(event).pipe(
- Effect.catch((error) =>
- Effect.flatMap(nowIso, (createdAt) =>
- appendCaptureFailureActivity({
- threadId: event.payload.threadId,
- turnId: event.payload.turnId,
- detail: error.message,
- createdAt,
- }).pipe(Effect.catch(() => Effect.void)),
- ),
- ),
- );
}
});
const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* (
event: ProviderRuntimeEvent,
) {
+ if (event.type === "session.exited") {
+ startedTurns.delete(event.threadId);
+ pending.delete(event.threadId);
+ return;
+ }
+
if (event.type === "turn.started") {
+ const turnId = toTurnId(event.turnId);
+ const activeTurnId = (yield* agentController.listSessions()).find((session) =>
+ sameId(session.threadId, event.threadId),
+ )?.activeTurnId;
+ const mayReplace = pending.has(event.threadId) && sameId(activeTurnId, turnId);
+ if (turnId !== null && (!startedTurns.has(event.threadId) || mayReplace)) {
+ startedTurns.set(event.threadId, turnId);
+ pending.delete(event.threadId);
+ }
yield* ensurePreTurnBaselineFromTurnStart(event);
return;
}
- if (event.type === "turn.completed") {
+ if (event.type === "turn.completed" || event.type === "turn.aborted") {
const turnId = toTurnId(event.turnId);
- yield* refreshLocalGitStatusFromTurnCompletion(event);
+ const thread = yield* resolveThreadDetail(event.threadId);
+ const startedTurnId = startedTurns.get(event.threadId);
+ const isTrackedTurn = sameId(startedTurnId, turnId);
+ if (isTrackedTurn) startedTurns.delete(event.threadId);
+ if (event.type === "turn.completed") {
+ yield* statusRefreshWorker.enqueue(event);
+ }
+ if (isTrackedTurn || sameId(thread?.session?.activeTurnId, turnId)) {
+ pending.delete(event.threadId);
+ }
+ if (
+ event.type === "turn.aborted" &&
+ !isTrackedTurn &&
+ !sameId(thread?.session?.activeTurnId, turnId)
+ ) {
+ return;
+ }
yield* captureCheckpointFromTurnCompletion(event).pipe(
Effect.catch((error) =>
Effect.flatMap(nowIso, (createdAt) =>
@@ -919,8 +893,7 @@ const make = Effect.gen(function* () {
if (
event.type !== "thread.turn-start-requested" &&
event.type !== "thread.message-sent" &&
- event.type !== "thread.checkpoint-revert-requested" &&
- event.type !== "thread.turn-diff-completed"
+ event.type !== "thread.checkpoint-revert-requested"
) {
return Effect.void;
}
@@ -930,7 +903,12 @@ const make = Effect.gen(function* () {
yield* forkParked(
Stream.runForEach(agentController.streamEvents, (event) => {
- if (event.type !== "turn.started" && event.type !== "turn.completed") {
+ if (
+ event.type !== "turn.started" &&
+ event.type !== "turn.completed" &&
+ event.type !== "turn.aborted" &&
+ event.type !== "session.exited"
+ ) {
return Effect.void;
}
return worker.enqueue({ source: "runtime", event });
@@ -940,7 +918,7 @@ const make = Effect.gen(function* () {
return {
start,
- drain: worker.drain,
+ drain: worker.drain.pipe(Effect.andThen(statusRefreshWorker.drain)),
} satisfies CheckpointReactorShape;
});
diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
index bb309d226..52351e644 100644
--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
@@ -1931,7 +1931,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionTurnRepository.upsertByTurnId({
...existingTurn.value,
assistantMessageId: event.payload.assistantMessageId,
- state: turnStillRunning ? existingTurn.value.state : nextState,
+ state:
+ turnStillRunning || existingTurn.value.state === "interrupted"
+ ? existingTurn.value.state
+ : nextState,
checkpointTurnCount: event.payload.checkpointTurnCount,
checkpointRef: event.payload.checkpointRef,
checkpointStatus: event.payload.status,
diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts
index df694fef2..5966aad67 100644
--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts
+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts
@@ -2,6 +2,7 @@
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
+import * as NodeChildProcess from "node:child_process";
import {
OrchestrationReadModel,
@@ -52,6 +53,9 @@ import {
type AgentControllerShape,
} from "../../provider/Services/AgentController.ts";
import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";
+import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts";
+import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
+import * as VcsProcess from "../../vcs/VcsProcess.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
@@ -277,9 +281,15 @@ describe("ProviderRuntimeIngestion", () => {
threadTitle?: string;
botOwned?: boolean;
botUsageCap?: { readonly unit: "tokens"; readonly limit: number } | null;
+ workspaceSubdirectory?: string;
}) {
- const workspaceRoot = makeTempDir("t3-provider-project-");
- NodeFS.mkdirSync(NodePath.join(workspaceRoot, ".git"));
+ const repositoryRoot = makeTempDir("t3-provider-project-");
+ NodeChildProcess.execFileSync("git", ["init", "--initial-branch=main"], {
+ cwd: repositoryRoot,
+ stdio: "ignore",
+ });
+ const workspaceRoot = NodePath.join(repositoryRoot, options?.workspaceSubdirectory ?? "");
+ NodeFS.mkdirSync(workspaceRoot, { recursive: true });
const provider = createAgentControllerHarness();
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
@@ -306,6 +316,8 @@ describe("ProviderRuntimeIngestion", () => {
Layer.provideMerge(ChannelDeliveryStoreLive.pipe(Layer.provide(SqlitePersistenceMemory))),
Layer.provideMerge(ServerSecretStore.layer),
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
+ Layer.provideMerge(CheckpointStore.layer.pipe(Layer.provide(VcsDriverRegistry.layer))),
+ Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), workspaceRoot)),
Layer.provideMerge(NodeServices.layer),
);
@@ -4049,6 +4061,30 @@ describe("ProviderRuntimeIngestion", () => {
expect(checkpoint?.checkpointRef).toBe("provider-diff:evt-turn-diff-updated");
});
+ effectIt.effect("tracks provider diff updates from a nested Git workspace", () =>
+ Effect.gen(function* () {
+ const harness = yield* Effect.promise(() =>
+ createHarness({ workspaceSubdirectory: "apps/server" }),
+ );
+ harness.emit({
+ type: "turn.diff.updated",
+ eventId: asEventId("evt-nested-diff"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt: "2026-01-01T00:00:00.000Z",
+ threadId: asThreadId("thread-1"),
+ turnId: asTurnId("nested-turn"),
+ payload: {
+ unifiedDiff: "diff --git a/apps/server/file.ts b/apps/server/file.ts\n+new\n",
+ },
+ });
+ yield* Effect.promise(harness.drain);
+ const snapshot = yield* Effect.promise(harness.readModel);
+ expect(snapshot.threads[0]?.checkpoints).toEqual([
+ expect.objectContaining({ turnId: "nested-turn", status: "missing" }),
+ ]);
+ }),
+ );
+
it("does not replace the app title with provider metadata", async () => {
const harness = await createHarness({ threadTitle: "Bot conversation" });
const now = "2026-01-01T00:00:00.000Z";
diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
index 37402dc94..2afc561ed 100644
--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
@@ -38,13 +38,13 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { AgentController } from "../../provider/Services/AgentController.ts";
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
+import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts";
import { ProjectionThreadActivityRepository } from "../../persistence/Services/ProjectionThreadActivities.ts";
import { ProjectionThreadActivityRepositoryLive } from "../../persistence/Layers/ProjectionThreadActivities.ts";
import { ProjectionThreadMessageRepository } from "../../persistence/Services/ProjectionThreadMessages.ts";
import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/ProjectionThreadMessages.ts";
import { ProjectionThreadProposedPlanRepository } from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
import { ProjectionThreadProposedPlanRepositoryLive } from "../../persistence/Layers/ProjectionThreadProposedPlans.ts";
-import { isGitRepository } from "../../git/Utils.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ThreadBackgroundLivenessService } from "../ThreadBackgroundLiveness.ts";
import { ThreadPlanProgressService } from "../ThreadPlanProgress.ts";
@@ -925,6 +925,7 @@ const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const agentController = yield* AgentController;
+ const checkpointStore = yield* CheckpointStore.CheckpointStore;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const projectionThreadMessages = yield* ProjectionThreadMessageRepository;
const projectionThreadActivities = yield* ProjectionThreadActivityRepository;
@@ -2174,7 +2175,14 @@ const make = Effect.gen(function* () {
: undefined;
const workspaceCwd =
checkpointContext?.worktreePath ?? checkpointContext?.workspaceRoot ?? undefined;
- if (turnId && checkpointContext && workspaceCwd && isGitRepository(workspaceCwd)) {
+ if (
+ turnId &&
+ checkpointContext &&
+ workspaceCwd &&
+ (yield* checkpointStore
+ .isGitRepository(workspaceCwd)
+ .pipe(Effect.orElseSucceed(() => false)))
+ ) {
// Skip if a checkpoint already exists for this turn. A real
// (non-placeholder) capture from CheckpointReactor should not
// be clobbered, and dispatching a duplicate placeholder for the
diff --git a/apps/server/src/orchestration/projector.test.ts b/apps/server/src/orchestration/projector.test.ts
index 6b691acf3..3faeea372 100644
--- a/apps/server/src/orchestration/projector.test.ts
+++ b/apps/server/src/orchestration/projector.test.ts
@@ -413,6 +413,172 @@ describe("orchestration projector", () => {
expect(settledThread?.latestTurn?.completedAt).toBe(settledAt);
});
+ it.effect.each([
+ ["ready", "completed"],
+ ["interrupted", "interrupted"],
+ ] as const)(
+ "preserves the turn state after a %s session captures its checkpoint",
+ ([status, state]) =>
+ Effect.gen(function* () {
+ const createdAt = "2026-02-23T08:00:00.000Z";
+ const startedAt = "2026-02-23T08:00:05.000Z";
+ const settledAt = "2026-02-23T08:01:00.000Z";
+ const afterCreate = yield* projectEvent(
+ createEmptyReadModel(createdAt),
+ makeEvent({
+ sequence: 1,
+ type: "thread.created",
+ aggregateKind: "thread",
+ aggregateId: "thread-1",
+ occurredAt: createdAt,
+ commandId: "cmd-create",
+ payload: {
+ threadId: "thread-1",
+ projectId: "project-1",
+ title: "demo",
+ modelSelection: {
+ provider: ProviderDriverKind.make("codex"),
+ model: "gpt-5.3-codex",
+ },
+ runtimeMode: "full-access",
+ branch: null,
+ worktreePath: null,
+ createdAt,
+ updatedAt: createdAt,
+ },
+ }),
+ );
+ const afterRunning = yield* projectEvent(
+ afterCreate,
+ makeEvent({
+ sequence: 2,
+ type: "thread.session-set",
+ aggregateKind: "thread",
+ aggregateId: "thread-1",
+ occurredAt: startedAt,
+ commandId: "cmd-running",
+ payload: {
+ threadId: "thread-1",
+ session: {
+ threadId: "thread-1",
+ status: "running",
+ providerName: "codex",
+ providerSessionId: "session-1",
+ providerThreadId: "provider-thread-1",
+ runtimeMode: "approval-required",
+ activeTurnId: "turn-1",
+ lastError: null,
+ updatedAt: startedAt,
+ },
+ },
+ }),
+ );
+ const afterSettled = yield* projectEvent(
+ afterRunning,
+ makeEvent({
+ sequence: 3,
+ type: "thread.session-set",
+ aggregateKind: "thread",
+ aggregateId: "thread-1",
+ occurredAt: settledAt,
+ commandId: "cmd-settled",
+ payload: {
+ threadId: "thread-1",
+ session: {
+ threadId: "thread-1",
+ status,
+ providerName: "codex",
+ providerSessionId: "session-1",
+ providerThreadId: "provider-thread-1",
+ runtimeMode: "approval-required",
+ activeTurnId: null,
+ lastError: null,
+ updatedAt: settledAt,
+ },
+ },
+ }),
+ );
+ const afterCheckpoint = yield* projectEvent(
+ afterSettled,
+ makeEvent({
+ sequence: 4,
+ type: "thread.turn-diff-completed",
+ aggregateKind: "thread",
+ aggregateId: "thread-1",
+ occurredAt: settledAt,
+ commandId: "cmd-checkpoint",
+ payload: {
+ threadId: "thread-1",
+ turnId: "turn-1",
+ checkpointTurnCount: 1,
+ checkpointRef: "refs/t3/checkpoints/thread-1/turn/1",
+ status: "ready",
+ files: [],
+ assistantMessageId: "assistant-1",
+ completedAt: settledAt,
+ },
+ }),
+ );
+
+ expect(afterCheckpoint.threads[0]?.latestTurn?.state).toBe(state);
+ expect(afterCheckpoint.threads[0]?.checkpoints[0]?.status).toBe("ready");
+ }),
+ );
+
+ it.effect("does not treat a missing checkpoint as an interruption", () =>
+ Effect.gen(function* () {
+ const createdAt = "2026-02-23T08:00:00.000Z";
+ const afterCreate = yield* projectEvent(
+ createEmptyReadModel(createdAt),
+ makeEvent({
+ sequence: 1,
+ type: "thread.created",
+ aggregateKind: "thread",
+ aggregateId: "thread-1",
+ occurredAt: createdAt,
+ commandId: "cmd-create",
+ payload: {
+ threadId: "thread-1",
+ projectId: "project-1",
+ title: "demo",
+ modelSelection: {
+ provider: ProviderDriverKind.make("codex"),
+ model: "gpt-5.3-codex",
+ },
+ runtimeMode: "full-access",
+ branch: null,
+ worktreePath: null,
+ createdAt,
+ updatedAt: createdAt,
+ },
+ }),
+ );
+ const afterCheckpoint = yield* projectEvent(
+ afterCreate,
+ makeEvent({
+ sequence: 2,
+ type: "thread.turn-diff-completed",
+ aggregateKind: "thread",
+ aggregateId: "thread-1",
+ occurredAt: createdAt,
+ commandId: "cmd-placeholder",
+ payload: {
+ threadId: "thread-1",
+ turnId: "turn-1",
+ checkpointTurnCount: 1,
+ checkpointRef: "provider-diff:placeholder",
+ status: "missing",
+ files: [],
+ assistantMessageId: "assistant-1",
+ completedAt: createdAt,
+ },
+ }),
+ );
+
+ expect(afterCheckpoint.threads[0]?.latestTurn?.state).toBe("completed");
+ }),
+ );
+
it("updates canonical thread runtime mode from thread.runtime-mode-set", async () => {
const createdAt = "2026-02-23T08:00:00.000Z";
const updatedAt = "2026-02-23T08:00:05.000Z";
diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts
index 55f9a8a6b..dc78ca83f 100644
--- a/apps/server/src/orchestration/projector.ts
+++ b/apps/server/src/orchestration/projector.ts
@@ -80,7 +80,7 @@ const MAX_THREAD_CHECKPOINTS = 500;
function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error") {
if (status === "error") return "error" as const;
- if (status === "missing") return "interrupted" as const;
+ // Match SQL and client projections: a missing git ref is not an interruption.
return "completed" as const;
}
@@ -1288,7 +1288,11 @@ export function projectEvent(
? thread.latestTurn
: {
turnId: payload.turnId,
- state: checkpointStatusToLatestTurnState(payload.status),
+ state:
+ thread.latestTurn?.turnId === payload.turnId &&
+ thread.latestTurn.state === "interrupted"
+ ? "interrupted"
+ : checkpointStatusToLatestTurnState(payload.status),
requestedAt:
thread.latestTurn?.turnId === payload.turnId
? thread.latestTurn.requestedAt
diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts
index b46a66c7f..11a158014 100644
--- a/apps/server/src/vcs/GitVcsDriver.ts
+++ b/apps/server/src/vcs/GitVcsDriver.ts
@@ -43,6 +43,7 @@ export interface ExecuteGitInput {
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number | null;
readonly maxOutputBytes?: number;
+ readonly outputMode?: VcsProcess.VcsProcessInput["outputMode"];
readonly appendTruncationMarker?: boolean;
readonly progress?: ExecuteGitProgress;
}
@@ -431,6 +432,7 @@ const gitCommand = (
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
+ readonly outputMode?: VcsProcess.VcsProcessInput["outputMode"];
readonly appendTruncationMarker?: boolean;
},
) =>
@@ -447,6 +449,7 @@ const gitCommand = (
: {}),
...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
+ ...(options?.outputMode !== undefined ? { outputMode: options.outputMode } : {}),
...(options?.appendTruncationMarker !== undefined
? { appendTruncationMarker: options.appendTruncationMarker }
: {}),
@@ -485,6 +488,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
+ ...(input.outputMode !== undefined ? { outputMode: input.outputMode } : {}),
...(input.appendTruncationMarker !== undefined
? { appendTruncationMarker: input.appendTruncationMarker }
: {}),
@@ -838,6 +842,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
"checkpoint.from_ref": input.fromCheckpointRef,
"checkpoint.to_ref": input.toCheckpointRef,
"checkpoint.ignore_whitespace": input.ignoreWhitespace,
+ "checkpoint.format": input.format ?? "patch",
"checkpoint.fallback_from_to_head": input.fallbackFromToHead,
});
@@ -869,16 +874,22 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
cwd: input.cwd,
args: [
"diff",
- "--patch",
+ ...(input.format === "numstat" ? ["--numstat", "-z"] : ["--patch"]),
"--no-color",
"--no-ext-diff",
"--no-textconv",
...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
`${fromRevision}^{commit}`,
`${input.toCheckpointRef}^{commit}`,
+ // Numstat summaries are turn file lists. Nested workspaces capture
+ // with `git add -A -- .`, but a sibling commit on the parent HEAD
+ // still appears in a full-tree comparison. Restrict automatic
+ // summaries to this cwd; on-demand patches stay whole-tree.
+ ...(input.format === "numstat" ? ["--", "."] : []),
],
allowNonZeroExit: true,
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
+ outputMode: input.format === "numstat" ? "error" : "truncate",
});
if (result.exitCode !== 0) {
diff --git a/apps/server/src/vcs/VcsDriver.ts b/apps/server/src/vcs/VcsDriver.ts
index 9cf957f22..0fbf75db7 100644
--- a/apps/server/src/vcs/VcsDriver.ts
+++ b/apps/server/src/vcs/VcsDriver.ts
@@ -31,6 +31,7 @@ export interface VcsDiffCheckpointsInput {
readonly toCheckpointRef: CheckpointRef;
readonly fallbackFromToHead?: boolean;
readonly ignoreWhitespace: boolean;
+ readonly format?: "patch" | "numstat";
}
export interface VcsDeleteCheckpointRefsInput {
diff --git a/apps/server/src/vcs/VcsProcess.test.ts b/apps/server/src/vcs/VcsProcess.test.ts
index bd3e5b4cd..c717913c7 100644
--- a/apps/server/src/vcs/VcsProcess.test.ts
+++ b/apps/server/src/vcs/VcsProcess.test.ts
@@ -1,5 +1,5 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
-import { describe, expect, it } from "@effect/vitest";
+import { assert, describe, expect, it } from "@effect/vitest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
@@ -298,6 +298,24 @@ describe("VcsProcess.run", () => {
}).pipe(provideLive),
);
+ it.effect("fails with measured byte counts when output must not be truncated", () =>
+ Effect.gen(function* () {
+ const error = yield* run({
+ operation: "test.output-limit",
+ command: "node",
+ args: ["-e", "process.stdout.write('x'.repeat(2048))"],
+ cwd: process.cwd(),
+ maxOutputBytes: 128,
+ outputMode: "error",
+ }).pipe(Effect.flip);
+
+ assert(error._tag === "VcsProcessOutputLimitError");
+ expect(error.stream).toBe("stdout");
+ expect(error.maxBytes).toBe(128);
+ expect(error.observedBytes).toBeGreaterThan(error.maxBytes);
+ }).pipe(provideLive),
+ );
+
it.effect("fails with VcsProcessTimeoutError on timeout", () =>
Effect.gen(function* () {
const errorFiber = yield* run({
diff --git a/apps/server/src/vcs/VcsProcess.ts b/apps/server/src/vcs/VcsProcess.ts
index f385bf6b6..b4a87d0c9 100644
--- a/apps/server/src/vcs/VcsProcess.ts
+++ b/apps/server/src/vcs/VcsProcess.ts
@@ -28,6 +28,7 @@ export interface VcsProcessInput {
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
+ readonly outputMode?: ProcessRunner.ProcessRunInput["outputMode"];
readonly appendTruncationMarker?: boolean;
}
@@ -120,7 +121,7 @@ export const make = Effect.gen(function* () {
...(input.env !== undefined ? { env: input.env } : {}),
timeout: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
maxOutputBytes: input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
- outputMode: "truncate",
+ outputMode: input.outputMode ?? "truncate",
truncatedMarker: input.appendTruncationMarker ? OUTPUT_TRUNCATED_MARKER : "",
timeoutBehavior: "error",
})
diff --git a/docs/internals/glossary.md b/docs/internals/glossary.md
index 9d89aa518..522c3a936 100644
--- a/docs/internals/glossary.md
+++ b/docs/internals/glossary.md
@@ -148,7 +148,7 @@ The starting checkpoint for diffing a thread timeline. This flow is surfaced thr
#### Checkpoint diff
-The patch difference between two checkpoints. Query logic lives in [CheckpointDiffQuery.ts][20], diff parsing lives in [Diffs.ts][23], and finalization is coordinated by [CheckpointReactor.ts][6].
+The difference between two checkpoints. On-demand diffs stay as patches; automatic turn summaries use NUL-delimited Git numstat. Query logic lives in [CheckpointDiffQuery.ts][20], summary parsing lives in [Diffs.ts][23], and finalization is coordinated by [CheckpointReactor.ts][6].
#### Turn diff
diff --git a/packages/client-runtime/src/state/threadReducer.test.ts b/packages/client-runtime/src/state/threadReducer.test.ts
index 1860eaff2..f2abec2e8 100644
--- a/packages/client-runtime/src/state/threadReducer.test.ts
+++ b/packages/client-runtime/src/state/threadReducer.test.ts
@@ -1261,6 +1261,71 @@ describe("applyThreadDetailEvent", () => {
expect(result.thread.latestTurn?.state).toBe("completed");
}
});
+
+ it("keeps an interrupted turn interrupted when its checkpoint becomes ready", () => {
+ const interrupted: OrchestrationThread = {
+ ...baseThread,
+ latestTurn: {
+ turnId: TurnId.make("turn-1"),
+ state: "interrupted",
+ requestedAt: "2026-04-01T11:00:00.000Z",
+ startedAt: "2026-04-01T11:00:00.000Z",
+ completedAt: "2026-04-01T11:30:00.000Z",
+ assistantMessageId: MessageId.make("msg-3"),
+ },
+ };
+
+ const result = applyThreadDetailEvent(interrupted, {
+ ...baseEventFields,
+ sequence: 14,
+ occurredAt: "2026-04-01T12:00:00.000Z",
+ aggregateKind: "thread",
+ aggregateId: ThreadId.make("thread-1"),
+ type: "thread.turn-diff-completed",
+ payload: {
+ threadId: ThreadId.make("thread-1"),
+ turnId: TurnId.make("turn-1"),
+ checkpointTurnCount: 1,
+ checkpointRef: CheckpointRef.make("ref-1"),
+ status: "ready",
+ files: [],
+ assistantMessageId: MessageId.make("msg-3"),
+ completedAt: "2026-04-01T12:00:00.000Z",
+ },
+ });
+
+ expect(result.kind).toBe("updated");
+ if (result.kind === "updated") {
+ expect(result.thread.latestTurn?.state).toBe("interrupted");
+ expect(result.thread.checkpoints[0]?.status).toBe("ready");
+ }
+ });
+
+ it("does not treat a missing checkpoint as an interruption", () => {
+ const result = applyThreadDetailEvent(baseThread, {
+ ...baseEventFields,
+ sequence: 15,
+ occurredAt: "2026-04-01T12:00:00.000Z",
+ aggregateKind: "thread",
+ aggregateId: ThreadId.make("thread-1"),
+ type: "thread.turn-diff-completed",
+ payload: {
+ threadId: ThreadId.make("thread-1"),
+ turnId: TurnId.make("turn-1"),
+ checkpointTurnCount: 1,
+ checkpointRef: CheckpointRef.make("provider-diff:placeholder"),
+ status: "missing",
+ files: [],
+ assistantMessageId: MessageId.make("msg-3"),
+ completedAt: "2026-04-01T12:00:00.000Z",
+ },
+ });
+
+ expect(result.kind).toBe("updated");
+ if (result.kind === "updated") {
+ expect(result.thread.latestTurn?.state).toBe("completed");
+ }
+ });
});
describe("thread.reverted", () => {
diff --git a/packages/client-runtime/src/state/threadReducer.ts b/packages/client-runtime/src/state/threadReducer.ts
index 20d116dad..a1b3cbf94 100644
--- a/packages/client-runtime/src/state/threadReducer.ts
+++ b/packages/client-runtime/src/state/threadReducer.ts
@@ -564,7 +564,10 @@ export function applyThreadDetailEvent(
(thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
? {
turnId: event.payload.turnId,
- state: checkpointStatusToTurnState(event.payload.status),
+ state:
+ thread.latestTurn?.state === "interrupted"
+ ? "interrupted"
+ : checkpointStatusToTurnState(event.payload.status),
requestedAt: thread.latestTurn?.requestedAt ?? event.payload.completedAt,
startedAt: thread.latestTurn?.startedAt ?? event.payload.completedAt,
completedAt: event.payload.completedAt,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 31853f9a5..5d8d1f786 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -504,7 +504,7 @@ importers:
version: 0.9.4(patch_hash=ab9ff544009e1891cfe3930105862d3699007f38922a79f3c98d90018deca368)
'@mastra/code-sdk':
specifier: 1.5.1
'@mastra/core':
specifier: 1.63.0
@@ -523,9 +523,6 @@ importers:
'@photon-ai/chat-adapter-imessage':
specifier: 3.2.0
- '@pierre/diffs':
- specifier: 'catalog:'
- version: 1.3.0-beta.10(patch_hash=7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb51452aa3380db91aa)(@shikijs/[email protected])([email protected]([email protected]))([email protected])
'@upstash/box':
specifier: 0.5.3
version: 0.5.3([email protected])
@@ -16341,7 +16338,7 @@ snapshots:
postcss: 8.5.26
resolve-from: 5.0.0
optionalDependencies:
- expo: 56.0.12(deb8cbf3e0f411b34ba85a995c9982ba)
+ expo: 56.0.12(8895228379997a2a064f9644cda56ed0)
transitivePeerDependencies:
- bufferutil
- supports-color
@@ -17157,7 +17154,7 @@ snapshots:
- supports-color
- utf-8-validate
dependencies:
'@agentclientprotocol/sdk': 0.21.1([email protected])
'@ai-sdk/amazon-bedrock': 3.0.120([email protected])
@@ -21050,8 +21047,8 @@ snapshots:
react-refresh: 0.14.2
optionalDependencies:
'@babel/runtime': 7.29.7
- expo: 56.0.12(deb8cbf3e0f411b34ba85a995c9982ba)
- expo-widgets: 56.0.19(32843e0c0883df8bccfa0b8323659df5)
+ expo: 56.0.12(8895228379997a2a064f9644cda56ed0)
+ expo-widgets: 56.0.19(3cdc0dde9f93166d952f1e1bd0cb25c0)
transitivePeerDependencies:
- '@babel/core'
- supports-color
@@ -22984,22 +22981,6 @@ snapshots:
expo: 56.0.12(8895228379997a2a064f9644cda56ed0)
- [email protected](32843e0c0883df8bccfa0b8323659df5):
- dependencies:
- '@expo/plist': 0.7.0
- '@expo/ui': 56.0.18(32843e0c0883df8bccfa0b8323659df5)
- expo: 56.0.12(deb8cbf3e0f411b34ba85a995c9982ba)
- react: 19.2.6
- transitivePeerDependencies:
- - '@babel/core'
- - '@types/react'
- - '@types/react-dom'
- - react-dom
- - react-native-reanimated
- - react-native-worklets
- optional: true
-
[email protected](3cdc0dde9f93166d952f1e1bd0cb25c0):
dependencies:
'@expo/plist': 0.7.0