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

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.
@@ -373,7 +373,8 @@ export class OriginObjects {
373
373
  if (segments.slice(0, -1).some((segment) => ALWAYS_IGNORED.has(segment)))
374
374
  return true;
375
375
  if (!treeOid) return false;
376
- if (await this.entry(treeOid, filePath)) return false;
376
+ // A path through a link is tracked by nothing; the write itself says so.
377
+ if (await this.entry(treeOid, filePath).catch(() => null)) return false;
377
378
  let ignored = false;
378
379
  for (let depth = 0; depth < segments.length; depth++) {
379
380
  const directory = segments.slice(0, depth).join("/");
@@ -401,14 +402,18 @@ export class OriginObjects {
401
402
  * `treeOid` with `changes` applied (path to an existing blob, or `null`
402
403
  * to delete), written to the origin. Returns the new tree id. With
403
404
  * `skipMissingDeletes`, deleting a path the tree lacks is not an error.
405
+ * With `replaceLinks`, a change to a path that is a link replaces or
406
+ * deletes the link's own entry; a path through a link is always refused.
407
+ * A file may take the place of a folder whose every file the same
408
+ * changes delete.
404
409
  */
405
410
  async writeTree(
406
411
  treeOid: string | null,
407
412
  changes: ReadonlyMap<string, TreeChange>,
408
- options?: { skipMissingDeletes?: boolean },
413
+ options?: { skipMissingDeletes?: boolean; replaceLinks?: boolean },
409
414
  ): Promise<string> {
410
415
  return (
411
- (await this.rewrite(treeOid, changes, "", options?.skipMissingDeletes)) ??
416
+ (await this.rewrite(treeOid, changes, "", options ?? {})) ??
412
417
  this.write({ type: "tree", data: new Uint8Array() })
413
418
  );
414
419
  }
@@ -417,8 +422,9 @@ export class OriginObjects {
417
422
  treeOid: string | null,
418
423
  changes: ReadonlyMap<string, TreeChange>,
419
424
  base: string,
420
- skipMissingDeletes = false,
425
+ options: { skipMissingDeletes?: boolean; replaceLinks?: boolean },
421
426
  ): Promise<string | null> {
427
+ const skipMissingDeletes = options.skipMissingDeletes ?? false;
422
428
  // Keyed by the stored bytes, so names that are not UTF-8 (and would
423
429
  // decode alike) stay distinct entries.
424
430
  const entries = new Map(
@@ -428,21 +434,41 @@ export class OriginObjects {
428
434
  ]),
429
435
  );
430
436
  const keyed = (name: string) => nameKey(new TextEncoder().encode(name));
437
+ const leaves = new Map<string, TreeChange>();
431
438
  const nested = new Map<string, Map<string, TreeChange>>();
432
439
  for (const [filePath, change] of changes) {
433
440
  const slash = filePath.indexOf("/");
434
- if (slash >= 0) {
435
- const directory = filePath.slice(0, slash);
436
- const inner = nested.get(directory) ?? new Map<string, TreeChange>();
437
- inner.set(filePath.slice(slash + 1), change);
438
- nested.set(directory, inner);
441
+ if (slash < 0) {
442
+ leaves.set(filePath, change);
439
443
  continue;
440
444
  }
441
- const existing = entries.get(keyed(filePath));
445
+ const directory = filePath.slice(0, slash);
446
+ const inner = nested.get(directory) ?? new Map<string, TreeChange>();
447
+ inner.set(filePath.slice(slash + 1), change);
448
+ nested.set(directory, inner);
449
+ }
450
+ for (const [filePath, change] of leaves) {
442
451
  const fullPath = `${base}${filePath}`;
452
+ const inside = nested.get(filePath);
453
+ const found = entries.get(keyed(filePath));
454
+ // A file where a folder was: the folder goes when the same changes
455
+ // delete everything in it.
456
+ if (
457
+ found &&
458
+ isTreeMode(found.mode) &&
459
+ change !== null &&
460
+ inside &&
461
+ [...inside.values()].every((entry) => entry === null) &&
462
+ (await this.rewrite(found.oid, inside, `${fullPath}/`, options)) ===
463
+ null
464
+ ) {
465
+ entries.delete(keyed(filePath));
466
+ nested.delete(filePath);
467
+ }
468
+ const existing = entries.get(keyed(filePath));
443
469
  if (existing && isTreeMode(existing.mode))
444
470
  throw new DraftPathError({ code: "EISDIR", path: fullPath });
445
- if (existing?.mode === SYMLINK_MODE)
471
+ if (existing?.mode === SYMLINK_MODE && !options.replaceLinks)
446
472
  throw new DraftPathError({ code: "ELOOP", path: fullPath });
447
473
  if (change === null) {
448
474
  if (!existing) {
@@ -480,7 +506,7 @@ export class OriginObjects {
480
506
  existing?.oid ?? null,
481
507
  inner,
482
508
  `${fullPath}/`,
483
- skipMissingDeletes,
509
+ options,
484
510
  );
485
511
  return { directory, oid, keep: false };
486
512
  }),
@@ -7,7 +7,7 @@ import {
7
7
  } from "@catamorphic/workflow/project-layout";
8
8
  import { FsBackend } from "./fs-backend.js";
9
9
  import { push } from "./git-sync.js";
10
- import { discoverLocalFolder } from "./native-git.js";
10
+ import { discoverLocalFolder, nativeGit } from "./native-git.js";
11
11
  import { NativeProjectRepo } from "./native-project-repo.js";
12
12
  import { cloneFromRemote } from "./network.js";
13
13
  import {
@@ -19,6 +19,12 @@ import {
19
19
  } from "./origin-draft.js";
20
20
  import { GitObjectCache } from "./origin-objects.js";
21
21
  import { ProjectRepoImpl } from "./project-repo.js";
22
+ import {
23
+ currentSessionWork,
24
+ type SessionWork,
25
+ sessionBranchName,
26
+ writeCheckpoint,
27
+ } from "./session-checkpoint.js";
22
28
  import type {
23
29
  DraftSupport,
24
30
  GitCredentials,
@@ -61,6 +67,24 @@ const SYSTEM_AUTHOR = {
61
67
  email: "system@work.software",
62
68
  };
63
69
 
70
+ /**
71
+ * Materialize the checkpoint as Git objects describe it. Managed copies
72
+ * may have been initialized with symlinks or executable bits disabled.
73
+ */
74
+ 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
+ ]);
86
+ }
87
+
64
88
  export class ProjectManager {
65
89
  /** Origin objects this process has read; safe to lose. */
66
90
  private readonly objects = new GitObjectCache();
@@ -337,8 +361,7 @@ export class ProjectManager {
337
361
  throw new Error(
338
362
  "Session has uncheckpointed work on this machine. Recover it before moving the session.",
339
363
  );
340
- await repo.moveBranch("main", fetched.sha);
341
- await repo.checkout("main");
364
+ await resetSessionCheckout(repo.repoPath, fetched.sha);
342
365
  }
343
366
  }
344
367
  return repo;
@@ -348,33 +371,148 @@ export class ProjectManager {
348
371
  }
349
372
  }
350
373
 
374
+ /**
375
+ * Checkpoint a session's copy (ADR 0344): one commit on the session's
376
+ * ref whose tree is the copy's working tree and whose second parent is
377
+ * the agent's HEAD, written when files changed or the agent's branch,
378
+ * HEAD or pushed branch moved. The agent's commits must already be in
379
+ * the copy. Returns the session's checkpoint, new or not.
380
+ */
351
381
  async checkpointSession(args: {
352
382
  tenantId: string;
353
383
  projectId: string;
354
384
  sessionId: string;
355
385
  message: string;
356
386
  author: { name: string; email: string };
387
+ /** The workspace's base: the agent's HEAD before its first checkpoint. */
388
+ base: string;
389
+ /** The agent's branch and HEAD as just saved; as recorded when left out. */
390
+ work?: { head: string; branch: string };
391
+ /** The branch this chat just pushed for a pull request (ADR 0345). */
392
+ pushed?: { branch: string; commit: string };
393
+ /** Build the sandbox's validated tree while its copy is open. */
394
+ snapshot?: (input: {
395
+ repoPath: string;
396
+ recorded: SessionWork & { checkpoint: string };
397
+ containLinks: boolean;
398
+ }) => Promise<{ tree?: string; work: { head: string; branch: string } }>;
399
+ /** Check the workspace claim just before publishing. */
400
+ held?: () => void | Promise<void>;
357
401
  }): Promise<string> {
358
- const repo = await this.openSession(args);
402
+ const repo = await this.openSession({ ...args, refresh: true });
359
403
  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
- });
404
+ const sha = await this.checkpointCopy({
405
+ ...args,
406
+ repo,
407
+ publish: async (head, previous) => {
408
+ await args.held?.();
409
+ await this.publishSession({
410
+ ...args,
411
+ repo,
412
+ head,
413
+ force: false,
414
+ ...(args.snapshot ? { expected: previous } : {}),
415
+ });
416
+ },
417
+ });
372
418
  return sha;
373
419
  } finally {
374
420
  await repo.dispose();
375
421
  }
376
422
  }
377
423
 
424
+ private async checkpointCopy(args: {
425
+ repo: ProjectRepo;
426
+ sessionId: string;
427
+ message: string;
428
+ author: { name: string; email: string };
429
+ base: string;
430
+ work?: { head: string; branch: string };
431
+ pushed?: { branch: string; commit: string };
432
+ snapshot?: Parameters<ProjectManager["checkpointSession"]>[0]["snapshot"];
433
+ publish?: (head: string, previous: string) => Promise<void>;
434
+ }): Promise<string> {
435
+ const { repo } = args;
436
+ const recorded = await currentSessionWork({
437
+ repoPath: repo.repoPath,
438
+ sessionId: args.sessionId,
439
+ base: args.base,
440
+ });
441
+ const snapshot = await args.snapshot?.({
442
+ repoPath: repo.repoPath,
443
+ recorded,
444
+ containLinks: repo instanceof NativeProjectRepo,
445
+ });
446
+ const saved = snapshot?.work ?? args.work;
447
+ const pushed = args.pushed ?? recorded.pushed;
448
+ const work: SessionWork = {
449
+ head: saved?.head ?? recorded.head,
450
+ branch: saved?.branch ?? recorded.branch,
451
+ ...(pushed ? { pushed } : {}),
452
+ };
453
+ const previousTree = (
454
+ await nativeGit(repo.repoPath, [
455
+ "rev-parse",
456
+ `${recorded.checkpoint}^{tree}`,
457
+ ])
458
+ ).trim();
459
+ const dirty = !snapshot && (await repo.status()).dirty;
460
+ const moved =
461
+ work.head !== recorded.head ||
462
+ work.branch !== recorded.branch ||
463
+ work.pushed?.branch !== recorded.pushed?.branch ||
464
+ work.pushed?.commit !== recorded.pushed?.commit;
465
+
466
+ if (
467
+ !dirty &&
468
+ !moved &&
469
+ (!snapshot?.tree || snapshot.tree === previousTree)
470
+ ) {
471
+ await args.publish?.(recorded.checkpoint, recorded.checkpoint);
472
+ return recorded.checkpoint;
473
+ }
474
+
475
+ const tree =
476
+ snapshot?.tree ??
477
+ (dirty ? await repo.commit(args.message, args.author) : previousTree);
478
+ const sha = await writeCheckpoint({
479
+ repoPath: repo.repoPath,
480
+ tree,
481
+ previous: recorded.checkpoint,
482
+ message: args.message,
483
+ author: args.author,
484
+ work,
485
+ });
486
+ // Until the origin has accepted the checkpoint, leave the working copy
487
+ // at its previous state so another replica can repeat the same save.
488
+ await args.publish?.(sha, recorded.checkpoint);
489
+ if (snapshot) await resetSessionCheckout(repo.repoPath, sha);
490
+ else await repo.moveBranch("main", sha);
491
+ return sha;
492
+ }
493
+
494
+ /**
495
+ * Where a session's work stands (ADR 0344): its checkpoint, its agent's
496
+ * branch and HEAD, and the branch it last pushed.
497
+ */
498
+ async sessionWork(args: {
499
+ tenantId: string;
500
+ projectId: string;
501
+ sessionId: string;
502
+ base: string;
503
+ }): Promise<SessionWork & { checkpoint: string }> {
504
+ const repo = await this.openSession(args);
505
+ try {
506
+ return await currentSessionWork({
507
+ repoPath: repo.repoPath,
508
+ sessionId: args.sessionId,
509
+ base: args.base,
510
+ });
511
+ } finally {
512
+ await repo.dispose();
513
+ }
514
+ }
515
+
378
516
  /**
379
517
  * The host's bare mirror of the project's linked remote, or null when
380
518
  * this storage keeps none (ADR 0178).
@@ -384,20 +522,103 @@ export class ProjectManager {
384
522
  }
385
523
 
386
524
  /**
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`).
525
+ * The commit the project's own `main` stands on: its origin's, or on a
526
+ * host without one this machine's copy's. Where a chat starts when its
527
+ * project has no linked repository (ADR 0344).
528
+ */
529
+ async mainCommit(args: {
530
+ tenantId: string;
531
+ projectId: string;
532
+ }): Promise<string> {
533
+ if (
534
+ this.remote &&
535
+ (await this.remote.exists(args.tenantId, args.projectId))
536
+ ) {
537
+ const sha = await this.remote.withOrigin(
538
+ args.tenantId,
539
+ args.projectId,
540
+ (origin) => origin.resolveRef("refs/heads/main"),
541
+ );
542
+ if (sha) return sha;
543
+ }
544
+ const repo = await this.open(args.tenantId, args.projectId);
545
+ try {
546
+ return await repo.resolveRef("HEAD");
547
+ } finally {
548
+ await repo.dispose();
549
+ }
550
+ }
551
+
552
+ /**
553
+ * Make sure a session's copy holds its base commit: from the project
554
+ * mirror where `pin` names it there, else from the project's own `main`.
555
+ */
556
+ private async bringBase(args: {
557
+ tenantId: string;
558
+ projectId: string;
559
+ repo: ProjectRepo;
560
+ pin?: string;
561
+ commit: string;
562
+ }): Promise<void> {
563
+ const { repo } = args;
564
+ if (args.pin) {
565
+ const mirrorPath = this.mirrorPath(args);
566
+ if (!mirrorPath) throw new Error("This host keeps no project mirror");
567
+ await copyFromMirror({
568
+ mirrorPath,
569
+ pin: args.pin,
570
+ repoPath: repo.repoPath,
571
+ into: "refs/work/base",
572
+ });
573
+ } else if (this.remote) {
574
+ const { fetchRemote } = await import("./git-sync.js");
575
+ await fetchRemote({
576
+ dev: repo,
577
+ remote: this.remote,
578
+ tenantId: args.tenantId,
579
+ projectId: args.projectId,
580
+ remoteBranch: "main",
581
+ });
582
+ } else {
583
+ const main = await this.open(args.tenantId, args.projectId);
584
+ try {
585
+ if (path.resolve(main.repoPath) !== path.resolve(repo.repoPath))
586
+ await nativeGit(repo.repoPath, [
587
+ "fetch",
588
+ "--quiet",
589
+ "--no-tags",
590
+ "--no-write-fetch-head",
591
+ main.repoPath,
592
+ "+HEAD:refs/work/base",
593
+ ]);
594
+ } finally {
595
+ await main.dispose();
596
+ }
597
+ }
598
+ await nativeGit(repo.repoPath, [
599
+ "cat-file",
600
+ "-e",
601
+ `${args.commit}^{commit}`,
602
+ ]).catch(() => {
603
+ throw new Error(
604
+ `The workspace's base ${args.commit.slice(0, 12)} is not in the project's history on this host`,
605
+ );
606
+ });
607
+ }
608
+
609
+ /**
610
+ * Put a session's copy at its base and publish it as the session's ref
611
+ * (ADRs 0178, 0344): a commit pinned in the project mirror (`pin`), or
612
+ * one the project's own origin holds. Whatever the copy held is replaced.
391
613
  */
392
614
  async setSessionBase(args: {
393
615
  tenantId: string;
394
616
  projectId: string;
395
617
  sessionId: string;
396
- pin: string;
618
+ /** The mirror ref that keeps the commit; left out for the origin's own. */
619
+ pin?: string;
397
620
  commit: string;
398
621
  }): Promise<void> {
399
- const mirrorPath = this.mirrorPath(args);
400
- if (!mirrorPath) throw new Error("This host keeps no project mirror");
401
622
  const repo = await this.openSession({
402
623
  tenantId: args.tenantId,
403
624
  projectId: args.projectId,
@@ -405,25 +626,75 @@ export class ProjectManager {
405
626
  refresh: true,
406
627
  });
407
628
  try {
408
- await copyFromMirror({
409
- mirrorPath,
410
- pin: args.pin,
629
+ await this.bringBase({ ...args, repo });
630
+ const checkpoint = await writeCheckpoint({
411
631
  repoPath: repo.repoPath,
412
- into: "refs/work/base",
632
+ tree: args.commit,
633
+ previous: args.commit,
634
+ message: "Start the workspace",
635
+ author: SYSTEM_AUTHOR,
636
+ work: { head: args.commit, branch: sessionBranchName(args.sessionId) },
413
637
  });
414
- await repo.moveBranch("main", args.commit);
415
- await repo.checkout("main");
638
+ await this.publishSession({ ...args, repo, head: checkpoint });
639
+ await resetSessionCheckout(repo.repoPath, checkpoint);
416
640
  await repo.resetWorkingTree();
417
- await this.publishSession({ ...args, repo, head: args.commit });
418
641
  } finally {
419
642
  await repo.dispose();
420
643
  }
421
644
  }
422
645
 
423
646
  /**
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.
647
+ * Give a session that has saved work but no base one (ADR 0344): its
648
+ * checkpoint becomes one on top of `commit`, with the same files, so its
649
+ * sandbox comes back standing on the base with that work uncommitted.
650
+ */
651
+ async adoptSessionBase(args: {
652
+ tenantId: string;
653
+ projectId: string;
654
+ sessionId: string;
655
+ pin?: string;
656
+ commit: string;
657
+ message: string;
658
+ author: { name: string; email: string };
659
+ }): Promise<void> {
660
+ const repo = await this.openSession({
661
+ tenantId: args.tenantId,
662
+ projectId: args.projectId,
663
+ sessionId: args.sessionId,
664
+ refresh: true,
665
+ });
666
+ try {
667
+ await this.bringBase({ ...args, repo });
668
+ const previous = await repo.resolveRef("HEAD");
669
+ const snapshot = (await repo.status()).dirty
670
+ ? await repo.commit(args.message, args.author)
671
+ : previous;
672
+ const sha = await writeCheckpoint({
673
+ repoPath: repo.repoPath,
674
+ tree: snapshot,
675
+ previous,
676
+ message: args.message,
677
+ author: args.author,
678
+ work: {
679
+ head: args.commit,
680
+ branch: sessionBranchName(args.sessionId),
681
+ },
682
+ });
683
+ await repo.moveBranch("main", sha);
684
+ await this.publishSession({ ...args, repo, head: sha, force: false });
685
+ } finally {
686
+ await repo.dispose();
687
+ }
688
+ }
689
+
690
+ /**
691
+ * Move a session's work to a new base pinned in the mirror (ADRs 0178,
692
+ * 0344). The agent's checkout is rebuilt in the copy, standing on its
693
+ * HEAD with its saved files as one more commit, and moved as any checkout
694
+ * is: `reset` discards its commits and changes, `rebase` replays its
695
+ * commits and then its changes, which come back uncommitted. A rebase
696
+ * that conflicts leaves the copy as it was. What results is the
697
+ * session's next checkpoint, on top of the last.
427
698
  */
428
699
  async moveSessionBase(args: {
429
700
  tenantId: string;
@@ -433,6 +704,7 @@ export class ProjectManager {
433
704
  from: string;
434
705
  to: string;
435
706
  update: "reset" | "rebase";
707
+ author: { name: string; email: string };
436
708
  }): Promise<BaseMoveOutcome> {
437
709
  const mirrorPath = this.mirrorPath(args);
438
710
  if (!mirrorPath) throw new Error("This host keeps no project mirror");
@@ -442,18 +714,97 @@ export class ProjectManager {
442
714
  sessionId: args.sessionId,
443
715
  refresh: true,
444
716
  });
717
+ const git = (gitArgs: readonly string[]) =>
718
+ nativeGit(repo.repoPath, gitArgs).then((output) => output.trim());
445
719
  try {
446
- const outcome = await moveCheckoutBase({
720
+ // Whatever the copy holds beyond its last checkpoint is work too.
721
+ await this.checkpointCopy({
722
+ repo,
723
+ sessionId: args.sessionId,
724
+ message: "Save the workspace before moving its base",
725
+ author: args.author,
726
+ base: args.from,
727
+ });
728
+ const work = await currentSessionWork({
447
729
  repoPath: repo.repoPath,
448
- mirrorPath,
449
- pin: args.pin,
450
- from: args.from,
451
- to: args.to,
452
- update: args.update,
730
+ sessionId: args.sessionId,
731
+ base: args.from,
732
+ });
733
+ // The agent's uncommitted changes ride along as one commit on its
734
+ // HEAD, so a rebase replays them and reports their conflicts.
735
+ const uncommitted =
736
+ (await git(["rev-parse", `${work.checkpoint}^{tree}`])) !==
737
+ (await git(["rev-parse", `${work.head}^{tree}`]));
738
+ const marker = `Work: uncommitted changes ${work.checkpoint}`;
739
+ const start = uncommitted
740
+ ? await git([
741
+ "-c",
742
+ `user.name=${args.author.name}`,
743
+ "-c",
744
+ `user.email=${args.author.email}`,
745
+ "commit-tree",
746
+ `${work.checkpoint}^{tree}`,
747
+ "-p",
748
+ work.head,
749
+ "-m",
750
+ marker,
751
+ ])
752
+ : work.head;
753
+ const stand = async (commit: string) => {
754
+ await git(["update-ref", "--no-deref", "HEAD", commit]);
755
+ await git(["reset", "--quiet"]);
756
+ };
757
+ await stand(start);
758
+ let outcome: BaseMoveOutcome;
759
+ let moved: { tip: string; head: string } | undefined;
760
+ try {
761
+ outcome = await moveCheckoutBase({
762
+ repoPath: repo.repoPath,
763
+ mirrorPath,
764
+ pin: args.pin,
765
+ from: args.from,
766
+ to: args.to,
767
+ update: args.update,
768
+ });
769
+ if (outcome.status === "moved") {
770
+ const tip = outcome.head;
771
+ // The changes' commit is gone when the new base already has them.
772
+ const carried =
773
+ uncommitted &&
774
+ args.update === "rebase" &&
775
+ (await git(["log", "-1", "--format=%s", tip])) === marker;
776
+ moved = {
777
+ tip,
778
+ head: carried ? await git(["rev-parse", `${tip}^`]) : tip,
779
+ };
780
+ }
781
+ } finally {
782
+ // Back on the session's checkpoints, whatever happened.
783
+ await git(["symbolic-ref", "HEAD", "refs/heads/main"]);
784
+ }
785
+ if (!moved) {
786
+ await git(["reset", "--quiet"]);
787
+ return { ...outcome, head: work.head };
788
+ }
789
+ const sha = await writeCheckpoint({
790
+ repoPath: repo.repoPath,
791
+ tree: moved.tip,
792
+ previous: work.checkpoint,
793
+ message:
794
+ args.update === "reset"
795
+ ? "Reset the workspace to a new base"
796
+ : "Rebase the workspace onto a new base",
797
+ author: args.author,
798
+ work: {
799
+ head: moved.head,
800
+ branch: work.branch,
801
+ ...(work.pushed ? { pushed: work.pushed } : {}),
802
+ },
453
803
  });
454
- if (outcome.status === "moved")
455
- await this.publishSession({ ...args, repo, head: outcome.head });
456
- return outcome;
804
+ await repo.moveBranch("main", sha);
805
+ await git(["reset", "--quiet"]);
806
+ await this.publishSession({ ...args, repo, head: sha, force: false });
807
+ return { status: "moved", head: moved.head };
457
808
  } finally {
458
809
  await repo.dispose();
459
810
  }
@@ -465,6 +816,9 @@ export class ProjectManager {
465
816
  sessionId: string;
466
817
  repo: ProjectRepo;
467
818
  head: string;
819
+ /** False for a checkpoint on top of the last; default true. */
820
+ force?: boolean;
821
+ expected?: string;
468
822
  }): Promise<void> {
469
823
  if (!this.remote) return;
470
824
  await push({
@@ -474,7 +828,8 @@ export class ProjectManager {
474
828
  projectId: args.projectId,
475
829
  remoteBranch: `sessions/${args.sessionId}`,
476
830
  localSha: args.head,
477
- force: true,
831
+ force: args.force ?? true,
832
+ ...(args.expected ? { expected: args.expected } : {}),
478
833
  });
479
834
  }
480
835
 
@@ -496,10 +851,9 @@ export class ProjectManager {
496
851
  refresh: true,
497
852
  });
498
853
  try {
499
- await repo.moveBranch("main", args.commit);
500
- await repo.checkout("main");
501
- await repo.resetWorkingTree();
502
854
  await this.publishSession({ ...args, repo, head: args.commit });
855
+ await resetSessionCheckout(repo.repoPath, args.commit);
856
+ await repo.resetWorkingTree();
503
857
  } finally {
504
858
  await repo.dispose();
505
859
  }
@@ -234,8 +234,18 @@ export class ProjectRepoImpl implements ProjectRepo {
234
234
  return readFileSnapshot({
235
235
  paths,
236
236
  options,
237
- read: async (file, maxBytes) =>
238
- new TextDecoder().decode(await this.readSnapshotBytes(file, maxBytes)),
237
+ read: async (file, maxBytes) => {
238
+ // A link is never opened here: a workspace's save keeps links as
239
+ // links (ADR 0343), and one may point outside the working copy.
240
+ if (
241
+ !this.followsSymlinks &&
242
+ (await fs.lstat(path.join(this.repoPath, file))).isSymbolicLink()
243
+ )
244
+ return null;
245
+ return new TextDecoder().decode(
246
+ await this.readSnapshotBytes(file, maxBytes),
247
+ );
248
+ },
239
249
  });
240
250
  }
241
251
 
@@ -244,7 +254,12 @@ export class ProjectRepoImpl implements ProjectRepo {
244
254
  maxBytes: number,
245
255
  ): Promise<Uint8Array> {
246
256
  assertSafePath(file);
247
- const handle = await fs.open(path.join(this.repoPath, file), "r");
257
+ const handle = await fs.open(
258
+ path.join(this.repoPath, file),
259
+ this.followsSymlinks
260
+ ? nodeFs.constants.O_RDONLY
261
+ : nodeFs.constants.O_RDONLY | (nodeFs.constants.O_NOFOLLOW ?? 0),
262
+ );
248
263
  try {
249
264
  const size = (await handle.stat()).size;
250
265
  if (size > maxBytes)