@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.
@@ -0,0 +1,210 @@
1
+ import { MANAGED_BRANCH_PREFIX } from "@catamorphic/workflow/project-layout";
2
+ import { nativeGit } from "./native-git.js";
3
+ import { isValidRefName } from "./ref-names.js";
4
+
5
+ /**
6
+ * A session's checkpoint (ADR 0344): one commit per save on the session's
7
+ * own ref, never on the agent's branch. Its tree is the working tree as
8
+ * saved; its parents are the checkpoint before it and then the agent's
9
+ * HEAD; its trailers name the agent's branch and HEAD, and the branch this
10
+ * chat last pushed for a pull request. One ref moved by one compare-and-swap
11
+ * keeps a rollback, the agent's commits and its branch name together.
12
+ */
13
+ export interface SessionWork {
14
+ /** The commit the agent's checkout stands on. */
15
+ head: string;
16
+ /** The branch checked out there. */
17
+ branch: string;
18
+ /** What this chat last pushed to the project's repository (ADR 0345). */
19
+ pushed?: { branch: string; commit: string };
20
+ }
21
+
22
+ const COMMIT = /^[0-9a-f]{40}$|^[0-9a-f]{64}$/;
23
+ const BRANCH_TRAILER = "Work-Branch";
24
+ const HEAD_TRAILER = "Work-Head";
25
+ const PUSHED_TRAILER = "Work-Pushed";
26
+
27
+ /** Refuse work no checkpoint may record: a bad commit id or branch name. */
28
+ export function assertSessionWork(work: SessionWork): void {
29
+ if (!COMMIT.test(work.head))
30
+ throw new Error("A checkpoint names its agent's HEAD by a full commit id");
31
+ if (!isSessionBranchName(work.branch))
32
+ throw new Error(
33
+ `A checkpoint cannot record the branch ${JSON.stringify(work.branch.slice(0, 200))}`,
34
+ );
35
+ if (
36
+ work.pushed &&
37
+ (!COMMIT.test(work.pushed.commit) ||
38
+ !isSessionBranchName(work.pushed.branch))
39
+ )
40
+ throw new Error("A checkpoint cannot record that pushed branch");
41
+ }
42
+
43
+ /** A branch name a session may stand on: Git's rules, and no option or refspec. */
44
+ export function isSessionBranchName(name: string): boolean {
45
+ return (
46
+ name.length <= 255 &&
47
+ isValidRefName(name) &&
48
+ !name.startsWith("-") &&
49
+ !name.includes("+") &&
50
+ name !== "HEAD"
51
+ );
52
+ }
53
+
54
+ /**
55
+ * The branch a session's checkout starts on: `work/` and the first eight
56
+ * hex digits of its id, the same on a server and on a person's computer.
57
+ */
58
+ export function sessionBranchName(sessionId: string): string {
59
+ return `${MANAGED_BRANCH_PREFIX}${sessionId.replaceAll("-", "").slice(0, 8)}`;
60
+ }
61
+
62
+ /** A checkpoint's commit message: what was saved, then its trailers. */
63
+ export function checkpointMessage(input: {
64
+ message: string;
65
+ work: SessionWork;
66
+ }): string {
67
+ assertSessionWork(input.work);
68
+ const subject =
69
+ input.message
70
+ .split("\n")
71
+ .map((line) => line.trim())
72
+ .find(Boolean) ?? "Checkpoint";
73
+ return [
74
+ subject,
75
+ "",
76
+ `${BRANCH_TRAILER}: ${input.work.branch}`,
77
+ `${HEAD_TRAILER}: ${input.work.head}`,
78
+ ...(input.work.pushed
79
+ ? [
80
+ `${PUSHED_TRAILER}: ${input.work.pushed.branch} ${input.work.pushed.commit}`,
81
+ ]
82
+ : []),
83
+ "",
84
+ ].join("\n");
85
+ }
86
+
87
+ /**
88
+ * What a checkpoint's message records, or null for a commit that is not a
89
+ * checkpoint (the base a session started on, or one from before sessions
90
+ * kept their agent's branch).
91
+ */
92
+ export function parseCheckpointMessage(message: string): SessionWork | null {
93
+ // Trailers are the last paragraph; the subject may quote anything.
94
+ const paragraphs = message.trimEnd().split(/\n{2,}/);
95
+ const last = paragraphs.length > 1 ? paragraphs.at(-1) : undefined;
96
+ if (!last) return null;
97
+ const trailers = new Map<string, string>();
98
+ for (const line of last.split("\n")) {
99
+ const separator = line.indexOf(": ");
100
+ if (separator > 0)
101
+ trailers.set(line.slice(0, separator), line.slice(separator + 2).trim());
102
+ }
103
+ const head = trailers.get(HEAD_TRAILER);
104
+ const branch = trailers.get(BRANCH_TRAILER);
105
+ if (!head || !branch || !COMMIT.test(head) || !isSessionBranchName(branch))
106
+ return null;
107
+ const [pushedBranch = "", pushedCommit = ""] = (
108
+ trailers.get(PUSHED_TRAILER) ?? ""
109
+ ).split(" ");
110
+ return {
111
+ head,
112
+ branch,
113
+ ...(isSessionBranchName(pushedBranch) && COMMIT.test(pushedCommit)
114
+ ? { pushed: { branch: pushedBranch, commit: pushedCommit } }
115
+ : {}),
116
+ };
117
+ }
118
+
119
+ /** Read a commit already identified by the host as a session checkpoint. */
120
+ export async function readSessionWork(input: {
121
+ repoPath: string;
122
+ commit: string;
123
+ }): Promise<SessionWork | null> {
124
+ if (!COMMIT.test(input.commit)) return null;
125
+ const message = await nativeGit(input.repoPath, [
126
+ "log",
127
+ "-1",
128
+ "--format=%B",
129
+ input.commit,
130
+ ]).catch(() => "");
131
+ return parseCheckpointMessage(message);
132
+ }
133
+
134
+ /**
135
+ * Write a checkpoint commit in the repository at `repoPath`: `tree` as
136
+ * saved, on top of the checkpoint before it, with the agent's HEAD as its
137
+ * second parent so one ref keeps the agent's commits reachable. Returns
138
+ * its id; the caller moves the session's ref.
139
+ */
140
+ export async function writeCheckpoint(input: {
141
+ repoPath: string;
142
+ /** A commit or tree whose tree is the working tree as saved. */
143
+ tree: string;
144
+ previous: string;
145
+ message: string;
146
+ author: { name: string; email: string };
147
+ work: SessionWork;
148
+ }): Promise<string> {
149
+ assertSessionWork(input.work);
150
+ const tree = (
151
+ await nativeGit(input.repoPath, [
152
+ "rev-parse",
153
+ "--verify",
154
+ `${input.tree}^{tree}`,
155
+ ])
156
+ ).trim();
157
+ // The agent's HEAD must be here whole before a ref makes it reachable.
158
+ await nativeGit(input.repoPath, [
159
+ "cat-file",
160
+ "-e",
161
+ `${input.work.head}^{commit}`,
162
+ ]);
163
+ return (
164
+ await nativeGit(input.repoPath, [
165
+ "-c",
166
+ `user.name=${input.author.name}`,
167
+ "-c",
168
+ `user.email=${input.author.email}`,
169
+ "commit-tree",
170
+ tree,
171
+ "-p",
172
+ input.previous,
173
+ ...(input.work.head === input.previous ? [] : ["-p", input.work.head]),
174
+ "-m",
175
+ checkpointMessage({ message: input.message, work: input.work }),
176
+ ])
177
+ ).trim();
178
+ }
179
+
180
+ /**
181
+ * Where a session's work stands in its copy at `repoPath`: its latest
182
+ * checkpoint and what that records. Before its first checkpoint the agent's
183
+ * HEAD is the workspace's `base` and its branch the session's own.
184
+ */
185
+ export async function currentSessionWork(input: {
186
+ repoPath: string;
187
+ sessionId: string;
188
+ base: string;
189
+ }): Promise<SessionWork & { checkpoint: string }> {
190
+ const checkpoint = (
191
+ await nativeGit(input.repoPath, [
192
+ "rev-parse",
193
+ "--verify",
194
+ "refs/heads/main^{commit}",
195
+ ])
196
+ ).trim();
197
+ // Older workspaces and rollbacks can point directly at a repository base.
198
+ // Its commit message belongs to the repository, not to this session.
199
+ const recorded =
200
+ checkpoint === input.base
201
+ ? null
202
+ : await readSessionWork({ repoPath: input.repoPath, commit: checkpoint });
203
+ return {
204
+ checkpoint,
205
+ ...(recorded ?? {
206
+ head: input.base,
207
+ branch: sessionBranchName(input.sessionId),
208
+ }),
209
+ };
210
+ }
@@ -277,48 +277,49 @@ export async function moveCheckoutBase(opts: {
277
277
  * A packfile holding `head` and its history back to `base`, and the
278
278
  * commits a receiver must record as shallow. A sandbox seeded from it has
279
279
  * the real commits (so `git log`, `diff`, and pushes of new branches work)
280
- * without the repository's whole history.
280
+ * without the repository's history before the base. With `tree`, the pack
281
+ * also holds that tree whole: a session's working tree as last saved (ADR
282
+ * 0344), which its sandbox puts back on top of `head`.
281
283
  */
282
284
  export async function buildSeedPack(opts: {
283
285
  repoPath: string;
284
286
  head: string;
285
287
  base: string;
288
+ tree?: string;
286
289
  }): 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);
290
+ for (const id of [opts.head, opts.base, ...(opts.tree ? [opts.tree] : [])])
291
+ if (!COMMIT.test(id)) throw new Error("A seed pack names full object ids");
292
+ const objects = path.resolve(
293
+ opts.repoPath,
294
+ (
295
+ await nativeGit(opts.repoPath, ["rev-parse", "--git-path", "objects"])
296
+ ).trim(),
297
+ );
298
+ if (/[\n"]/.test(objects))
299
+ throw new Error("The repository's path cannot be packed from");
294
300
  const directory = await fs.mkdtemp(path.join(tmpdir(), "work-seed-"));
295
301
  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(() => []);
302
+ // A repository of its own that borrows the copy's objects and ends
303
+ // history at the base, so the walk below stops there without a ref or
304
+ // a shallow file ever being written into the copy itself.
305
+ await nativeGit(directory, [
306
+ "init",
307
+ "--bare",
308
+ "--quiet",
309
+ ...(opts.base.length === 64 ? ["--object-format=sha256"] : []),
310
+ ]);
311
+ await fs.writeFile(
312
+ path.join(directory, "objects", "info", "alternates"),
313
+ `${objects}\n`,
314
+ );
315
+ await fs.writeFile(path.join(directory, "shallow"), `${opts.base}\n`);
316
316
  const pack = await gitOutput({
317
317
  cwd: directory,
318
318
  args: ["pack-objects", "--revs", "--stdout", "--quiet"],
319
- input: `${opts.head}\n`,
319
+ // The base itself too: a head that left it still needs it as its ref.
320
+ input: `${[opts.head, opts.base, ...(opts.tree ? [opts.tree] : [])].join("\n")}\n`,
320
321
  });
321
- return { pack, shallow };
322
+ return { pack, shallow: [opts.base] };
322
323
  } finally {
323
324
  await fs.rm(directory, { recursive: true, force: true });
324
325
  }