Open History to see the last commit
1/**
2 * CheckpointStoreLive - Filesystem checkpoint store adapter layer.
3 *
4 * Implements hidden Git-ref checkpoint capture/restore directly with
5 * Effect-native child process execution (`effect/unstable/process`).
6 *
7 * This layer owns filesystem/Git interactions only; it does not persist
8 * checkpoint metadata and does not coordinate provider rollback semantics.
9 *
10 * @module CheckpointStoreLive
11 */
12import { randomUUID } from "node:crypto";
13
14import { Effect, Layer, FileSystem, Path } from "effect";
15
16import { CheckpointInvariantError } from "../Errors.ts";
17import { GitCommandError } from "@workbench/contracts";
18import { GitCore } from "../../git/Services/GitCore.ts";
19import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
20import { CheckpointRef } from "@workbench/contracts";
21
22const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
23
24const makeCheckpointStore = Effect.gen(function* () {
25 const fs = yield* FileSystem.FileSystem;
26 const path = yield* Path.Path;
27 const git = yield* GitCore;
28
29 const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
30 git
31 .execute({
32 operation: "CheckpointStore.resolveHeadCommit",
33 cwd,
34 args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
35 allowNonZeroExit: true,
36 })
37 .pipe(
38 Effect.map((result) => {
39 if (result.code !== 0) {
40 return null;
41 }
42 const commit = result.stdout.trim();
43 return commit.length > 0 ? commit : null;
44 }),
45 );
46
47 const hasHeadCommit = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
48 git
49 .execute({
50 operation: "CheckpointStore.hasHeadCommit",
51 cwd,
52 args: ["rev-parse", "--verify", "HEAD"],
53 allowNonZeroExit: true,
54 })
55 .pipe(Effect.map((result) => result.code === 0));
56
57 const resolveCheckpointCommit = (
58 cwd: string,
59 checkpointRef: CheckpointRef,
60 ): Effect.Effect<string | null, GitCommandError> =>
61 git
62 .execute({
63 operation: "CheckpointStore.resolveCheckpointCommit",
64 cwd,
65 args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
66 allowNonZeroExit: true,
67 })
68 .pipe(
69 Effect.map((result) => {
70 if (result.code !== 0) {
71 return null;
72 }
73 const commit = result.stdout.trim();
74 return commit.length > 0 ? commit : null;
75 }),
76 );
77
78 const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
79 git
80 .execute({
81 operation: "CheckpointStore.isGitRepository",
82 cwd,
83 args: ["rev-parse", "--is-inside-work-tree"],
84 allowNonZeroExit: true,
85 })
86 .pipe(
87 Effect.map((result) => result.code === 0 && result.stdout.trim() === "true"),
88 Effect.catch(() => Effect.succeed(false)),
89 );
90
91 const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
92 "captureCheckpoint",
93 )(function* (input) {
94 const operation = "CheckpointStore.captureCheckpoint";
95
96 yield* Effect.acquireUseRelease(
97 fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
98 Effect.fn("captureCheckpoint.withTempDirectory")(function* (tempDir) {
99 const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
100 const commitEnv: NodeJS.ProcessEnv = {
101 ...process.env,
102 GIT_INDEX_FILE: tempIndexPath,
103 GIT_AUTHOR_NAME: "Workbench",
104 GIT_AUTHOR_EMAIL: "workbench@users.noreply.github.com",
105 GIT_COMMITTER_NAME: "Workbench",
106 GIT_COMMITTER_EMAIL: "workbench@users.noreply.github.com",
107 };
108
109 const headExists = yield* hasHeadCommit(input.cwd);
110 if (headExists) {
111 yield* git.execute({
112 operation,
113 cwd: input.cwd,
114 args: ["read-tree", "HEAD"],
115 env: commitEnv,
116 });
117 }
118
119 yield* git.execute({
120 operation,
121 cwd: input.cwd,
122 args: ["add", "-A", "--", "."],
123 env: commitEnv,
124 });
125
126 const writeTreeResult = yield* git.execute({
127 operation,
128 cwd: input.cwd,
129 args: ["write-tree"],
130 env: commitEnv,
131 });
132 const treeOid = writeTreeResult.stdout.trim();
133 if (treeOid.length === 0) {
134 return yield* new GitCommandError({
135 operation,
136 command: "git write-tree",
137 cwd: input.cwd,
138 detail: "git write-tree returned an empty tree oid.",
139 });
140 }
141
142 const message = `t3 checkpoint ref=${input.checkpointRef}`;
143 const commitTreeResult = yield* git.execute({
144 operation,
145 cwd: input.cwd,
146 args: ["commit-tree", treeOid, "-m", message],
147 env: commitEnv,
148 });
149 const commitOid = commitTreeResult.stdout.trim();
150 if (commitOid.length === 0) {
151 return yield* new GitCommandError({
152 operation,
153 command: "git commit-tree",
154 cwd: input.cwd,
155 detail: "git commit-tree returned an empty commit oid.",
156 });
157 }
158
159 yield* git.execute({
160 operation,
161 cwd: input.cwd,
162 args: ["update-ref", input.checkpointRef, commitOid],
163 });
164 }),
165 (tempDir) => fs.remove(tempDir, { recursive: true }),
166 ).pipe(
167 Effect.catchTags({
168 PlatformError: (error) =>
169 Effect.fail(
170 new CheckpointInvariantError({
171 operation: "CheckpointStore.captureCheckpoint",
172 detail: "Failed to capture checkpoint.",
173 cause: error,
174 }),
175 ),
176 }),
177 );
178 });
179
180 const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
181 resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
182 Effect.map((commit) => commit !== null),
183 );
184
185 const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = Effect.fn(
186 "restoreCheckpoint",
187 )(function* (input) {
188 const operation = "CheckpointStore.restoreCheckpoint";
189
190 let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
191
192 if (!commitOid && input.fallbackToHead === true) {
193 commitOid = yield* resolveHeadCommit(input.cwd);
194 }
195
196 if (!commitOid) {
197 return false;
198 }
199
200 yield* git.execute({
201 operation,
202 cwd: input.cwd,
203 args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
204 });
205 yield* git.execute({
206 operation,
207 cwd: input.cwd,
208 args: ["clean", "-fd", "--", "."],
209 });
210
211 const headExists = yield* hasHeadCommit(input.cwd);
212 if (headExists) {
213 yield* git.execute({
214 operation,
215 cwd: input.cwd,
216 args: ["reset", "--quiet", "--", "."],
217 });
218 }
219
220 return true;
221 });
222
223 const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")(
224 function* (input) {
225 const operation = "CheckpointStore.diffCheckpoints";
226
227 let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
228 const toCommitOid = yield* resolveCheckpointCommit(input.cwd, input.toCheckpointRef);
229
230 if (!fromCommitOid && input.fallbackFromToHead === true) {
231 const headCommit = yield* resolveHeadCommit(input.cwd);
232 if (headCommit) {
233 fromCommitOid = headCommit;
234 }
235 }
236
237 if (!fromCommitOid || !toCommitOid) {
238 return yield* new GitCommandError({
239 operation,
240 command: "git diff",
241 cwd: input.cwd,
242 detail: "Checkpoint ref is unavailable for diff operation.",
243 });
244 }
245
246 const result = yield* git.execute({
247 operation,
248 cwd: input.cwd,
249 args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
250 maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
251 });
252
253 return result.stdout;
254 },
255 );
256
257 const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn(
258 "deleteCheckpointRefs",
259 )(function* (input) {
260 const operation = "CheckpointStore.deleteCheckpointRefs";
261
262 yield* Effect.forEach(
263 input.checkpointRefs,
264 (checkpointRef) =>
265 git.execute({
266 operation,
267 cwd: input.cwd,
268 args: ["update-ref", "-d", checkpointRef],
269 allowNonZeroExit: true,
270 }),
271 { discard: true },
272 );
273 });
274
275 return {
276 isGitRepository,
277 captureCheckpoint,
278 hasCheckpointRef,
279 restoreCheckpoint,
280 diffCheckpoints,
281 deleteCheckpointRefs,
282 } satisfies CheckpointStoreShape;
283});
284
285export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore);