Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CheckpointStore.ts

282 lines8.8 KB

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 { GitServiceLive } from "../../git/Layers/GitService.ts";
19import { GitService } from "../../git/Services/GitService.ts";
20import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
21import { CheckpointRef } from "@t3tools/contracts";
22​
23const makeCheckpointStore = Effect.gen(function* () {
24 const fs = yield* FileSystem.FileSystem;
25 const path = yield* Path.Path;
26 const git = yield* GitService;
27​
28 const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
29 git
30 .execute({
31 operation: "CheckpointStore.resolveHeadCommit",
32 cwd,
33 args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
34 allowNonZeroExit: true,
35 })
36 .pipe(
37 Effect.map((result) => {
38 if (result.code !== 0) {
39 return null;
40 }
41 const commit = result.stdout.trim();
42 return commit.length > 0 ? commit : null;
43 }),
44 );
45​
46 const hasHeadCommit = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
47 git
48 .execute({
49 operation: "CheckpointStore.hasHeadCommit",
50 cwd,
51 args: ["rev-parse", "--verify", "HEAD"],
52 allowNonZeroExit: true,
53 })
54 .pipe(Effect.map((result) => result.code === 0));
55​
56 const resolveCheckpointCommit = (
57 cwd: string,
58 checkpointRef: CheckpointRef,
59 ): Effect.Effect<string | null, GitCommandError> =>
60 git
61 .execute({
62 operation: "CheckpointStore.resolveCheckpointCommit",
63 cwd,
64 args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
65 allowNonZeroExit: true,
66 })
67 .pipe(
68 Effect.map((result) => {
69 if (result.code !== 0) {
70 return null;
71 }
72 const commit = result.stdout.trim();
73 return commit.length > 0 ? commit : null;
74 }),
75 );
76​
77 const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
78 git
79 .execute({
80 operation: "CheckpointStore.isGitRepository",
81 cwd,
82 args: ["rev-parse", "--is-inside-work-tree"],
83 allowNonZeroExit: true,
84 })
85 .pipe(
86 Effect.map((result) => result.code === 0 && result.stdout.trim() === "true"),
87 Effect.catch(() => Effect.succeed(false)),
88 );
89​
90 const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = (input) =>
91 Effect.gen(function* () {
92 const operation = "CheckpointStore.captureCheckpoint";
93​
94 yield* Effect.acquireUseRelease(
95 fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
96 (tempDir) =>
97 Effect.gen(function* () {
98 const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
99 const commitEnv: NodeJS.ProcessEnv = {
100 ...process.env,
101 GIT_INDEX_FILE: tempIndexPath,
102 GIT_AUTHOR_NAME: "T3 Code",
103 GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com",
104 GIT_COMMITTER_NAME: "T3 Code",
105 GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com",
106 };
107​
108 const headExists = yield* hasHeadCommit(input.cwd);
109 if (headExists) {
110 yield* git.execute({
111 operation,
112 cwd: input.cwd,
113 args: ["read-tree", "HEAD"],
114 env: commitEnv,
115 });
116 }
117​
118 yield* git.execute({
119 operation,
120 cwd: input.cwd,
121 args: ["add", "-A", "--", "."],
122 env: commitEnv,
123 });
124​
125 const writeTreeResult = yield* git.execute({
126 operation,
127 cwd: input.cwd,
128 args: ["write-tree"],
129 env: commitEnv,
130 });
131 const treeOid = writeTreeResult.stdout.trim();
132 if (treeOid.length === 0) {
133 return yield* new GitCommandError({
134 operation,
135 command: "git write-tree",
136 cwd: input.cwd,
137 detail: "git write-tree returned an empty tree oid.",
138 });
139 }
140​
141 const message = `t3 checkpoint ref=${input.checkpointRef}`;
142 const commitTreeResult = yield* git.execute({
143 operation,
144 cwd: input.cwd,
145 args: ["commit-tree", treeOid, "-m", message],
146 env: commitEnv,
147 });
148 const commitOid = commitTreeResult.stdout.trim();
149 if (commitOid.length === 0) {
150 return yield* new GitCommandError({
151 operation,
152 command: "git commit-tree",
153 cwd: input.cwd,
154 detail: "git commit-tree returned an empty commit oid.",
155 });
156 }
157​
158 yield* git.execute({
159 operation,
160 cwd: input.cwd,
161 args: ["update-ref", input.checkpointRef, commitOid],
162 });
163 }),
164 (tempDir) => fs.remove(tempDir, { recursive: true }),
165 ).pipe(
166 Effect.catchTags({
167 PlatformError: (error) =>
168 Effect.fail(
169 new CheckpointInvariantError({
170 operation: "CheckpointStore.captureCheckpoint",
171 detail: "Failed to capture checkpoint.",
172 cause: error,
173 }),
174 ),
175 }),
176 );
177 });
178​
179 const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
180 resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
181 Effect.map((commit) => commit !== null),
182 );
183​
184 const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = (input) =>
185 Effect.gen(function* () {
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"] = (input) =>
222 Effect.gen(function* () {
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 const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = (input) =>
254 Effect.gen(function* () {
255 const operation = "CheckpointStore.deleteCheckpointRefs";
256​
257 yield* Effect.forEach(
258 input.checkpointRefs,
259 (checkpointRef) =>
260 git.execute({
261 operation,
262 cwd: input.cwd,
263 args: ["update-ref", "-d", checkpointRef],
264 allowNonZeroExit: true,
265 }),
266 { discard: true },
267 );
268 });
269​
270 return {
271 isGitRepository,
272 captureCheckpoint,
273 hasCheckpointRef,
274 restoreCheckpoint,
275 diffCheckpoints,
276 deleteCheckpointRefs,
277 } satisfies CheckpointStoreShape;
278});
279​
280export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore).pipe(
281 Layer.provideMerge(GitServiceLive),
282);