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

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,400 @@
1
+ import { execFile } from "node:child_process";
2
+ import fs from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import { nativeGit } from "./native-git.js";
6
+ import type { GitCredentials } from "./types.js";
7
+
8
+ /**
9
+ * A session workspace's base (ADR 0178): the ref a caller asked for on the
10
+ * project's linked remote and the commit it named when fetched.
11
+ */
12
+ export interface WorkspaceBase {
13
+ ref: string;
14
+ commit: string;
15
+ }
16
+
17
+ const COMMIT = /^[0-9a-f]{40}$|^[0-9a-f]{64}$/;
18
+
19
+ /**
20
+ * Validate a ref a caller names: a branch, a tag, a full ref such as
21
+ * `refs/pull/42/head`, or a full commit id. Anything that could be read as
22
+ * an option or a refspec (`-x`, `a:b`, `+a`) is refused.
23
+ */
24
+ export function parseWorkspaceRef(value: string): string {
25
+ const ref = value.trim();
26
+ if (COMMIT.test(ref)) return ref;
27
+ if (
28
+ ref.length === 0 ||
29
+ ref.length > 255 ||
30
+ ref.startsWith("-") ||
31
+ ref.startsWith("/") ||
32
+ ref.endsWith("/") ||
33
+ ref.endsWith(".") ||
34
+ ref.endsWith(".lock") ||
35
+ ref.includes("..") ||
36
+ ref.includes("//") ||
37
+ ref.includes("@{") ||
38
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: refusing control characters is the point
39
+ /[\s:~^?*[\\\u0000-\u001f\u007f+]/.test(ref)
40
+ ) {
41
+ throw new Error(
42
+ `'${value}' is not a branch, tag, commit, or full ref such as refs/pull/42/head`,
43
+ );
44
+ }
45
+ return ref;
46
+ }
47
+
48
+ /** Whether a ref names a commit id rather than a ref name. */
49
+ export function isCommitId(ref: string): boolean {
50
+ return COMMIT.test(ref);
51
+ }
52
+
53
+ /**
54
+ * Replica memory (a), ADR 0193: guards a bare mirror on this process's own
55
+ * disk. The mirror is a cache of commits, and each process has its own.
56
+ */
57
+ const mirrorLocks = new Map<string, Promise<unknown>>();
58
+
59
+ /** One Git operation per mirror at a time, in this process. */
60
+ async function withMirrorLock<T>(
61
+ mirrorPath: string,
62
+ work: () => Promise<T>,
63
+ ): Promise<T> {
64
+ const previous = mirrorLocks.get(mirrorPath) ?? Promise.resolve();
65
+ const next = previous.then(work, work);
66
+ const settled = next.then(
67
+ () => undefined,
68
+ () => undefined,
69
+ );
70
+ mirrorLocks.set(mirrorPath, settled);
71
+ try {
72
+ return await next;
73
+ } finally {
74
+ if (mirrorLocks.get(mirrorPath) === settled) mirrorLocks.delete(mirrorPath);
75
+ }
76
+ }
77
+
78
+ async function ensureMirror(mirrorPath: string): Promise<void> {
79
+ const exists = await fs.access(path.join(mirrorPath, "HEAD")).then(
80
+ () => true,
81
+ () => false,
82
+ );
83
+ if (exists) return;
84
+ await fs.mkdir(mirrorPath, { recursive: true });
85
+ await nativeGit(mirrorPath, ["init", "--bare", "--quiet"]);
86
+ // Pinned refs keep what sessions stand on; nothing else is kept.
87
+ await nativeGit(mirrorPath, ["config", "gc.auto", "0"]);
88
+ }
89
+
90
+ /**
91
+ * Fetch `ref` from a network remote into the host's bare mirror of it and
92
+ * pin the commit under `pin` (for example `refs/sessions/<id>`). The fetch
93
+ * is incremental: the mirror keeps what earlier sessions fetched, so a pull
94
+ * request head costs only its new objects. Credentials are sent as a header
95
+ * for this one command and never written to the mirror's configuration.
96
+ */
97
+ export async function fetchIntoMirror(opts: {
98
+ mirrorPath: string;
99
+ url: string;
100
+ credentials?: GitCredentials;
101
+ ref: string;
102
+ pin: string;
103
+ }): Promise<{ commit: string }> {
104
+ const ref = parseWorkspaceRef(opts.ref);
105
+ assertPinRef(opts.pin);
106
+ return withMirrorLock(opts.mirrorPath, async () => {
107
+ await ensureMirror(opts.mirrorPath);
108
+ const known =
109
+ isCommitId(ref) &&
110
+ (await nativeGit(opts.mirrorPath, [
111
+ "cat-file",
112
+ "-e",
113
+ `${ref}^{commit}`,
114
+ ]).then(
115
+ () => true,
116
+ () => false,
117
+ ));
118
+ if (!known) {
119
+ await nativeGit(
120
+ opts.mirrorPath,
121
+ [
122
+ "fetch",
123
+ "--quiet",
124
+ "--no-tags",
125
+ "--no-write-fetch-head",
126
+ opts.url,
127
+ `+${ref}:${opts.pin}`,
128
+ ],
129
+ opts.credentials ? { ...opts.credentials, url: opts.url } : undefined,
130
+ ).catch((error: unknown) => {
131
+ throw new Error(
132
+ `Could not fetch '${ref}' from the project's remote: ${gitErrorText(error)}`,
133
+ );
134
+ });
135
+ } else {
136
+ await nativeGit(opts.mirrorPath, ["update-ref", opts.pin, ref]);
137
+ }
138
+ const commit = (
139
+ await nativeGit(opts.mirrorPath, [
140
+ "rev-parse",
141
+ "--verify",
142
+ `${opts.pin}^{commit}`,
143
+ ])
144
+ ).trim();
145
+ return { commit };
146
+ });
147
+ }
148
+
149
+ /** Drop a pin (a closed session's base). Missing is a no-op. */
150
+ export async function unpinMirrorRef(opts: {
151
+ mirrorPath: string;
152
+ pin: string;
153
+ }): Promise<void> {
154
+ assertPinRef(opts.pin);
155
+ const exists = await fs.access(path.join(opts.mirrorPath, "HEAD")).then(
156
+ () => true,
157
+ () => false,
158
+ );
159
+ if (!exists) return;
160
+ await withMirrorLock(opts.mirrorPath, () =>
161
+ nativeGit(opts.mirrorPath, ["update-ref", "-d", opts.pin]).catch(() => ""),
162
+ );
163
+ }
164
+
165
+ /** Files that differ between two commits of the mirror, at most `limit`. */
166
+ export async function mirrorChangedFiles(opts: {
167
+ mirrorPath: string;
168
+ from: string;
169
+ to: string;
170
+ limit?: number;
171
+ }): Promise<{ files: string[]; total: number }> {
172
+ const output = await nativeGit(opts.mirrorPath, [
173
+ "diff",
174
+ "--name-only",
175
+ "--no-renames",
176
+ "-z",
177
+ opts.from,
178
+ opts.to,
179
+ ]).catch(() => "");
180
+ const all = output.split("\0").filter(Boolean);
181
+ return { files: all.slice(0, opts.limit ?? 50), total: all.length };
182
+ }
183
+
184
+ /**
185
+ * Copy a pinned commit, with its history, from the mirror into a working
186
+ * copy under `into`. Native Git negotiates what the copy already has, so a
187
+ * copy seeded from the project's main receives only the difference.
188
+ */
189
+ export async function copyFromMirror(opts: {
190
+ mirrorPath: string;
191
+ pin: string;
192
+ repoPath: string;
193
+ into: string;
194
+ }): Promise<void> {
195
+ assertPinRef(opts.pin);
196
+ assertPinRef(opts.into);
197
+ await withMirrorLock(opts.mirrorPath, () =>
198
+ nativeGit(opts.repoPath, [
199
+ "fetch",
200
+ "--quiet",
201
+ "--no-tags",
202
+ "--no-write-fetch-head",
203
+ opts.mirrorPath,
204
+ `+${opts.pin}:${opts.into}`,
205
+ ]),
206
+ );
207
+ }
208
+
209
+ /** How a base move ended (ADR 0178). */
210
+ export type BaseMoveOutcome =
211
+ | { status: "moved"; head: string }
212
+ /** The rebase stopped on conflicts and was undone; `head` is unchanged. */
213
+ | { status: "conflict"; head: string; files: string[] };
214
+
215
+ const MOVE_AUTHOR = [
216
+ "-c",
217
+ "user.name=Work",
218
+ "-c",
219
+ "user.email=system@work.software",
220
+ ] as const;
221
+
222
+ /**
223
+ * Move a checkout from base `from` to base `to`, a commit pinned in the
224
+ * mirror. `reset` discards the checkout's own commits and changes; `rebase`
225
+ * replays its commits since `from` onto `to` (keeping uncommitted changes)
226
+ * and, when that conflicts, puts everything back as it was so the caller
227
+ * can tell the agent instead of losing work.
228
+ */
229
+ export async function moveCheckoutBase(opts: {
230
+ repoPath: string;
231
+ mirrorPath: string;
232
+ pin: string;
233
+ from: string;
234
+ to: string;
235
+ update: "reset" | "rebase";
236
+ }): Promise<BaseMoveOutcome> {
237
+ await copyFromMirror({
238
+ mirrorPath: opts.mirrorPath,
239
+ pin: opts.pin,
240
+ repoPath: opts.repoPath,
241
+ into: "refs/work/base",
242
+ });
243
+ const head = async () =>
244
+ (await nativeGit(opts.repoPath, ["rev-parse", "HEAD"])).trim();
245
+ if (opts.update === "reset") {
246
+ await nativeGit(opts.repoPath, ["reset", "--quiet", "--hard", opts.to]);
247
+ await nativeGit(opts.repoPath, ["clean", "-fdq"]);
248
+ return { status: "moved", head: await head() };
249
+ }
250
+ try {
251
+ await nativeGit(opts.repoPath, [
252
+ ...MOVE_AUTHOR,
253
+ "rebase",
254
+ "--quiet",
255
+ "--autostash",
256
+ "--onto",
257
+ opts.to,
258
+ opts.from,
259
+ ]);
260
+ return { status: "moved", head: await head() };
261
+ } catch {
262
+ const files = (
263
+ await nativeGit(opts.repoPath, [
264
+ "diff",
265
+ "--name-only",
266
+ "--diff-filter=U",
267
+ ]).catch(() => "")
268
+ )
269
+ .split("\n")
270
+ .filter(Boolean);
271
+ await nativeGit(opts.repoPath, ["rebase", "--abort"]).catch(() => "");
272
+ return { status: "conflict", head: await head(), files };
273
+ }
274
+ }
275
+
276
+ /**
277
+ * A packfile holding `head` and its history back to `base`, and the
278
+ * commits a receiver must record as shallow. A sandbox seeded from it has
279
+ * the real commits (so `git log`, `diff`, and pushes of new branches work)
280
+ * without the repository's whole history.
281
+ */
282
+ export async function buildSeedPack(opts: {
283
+ repoPath: string;
284
+ head: string;
285
+ base: string;
286
+ }): Promise<{ pack: Uint8Array; shallow: string[] }> {
287
+ const depth = await nativeGit(opts.repoPath, [
288
+ "rev-list",
289
+ "--count",
290
+ `${opts.base}..${opts.head}`,
291
+ ])
292
+ .then((count) => Number.parseInt(count.trim(), 10) + 1)
293
+ .catch(() => 1);
294
+ const directory = await fs.mkdtemp(path.join(tmpdir(), "work-seed-"));
295
+ try {
296
+ await nativeGit(directory, ["init", "--bare", "--quiet"]);
297
+ // A private ref names the head for the shallow fetch below.
298
+ const pin = `refs/work/seed/${process.pid}-${Date.now()}`;
299
+ await nativeGit(opts.repoPath, ["update-ref", pin, opts.head]);
300
+ try {
301
+ await nativeGit(directory, [
302
+ "fetch",
303
+ "--quiet",
304
+ "--no-tags",
305
+ `--depth=${depth}`,
306
+ `file://${path.resolve(opts.repoPath)}`,
307
+ `+${pin}:refs/heads/main`,
308
+ ]);
309
+ } finally {
310
+ await nativeGit(opts.repoPath, ["update-ref", "-d", pin]).catch(() => "");
311
+ }
312
+ const shallow = await fs
313
+ .readFile(path.join(directory, "shallow"), "utf8")
314
+ .then((text) => text.split("\n").filter(Boolean))
315
+ .catch(() => []);
316
+ const pack = await gitOutput({
317
+ cwd: directory,
318
+ args: ["pack-objects", "--revs", "--stdout", "--quiet"],
319
+ input: `${opts.head}\n`,
320
+ });
321
+ return { pack, shallow };
322
+ } finally {
323
+ await fs.rm(directory, { recursive: true, force: true });
324
+ }
325
+ }
326
+
327
+ /**
328
+ * Shell that installs a seed pack uploaded as base64 at `packFile` into the
329
+ * repository in the current directory and records `shallow` commits. It
330
+ * leaves refs and the working tree to the caller.
331
+ */
332
+ export function seedPackInstallScript(opts: {
333
+ packFile: string;
334
+ shallow: readonly string[];
335
+ }): string {
336
+ for (const commit of opts.shallow) {
337
+ if (!COMMIT.test(commit)) throw new Error("Invalid shallow commit");
338
+ }
339
+ const gitDir = `"$(git rev-parse --git-dir)"`;
340
+ return [
341
+ `base64 -d < ${shellQuote(opts.packFile)} | git index-pack --stdin --fix-thin >/dev/null`,
342
+ `rm -f ${shellQuote(opts.packFile)}`,
343
+ ...(opts.shallow.length > 0
344
+ ? [
345
+ `touch ${gitDir}/shallow`,
346
+ `printf '%s\\n' ${opts.shallow.join(" ")} >> ${gitDir}/shallow`,
347
+ `sort -u -o ${gitDir}/shallow ${gitDir}/shallow`,
348
+ ]
349
+ : []),
350
+ ].join(" && ");
351
+ }
352
+
353
+ export function shellQuote(value: string): string {
354
+ return `'${value.replaceAll("'", `'\\''`)}'`;
355
+ }
356
+
357
+ function assertPinRef(ref: string): void {
358
+ if (!/^refs\/[A-Za-z0-9._/-]+$/.test(ref) || ref.includes("..")) {
359
+ throw new Error(`Invalid mirror ref '${ref}'`);
360
+ }
361
+ }
362
+
363
+ function gitErrorText(error: unknown): string {
364
+ const stderr =
365
+ error && typeof error === "object" && "stderr" in error
366
+ ? String(error.stderr)
367
+ : "";
368
+ const text = (stderr || (error instanceof Error ? error.message : ""))
369
+ .split("\n")
370
+ .map((line) => line.trim())
371
+ .filter((line) => line.length > 0 && !/authorization/i.test(line))
372
+ .slice(-2)
373
+ .join(" ");
374
+ return text || "the remote refused the request";
375
+ }
376
+
377
+ /** Run Git and collect its binary standard output (a pack may be large). */
378
+ function gitOutput(opts: {
379
+ cwd: string;
380
+ args: readonly string[];
381
+ input?: string;
382
+ }): Promise<Uint8Array> {
383
+ return new Promise((resolve, reject) => {
384
+ const child = execFile(
385
+ "git",
386
+ ["-C", opts.cwd, ...opts.args],
387
+ {
388
+ encoding: "buffer",
389
+ maxBuffer: 2 * 1024 * 1024 * 1024,
390
+ timeout: 15 * 60_000,
391
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
392
+ },
393
+ (error, stdout) => {
394
+ if (error) reject(error);
395
+ else resolve(new Uint8Array(stdout));
396
+ },
397
+ );
398
+ child.stdin?.end(opts.input ?? "");
399
+ });
400
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.