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