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 { VcsProcessExitError } from "@t3tools/contracts";
18import { VcsDriverRegistry } from "../../vcs/VcsDriverRegistry.ts";
19import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
20import { CheckpointRef } from "@t3tools/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 vcsRegistry = yield* VcsDriverRegistry;
28 const vcs = {
29 execute: (input: {
30 readonly operation: string;
31 readonly cwd: string;
32 readonly args: ReadonlyArray<string>;
33 readonly stdin?: string;
34 readonly env?: NodeJS.ProcessEnv;
35 readonly allowNonZeroExit?: boolean;
36 readonly timeoutMs?: number;
37 readonly maxOutputBytes?: number;
38 readonly truncateOutputAtMaxBytes?: boolean;
39 }) =>
40 vcsRegistry
41 .resolve({ cwd: input.cwd, requestedKind: "git" })
42 .pipe(Effect.flatMap((handle) => handle.driver.execute(input))),
43 };
44
45 const resolveHeadCommit = (cwd: string) =>
46 vcs
47 .execute({
48 operation: "CheckpointStore.resolveHeadCommit",
49 cwd,
50 args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
51 allowNonZeroExit: true,
52 })
53 .pipe(
54 Effect.map((result) => {
55 if (result.exitCode !== 0) {
56 return null;
57 }
58 const commit = result.stdout.trim();
59 return commit.length > 0 ? commit : null;
60 }),
61 );
62
63 const hasHeadCommit = (cwd: string) =>
64 vcs
65 .execute({
66 operation: "CheckpointStore.hasHeadCommit",
67 cwd,
68 args: ["rev-parse", "--verify", "HEAD"],
69 allowNonZeroExit: true,
70 })
71 .pipe(Effect.map((result) => result.exitCode === 0));
72
73 const resolveCheckpointCommit = (cwd: string, checkpointRef: CheckpointRef) =>
74 vcs
75 .execute({
76 operation: "CheckpointStore.resolveCheckpointCommit",
77 cwd,
78 args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
79 allowNonZeroExit: true,
80 })
81 .pipe(
82 Effect.map((result) => {
83 if (result.exitCode !== 0) {
84 return null;
85 }
86 const commit = result.stdout.trim();
87 return commit.length > 0 ? commit : null;
88 }),
89 );
90
91 const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
92 vcs
93 .execute({
94 operation: "CheckpointStore.isGitRepository",
95 cwd,
96 args: ["rev-parse", "--is-inside-work-tree"],
97 allowNonZeroExit: true,
98 })
99 .pipe(
100 Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"),
101 Effect.catch(() => Effect.succeed(false)),
102 );
103
104 const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
105 "captureCheckpoint",
106 )(function* (input) {
107 const operation = "CheckpointStore.captureCheckpoint";
108
109 yield* Effect.acquireUseRelease(
110 fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
111 Effect.fn("captureCheckpoint.withTempDirectory")(function* (tempDir) {
112 const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
113 const commitEnv: NodeJS.ProcessEnv = {
114 ...process.env,
115 GIT_INDEX_FILE: tempIndexPath,
116 GIT_AUTHOR_NAME: "T3 Code",
117 GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com",
118 GIT_COMMITTER_NAME: "T3 Code",
119 GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com",
120 };
121
122 const headExists = yield* hasHeadCommit(input.cwd);
123 if (headExists) {
124 yield* vcs.execute({
125 operation,
126 cwd: input.cwd,
127 args: ["read-tree", "HEAD"],
128 env: commitEnv,
129 });
130 }
131
132 yield* vcs.execute({
133 operation,
134 cwd: input.cwd,
135 args: ["add", "-A", "--", "."],
136 env: commitEnv,
137 });
138
139 const writeTreeResult = yield* vcs.execute({
140 operation,
141 cwd: input.cwd,
142 args: ["write-tree"],
143 env: commitEnv,
144 });
145 const treeOid = writeTreeResult.stdout.trim();
146 if (treeOid.length === 0) {
147 return yield* new VcsProcessExitError({
148 operation,
149 command: "git write-tree",
150 cwd: input.cwd,
151 exitCode: 0,
152 detail: "git write-tree returned an empty tree oid.",
153 });
154 }
155
156 const message = `t3 checkpoint ref=${input.checkpointRef}`;
157 const commitTreeResult = yield* vcs.execute({
158 operation,
159 cwd: input.cwd,
160 args: ["commit-tree", treeOid, "-m", message],
161 env: commitEnv,
162 });
163 const commitOid = commitTreeResult.stdout.trim();
164 if (commitOid.length === 0) {
165 return yield* new VcsProcessExitError({
166 operation,
167 command: "git commit-tree",
168 cwd: input.cwd,
169 exitCode: 0,
170 detail: "git commit-tree returned an empty commit oid.",
171 });
172 }
173
174 yield* vcs.execute({
175 operation,
176 cwd: input.cwd,
177 args: ["update-ref", input.checkpointRef, commitOid],
178 });
179 }),
180 (tempDir) => fs.remove(tempDir, { recursive: true }),
181 ).pipe(
182 Effect.catchTags({
183 PlatformError: (error) =>
184 Effect.fail(
185 new CheckpointInvariantError({
186 operation: "CheckpointStore.captureCheckpoint",
187 detail: "Failed to capture checkpoint.",
188 cause: error,
189 }),
190 ),
191 }),
192 );
193 });
194
195 const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
196 resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
197 Effect.map((commit) => commit !== null),
198 );
199
200 const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = Effect.fn(
201 "restoreCheckpoint",
202 )(function* (input) {
203 const operation = "CheckpointStore.restoreCheckpoint";
204
205 let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
206
207 if (!commitOid && input.fallbackToHead === true) {
208 commitOid = yield* resolveHeadCommit(input.cwd);
209 }
210
211 if (!commitOid) {
212 return false;
213 }
214
215 yield* vcs.execute({
216 operation,
217 cwd: input.cwd,
218 args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
219 });
220 yield* vcs.execute({
221 operation,
222 cwd: input.cwd,
223 args: ["clean", "-fd", "--", "."],
224 });
225
226 const headExists = yield* hasHeadCommit(input.cwd);
227 if (headExists) {
228 yield* vcs.execute({
229 operation,
230 cwd: input.cwd,
231 args: ["reset", "--quiet", "--", "."],
232 });
233 }
234
235 return true;
236 });
237
238 const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")(
239 function* (input) {
240 const operation = "CheckpointStore.diffCheckpoints";
241
242 let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
243 const toCommitOid = yield* resolveCheckpointCommit(input.cwd, input.toCheckpointRef);
244
245 if (!fromCommitOid && input.fallbackFromToHead === true) {
246 const headCommit = yield* resolveHeadCommit(input.cwd);
247 if (headCommit) {
248 fromCommitOid = headCommit;
249 }
250 }
251
252 if (!fromCommitOid || !toCommitOid) {
253 return yield* new VcsProcessExitError({
254 operation,
255 command: "git diff",
256 cwd: input.cwd,
257 exitCode: 1,
258 detail: "Checkpoint ref is unavailable for diff operation.",
259 });
260 }
261
262 const diffArgs = [
263 "diff",
264 "--patch",
265 "--minimal",
266 "--no-color",
267 ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
268 fromCommitOid,
269 toCommitOid,
270 ];
271
272 const result = yield* vcs.execute({
273 operation,
274 cwd: input.cwd,
275 args: diffArgs,
276 maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
277 });
278
279 return result.stdout;
280 },
281 );
282
283 const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn(
284 "deleteCheckpointRefs",
285 )(function* (input) {
286 const operation = "CheckpointStore.deleteCheckpointRefs";
287
288 yield* Effect.forEach(
289 input.checkpointRefs,
290 (checkpointRef) =>
291 vcs.execute({
292 operation,
293 cwd: input.cwd,
294 args: ["update-ref", "-d", checkpointRef],
295 allowNonZeroExit: true,
296 }),
297 { discard: true },
298 );
299 });
300
301 return {
302 isGitRepository,
303 captureCheckpoint,
304 hasCheckpointRef,
305 restoreCheckpoint,
306 diffCheckpoints,
307 deleteCheckpointRefs,
308 } satisfies CheckpointStoreShape;
309});
310
311export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore);