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 "../../git/Errors.ts";
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"] = (input) =>
90 Effect.gen(function* () {
91 const operation = "CheckpointStore.captureCheckpoint";
92
93 yield* Effect.acquireUseRelease(
94 fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
95 (tempDir) =>
96 Effect.gen(function* () {
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"] = (input) =>
184 Effect.gen(function* () {
185 const operation = "CheckpointStore.restoreCheckpoint";
186
187 let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
188
189 if (!commitOid && input.fallbackToHead === true) {
190 commitOid = yield* resolveHeadCommit(input.cwd);
191 }
192
193 if (!commitOid) {
194 return false;
195 }
196
197 yield* git.execute({
198 operation,
199 cwd: input.cwd,
200 args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
201 });
202 yield* git.execute({
203 operation,
204 cwd: input.cwd,
205 args: ["clean", "-fd", "--", "."],
206 });
207
208 const headExists = yield* hasHeadCommit(input.cwd);
209 if (headExists) {
210 yield* git.execute({
211 operation,
212 cwd: input.cwd,
213 args: ["reset", "--quiet", "--", "."],
214 });
215 }
216
217 return true;
218 });
219
220 const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = (input) =>
221 Effect.gen(function* () {
222 const operation = "CheckpointStore.diffCheckpoints";
223
224 let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
225 const toCommitOid = yield* resolveCheckpointCommit(input.cwd, input.toCheckpointRef);
226
227 if (!fromCommitOid && input.fallbackFromToHead === true) {
228 const headCommit = yield* resolveHeadCommit(input.cwd);
229 if (headCommit) {
230 fromCommitOid = headCommit;
231 }
232 }
233
234 if (!fromCommitOid || !toCommitOid) {
235 return yield* new GitCommandError({
236 operation,
237 command: "git diff",
238 cwd: input.cwd,
239 detail: "Checkpoint ref is unavailable for diff operation.",
240 });
241 }
242
243 const result = yield* git.execute({
244 operation,
245 cwd: input.cwd,
246 args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
247 });
248
249 return result.stdout;
250 });
251
252 const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = (input) =>
253 Effect.gen(function* () {
254 const operation = "CheckpointStore.deleteCheckpointRefs";
255
256 yield* Effect.forEach(
257 input.checkpointRefs,
258 (checkpointRef) =>
259 git.execute({
260 operation,
261 cwd: input.cwd,
262 args: ["update-ref", "-d", checkpointRef],
263 allowNonZeroExit: true,
264 }),
265 { discard: true },
266 );
267 });
268
269 return {
270 isGitRepository,
271 captureCheckpoint,
272 hasCheckpointRef,
273 restoreCheckpoint,
274 diffCheckpoints,
275 deleteCheckpointRefs,
276 } satisfies CheckpointStoreShape;
277});
278
279export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore);