Skip to content
TypeScript

fix(server): detect nested Git workspaces for checkpoints (#9842)

Julius Marminge0dd5c64bcfac
diff --git a/apps/server/src/git/Utils.ts b/apps/server/src/git/Utils.ts
deleted file mode 100644
index e4a703f4454..00000000000
--- 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 a01a938187f..2f2c4b30525 100644
--- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts
+++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts
@@ -590,6 +590,83 @@ describe("CheckpointReactor", () => {
}),
);
+ 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([]);
+ }),
+ );
+
it("refreshes local git status state on turn completion using the session cwd", async () => {
const gitStatusRefreshCalls: string[] = [];
const harness = await createHarness({
diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts
index 0a56eb84096..108abd5d06b 100644
--- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts
+++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts
@@ -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";
import * as PullRequestService from "../../pullRequest/PullRequestService.ts";
@@ -181,8 +180,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
@@ -192,7 +189,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,
@@ -213,7 +210,7 @@ const make = Effect.gen(function* () {
if (!cwd) {
return undefined;
}
- if (!isGitWorkspace(cwd)) {
+ if (!(yield* checkpointStore.isGitRepository(cwd))) {
return undefined;
}
return cwd;
@@ -751,7 +748,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,
diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts
index 923e8c16f54..827e14734dc 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,
@@ -44,6 +45,9 @@ import {
type ProviderServiceShape,
} from "../../provider/Services/ProviderService.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";
@@ -257,9 +261,15 @@ describe("ProviderRuntimeIngestion", () => {
async function createHarness(options?: {
serverSettings?: Partial<ServerSettings>;
threadTitle?: string;
+ 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 = createProviderServiceHarness();
const sqlCounter = makeSqlStatementCounter();
const orchestrationLayer = OrchestrationEngineLive.pipe(
@@ -284,6 +294,8 @@ describe("ProviderRuntimeIngestion", () => {
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
+ Layer.provideMerge(CheckpointStore.layer.pipe(Layer.provide(VcsDriverRegistry.layer))),
+ Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(Layer.succeed(Tracer.Tracer, sqlCounter.tracer)),
@@ -3177,6 +3189,33 @@ describe("ProviderRuntimeIngestion", () => {
});
});
+ effectIt.effect("tracks provider diff updates from a nested Git workspace", () =>
+ Effect.gen(function* () {
+ const harness = yield* Effect.promise(() =>
+ createHarness({ workspaceSubdirectory: "apps/server" }),
+ );
+ yield* Effect.promise(() =>
+ harness.emitAndDrain([
+ {
+ 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",
+ },
+ },
+ ]),
+ );
+ const snapshot = yield* Effect.promise(harness.readModel);
+ expect(snapshot.threads[0]?.checkpoints).toEqual([
+ expect.objectContaining({ turnId: "nested-turn", status: "missing" }),
+ ]);
+ }),
+ );
+
it("consumes P1 runtime events into thread metadata, diff checkpoints, and activities", async () => {
const harness = await createHarness();
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 449123d2e9d..a9be5d5b6e1 100644
--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
@@ -36,7 +36,7 @@ import { formatTokens } from "@t3tools/shared/usageFormat";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
-import { isGitRepository } from "../../git/Utils.ts";
+import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ThreadBackgroundLivenessService } from "../ThreadBackgroundLiveness.ts";
import { ThreadPlanProgressService } from "../ThreadPlanProgress.ts";
@@ -956,6 +956,7 @@ const make = Effect.gen(function* () {
const providerService = yield* ProviderService;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const serverSettingsService = yield* ServerSettingsService;
+ const checkpointStore = yield* CheckpointStore.CheckpointStore;
const providerCommandId = (event: ProviderRuntimeEvent, tag: string) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => CommandId.make(`provider:${event.eventId}:${tag}:${uuid}`)),
@@ -2013,7 +2014,12 @@ 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))
+ ) {
// 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