@catamorphic/git 0.0.0-stage → 0.1.0-alpha.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/LICENSE.txt +202 -0
  2. package/NOTICE.txt +32 -0
  3. package/dist/checkout-remote-backend.d.ts +12 -0
  4. package/dist/checkout-remote-backend.d.ts.map +1 -0
  5. package/dist/file-reads.d.ts +15 -0
  6. package/dist/file-reads.d.ts.map +1 -0
  7. package/dist/fs-backend.d.ts +30 -0
  8. package/dist/fs-backend.d.ts.map +1 -0
  9. package/dist/fs-remote-backend.d.ts +47 -0
  10. package/dist/fs-remote-backend.d.ts.map +1 -0
  11. package/dist/git-object-codec.d.ts +31 -0
  12. package/dist/git-object-codec.d.ts.map +1 -0
  13. package/dist/git-sync.d.ts +61 -0
  14. package/dist/git-sync.d.ts.map +1 -0
  15. package/dist/in-memory-object-store.d.ts +23 -0
  16. package/dist/in-memory-object-store.d.ts.map +1 -0
  17. package/dist/index.d.ts +24 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +4746 -0
  20. package/dist/index.js.map +32 -0
  21. package/dist/migrate-workflow.d.ts +12 -0
  22. package/dist/migrate-workflow.d.ts.map +1 -0
  23. package/dist/native-git.d.ts +25 -0
  24. package/dist/native-git.d.ts.map +1 -0
  25. package/dist/native-project-repo.d.ts +57 -0
  26. package/dist/native-project-repo.d.ts.map +1 -0
  27. package/dist/network-sync.d.ts +58 -0
  28. package/dist/network-sync.d.ts.map +1 -0
  29. package/dist/network.d.ts +81 -0
  30. package/dist/network.d.ts.map +1 -0
  31. package/dist/object-remote-backend.d.ts +95 -0
  32. package/dist/object-remote-backend.d.ts.map +1 -0
  33. package/dist/object-store.d.ts +42 -0
  34. package/dist/object-store.d.ts.map +1 -0
  35. package/dist/origin-draft.d.ts +264 -0
  36. package/dist/origin-draft.d.ts.map +1 -0
  37. package/dist/origin-objects.d.ts +201 -0
  38. package/dist/origin-objects.d.ts.map +1 -0
  39. package/dist/personal-files.d.ts +6 -0
  40. package/dist/personal-files.d.ts.map +1 -0
  41. package/dist/project-manager.d.ts +214 -0
  42. package/dist/project-manager.d.ts.map +1 -0
  43. package/dist/project-repo.d.ts +79 -0
  44. package/dist/project-repo.d.ts.map +1 -0
  45. package/dist/ref-moved-error.d.ts +13 -0
  46. package/dist/ref-moved-error.d.ts.map +1 -0
  47. package/dist/ref-names.d.ts +18 -0
  48. package/dist/ref-names.d.ts.map +1 -0
  49. package/dist/types.d.ts +276 -0
  50. package/dist/types.d.ts.map +1 -0
  51. package/dist/workspace-mirror.d.ts +110 -0
  52. package/dist/workspace-mirror.d.ts.map +1 -0
  53. package/package.json +53 -4
  54. package/src/checkout-remote-backend.ts +154 -0
  55. package/src/diff3.d.ts +16 -0
  56. package/src/file-reads.ts +53 -0
  57. package/src/fs-backend.ts +206 -0
  58. package/src/fs-remote-backend.ts +252 -0
  59. package/src/git-object-codec.ts +87 -0
  60. package/src/git-sync.ts +539 -0
  61. package/src/in-memory-object-store.ts +60 -0
  62. package/src/index.ts +110 -0
  63. package/src/migrate-workflow.ts +30 -0
  64. package/src/native-git.ts +177 -0
  65. package/src/native-project-repo.ts +515 -0
  66. package/src/network-sync.ts +239 -0
  67. package/src/network.ts +269 -0
  68. package/src/object-remote-backend.ts +366 -0
  69. package/src/object-store.ts +41 -0
  70. package/src/origin-draft.ts +1033 -0
  71. package/src/origin-objects.ts +906 -0
  72. package/src/personal-files.ts +57 -0
  73. package/src/project-manager.ts +743 -0
  74. package/src/project-repo.ts +800 -0
  75. package/src/ref-moved-error.ts +18 -0
  76. package/src/ref-names.ts +47 -0
  77. package/src/types.ts +289 -0
  78. package/src/workspace-mirror.ts +400 -0
  79. package/README.md +0 -3
@@ -0,0 +1,800 @@
1
+ import nodeFs from "node:fs";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import {
5
+ PROJECT_WORKSPACE_ROOT,
6
+ publishedRef,
7
+ } from "@catamorphic/workflow/project-layout";
8
+ import ignore, { type Ignore } from "ignore";
9
+ import git from "isomorphic-git";
10
+ import { type FileReadOptions, readFileSnapshot } from "./file-reads.js";
11
+ import { isPersonalFile } from "./personal-files.js";
12
+ import { assertResolvableRef } from "./ref-names.js";
13
+ import type {
14
+ BranchInfo,
15
+ CommitInfo,
16
+ DiffEntry,
17
+ ProjectRepo,
18
+ RepoStatus,
19
+ } from "./types.js";
20
+
21
+ const IGNORED_DIRS = new Set(["node_modules", ".git", "dist", ".turbo"]);
22
+ // git.add processes array inputs concurrently, even with parallel: false.
23
+ // Bound file reads while amortizing full-index serialization across each batch.
24
+ const STAGING_BATCH_SIZE = 128;
25
+
26
+ /**
27
+ * Dot-directories that are project content despite the hidden-file skip
28
+ * below. `.work/` holds authored capabilities and shared config;
29
+ * `.agents/` may contain the owner's harness instructions. Git ignore rules
30
+ * distinguish local data and build outputs from versioned content.
31
+ */
32
+ const ALLOWED_DOT_DIRS = new Set([".agents", PROJECT_WORKSPACE_ROOT]);
33
+
34
+ /**
35
+ * Dot-FILES that are project content: the seeded ignore rules must be
36
+ * committed (an untracked .gitignore reads as a permanently dirty tree,
37
+ * which would defer every remote sync).
38
+ */
39
+ const ALLOWED_DOT_FILES = new Set([".gitignore"]);
40
+
41
+ export function assertSafePath(filePath: string): void {
42
+ const normalized = path.normalize(filePath);
43
+ if (path.isAbsolute(normalized)) {
44
+ throw new Error("Absolute paths not allowed");
45
+ }
46
+ if (normalized.startsWith("..")) {
47
+ throw new Error("Path traversal detected");
48
+ }
49
+ if (isPersonalFile(normalized)) {
50
+ throw new Error(
51
+ "Personal files are local-only and cannot be accessed through project APIs",
52
+ );
53
+ }
54
+ // Any `.git` segment, in any case: case-insensitive filesystems alias it.
55
+ if (
56
+ normalized
57
+ .split(/[\\/]/)
58
+ .some((segment) => segment.toLowerCase() === ".git")
59
+ ) {
60
+ throw new Error("Cannot access .git directory");
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Refuse a path that passes through a symbolic link: a committed link must
66
+ * never let file APIs read or write outside the working copy.
67
+ */
68
+ async function assertNoSymlinks(root: string, filePath: string) {
69
+ let current = root;
70
+ for (const segment of path.normalize(filePath).split(path.sep)) {
71
+ if (!segment || segment === ".") continue;
72
+ current = path.join(current, segment);
73
+ const stat = await fs.lstat(current).catch(() => undefined);
74
+ if (!stat) return;
75
+ if (stat.isSymbolicLink())
76
+ throw new Error("Symbolic links cannot be read or written here");
77
+ }
78
+ }
79
+
80
+ export async function walkDirectory(
81
+ dir: string,
82
+ base: string,
83
+ options?: {
84
+ excludeNestedRepositories?: boolean;
85
+ includeHidden?: boolean;
86
+ tracked: Set<string>;
87
+ trackedDirectories: Set<string>;
88
+ rules: Array<{ base: string; matcher: Ignore }>;
89
+ },
90
+ ): Promise<string[]> {
91
+ if (
92
+ options?.excludeNestedRepositories &&
93
+ dir !== base &&
94
+ (await fs.stat(path.join(dir, ".git")).then(
95
+ () => true,
96
+ () => false,
97
+ ))
98
+ )
99
+ return [];
100
+ const rules = options ? [...options.rules] : [];
101
+ if (options) {
102
+ const content = await fs
103
+ .readFile(path.join(dir, ".gitignore"), "utf8")
104
+ .catch(() => "");
105
+ if (content) rules.push({ base: dir, matcher: ignore().add(content) });
106
+ }
107
+ const entries = await fs.readdir(dir, { withFileTypes: true });
108
+ const results: string[] = [];
109
+
110
+ for (const entry of entries) {
111
+ if (IGNORED_DIRS.has(entry.name)) continue;
112
+ if (
113
+ !options?.includeHidden &&
114
+ entry.name.startsWith(".") &&
115
+ !ALLOWED_DOT_DIRS.has(entry.name) &&
116
+ !ALLOWED_DOT_FILES.has(entry.name)
117
+ )
118
+ continue;
119
+
120
+ const fullPath = path.join(dir, entry.name);
121
+ const relativePath = path.relative(base, fullPath);
122
+ if (isPersonalFile(relativePath)) continue;
123
+
124
+ if (options) {
125
+ let ignored = false;
126
+ for (const rule of rules) {
127
+ const result = rule.matcher.test(
128
+ path.relative(rule.base, fullPath) + (entry.isDirectory() ? "/" : ""),
129
+ );
130
+ if (result.ignored) ignored = true;
131
+ if (result.unignored) ignored = false;
132
+ }
133
+ if (
134
+ ignored &&
135
+ !options.tracked.has(relativePath) &&
136
+ !options.trackedDirectories.has(relativePath)
137
+ )
138
+ continue;
139
+ }
140
+ if (entry.isDirectory()) {
141
+ const nested = await walkDirectory(
142
+ fullPath,
143
+ base,
144
+ options ? { ...options, rules } : undefined,
145
+ );
146
+ results.push(...nested);
147
+ } else {
148
+ results.push(relativePath);
149
+ }
150
+ }
151
+
152
+ return results;
153
+ }
154
+
155
+ export class ProjectRepoImpl implements ProjectRepo {
156
+ /**
157
+ * Managed working copies (servers) never follow symbolic links; a
158
+ * person's own folder on their computer may hold theirs.
159
+ */
160
+ protected readonly followsSymlinks: boolean = false;
161
+
162
+ constructor(
163
+ readonly projectId: string,
164
+ readonly repoPath: string,
165
+ private readonly releaseFn: () => Promise<void>,
166
+ ) {}
167
+
168
+ async readFile(filePath: string): Promise<string> {
169
+ assertSafePath(filePath);
170
+ if (!this.followsSymlinks) await assertNoSymlinks(this.repoPath, filePath);
171
+ return fs.readFile(path.join(this.repoPath, filePath), "utf-8");
172
+ }
173
+
174
+ async writeFile(filePath: string, content: string): Promise<void> {
175
+ assertSafePath(filePath);
176
+ if (!this.followsSymlinks) await assertNoSymlinks(this.repoPath, filePath);
177
+ const fullPath = path.join(this.repoPath, filePath);
178
+ await fs.mkdir(path.dirname(fullPath), { recursive: true });
179
+ await fs.writeFile(fullPath, content);
180
+ }
181
+
182
+ async deleteFile(filePath: string): Promise<void> {
183
+ assertSafePath(filePath);
184
+ if (!this.followsSymlinks) await assertNoSymlinks(this.repoPath, filePath);
185
+ await fs.unlink(path.join(this.repoPath, filePath));
186
+ }
187
+
188
+ async listFiles(opts?: { prefix?: string }): Promise<string[]> {
189
+ if (!opts?.prefix) return walkDirectory(this.repoPath, this.repoPath);
190
+ assertSafePath(opts.prefix);
191
+ try {
192
+ return await walkDirectory(
193
+ path.join(this.repoPath, opts.prefix),
194
+ this.repoPath,
195
+ );
196
+ } catch (error) {
197
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
198
+ return [];
199
+ throw error;
200
+ }
201
+ }
202
+
203
+ async readAllFiles(
204
+ options: FileReadOptions = {},
205
+ ): Promise<Record<string, string>> {
206
+ const tracked = new Set(
207
+ await git.listFiles({ fs: nodeFs, dir: this.repoPath }),
208
+ );
209
+ const trackedDirectories = new Set<string>();
210
+ for (const file of tracked) {
211
+ let directory = path.dirname(file);
212
+ while (directory !== ".") {
213
+ trackedDirectories.add(directory);
214
+ directory = path.dirname(directory);
215
+ }
216
+ }
217
+ const excludes = await fs
218
+ .readFile(path.join(this.repoPath, ".git/info/exclude"), "utf8")
219
+ .catch(() => "");
220
+ const paths = await walkDirectory(this.repoPath, this.repoPath, {
221
+ excludeNestedRepositories: options.excludeNestedRepositories,
222
+ tracked,
223
+ trackedDirectories,
224
+ rules: excludes
225
+ ? [{ base: this.repoPath, matcher: ignore().add(excludes) }]
226
+ : [],
227
+ });
228
+ return readFileSnapshot({
229
+ paths,
230
+ options,
231
+ read: async (file, maxBytes) =>
232
+ new TextDecoder().decode(await this.readSnapshotBytes(file, maxBytes)),
233
+ });
234
+ }
235
+
236
+ protected async readSnapshotBytes(
237
+ file: string,
238
+ maxBytes: number,
239
+ ): Promise<Uint8Array> {
240
+ assertSafePath(file);
241
+ const handle = await fs.open(path.join(this.repoPath, file), "r");
242
+ try {
243
+ const size = (await handle.stat()).size;
244
+ if (size > maxBytes)
245
+ throw new Error(
246
+ `Project file '${file}' exceeds the ${maxBytes}-byte snapshot limit`,
247
+ );
248
+ // A concurrent writer cannot make this read grow beyond its budget.
249
+ const buffer = Buffer.alloc(size + 1);
250
+ let bytesRead = 0;
251
+ while (bytesRead < buffer.length) {
252
+ const chunk = await handle.read(
253
+ buffer,
254
+ bytesRead,
255
+ buffer.length - bytesRead,
256
+ bytesRead,
257
+ );
258
+ if (chunk.bytesRead === 0) break;
259
+ bytesRead += chunk.bytesRead;
260
+ }
261
+ if (bytesRead > size)
262
+ throw new Error(
263
+ `Project file '${file}' changed during snapshot; retry the read`,
264
+ );
265
+ return buffer.subarray(0, bytesRead);
266
+ } finally {
267
+ await handle.close();
268
+ }
269
+ }
270
+
271
+ async readAllFilesAtRef(
272
+ ref: string,
273
+ options?: FileReadOptions,
274
+ ): Promise<Record<string, string>> {
275
+ return this.walkFilesAtRef(ref, undefined, options);
276
+ }
277
+
278
+ async readFilesAtRef(
279
+ ref: string,
280
+ opts: { prefix: string },
281
+ ): Promise<Record<string, string>> {
282
+ return this.walkFilesAtRef(ref, opts.prefix);
283
+ }
284
+
285
+ async readBlobAtRef(
286
+ ref: string,
287
+ filePath: string,
288
+ options?: { maxBytes?: number },
289
+ ): Promise<Uint8Array | null> {
290
+ assertSafePath(filePath);
291
+ assertResolvableRef(ref);
292
+ let blob: Uint8Array;
293
+ try {
294
+ const oid = await git.resolveRef({ fs: nodeFs, dir: this.repoPath, ref });
295
+ blob = (
296
+ await git.readBlob({
297
+ fs: nodeFs,
298
+ dir: this.repoPath,
299
+ oid,
300
+ filepath: filePath,
301
+ })
302
+ ).blob;
303
+ } catch {
304
+ return null;
305
+ }
306
+ if (options?.maxBytes !== undefined && blob.byteLength > options.maxBytes)
307
+ throw new Error(
308
+ `Project file '${filePath}' exceeds the ${options.maxBytes}-byte snapshot limit`,
309
+ );
310
+ return blob;
311
+ }
312
+
313
+ async readFileBytes(filePath: string): Promise<Uint8Array | null> {
314
+ assertSafePath(filePath);
315
+ if (!this.followsSymlinks) await assertNoSymlinks(this.repoPath, filePath);
316
+ try {
317
+ return new Uint8Array(
318
+ await fs.readFile(path.join(this.repoPath, filePath)),
319
+ );
320
+ } catch {
321
+ return null;
322
+ }
323
+ }
324
+
325
+ async listFilesAtRef(
326
+ ref: string,
327
+ opts?: { prefix?: string },
328
+ ): Promise<string[]> {
329
+ return (await this.listBlobsAtRef(ref, opts)).map((entry) => entry.path);
330
+ }
331
+
332
+ async listBlobsAtRef(
333
+ ref: string,
334
+ opts?: { prefix?: string },
335
+ ): Promise<Array<{ path: string; oid: string }>> {
336
+ assertResolvableRef(ref);
337
+ const oid = await git.resolveRef({ fs: nodeFs, dir: this.repoPath, ref });
338
+ const prefix = opts?.prefix;
339
+ const blobs: Array<{ path: string; oid: string }> = [];
340
+ await git.walk({
341
+ fs: nodeFs,
342
+ dir: this.repoPath,
343
+ trees: [git.TREE({ ref: oid })],
344
+ map: async (filepath, [entry]) => {
345
+ if (filepath === "." || !entry) return;
346
+ if (isPersonalFile(filepath)) return null;
347
+ if (prefix !== undefined) {
348
+ const inside = filepath.startsWith(prefix);
349
+ const onTheWay = prefix.startsWith(`${filepath}/`);
350
+ if (!inside && !onTheWay) return null;
351
+ if (!inside) return;
352
+ }
353
+ if ((await entry.type()) === "blob") {
354
+ blobs.push({ path: filepath, oid: (await entry.oid()) ?? "" });
355
+ }
356
+ },
357
+ });
358
+ return blobs.sort((a, b) => a.path.localeCompare(b.path));
359
+ }
360
+
361
+ private async walkFilesAtRef(
362
+ ref: string,
363
+ prefix?: string,
364
+ options?: FileReadOptions,
365
+ ): Promise<Record<string, string>> {
366
+ const blobs = await this.listBlobsAtRef(
367
+ ref,
368
+ prefix ? { prefix } : undefined,
369
+ );
370
+ return readFileSnapshot({
371
+ paths: blobs.map((blob) => blob.path),
372
+ options,
373
+ read: async (file, maxBytes) => {
374
+ const content = await this.readBlobAtRef(ref, file, { maxBytes });
375
+ if (!content)
376
+ throw new Error(`Project file '${file}' disappeared from '${ref}'`);
377
+ return new TextDecoder().decode(content);
378
+ },
379
+ });
380
+ }
381
+
382
+ async commit(
383
+ message: string,
384
+ author: { name: string; email: string },
385
+ opts?: { paths?: readonly string[]; allowEmpty?: boolean },
386
+ ): Promise<string> {
387
+ for (const file of opts?.paths ?? []) assertSafePath(file);
388
+ // Keep index/object caches local to this operation, never to the repo's
389
+ // lifetime: large projects must not retain them after a checkpoint.
390
+ const cache = {};
391
+ const indexedFiles = await git.listFiles({
392
+ fs: nodeFs,
393
+ dir: this.repoPath,
394
+ cache,
395
+ });
396
+ if (indexedFiles.some(isPersonalFile)) {
397
+ throw new Error(
398
+ "Personal files are tracked. Remove them from the git index before checkpointing or sharing this project.",
399
+ );
400
+ }
401
+ const only = opts?.paths ? new Set(opts.paths) : null;
402
+ const files = (await this.listFiles()).filter(
403
+ (file) => !only || only.has(file),
404
+ );
405
+ for (let offset = 0; offset < files.length; offset += STAGING_BATCH_SIZE) {
406
+ await git.add({
407
+ fs: nodeFs,
408
+ dir: this.repoPath,
409
+ filepath: files.slice(offset, offset + STAGING_BATCH_SIZE),
410
+ parallel: false,
411
+ cache,
412
+ });
413
+ }
414
+
415
+ const status = await git.statusMatrix({
416
+ fs: nodeFs,
417
+ dir: this.repoPath,
418
+ cache,
419
+ });
420
+ for (const [filepath, head, workdir, stage] of status) {
421
+ if (only && !only.has(filepath)) continue;
422
+ if (head === 1 && workdir === 0 && stage === 1) {
423
+ await git.remove({ fs: nodeFs, dir: this.repoPath, filepath, cache });
424
+ }
425
+ }
426
+
427
+ return git.commit({
428
+ fs: nodeFs,
429
+ dir: this.repoPath,
430
+ message,
431
+ author,
432
+ cache,
433
+ });
434
+ }
435
+
436
+ async log(options?: {
437
+ maxCount?: number;
438
+ ref?: string;
439
+ }): Promise<CommitInfo[]> {
440
+ if (options?.ref) assertResolvableRef(options.ref);
441
+ try {
442
+ const commits = await git.log({
443
+ fs: nodeFs,
444
+ dir: this.repoPath,
445
+ depth: options?.maxCount,
446
+ ref: options?.ref,
447
+ });
448
+ return commits.map((c) => ({
449
+ sha: c.oid,
450
+ message: c.commit.message,
451
+ author: {
452
+ name: c.commit.author.name,
453
+ email: c.commit.author.email,
454
+ },
455
+ timestamp: c.commit.author.timestamp,
456
+ }));
457
+ } catch {
458
+ return [];
459
+ }
460
+ }
461
+
462
+ async resolveRef(ref = "HEAD"): Promise<string> {
463
+ assertResolvableRef(ref);
464
+ return git.resolveRef({
465
+ fs: nodeFs,
466
+ dir: this.repoPath,
467
+ ref,
468
+ });
469
+ }
470
+
471
+ async checkout(ref?: string): Promise<void> {
472
+ await git.checkout({
473
+ fs: nodeFs,
474
+ dir: this.repoPath,
475
+ ref: ref ?? "main",
476
+ force: true,
477
+ });
478
+ }
479
+
480
+ async status(): Promise<RepoStatus> {
481
+ const branch = await this.currentBranch();
482
+ const matrix = await git.statusMatrix({
483
+ fs: nodeFs,
484
+ dir: this.repoPath,
485
+ });
486
+ const modifiedFiles = matrix
487
+ .filter(([, head, workdir]) => head !== workdir)
488
+ .map(([filepath]) => filepath);
489
+
490
+ const baseCommit = await this.resolveRef("HEAD").catch(() => null);
491
+ const remoteRef = publishedRef();
492
+ const remoteHead = await git
493
+ .resolveRef({ fs: nodeFs, dir: this.repoPath, ref: remoteRef })
494
+ .catch(() => null);
495
+
496
+ const { ahead, behind } = await computeAheadBehind({
497
+ dir: this.repoPath,
498
+ local: baseCommit,
499
+ remote: remoteHead,
500
+ });
501
+
502
+ return {
503
+ branch,
504
+ dirty: modifiedFiles.length > 0,
505
+ modifiedFiles,
506
+ ahead,
507
+ behind,
508
+ baseCommit,
509
+ remoteHead,
510
+ };
511
+ }
512
+
513
+ async currentBranch(): Promise<string> {
514
+ const name = await git.currentBranch({
515
+ fs: nodeFs,
516
+ dir: this.repoPath,
517
+ fullname: false,
518
+ });
519
+ return name ?? "main";
520
+ }
521
+
522
+ async listBranches(): Promise<BranchInfo[]> {
523
+ const current = await this.currentBranch();
524
+ const names = await git.listBranches({
525
+ fs: nodeFs,
526
+ dir: this.repoPath,
527
+ });
528
+ const entries = await Promise.all(
529
+ names.map(async (name) => {
530
+ const sha = await git
531
+ .resolveRef({
532
+ fs: nodeFs,
533
+ dir: this.repoPath,
534
+ ref: `refs/heads/${name}`,
535
+ })
536
+ .catch(() => "");
537
+ const createdAt = await tipTimestamp(this.repoPath, sha);
538
+ return {
539
+ name,
540
+ commit: sha,
541
+ isCurrent: name === current,
542
+ createdAt,
543
+ };
544
+ }),
545
+ );
546
+ return entries.sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0));
547
+ }
548
+
549
+ async createBranch(name: string, fromRef?: string): Promise<void> {
550
+ await git.branch({
551
+ fs: nodeFs,
552
+ dir: this.repoPath,
553
+ ref: name,
554
+ object: fromRef,
555
+ checkout: true,
556
+ });
557
+ }
558
+
559
+ async deleteBranch(name: string): Promise<void> {
560
+ await git.deleteBranch({
561
+ fs: nodeFs,
562
+ dir: this.repoPath,
563
+ ref: name,
564
+ });
565
+ }
566
+
567
+ async hasBranch(name: string): Promise<boolean> {
568
+ try {
569
+ await git.resolveRef({
570
+ fs: nodeFs,
571
+ dir: this.repoPath,
572
+ ref: `refs/heads/${name}`,
573
+ });
574
+ return true;
575
+ } catch {
576
+ return false;
577
+ }
578
+ }
579
+
580
+ async workdirDiff(): Promise<DiffEntry[]> {
581
+ const matrix = await git.statusMatrix({
582
+ fs: nodeFs,
583
+ dir: this.repoPath,
584
+ });
585
+ const decoder = new TextDecoder("utf-8");
586
+ const entries: DiffEntry[] = [];
587
+
588
+ for (const [filepath, head, workdir] of matrix) {
589
+ if (head === workdir) continue;
590
+
591
+ const headContent =
592
+ head === 1 ? await readBlobAtHead(this.repoPath, filepath) : null;
593
+ const workdirContent =
594
+ workdir === 0
595
+ ? null
596
+ : await readWorkdirFile(this.repoPath, filepath, decoder);
597
+
598
+ if (head === 0 && workdir !== 0) {
599
+ entries.push({
600
+ path: filepath,
601
+ kind: "added",
602
+ before: null,
603
+ after: workdirContent,
604
+ });
605
+ } else if (head !== 0 && workdir === 0) {
606
+ entries.push({
607
+ path: filepath,
608
+ kind: "deleted",
609
+ before: headContent,
610
+ after: null,
611
+ });
612
+ } else {
613
+ entries.push({
614
+ path: filepath,
615
+ kind: "modified",
616
+ before: headContent,
617
+ after: workdirContent,
618
+ });
619
+ }
620
+ }
621
+
622
+ return entries;
623
+ }
624
+
625
+ async diff(opts: { base: string; head: string }): Promise<DiffEntry[]> {
626
+ const baseFiles = new Map(
627
+ (await this.listBlobsAtRef(opts.base)).map((entry) => [
628
+ entry.path,
629
+ entry.oid,
630
+ ]),
631
+ );
632
+ const headFiles = new Map(
633
+ (await this.listBlobsAtRef(opts.head)).map((entry) => [
634
+ entry.path,
635
+ entry.oid,
636
+ ]),
637
+ );
638
+ const changed = [
639
+ ...new Set([...baseFiles.keys(), ...headFiles.keys()]),
640
+ ].filter((file) => baseFiles.get(file) !== headFiles.get(file));
641
+ const snapshots = await readFileSnapshot({
642
+ paths: changed.flatMap((file) => [`before/${file}`, `after/${file}`]),
643
+ read: async (key, maxBytes) => {
644
+ const before = key.startsWith("before/");
645
+ const file = key.slice(before ? 7 : 6);
646
+ if (!(before ? baseFiles : headFiles).has(file)) return "";
647
+ const blob = await this.readBlobAtRef(
648
+ before ? opts.base : opts.head,
649
+ file,
650
+ { maxBytes },
651
+ );
652
+ return blob ? new TextDecoder().decode(blob) : "";
653
+ },
654
+ });
655
+ const entries: DiffEntry[] = [];
656
+ for (const filepath of changed) {
657
+ const before = baseFiles.has(filepath)
658
+ ? (snapshots[`before/${filepath}`] ?? "")
659
+ : null;
660
+ const after = headFiles.has(filepath)
661
+ ? (snapshots[`after/${filepath}`] ?? "")
662
+ : null;
663
+ if (before === after) continue;
664
+ if (before == null && after != null) {
665
+ entries.push({
666
+ path: filepath,
667
+ kind: "added",
668
+ before: null,
669
+ after,
670
+ });
671
+ } else if (before != null && after == null) {
672
+ entries.push({
673
+ path: filepath,
674
+ kind: "deleted",
675
+ before,
676
+ after: null,
677
+ });
678
+ } else {
679
+ entries.push({
680
+ path: filepath,
681
+ kind: "modified",
682
+ before,
683
+ after,
684
+ });
685
+ }
686
+ }
687
+ return entries;
688
+ }
689
+
690
+ async moveBranch(name: string, sha: string): Promise<void> {
691
+ await git.writeRef({
692
+ fs: nodeFs,
693
+ dir: this.repoPath,
694
+ ref: `refs/heads/${name}`,
695
+ value: sha,
696
+ force: true,
697
+ });
698
+ }
699
+
700
+ async resetWorkingTree(): Promise<void> {
701
+ const matrix = await git.statusMatrix({
702
+ fs: nodeFs,
703
+ dir: this.repoPath,
704
+ });
705
+ for (const [filepath, head, workdir] of matrix) {
706
+ if (head === workdir) continue;
707
+ if (head === 0) {
708
+ await fs.unlink(path.join(this.repoPath, filepath)).catch(() => {});
709
+ } else {
710
+ await git.checkout({
711
+ fs: nodeFs,
712
+ dir: this.repoPath,
713
+ filepaths: [filepath],
714
+ force: true,
715
+ });
716
+ }
717
+ }
718
+ }
719
+
720
+ async dispose(): Promise<void> {
721
+ await this.releaseFn();
722
+ }
723
+ }
724
+
725
+ async function readBlobAtHead(
726
+ dir: string,
727
+ filepath: string,
728
+ ): Promise<string | null> {
729
+ try {
730
+ const headOid = await git.resolveRef({ fs: nodeFs, dir, ref: "HEAD" });
731
+ const { blob } = await git.readBlob({
732
+ fs: nodeFs,
733
+ dir,
734
+ oid: headOid,
735
+ filepath,
736
+ });
737
+ return new TextDecoder("utf-8").decode(blob);
738
+ } catch {
739
+ return null;
740
+ }
741
+ }
742
+
743
+ async function readWorkdirFile(
744
+ dir: string,
745
+ filepath: string,
746
+ decoder: TextDecoder,
747
+ ): Promise<string | null> {
748
+ try {
749
+ const buf = await fs.readFile(path.join(dir, filepath));
750
+ return decoder.decode(buf);
751
+ } catch {
752
+ return null;
753
+ }
754
+ }
755
+
756
+ async function tipTimestamp(dir: string, sha: string): Promise<number | null> {
757
+ if (!sha) return null;
758
+ try {
759
+ const [commit] = await git.log({
760
+ fs: nodeFs,
761
+ dir,
762
+ ref: sha,
763
+ depth: 1,
764
+ });
765
+ return commit?.commit.author.timestamp ?? null;
766
+ } catch {
767
+ return null;
768
+ }
769
+ }
770
+
771
+ async function computeAheadBehind(opts: {
772
+ dir: string;
773
+ local: string | null;
774
+ remote: string | null;
775
+ }): Promise<{ ahead: number; behind: number }> {
776
+ if (!opts.local || !opts.remote) return { ahead: 0, behind: 0 };
777
+ if (opts.local === opts.remote) return { ahead: 0, behind: 0 };
778
+
779
+ const localAncestry = await commitSet(opts.dir, opts.local);
780
+ const remoteAncestry = await commitSet(opts.dir, opts.remote);
781
+
782
+ let ahead = 0;
783
+ for (const sha of localAncestry) {
784
+ if (!remoteAncestry.has(sha)) ahead += 1;
785
+ }
786
+ let behind = 0;
787
+ for (const sha of remoteAncestry) {
788
+ if (!localAncestry.has(sha)) behind += 1;
789
+ }
790
+ return { ahead, behind };
791
+ }
792
+
793
+ async function commitSet(dir: string, ref: string): Promise<Set<string>> {
794
+ try {
795
+ const commits = await git.log({ fs: nodeFs, dir, ref, depth: 500 });
796
+ return new Set(commits.map((c) => c.oid));
797
+ } catch {
798
+ return new Set();
799
+ }
800
+ }