@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,743 @@
1
+ import fs from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import path from "node:path";
4
+ import {
5
+ PROJECT_GITIGNORE_PATH,
6
+ PROJECT_MANIFEST_PATH,
7
+ } from "@catamorphic/workflow/project-layout";
8
+ import { FsBackend } from "./fs-backend.js";
9
+ import { push } from "./git-sync.js";
10
+ import { discoverLocalFolder } from "./native-git.js";
11
+ import { NativeProjectRepo } from "./native-project-repo.js";
12
+ import { cloneFromRemote } from "./network.js";
13
+ import {
14
+ type DraftPublishResult,
15
+ DraftsUnsupportedError,
16
+ OriginDraftRepo,
17
+ type ProjectDraft,
18
+ publishFilesToOrigin,
19
+ } from "./origin-draft.js";
20
+ import { GitObjectCache } from "./origin-objects.js";
21
+ import { ProjectRepoImpl } from "./project-repo.js";
22
+ import type {
23
+ DraftSupport,
24
+ GitCredentials,
25
+ ProjectPathResolver,
26
+ ProjectRepo,
27
+ RemoteBackend,
28
+ StorageBackend,
29
+ } from "./types.js";
30
+ import {
31
+ type BaseMoveOutcome,
32
+ copyFromMirror,
33
+ moveCheckoutBase,
34
+ } from "./workspace-mirror.js";
35
+
36
+ /**
37
+ * Seeded into every new project (unless one exists): mirrors the
38
+ * checkpoint walker's IGNORED_DIRS so git status and the walker agree on
39
+ * what a project's history never contains.
40
+ */
41
+ export const PROJECT_GITIGNORE = `/app-data/
42
+ node_modules/
43
+ dist/
44
+ .turbo/
45
+ .DS_Store
46
+ `;
47
+
48
+ /** Stands in a copy while it is seeded; a copy still holding it is unfinished. */
49
+ const SEEDING_MARKER = ".git/work-seeding";
50
+
51
+ /**
52
+ * The identity core reads the published program as when no member reads
53
+ * it (roles, documents, tool rosters). It contains a NUL, which no stored
54
+ * user id can hold, so it never names a member's draft; `openDraft` opens
55
+ * the published program for it.
56
+ */
57
+ export const PROGRAM_READER_ID = "\u0000program-reader";
58
+
59
+ const SYSTEM_AUTHOR = {
60
+ name: "Work",
61
+ email: "system@work.software",
62
+ };
63
+
64
+ export class ProjectManager {
65
+ /** Origin objects this process has read; safe to lose. */
66
+ private readonly objects = new GitObjectCache();
67
+ private draftCheck: Promise<DraftSupport> | undefined;
68
+ /** First-time copy preparations in flight, by tenant, project, and copy. */
69
+ private readonly preparing = new Map<string, Promise<void>>();
70
+
71
+ constructor(
72
+ private readonly storage: StorageBackend,
73
+ private readonly remote?: RemoteBackend,
74
+ private readonly localRoots?: ProjectPathResolver,
75
+ ) {}
76
+
77
+ async open(
78
+ tenantId: string,
79
+ projectId: string,
80
+ externalUserId?: string,
81
+ ): Promise<ProjectRepo> {
82
+ const { repoPath, release } = await this.storage.acquireProject(
83
+ tenantId,
84
+ projectId,
85
+ externalUserId,
86
+ );
87
+ return (await this.localPath({ tenantId, projectId }))
88
+ ? new NativeProjectRepo(projectId, repoPath, release)
89
+ : new ProjectRepoImpl(projectId, repoPath, release);
90
+ }
91
+
92
+ /**
93
+ * A member's draft of the program (ADR 0191). A project in a local folder
94
+ * is its own draft, the folder itself. A project with a durable origin
95
+ * keeps each member's draft as a ref in it (`refs/work/drafts/<member>`),
96
+ * read and written as objects: every replica sees the same draft and none
97
+ * holds it on disk. Only a host without an origin keeps a working copy
98
+ * per member on this machine.
99
+ */
100
+ async openDraft(input: {
101
+ tenantId: string;
102
+ projectId: string;
103
+ externalUserId: string;
104
+ }): Promise<ProjectDraft> {
105
+ if (input.externalUserId === PROGRAM_READER_ID)
106
+ return this.openPublished(input);
107
+ if (await this.localPath(input))
108
+ return this.open(input.tenantId, input.projectId, input.externalUserId);
109
+ if (this.remote) {
110
+ const support = await this.draftSupport();
111
+ if (!support.supported) throw new DraftsUnsupportedError(support.reason);
112
+ return new OriginDraftRepo({
113
+ ...input,
114
+ remote: this.remote,
115
+ cache: this.objects,
116
+ });
117
+ }
118
+ return this.openCopy(input.tenantId, input.projectId, input.externalUserId);
119
+ }
120
+
121
+ /**
122
+ * Whether this host's origin can keep members' drafts (ADR 0191), checked
123
+ * once per process: hosts call it at boot to fail fast, and
124
+ * {@link openDraft} refuses drafts on an origin that cannot keep them.
125
+ */
126
+ draftSupport(): Promise<DraftSupport> {
127
+ // A check that could not run (a transient store error) is not an
128
+ // answer: the next call asks again.
129
+ this.draftCheck ??= (
130
+ this.remote?.draftSupport
131
+ ? this.remote.draftSupport()
132
+ : Promise.resolve<DraftSupport>({ supported: true })
133
+ ).catch((error: unknown) => {
134
+ this.draftCheck = undefined;
135
+ throw error;
136
+ });
137
+ return this.draftCheck;
138
+ }
139
+
140
+ /**
141
+ * The published program, read by no member: a project's local folder, or
142
+ * a read-only view of its origin's `main` (no draft is ever read or
143
+ * created), or this machine's copy on a host without an origin.
144
+ */
145
+ async openPublished(input: {
146
+ tenantId: string;
147
+ projectId: string;
148
+ }): Promise<ProjectDraft> {
149
+ if (this.remote && !(await this.localPath(input)))
150
+ return new OriginDraftRepo({
151
+ ...input,
152
+ externalUserId: null,
153
+ remote: this.remote,
154
+ cache: this.objects,
155
+ });
156
+ return this.open(input.tenantId, input.projectId);
157
+ }
158
+
159
+ /**
160
+ * The folder a member's `store/` view is mirrored in around agent turns
161
+ * when their draft has no folder of its own (a server draft), or null
162
+ * when this storage keeps no local folders. A disposable cache: the
163
+ * store itself lives behind the documents service.
164
+ */
165
+ async draftStoreFolder(input: {
166
+ tenantId: string;
167
+ projectId: string;
168
+ externalUserId: string;
169
+ }): Promise<string | null> {
170
+ const folder = this.storage.cachePath?.(
171
+ input.tenantId,
172
+ input.projectId,
173
+ `store-${input.externalUserId}`,
174
+ );
175
+ if (!folder) return null;
176
+ await fs.mkdir(folder, { recursive: true });
177
+ return folder;
178
+ }
179
+
180
+ /**
181
+ * Publish files as one commit on the origin's `main`, never touching a
182
+ * member's draft (ADR 0191). With `base`, the commit the files were
183
+ * edited from, they merge with what was published since and report
184
+ * conflicts instead of overwriting.
185
+ */
186
+ async publishFiles(input: {
187
+ tenantId: string;
188
+ projectId: string;
189
+ files: Record<string, string>;
190
+ base?: string;
191
+ message: string;
192
+ author: { name: string; email: string };
193
+ guard?: (paths: readonly string[]) => void;
194
+ }): Promise<DraftPublishResult> {
195
+ if (!this.remote)
196
+ throw new Error("Publishing requires durable project storage");
197
+ return publishFilesToOrigin({
198
+ ...input,
199
+ remote: this.remote,
200
+ cache: this.objects,
201
+ });
202
+ }
203
+
204
+ /**
205
+ * Open (creating if needed) this machine's working copy `copyId` of a
206
+ * project, seeded from the origin's `main` when it is new: a session's
207
+ * copy, or a member's copy on a host without an origin.
208
+ */
209
+ private async openCopy(
210
+ tenantId: string,
211
+ projectId: string,
212
+ externalUserId: string,
213
+ ): Promise<ProjectRepo> {
214
+ // Two first opens of one copy in this process share one preparation,
215
+ // so neither reads objects the other has not finished writing.
216
+ const key = JSON.stringify([tenantId, projectId, externalUserId]);
217
+ let pending = this.preparing.get(key);
218
+ if (!pending) {
219
+ pending = this.prepareCopy({
220
+ tenantId,
221
+ projectId,
222
+ externalUserId,
223
+ }).finally(() => this.preparing.delete(key));
224
+ this.preparing.set(key, pending);
225
+ }
226
+ await pending;
227
+ return this.open(tenantId, projectId, externalUserId);
228
+ }
229
+
230
+ /**
231
+ * Create a copy seeded from the origin's `main` unless a complete one
232
+ * exists. A marker stands in the copy while it is seeded: a seeding that
233
+ * failed, or a process that stopped part way, leaves a copy the next open
234
+ * starts over instead of treating as ready.
235
+ */
236
+ private async prepareCopy(args: {
237
+ tenantId: string;
238
+ projectId: string;
239
+ externalUserId: string;
240
+ }): Promise<void> {
241
+ const { tenantId, projectId, externalUserId } = args;
242
+ if (await this.storage.exists(tenantId, projectId, externalUserId)) {
243
+ const { repoPath, release } = await this.storage.acquireProject(
244
+ tenantId,
245
+ projectId,
246
+ externalUserId,
247
+ );
248
+ await release();
249
+ const unfinished = await fs
250
+ .access(path.join(repoPath, SEEDING_MARKER))
251
+ .then(
252
+ () => true,
253
+ () => false,
254
+ );
255
+ if (!unfinished) return;
256
+ await this.storage.deleteCopy(tenantId, projectId, externalUserId);
257
+ }
258
+ const repoPath = await this.storage.initProject(tenantId, projectId, {
259
+ externalUserId,
260
+ });
261
+ if (!this.remote) return;
262
+ const marker = path.join(repoPath, SEEDING_MARKER);
263
+ await fs.writeFile(marker, "");
264
+ const { release } = await this.storage.acquireProject(
265
+ tenantId,
266
+ projectId,
267
+ externalUserId,
268
+ );
269
+ const repo = new ProjectRepoImpl(projectId, repoPath, release);
270
+ try {
271
+ await seedFromOrigin({
272
+ remote: this.remote,
273
+ tenantId,
274
+ projectId,
275
+ dev: repo,
276
+ });
277
+ await fs.rm(marker, { force: true });
278
+ } catch (error) {
279
+ await repo.dispose();
280
+ await this.storage
281
+ .deleteCopy(tenantId, projectId, externalUserId)
282
+ .catch(() => {});
283
+ throw error;
284
+ }
285
+ await repo.dispose();
286
+ }
287
+
288
+ /** An isolated origin snapshot, removed on disposal even with host-mapped projects. */
289
+ async openEphemeral(args: {
290
+ tenantId: string;
291
+ projectId: string;
292
+ }): Promise<ProjectRepo> {
293
+ if (!this.remote)
294
+ throw new Error("An ephemeral checkout requires durable project storage");
295
+ const directory = await fs.mkdtemp(
296
+ path.join(tmpdir(), "catamorphic-checkout-"),
297
+ );
298
+ const cleanup = () => fs.rm(directory, { recursive: true, force: true });
299
+ try {
300
+ const storage = new FsBackend(directory);
301
+ const repoPath = await storage.initProject(args.tenantId, args.projectId);
302
+ const repo = new ProjectRepoImpl(args.projectId, repoPath, cleanup);
303
+ await seedFromOrigin({ remote: this.remote, ...args, dev: repo });
304
+ return repo;
305
+ } catch (error) {
306
+ await cleanup();
307
+ throw error;
308
+ }
309
+ }
310
+
311
+ /** A recoverable session checkout; its branch never publishes project policy. */
312
+ async openSession(args: {
313
+ tenantId: string;
314
+ projectId: string;
315
+ sessionId: string;
316
+ refresh?: boolean;
317
+ }): Promise<ProjectRepo> {
318
+ const userId = `session-${args.sessionId}`;
319
+ const existed = await this.storage.exists(
320
+ args.tenantId,
321
+ args.projectId,
322
+ userId,
323
+ );
324
+ const repo = await this.openCopy(args.tenantId, args.projectId, userId);
325
+ try {
326
+ if (this.remote && (!existed || args.refresh)) {
327
+ const { fetchRemote } = await import("./git-sync.js");
328
+ const fetched = await fetchRemote({
329
+ dev: repo,
330
+ remote: this.remote,
331
+ tenantId: args.tenantId,
332
+ projectId: args.projectId,
333
+ remoteBranch: `sessions/${args.sessionId}`,
334
+ });
335
+ if (fetched.sha && fetched.sha !== (await repo.resolveRef("HEAD"))) {
336
+ if ((await repo.status()).dirty)
337
+ throw new Error(
338
+ "Session has uncheckpointed work on this machine. Recover it before moving the session.",
339
+ );
340
+ await repo.moveBranch("main", fetched.sha);
341
+ await repo.checkout("main");
342
+ }
343
+ }
344
+ return repo;
345
+ } catch (error) {
346
+ await repo.dispose();
347
+ throw error;
348
+ }
349
+ }
350
+
351
+ async checkpointSession(args: {
352
+ tenantId: string;
353
+ projectId: string;
354
+ sessionId: string;
355
+ message: string;
356
+ author: { name: string; email: string };
357
+ }): Promise<string> {
358
+ const repo = await this.openSession(args);
359
+ try {
360
+ const sha = (await repo.status()).dirty
361
+ ? await repo.commit(args.message, args.author)
362
+ : await repo.resolveRef("HEAD");
363
+ if (this.remote)
364
+ await push({
365
+ dev: repo,
366
+ remote: this.remote,
367
+ tenantId: args.tenantId,
368
+ projectId: args.projectId,
369
+ remoteBranch: `sessions/${args.sessionId}`,
370
+ localSha: sha,
371
+ });
372
+ return sha;
373
+ } finally {
374
+ await repo.dispose();
375
+ }
376
+ }
377
+
378
+ /**
379
+ * The host's bare mirror of the project's linked remote, or null when
380
+ * this storage keeps none (ADR 0178).
381
+ */
382
+ mirrorPath(args: { tenantId: string; projectId: string }): string | null {
383
+ return this.storage.mirrorPath?.(args.tenantId, args.projectId) ?? null;
384
+ }
385
+
386
+ /**
387
+ * Put a session's copy at a commit pinned in the project mirror and
388
+ * publish it as the session's branch (ADR 0178). Whatever the copy held is
389
+ * replaced: callers move the base only between turns, after the last
390
+ * checkpoint, or on purpose (`reset`).
391
+ */
392
+ async setSessionBase(args: {
393
+ tenantId: string;
394
+ projectId: string;
395
+ sessionId: string;
396
+ pin: string;
397
+ commit: string;
398
+ }): Promise<void> {
399
+ const mirrorPath = this.mirrorPath(args);
400
+ if (!mirrorPath) throw new Error("This host keeps no project mirror");
401
+ const repo = await this.openSession({
402
+ tenantId: args.tenantId,
403
+ projectId: args.projectId,
404
+ sessionId: args.sessionId,
405
+ refresh: true,
406
+ });
407
+ try {
408
+ await copyFromMirror({
409
+ mirrorPath,
410
+ pin: args.pin,
411
+ repoPath: repo.repoPath,
412
+ into: "refs/work/base",
413
+ });
414
+ await repo.moveBranch("main", args.commit);
415
+ await repo.checkout("main");
416
+ await repo.resetWorkingTree();
417
+ await this.publishSession({ ...args, repo, head: args.commit });
418
+ } finally {
419
+ await repo.dispose();
420
+ }
421
+ }
422
+
423
+ /**
424
+ * Move a session's copy to a new base pinned in the mirror (ADR 0178):
425
+ * `reset` replaces its checkpoints, `rebase` replays them onto the new
426
+ * base. A conflicting rebase leaves the copy as it was.
427
+ */
428
+ async moveSessionBase(args: {
429
+ tenantId: string;
430
+ projectId: string;
431
+ sessionId: string;
432
+ pin: string;
433
+ from: string;
434
+ to: string;
435
+ update: "reset" | "rebase";
436
+ }): Promise<BaseMoveOutcome> {
437
+ const mirrorPath = this.mirrorPath(args);
438
+ if (!mirrorPath) throw new Error("This host keeps no project mirror");
439
+ const repo = await this.openSession({
440
+ tenantId: args.tenantId,
441
+ projectId: args.projectId,
442
+ sessionId: args.sessionId,
443
+ refresh: true,
444
+ });
445
+ try {
446
+ const outcome = await moveCheckoutBase({
447
+ repoPath: repo.repoPath,
448
+ mirrorPath,
449
+ pin: args.pin,
450
+ from: args.from,
451
+ to: args.to,
452
+ update: args.update,
453
+ });
454
+ if (outcome.status === "moved")
455
+ await this.publishSession({ ...args, repo, head: outcome.head });
456
+ return outcome;
457
+ } finally {
458
+ await repo.dispose();
459
+ }
460
+ }
461
+
462
+ private async publishSession(args: {
463
+ tenantId: string;
464
+ projectId: string;
465
+ sessionId: string;
466
+ repo: ProjectRepo;
467
+ head: string;
468
+ }): Promise<void> {
469
+ if (!this.remote) return;
470
+ await push({
471
+ dev: args.repo,
472
+ remote: this.remote,
473
+ tenantId: args.tenantId,
474
+ projectId: args.projectId,
475
+ remoteBranch: `sessions/${args.sessionId}`,
476
+ localSha: args.head,
477
+ force: true,
478
+ });
479
+ }
480
+
481
+ /**
482
+ * Put a session's copy back at one of its own commits, discarding what
483
+ * came after (a rollback, ADR 0197), and publish it as the session's
484
+ * branch so its next sandbox is seeded from there.
485
+ */
486
+ async resetSession(args: {
487
+ tenantId: string;
488
+ projectId: string;
489
+ sessionId: string;
490
+ commit: string;
491
+ }): Promise<void> {
492
+ const repo = await this.openSession({
493
+ tenantId: args.tenantId,
494
+ projectId: args.projectId,
495
+ sessionId: args.sessionId,
496
+ refresh: true,
497
+ });
498
+ try {
499
+ await repo.moveBranch("main", args.commit);
500
+ await repo.checkout("main");
501
+ await repo.resetWorkingTree();
502
+ await this.publishSession({ ...args, repo, head: args.commit });
503
+ } finally {
504
+ await repo.dispose();
505
+ }
506
+ }
507
+
508
+ /**
509
+ * Forget a closed session's workspace: its `sessions/<id>` branch on the
510
+ * origin and its `session-<id>` copy on this machine. Commits already
511
+ * reachable elsewhere stay; missing pieces are no-ops.
512
+ */
513
+ async deleteSession(args: {
514
+ tenantId: string;
515
+ projectId: string;
516
+ sessionId: string;
517
+ }): Promise<void> {
518
+ if (
519
+ this.remote &&
520
+ (await this.remote.exists(args.tenantId, args.projectId))
521
+ )
522
+ await this.remote.withOrigin(args.tenantId, args.projectId, (origin) =>
523
+ origin.deleteRef({ ref: `refs/heads/sessions/${args.sessionId}` }),
524
+ );
525
+ await this.storage.deleteCopy(
526
+ args.tenantId,
527
+ args.projectId,
528
+ `session-${args.sessionId}`,
529
+ );
530
+ }
531
+
532
+ async localPath(input: {
533
+ tenantId: string;
534
+ projectId: string;
535
+ }): Promise<string | null> {
536
+ return (await this.localRoots?.(input.tenantId, input.projectId)) ?? null;
537
+ }
538
+
539
+ async create(
540
+ tenantId: string,
541
+ projectId: string,
542
+ opts?: {
543
+ name?: string;
544
+ initialFiles?: Record<string, string>;
545
+ externalUserId?: string;
546
+ /** Explicit directory for the working copy (user-visible folder). */
547
+ rootPath?: string;
548
+ /**
549
+ * Attach an existing Git checkout without writing files or history.
550
+ * The host handles explicit initialization of folders without Git.
551
+ */
552
+ importExisting?: boolean;
553
+ /**
554
+ * Start with no files at all: another authority fills the copy (a
555
+ * member's local copy of a server project), so no local manifest or
556
+ * seed may compete with the server's own on the first sync.
557
+ */
558
+ empty?: boolean;
559
+ /**
560
+ * Populate the working copy by cloning a network git remote (e.g. a
561
+ * GitHub repo) instead of scaffolding. Mutually exclusive with
562
+ * `importExisting`; `initialFiles` are skipped so the imported history
563
+ * stays pristine.
564
+ */
565
+ cloneFrom?: {
566
+ url: string;
567
+ credentials?: GitCredentials;
568
+ branch?: string;
569
+ };
570
+ },
571
+ ): Promise<ProjectRepo> {
572
+ if (opts?.importExisting) {
573
+ if (!opts.rootPath)
574
+ throw new Error("Opening a repository requires its folder path");
575
+ const checkout = await discoverLocalFolder({ path: opts.rootPath });
576
+ const local = await this.localPath({ tenantId, projectId });
577
+ if (!local || (await fs.realpath(local)) !== checkout.path)
578
+ throw new Error(
579
+ "Register the checkout's canonical folder with localCheckouts before importing it",
580
+ );
581
+ return new NativeProjectRepo(projectId, checkout.path, async () => {});
582
+ }
583
+ const repoPath = await this.storage.initProject(tenantId, projectId, {
584
+ externalUserId: opts?.externalUserId,
585
+ rootPath: opts?.rootPath,
586
+ });
587
+ const projectName = opts?.name ?? "my-project";
588
+ const local = await this.localPath({ tenantId, projectId });
589
+
590
+ if (opts?.cloneFrom) {
591
+ await cloneFromRemote({
592
+ repoPath,
593
+ native: Boolean(local),
594
+ url: opts.cloneFrom.url,
595
+ credentials: opts.cloneFrom.credentials,
596
+ branch: opts.cloneFrom.branch,
597
+ });
598
+ const repo = local
599
+ ? new NativeProjectRepo(projectId, repoPath, async () => {})
600
+ : new ProjectRepoImpl(projectId, repoPath, async () => {});
601
+ if (this.remote && !local) {
602
+ await this.remote.initRemote(tenantId, projectId);
603
+ await push({
604
+ dev: repo,
605
+ remote: this.remote,
606
+ tenantId,
607
+ projectId,
608
+ remoteBranch: "main",
609
+ });
610
+ }
611
+ return repo;
612
+ }
613
+
614
+ // No eager workspace scaffold (ADR 0043): a blank project is a git repo,
615
+ // a manifest, and whatever `initialFiles` (seed skills or a template's
616
+ // file map) provide. The workflow workspace arrives on demand.
617
+ const manifestPath = path.join(repoPath, PROJECT_MANIFEST_PATH);
618
+ const manifestExists = await fs.access(manifestPath).then(
619
+ () => true,
620
+ () => false,
621
+ );
622
+ if (!manifestExists && !opts?.empty) {
623
+ await fs.mkdir(path.dirname(manifestPath), { recursive: true });
624
+ await fs.writeFile(
625
+ manifestPath,
626
+ `${JSON.stringify(
627
+ {
628
+ name: projectName,
629
+ environments: {
630
+ default: {
631
+ description: "Run where this host places work",
632
+ workloads: ["agent", "workflow"],
633
+ },
634
+ },
635
+ defaultEnvironment: "default",
636
+ },
637
+ null,
638
+ 2,
639
+ )}\n`,
640
+ );
641
+ }
642
+
643
+ // Every project gets ignore rules from birth: without them the first
644
+ // `bun install` floods git status (and every changes UI) with the
645
+ // whole node_modules tree. Never overwrite one the user already has.
646
+ const gitignorePath = path.join(repoPath, PROJECT_GITIGNORE_PATH);
647
+ const gitignoreExists = await fs.access(gitignorePath).then(
648
+ () => true,
649
+ () => false,
650
+ );
651
+ if (!gitignoreExists && !opts?.empty) {
652
+ await fs.writeFile(gitignorePath, PROJECT_GITIGNORE);
653
+ }
654
+
655
+ if (opts?.initialFiles && !opts.empty) {
656
+ for (const [filePath, content] of Object.entries(opts.initialFiles)) {
657
+ const fullPath = path.join(repoPath, filePath);
658
+ await fs.mkdir(path.dirname(fullPath), { recursive: true });
659
+ await fs.writeFile(fullPath, content);
660
+ }
661
+ }
662
+
663
+ // Use the path initProject returned rather than re-acquiring: when the
664
+ // host supplies an explicit rootPath, that path is the initialized checkout.
665
+ const repo = local
666
+ ? new NativeProjectRepo(projectId, repoPath, async () => {})
667
+ : new ProjectRepoImpl(projectId, repoPath, async () => {});
668
+
669
+ const hasHead = await repo.resolveRef("HEAD").then(
670
+ () => true,
671
+ () => false,
672
+ );
673
+ if (!hasHead) {
674
+ // An empty copy (another authority fills it) still starts a history.
675
+ await repo.commit("Initial commit", SYSTEM_AUTHOR, { allowEmpty: true });
676
+ }
677
+
678
+ if (this.remote) {
679
+ await this.remote.initRemote(tenantId, projectId);
680
+ await push({
681
+ dev: repo,
682
+ remote: this.remote,
683
+ tenantId,
684
+ projectId,
685
+ remoteBranch: "main",
686
+ });
687
+ }
688
+
689
+ return repo;
690
+ }
691
+
692
+ async delete(tenantId: string, projectId: string): Promise<void> {
693
+ await this.storage.deleteProject(tenantId, projectId);
694
+ if (this.remote) {
695
+ await this.remote.deleteRemote(tenantId, projectId).catch(() => {});
696
+ }
697
+ }
698
+
699
+ async exists(
700
+ tenantId: string,
701
+ projectId: string,
702
+ externalUserId?: string,
703
+ ): Promise<boolean> {
704
+ return this.storage.exists(tenantId, projectId, externalUserId);
705
+ }
706
+
707
+ get remoteBackend(): RemoteBackend | undefined {
708
+ return this.remote;
709
+ }
710
+ }
711
+
712
+ async function seedFromOrigin(opts: {
713
+ remote: RemoteBackend;
714
+ tenantId: string;
715
+ projectId: string;
716
+ dev: ProjectRepo;
717
+ }): Promise<void> {
718
+ const { fetchRemote } = await import("./git-sync.js");
719
+ const fetched = await fetchRemote({
720
+ dev: opts.dev,
721
+ remote: opts.remote,
722
+ tenantId: opts.tenantId,
723
+ projectId: opts.projectId,
724
+ remoteBranch: "main",
725
+ });
726
+ if (fetched.sha) {
727
+ const nodeFs = (await import("node:fs")).default;
728
+ const git = (await import("isomorphic-git")).default;
729
+ await git.writeRef({
730
+ fs: nodeFs,
731
+ dir: opts.dev.repoPath,
732
+ ref: "refs/heads/main",
733
+ value: fetched.sha,
734
+ force: true,
735
+ });
736
+ await git.checkout({
737
+ fs: nodeFs,
738
+ dir: opts.dev.repoPath,
739
+ ref: "main",
740
+ force: true,
741
+ });
742
+ }
743
+ }