@catamorphic/git 0.1.0-alpha.42 → 0.1.0-alpha.44

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 (66) hide show
  1. package/dist/checkout-remote-backend.d.ts.map +1 -1
  2. package/dist/fs-backend.d.ts +8 -0
  3. package/dist/fs-backend.d.ts.map +1 -1
  4. package/dist/fs-remote-backend.d.ts +43 -9
  5. package/dist/fs-remote-backend.d.ts.map +1 -1
  6. package/dist/git-objects.d.ts +77 -0
  7. package/dist/git-objects.d.ts.map +1 -0
  8. package/dist/git-sync.d.ts +16 -17
  9. package/dist/git-sync.d.ts.map +1 -1
  10. package/dist/index.d.ts +6 -5
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +3912 -3059
  13. package/dist/index.js.map +23 -21
  14. package/dist/native-git.d.ts +114 -2
  15. package/dist/native-git.d.ts.map +1 -1
  16. package/dist/native-project-repo.d.ts +40 -5
  17. package/dist/native-project-repo.d.ts.map +1 -1
  18. package/dist/network-sync.d.ts.map +1 -1
  19. package/dist/network.d.ts +14 -9
  20. package/dist/network.d.ts.map +1 -1
  21. package/dist/object-origin-cache.d.ts +86 -0
  22. package/dist/object-origin-cache.d.ts.map +1 -0
  23. package/dist/object-remote-backend.d.ts +64 -10
  24. package/dist/object-remote-backend.d.ts.map +1 -1
  25. package/dist/origin-draft.d.ts.map +1 -1
  26. package/dist/origin-objects.d.ts +7 -2
  27. package/dist/origin-objects.d.ts.map +1 -1
  28. package/dist/project-manager.d.ts +22 -0
  29. package/dist/project-manager.d.ts.map +1 -1
  30. package/dist/project-paths.d.ts +20 -0
  31. package/dist/project-paths.d.ts.map +1 -0
  32. package/dist/ref-names.d.ts +35 -0
  33. package/dist/ref-names.d.ts.map +1 -1
  34. package/dist/types.d.ts +37 -4
  35. package/dist/types.d.ts.map +1 -1
  36. package/dist/workspace-checkout.d.ts +31 -0
  37. package/dist/workspace-checkout.d.ts.map +1 -0
  38. package/dist/workspace-mirror.d.ts +38 -5
  39. package/dist/workspace-mirror.d.ts.map +1 -1
  40. package/dist/workspace-save.d.ts +27 -2
  41. package/dist/workspace-save.d.ts.map +1 -1
  42. package/package.json +4 -4
  43. package/src/checkout-remote-backend.ts +77 -29
  44. package/src/fs-backend.ts +69 -7
  45. package/src/fs-remote-backend.ts +255 -133
  46. package/src/git-objects.ts +363 -0
  47. package/src/git-sync.ts +124 -453
  48. package/src/index.ts +17 -7
  49. package/src/native-git.ts +566 -25
  50. package/src/native-project-repo.ts +318 -99
  51. package/src/network-sync.ts +43 -35
  52. package/src/network.ts +177 -153
  53. package/src/object-origin-cache.ts +689 -0
  54. package/src/object-remote-backend.ts +277 -20
  55. package/src/origin-draft.ts +22 -15
  56. package/src/origin-objects.ts +21 -5
  57. package/src/project-manager.ts +261 -73
  58. package/src/project-paths.ts +142 -0
  59. package/src/ref-names.ts +56 -0
  60. package/src/types.ts +38 -4
  61. package/src/workspace-checkout.ts +192 -0
  62. package/src/workspace-mirror.ts +276 -68
  63. package/src/workspace-save.ts +99 -30
  64. package/dist/project-repo.d.ts +0 -81
  65. package/dist/project-repo.d.ts.map +0 -1
  66. package/src/project-repo.ts +0 -821
@@ -1,12 +1,15 @@
1
1
  import fs from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import path from "node:path";
4
+ import { getTracer, withSpan } from "@catamorphic/otel";
4
5
  import {
5
6
  PROJECT_GITIGNORE_PATH,
6
7
  PROJECT_MANIFEST_PATH,
8
+ publishedRef,
7
9
  } from "@catamorphic/workflow/project-layout";
8
10
  import { FsBackend } from "./fs-backend.js";
9
- import { push } from "./git-sync.js";
11
+ import { closeObjectReaders } from "./git-objects.js";
12
+ import { fetchRemote, push } from "./git-sync.js";
10
13
  import { discoverLocalFolder, nativeGit } from "./native-git.js";
11
14
  import { NativeProjectRepo } from "./native-project-repo.js";
12
15
  import { cloneFromRemote } from "./network.js";
@@ -18,7 +21,7 @@ import {
18
21
  publishFilesToOrigin,
19
22
  } from "./origin-draft.js";
20
23
  import { GitObjectCache } from "./origin-objects.js";
21
- import { ProjectRepoImpl } from "./project-repo.js";
24
+ import { assertObjectId, revisionThenPaths } from "./ref-names.js";
22
25
  import {
23
26
  currentSessionWork,
24
27
  type SessionWork,
@@ -37,6 +40,8 @@ import {
37
40
  type BaseMoveOutcome,
38
41
  copyFromMirror,
39
42
  moveCheckoutBase,
43
+ prepareMirror,
44
+ rebaseInProgress,
40
45
  } from "./workspace-mirror.js";
41
46
 
42
47
  /**
@@ -51,9 +56,37 @@ dist/
51
56
  .DS_Store
52
57
  `;
53
58
 
59
+ const tracer = getTracer("@catamorphic/git");
60
+
54
61
  /** Stands in a copy while it is seeded; a copy still holding it is unfinished. */
55
62
  const SEEDING_MARKER = ".git/work-seeding";
56
63
 
64
+ /**
65
+ * Whether a copy borrows objects from a folder that is gone (an origin's
66
+ * cache that was emptied, a temporary one a restart removed). Such a copy
67
+ * cannot be read; its origin still holds everything it published.
68
+ */
69
+ async function borrowsFromMissing(
70
+ repoPath: string,
71
+ layout: "checkout" | "bare" = "checkout",
72
+ ): Promise<boolean> {
73
+ const objects =
74
+ layout === "bare"
75
+ ? path.join(repoPath, "objects")
76
+ : path.join(repoPath, ".git", "objects");
77
+ const listed = await fs
78
+ .readFile(path.join(objects, "info", "alternates"), "utf8")
79
+ .catch(() => "");
80
+ for (const line of listed.split("\n").filter(Boolean)) {
81
+ const exists = await fs.access(path.resolve(objects, line)).then(
82
+ () => true,
83
+ () => false,
84
+ );
85
+ if (!exists) return true;
86
+ }
87
+ return false;
88
+ }
89
+
57
90
  /**
58
91
  * The identity core reads the published program as when no member reads
59
92
  * it (roles, documents, tool rosters). It contains a NUL, which no stored
@@ -72,25 +105,36 @@ const SYSTEM_AUTHOR = {
72
105
  * may have been initialized with symlinks or executable bits disabled.
73
106
  */
74
107
  async function resetSessionCheckout(repoPath: string, commit: string) {
75
- await nativeGit(repoPath, [
76
- "-c",
77
- "core.symlinks=true",
78
- "-c",
79
- "core.filemode=true",
80
- "-c",
81
- "core.autocrlf=false",
82
- "reset",
83
- "--hard",
84
- commit,
85
- ]);
108
+ assertObjectId(commit);
109
+ await nativeGit(
110
+ repoPath,
111
+ [
112
+ "-c",
113
+ "core.symlinks=true",
114
+ "-c",
115
+ "core.filemode=true",
116
+ "-c",
117
+ "core.autocrlf=false",
118
+ "reset",
119
+ "--hard",
120
+ ...revisionThenPaths(commit),
121
+ ],
122
+ undefined,
123
+ { timeoutMs: CHECKOUT_TIMEOUT_MS },
124
+ );
86
125
  }
87
126
 
127
+ /** How long writing a large repository's files into a copy may take. */
128
+ const CHECKOUT_TIMEOUT_MS = 30 * 60_000;
129
+
88
130
  export class ProjectManager {
89
131
  /** Origin objects this process has read; safe to lose. */
90
132
  private readonly objects = new GitObjectCache();
91
133
  private draftCheck: Promise<DraftSupport> | undefined;
92
134
  /** First-time copy preparations in flight, by tenant, project, and copy. */
93
135
  private readonly preparing = new Map<string, Promise<void>>();
136
+ /** Copies whose base this process is moving right now. */
137
+ private readonly moving = new Set<string>();
94
138
 
95
139
  constructor(
96
140
  private readonly storage: StorageBackend,
@@ -108,9 +152,11 @@ export class ProjectManager {
108
152
  projectId,
109
153
  externalUserId,
110
154
  );
111
- return (await this.localPath({ tenantId, projectId }))
112
- ? new NativeProjectRepo(projectId, repoPath, release)
113
- : new ProjectRepoImpl(projectId, repoPath, release);
155
+ // A person's own folder, or a copy Work manages: both are read and
156
+ // written with the Git program (ADR 0356).
157
+ return new NativeProjectRepo(projectId, repoPath, release, {
158
+ managed: !(await this.localPath({ tenantId, projectId })),
159
+ });
114
160
  }
115
161
 
116
162
  /**
@@ -276,8 +322,22 @@ export class ProjectManager {
276
322
  () => true,
277
323
  () => false,
278
324
  );
279
- if (!unfinished) return;
325
+ if (!unfinished) {
326
+ // Only a copy Work made and can make again: never a person's folder.
327
+ if (await this.localPath({ tenantId, projectId })) return;
328
+ // A folder that holds no repository (its creation or its removal
329
+ // stopped half way) is no copy: Git there would otherwise have
330
+ // nothing of its own to act on.
331
+ const whole = await fs.access(path.join(repoPath, ".git", "HEAD")).then(
332
+ () => true,
333
+ () => false,
334
+ );
335
+ if (whole && !(await borrowsFromMissing(repoPath))) return;
336
+ }
280
337
  await this.storage.deleteCopy(tenantId, projectId, externalUserId);
338
+ // Storage that would not remove it holds it for someone: leave it.
339
+ if (await this.storage.exists(tenantId, projectId, externalUserId))
340
+ return;
281
341
  }
282
342
  const repoPath = await this.storage.initProject(tenantId, projectId, {
283
343
  externalUserId,
@@ -290,7 +350,9 @@ export class ProjectManager {
290
350
  projectId,
291
351
  externalUserId,
292
352
  );
293
- const repo = new ProjectRepoImpl(projectId, repoPath, release);
353
+ const repo = new NativeProjectRepo(projectId, repoPath, release, {
354
+ managed: true,
355
+ });
294
356
  try {
295
357
  await seedFromOrigin({
296
358
  remote: this.remote,
@@ -319,11 +381,17 @@ export class ProjectManager {
319
381
  const directory = await fs.mkdtemp(
320
382
  path.join(tmpdir(), "catamorphic-checkout-"),
321
383
  );
322
- const cleanup = () => fs.rm(directory, { recursive: true, force: true });
384
+ const cleanup = async () => {
385
+ // Only this checkout reads the folder: its reader goes with it.
386
+ closeObjectReaders(directory);
387
+ await fs.rm(directory, { recursive: true, force: true });
388
+ };
323
389
  try {
324
390
  const storage = new FsBackend(directory);
325
391
  const repoPath = await storage.initProject(args.tenantId, args.projectId);
326
- const repo = new ProjectRepoImpl(args.projectId, repoPath, cleanup);
392
+ const repo = new NativeProjectRepo(args.projectId, repoPath, cleanup, {
393
+ managed: true,
394
+ });
327
395
  await seedFromOrigin({ remote: this.remote, ...args, dev: repo });
328
396
  return repo;
329
397
  } catch (error) {
@@ -347,14 +415,17 @@ export class ProjectManager {
347
415
  );
348
416
  const repo = await this.openCopy(args.tenantId, args.projectId, userId);
349
417
  try {
418
+ // Whoever is about to change the copy first finds it whole: a base
419
+ // move that stopped part way is put back on its checkpoint.
420
+ if (args.refresh) await this.settleInterruptedMove(repo);
350
421
  if (this.remote && (!existed || args.refresh)) {
351
- const { fetchRemote } = await import("./git-sync.js");
352
422
  const fetched = await fetchRemote({
353
423
  dev: repo,
354
424
  remote: this.remote,
355
425
  tenantId: args.tenantId,
356
426
  projectId: args.projectId,
357
427
  remoteBranch: `sessions/${args.sessionId}`,
428
+ borrow: true,
358
429
  });
359
430
  if (fetched.sha && fetched.sha !== (await repo.resolveRef("HEAD"))) {
360
431
  if ((await repo.status()).dirty)
@@ -421,6 +492,46 @@ export class ProjectManager {
421
492
  }
422
493
  }
423
494
 
495
+ /**
496
+ * Put a copy back on its last checkpoint when a base move left it part
497
+ * way: a rebase still in progress, or HEAD off the session's branch (the
498
+ * process stopped mid-move, or the move's undo failed). Everything the
499
+ * copy held was checkpointed before the move began, so nothing is lost;
500
+ * left as it is, the half-moved files would be saved as the chat's work.
501
+ */
502
+ private async settleInterruptedMove(repo: ProjectRepo): Promise<void> {
503
+ if (!(repo instanceof NativeProjectRepo) || !repo.managed) return;
504
+ if (this.moving.has(repo.repoPath))
505
+ throw new Error(
506
+ "This workspace's base is being moved. Try again when that has finished.",
507
+ );
508
+ const gitdir = path.join(repo.repoPath, ".git");
509
+ const head = (
510
+ await fs.readFile(path.join(gitdir, "HEAD"), "utf8").catch(() => "")
511
+ ).trim();
512
+ if (
513
+ head === "ref: refs/heads/main" &&
514
+ !(await rebaseInProgress(repo.repoPath))
515
+ )
516
+ return;
517
+ const checkpoint = (
518
+ await nativeGit(repo.repoPath, [
519
+ "rev-parse",
520
+ "--verify",
521
+ "--quiet",
522
+ "refs/heads/main^{commit}",
523
+ ]).catch(() => "")
524
+ ).trim();
525
+ // A copy with no checkpoint yet has nothing a move could have left.
526
+ if (!checkpoint) return;
527
+ await nativeGit(repo.repoPath, ["rebase", "--abort"]).catch(() => "");
528
+ for (const state of ["rebase-merge", "rebase-apply"])
529
+ await fs.rm(path.join(gitdir, state), { recursive: true, force: true });
530
+ await nativeGit(repo.repoPath, ["symbolic-ref", "HEAD", "refs/heads/main"]);
531
+ await resetSessionCheckout(repo.repoPath, checkpoint);
532
+ await repo.resetWorkingTree();
533
+ }
534
+
424
535
  private async checkpointCopy(args: {
425
536
  repo: ProjectRepo;
426
537
  sessionId: string;
@@ -433,6 +544,8 @@ export class ProjectManager {
433
544
  publish?: (head: string, previous: string) => Promise<void>;
434
545
  }): Promise<string> {
435
546
  const { repo } = args;
547
+ // Never a tree a base move left part way.
548
+ await this.settleInterruptedMove(repo);
436
549
  const recorded = await currentSessionWork({
437
550
  repoPath: repo.repoPath,
438
551
  sessionId: args.sessionId,
@@ -441,7 +554,7 @@ export class ProjectManager {
441
554
  const snapshot = await args.snapshot?.({
442
555
  repoPath: repo.repoPath,
443
556
  recorded,
444
- containLinks: repo instanceof NativeProjectRepo,
557
+ containLinks: repo instanceof NativeProjectRepo && !repo.managed,
445
558
  });
446
559
  const saved = snapshot?.work ?? args.work;
447
560
  const pushed = args.pushed ?? recorded.pushed;
@@ -521,6 +634,41 @@ export class ProjectManager {
521
634
  return this.storage.mirrorPath?.(args.tenantId, args.projectId) ?? null;
522
635
  }
523
636
 
637
+ /**
638
+ * Let the host's mirror of the project's linked repository borrow what
639
+ * the project's origin already holds on this machine (ADR 0356). The
640
+ * history that arrived when the repository was attached is then not
641
+ * downloaded a second time: fetching a ref into the mirror brings only
642
+ * what the origin lacks. A mirror whose lender is gone is emptied; it is
643
+ * a cache, and the next fetch pins what a chat stands on again.
644
+ */
645
+ async lendToMirror(args: {
646
+ tenantId: string;
647
+ projectId: string;
648
+ }): Promise<void> {
649
+ const mirrorPath = this.mirrorPath(args);
650
+ const remote = this.remote;
651
+ // A person's own folder never lends its objects.
652
+ if (!mirrorPath || !remote || (await this.localPath(args))) return;
653
+ if (!(await remote.exists(args.tenantId, args.projectId))) return;
654
+ if (await borrowsFromMissing(mirrorPath, "bare"))
655
+ await fs.rm(mirrorPath, { recursive: true, force: true });
656
+ await prepareMirror(mirrorPath);
657
+ await remote.withOrigin(args.tenantId, args.projectId, async (origin) => {
658
+ const main = await origin.resolveRef("refs/heads/main");
659
+ if (!main) return;
660
+ await origin.send({ repoPath: mirrorPath, commit: main, borrow: true });
661
+ // A ref of the mirror's own at the project's main: the remote is
662
+ // told the mirror has that history, and a commit of it is known to
663
+ // be the project's. Nothing else the origin holds is.
664
+ await nativeGit(mirrorPath, [
665
+ "update-ref",
666
+ "refs/work/origin/main",
667
+ main,
668
+ ]);
669
+ });
670
+ }
671
+
524
672
  /**
525
673
  * The commit the project's own `main` stands on: its origin's, or on a
526
674
  * host without one this machine's copy's. Where a chat starts when its
@@ -571,13 +719,13 @@ export class ProjectManager {
571
719
  into: "refs/work/base",
572
720
  });
573
721
  } else if (this.remote) {
574
- const { fetchRemote } = await import("./git-sync.js");
575
722
  await fetchRemote({
576
723
  dev: repo,
577
724
  remote: this.remote,
578
725
  tenantId: args.tenantId,
579
726
  projectId: args.projectId,
580
727
  remoteBranch: "main",
728
+ borrow: true,
581
729
  });
582
730
  } else {
583
731
  const main = await this.open(args.tenantId, args.projectId);
@@ -595,11 +743,24 @@ export class ProjectManager {
595
743
  await main.dispose();
596
744
  }
597
745
  }
598
- await nativeGit(repo.repoPath, [
599
- "cat-file",
600
- "-e",
601
- `${args.commit}^{commit}`,
602
- ]).catch(() => {
746
+ // The base must be in the history just brought, not merely somewhere
747
+ // in the copy: a copy Work manages borrows its origin's objects, where
748
+ // other chats' checkpoints and members' drafts are too (ADR 0356). A
749
+ // person's own folder borrows nothing, and stands where they put it.
750
+ const managed = repo instanceof NativeProjectRepo && repo.managed;
751
+ const within = args.pin
752
+ ? "refs/work/base"
753
+ : managed && this.remote
754
+ ? publishedRef("main")
755
+ : managed
756
+ ? "refs/work/base"
757
+ : undefined;
758
+ await nativeGit(
759
+ repo.repoPath,
760
+ within
761
+ ? ["merge-base", "--is-ancestor", args.commit, within]
762
+ : ["cat-file", "-e", `${args.commit}^{commit}`],
763
+ ).catch(() => {
603
764
  throw new Error(
604
765
  `The workspace's base ${args.commit.slice(0, 12)} is not in the project's history on this host`,
605
766
  );
@@ -664,6 +825,8 @@ export class ProjectManager {
664
825
  refresh: true,
665
826
  });
666
827
  try {
828
+ // Never a tree a base move left part way.
829
+ await this.settleInterruptedMove(repo);
667
830
  await this.bringBase({ ...args, repo });
668
831
  const previous = await repo.resolveRef("HEAD");
669
832
  const snapshot = (await repo.status()).dirty
@@ -754,10 +917,11 @@ export class ProjectManager {
754
917
  await git(["update-ref", "--no-deref", "HEAD", commit]);
755
918
  await git(["reset", "--quiet"]);
756
919
  };
757
- await stand(start);
920
+ this.moving.add(repo.repoPath);
758
921
  let outcome: BaseMoveOutcome;
759
922
  let moved: { tip: string; head: string } | undefined;
760
923
  try {
924
+ await stand(start);
761
925
  outcome = await moveCheckoutBase({
762
926
  repoPath: repo.repoPath,
763
927
  mirrorPath,
@@ -778,10 +942,18 @@ export class ProjectManager {
778
942
  head: carried ? await git(["rev-parse", `${tip}^`]) : tip,
779
943
  };
780
944
  }
945
+ } catch (error) {
946
+ // The move stopped part way (it ran too long, or could not be
947
+ // undone): the copy goes back to its checkpoint, which holds
948
+ // everything it had, before anyone reads its files as work.
949
+ this.moving.delete(repo.repoPath);
950
+ await this.settleInterruptedMove(repo).catch(() => {});
951
+ throw error;
781
952
  } finally {
782
- // Back on the session's checkpoints, whatever happened.
783
- await git(["symbolic-ref", "HEAD", "refs/heads/main"]);
953
+ this.moving.delete(repo.repoPath);
784
954
  }
955
+ // Back on the session's checkpoints.
956
+ await git(["symbolic-ref", "HEAD", "refs/heads/main"]);
785
957
  if (!moved) {
786
958
  await git(["reset", "--quiet"]);
787
959
  return { ...outcome, head: work.head };
@@ -942,27 +1114,46 @@ export class ProjectManager {
942
1114
  const local = await this.localPath({ tenantId, projectId });
943
1115
 
944
1116
  if (opts?.cloneFrom) {
945
- await cloneFromRemote({
946
- repoPath,
947
- native: Boolean(local),
948
- url: opts.cloneFrom.url,
949
- credentials: opts.cloneFrom.credentials,
950
- branch: opts.cloneFrom.branch,
951
- });
952
- const repo = local
953
- ? new NativeProjectRepo(projectId, repoPath, async () => {})
954
- : new ProjectRepoImpl(projectId, repoPath, async () => {});
955
- if (this.remote && !local) {
956
- await this.remote.initRemote(tenantId, projectId);
957
- await push({
958
- dev: repo,
959
- remote: this.remote,
960
- tenantId,
961
- projectId,
962
- remoteBranch: "main",
963
- });
964
- }
965
- return repo;
1117
+ const { cloneFrom } = opts;
1118
+ const remote = this.remote;
1119
+ // Attaching a repository: its history arrives as packs and is
1120
+ // published to the origin as packs, whatever its size (ADR 0356).
1121
+ return withSpan(
1122
+ {
1123
+ tracer,
1124
+ name: "git.project.attach",
1125
+ attributes: {
1126
+ "catamorphic.tenant.id": tenantId,
1127
+ "catamorphic.project.id": projectId,
1128
+ },
1129
+ },
1130
+ async () => {
1131
+ await cloneFromRemote({
1132
+ repoPath,
1133
+ managed: !local,
1134
+ url: cloneFrom.url,
1135
+ credentials: cloneFrom.credentials,
1136
+ branch: cloneFrom.branch,
1137
+ });
1138
+ const repo = new NativeProjectRepo(
1139
+ projectId,
1140
+ repoPath,
1141
+ async () => {},
1142
+ { managed: !local },
1143
+ );
1144
+ if (remote && !local) {
1145
+ await remote.initRemote(tenantId, projectId);
1146
+ await push({
1147
+ dev: repo,
1148
+ remote,
1149
+ tenantId,
1150
+ projectId,
1151
+ remoteBranch: "main",
1152
+ });
1153
+ }
1154
+ return repo;
1155
+ },
1156
+ );
966
1157
  }
967
1158
 
968
1159
  // No eager workspace scaffold (ADR 0043): a blank project is a git repo,
@@ -1016,9 +1207,9 @@ export class ProjectManager {
1016
1207
 
1017
1208
  // Use the path initProject returned rather than re-acquiring: when the
1018
1209
  // host supplies an explicit rootPath, that path is the initialized checkout.
1019
- const repo = local
1020
- ? new NativeProjectRepo(projectId, repoPath, async () => {})
1021
- : new ProjectRepoImpl(projectId, repoPath, async () => {});
1210
+ const repo = new NativeProjectRepo(projectId, repoPath, async () => {}, {
1211
+ managed: !local,
1212
+ });
1022
1213
 
1023
1214
  const hasHead = await repo.resolveRef("HEAD").then(
1024
1215
  () => true,
@@ -1069,29 +1260,26 @@ async function seedFromOrigin(opts: {
1069
1260
  projectId: string;
1070
1261
  dev: ProjectRepo;
1071
1262
  }): Promise<void> {
1072
- const { fetchRemote } = await import("./git-sync.js");
1263
+ // The copy borrows its origin's objects where they are on this machine,
1264
+ // so a copy of a large history costs its files, not its history.
1073
1265
  const fetched = await fetchRemote({
1074
1266
  dev: opts.dev,
1075
1267
  remote: opts.remote,
1076
1268
  tenantId: opts.tenantId,
1077
1269
  projectId: opts.projectId,
1078
1270
  remoteBranch: "main",
1271
+ borrow: true,
1079
1272
  });
1080
- if (fetched.sha) {
1081
- const nodeFs = (await import("node:fs")).default;
1082
- const git = (await import("isomorphic-git")).default;
1083
- await git.writeRef({
1084
- fs: nodeFs,
1085
- dir: opts.dev.repoPath,
1086
- ref: "refs/heads/main",
1087
- value: fetched.sha,
1088
- force: true,
1089
- });
1090
- await git.checkout({
1091
- fs: nodeFs,
1092
- dir: opts.dev.repoPath,
1093
- ref: "main",
1094
- force: true,
1095
- });
1096
- }
1273
+ if (!fetched.sha) return;
1274
+ await nativeGit(opts.dev.repoPath, [
1275
+ "update-ref",
1276
+ "refs/heads/main",
1277
+ fetched.sha,
1278
+ ]);
1279
+ await nativeGit(
1280
+ opts.dev.repoPath,
1281
+ ["reset", "--quiet", "--hard", "refs/heads/main"],
1282
+ undefined,
1283
+ { timeoutMs: CHECKOUT_TIMEOUT_MS },
1284
+ );
1097
1285
  }
@@ -0,0 +1,142 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { PROJECT_WORKSPACE_ROOT } from "@catamorphic/workflow/project-layout";
4
+ import ignore, { type Ignore } from "ignore";
5
+ import { isPersonalFile } from "./personal-files.js";
6
+
7
+ /** Directories a walk never enters. */
8
+ export const WALK_SKIPPED_DIRS: ReadonlySet<string> = new Set([
9
+ "node_modules",
10
+ ".git",
11
+ "dist",
12
+ ".turbo",
13
+ ]);
14
+
15
+ /**
16
+ * Dot-directories that are project content despite the hidden-file skip
17
+ * below. `.work/` holds authored capabilities and shared config;
18
+ * `.agents/` may contain the owner's harness instructions. Git ignore rules
19
+ * distinguish local data and build outputs from versioned content.
20
+ */
21
+ const ALLOWED_DOT_DIRS = new Set([".agents", PROJECT_WORKSPACE_ROOT]);
22
+
23
+ /**
24
+ * Dot-FILES that are project content: the seeded ignore rules must be
25
+ * committed (an untracked .gitignore reads as a permanently dirty tree,
26
+ * which would defer every remote sync).
27
+ */
28
+ const ALLOWED_DOT_FILES = new Set([".gitignore"]);
29
+
30
+ export function assertSafePath(filePath: string): void {
31
+ const normalized = path.normalize(filePath);
32
+ if (path.isAbsolute(normalized)) {
33
+ throw new Error("Absolute paths not allowed");
34
+ }
35
+ if (normalized.startsWith("..")) {
36
+ throw new Error("Path traversal detected");
37
+ }
38
+ if (isPersonalFile(normalized)) {
39
+ throw new Error(
40
+ "Personal files are local-only and cannot be accessed through project APIs",
41
+ );
42
+ }
43
+ // Any `.git` segment, in any case: case-insensitive filesystems alias it.
44
+ if (
45
+ normalized
46
+ .split(/[\\/]/)
47
+ .some((segment) => segment.toLowerCase() === ".git")
48
+ ) {
49
+ throw new Error("Cannot access .git directory");
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Refuse a path that passes through a symbolic link: a committed link must
55
+ * never let file APIs read or write outside the working copy.
56
+ */
57
+ export async function assertNoSymlinks(root: string, filePath: string) {
58
+ let current = root;
59
+ for (const segment of path.normalize(filePath).split(path.sep)) {
60
+ if (!segment || segment === ".") continue;
61
+ current = path.join(current, segment);
62
+ const stat = await fs.lstat(current).catch(() => undefined);
63
+ if (!stat) return;
64
+ if (stat.isSymbolicLink())
65
+ throw new Error("Symbolic links cannot be read or written here");
66
+ }
67
+ }
68
+
69
+ export async function walkDirectory(
70
+ dir: string,
71
+ base: string,
72
+ options?: {
73
+ excludeNestedRepositories?: boolean;
74
+ includeHidden?: boolean;
75
+ tracked: Set<string>;
76
+ trackedDirectories: Set<string>;
77
+ rules: Array<{ base: string; matcher: Ignore }>;
78
+ },
79
+ ): Promise<string[]> {
80
+ if (
81
+ options?.excludeNestedRepositories &&
82
+ dir !== base &&
83
+ (await fs.stat(path.join(dir, ".git")).then(
84
+ () => true,
85
+ () => false,
86
+ ))
87
+ )
88
+ return [];
89
+ const rules = options ? [...options.rules] : [];
90
+ if (options) {
91
+ const content = await fs
92
+ .readFile(path.join(dir, ".gitignore"), "utf8")
93
+ .catch(() => "");
94
+ if (content) rules.push({ base: dir, matcher: ignore().add(content) });
95
+ }
96
+ const entries = await fs.readdir(dir, { withFileTypes: true });
97
+ const results: string[] = [];
98
+
99
+ for (const entry of entries) {
100
+ if (WALK_SKIPPED_DIRS.has(entry.name)) continue;
101
+ if (
102
+ !options?.includeHidden &&
103
+ entry.name.startsWith(".") &&
104
+ !ALLOWED_DOT_DIRS.has(entry.name) &&
105
+ !ALLOWED_DOT_FILES.has(entry.name)
106
+ )
107
+ continue;
108
+
109
+ const fullPath = path.join(dir, entry.name);
110
+ const relativePath = path.relative(base, fullPath);
111
+ if (isPersonalFile(relativePath)) continue;
112
+
113
+ if (options) {
114
+ let ignored = false;
115
+ for (const rule of rules) {
116
+ const result = rule.matcher.test(
117
+ path.relative(rule.base, fullPath) + (entry.isDirectory() ? "/" : ""),
118
+ );
119
+ if (result.ignored) ignored = true;
120
+ if (result.unignored) ignored = false;
121
+ }
122
+ if (
123
+ ignored &&
124
+ !options.tracked.has(relativePath) &&
125
+ !options.trackedDirectories.has(relativePath)
126
+ )
127
+ continue;
128
+ }
129
+ if (entry.isDirectory()) {
130
+ const nested = await walkDirectory(
131
+ fullPath,
132
+ base,
133
+ options ? { ...options, rules } : undefined,
134
+ );
135
+ results.push(...nested);
136
+ } else {
137
+ results.push(relativePath);
138
+ }
139
+ }
140
+
141
+ return results;
142
+ }