Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/src/gitview/test/view.test.ts?version=160&format=json
309 linesFirst import 100%Last change First import in version 0, 1 version changed it

You're reading version 160. The newest is 318, and no version since then changed this file. Go to the newestCompare with 318

1// The git view: one commit per atom (or per label), trees equal to the
2// engine's projections, trailers git itself can read, and identical hashes
3// for the same set and options.
4
5import assert from "node:assert/strict";
6import fs from "node:fs";
7import { after, describe, it } from "node:test";
8import { type AtomId, history, labelContents, project } from "../../engine/index.ts";
9import { lines, Repo, Rng } from "../../engine/test/helpers.ts";
10import { GitViewError, gitEmail, headsOf, planView, type ViewResult, writeView } from "../index.ts";
11import { cleanup, commitFiles, freshPath, git, sorted, tempDir, workingFiles } from "./helpers.ts";
13after(cleanup);
15/** A small graph with parallel atoms, a file made from nothing, reasons, resolves and two labels. */
16function sample(): Repo {
17 const repo = Repo.init({
18 "src/app.ts": lines("const a = 1;", "const b = 2;", "const c = 3;", "const d = 4;", "export { a, b, c, d };"),
19 "README.md": lines("# App", "", "Says hello."),
20 });
21 const b = repo.edit({
22 author: "ann",
23 message: "b is two hundred",
24 edits: [{ file: "src/app.ts", old: "const b = 2;", new: "const b = 200;" }],
25 });
26 const util = repo.edit({
27 author: "bob",
28 message: "add a util file",
29 edits: [{ file: "src/util.ts", old: "", new: lines("export const twice = (x: number) => 2 * x;") }],
30 });
31 const readme = repo.edit({
32 author: "ann",
33 message: "document the new b",
34 edits: [{ file: "README.md", old: "Says hello.\n", new: "Says hello.\nb is 200 now.\n" }],
35 needs: [b.id],
36 reasons: [{ to: b.id, kind: "together", text: "the readme quotes b\nso they move together" }],
37 });
38 // Two inserts into the same gap, written against the same view: a conflict, then a resolution.
39 const before = new Set(repo.shared);
40 const x = repo.edit(
41 { author: "cy", message: "x after d", edits: [{ file: "src/app.ts", start: 4, end: 4, lines: ["const x = 0;"] }] },
42 before,
43 );
44 const y = repo.edit(
45 { author: "dee", message: "y after d", edits: [{ file: "src/app.ts", start: 4, end: 4, lines: ["const y = 0;"] }] },
46 before,
47 );
48 const xy = repo
49 .view()
50 .lines("src/app.ts")
51 .findIndex((l) => l.text === "const x = 0;" || l.text === "const y = 0;");
52 repo.edit({
53 author: "eve",
54 message: "keep both, x first",
55 edits: [{ file: "src/app.ts", start: xy, end: xy + 2, lines: ["const x = 0;", "const y = 0;"] }],
56 resolves: [x.id, y.id],
57 });
58 repo.graph.setLabel({ name: "b-change", head: readme.id, title: "Change b", message: "b and its docs" });
59 repo.graph.setLabel({ name: "util", head: util.id, title: "Util", message: "" });
60 return repo;
63/** Trailers as git itself parses them: one map per commit, oldest first. */
64function gitTrailers(dir: string): Map<string, string[]>[] {
65 const out = git(dir, ["log", "--reverse", "--format=%H%x00%(trailers:only,unfold)%x01"]);
66 return out
67 .split("\x01")
68 .map((s) => s.trim())
69 .filter((s) => s !== "")
70 .map((s) => {
71 const [, block] = s.split("\x00");
72 const map = new Map<string, string[]>();
73 for (const line of (block ?? "").split("\n")) {
74 const m = /^([^:]+): (.*)$/.exec(line.trim());
75 if (m) map.set(m[1]!, [...(map.get(m[1]!) ?? []), m[2]!]);
76 }
77 return map;
78 });
81describe("per-atom view", () => {
82 const repo = sample();
83 const graph = repo.graph;
84 const order = history(graph, repo.shared).map((a) => a.id);
85 let result: ViewResult;
86 const dir = freshPath("view");
88 it("writes one commit per atom, in history order, a0 first as the root", async () => {
89 result = await writeView(graph, repo.shared, dir);
90 assert.equal(result.commits.length, repo.shared.size);
91 assert.deepEqual(
92 result.commits.map((c) => c.atoms),
93 order.map((id) => [id]),
94 );
95 assert.equal(order[0], "a0");
96 const log = git(dir, ["log", "--reverse", "--format=%H %P"]).trim().split("\n");
97 assert.equal(log.length, order.length);
98 assert.equal(log[0]!.trim(), result.commits[0]!.oid, "the root commit has no parent");
99 log.forEach((line, i) => {
100 const [oid, parent] = line.split(" ");
101 assert.equal(oid, result.commits[i]!.oid);
102 if (i > 0) assert.equal(parent, result.commits[i - 1]!.oid);
103 });
104 assert.equal(git(dir, ["rev-parse", "HEAD"]).trim(), result.head);
105 assert.equal(git(dir, ["symbolic-ref", "HEAD"]).trim(), "refs/heads/main");
106 git(dir, ["fsck", "--strict"]);
107 });
109 it("gives each commit the projection of its prefix of history", async () => {
110 for (let i = 0; i < order.length; i++) {
111 const expected = sorted(project(graph, order.slice(0, i + 1)));
112 assert.deepEqual(await commitFiles(dir, result.commits[i]!.oid), expected, `commit ${i} (${order[i]})`);
113 }
114 });
116 it("checks the tip out, clean as far as git can tell", () => {
117 assert.deepEqual(workingFiles(dir), sorted(project(graph, repo.shared)));
118 assert.equal(git(dir, ["status", "--porcelain"]), "");
119 });
121 it("writes Atom, Deps, Resolves, Reason and View-Heads trailers that git reads", () => {
122 const trailers = gitTrailers(dir);
123 assert.equal(trailers.length, order.length);
124 order.forEach((id, i) => {
125 const t = trailers[i]!;
126 const atom = graph.atom(id);
127 assert.deepEqual(t.get("Atom"), [id]);
128 assert.deepEqual(t.get("Deps"), atom.deps.length > 0 ? [atom.deps.join(" ")] : undefined);
129 assert.deepEqual(t.get("Resolves"), atom.resolves.length > 0 ? [atom.resolves.join(" ")] : undefined);
130 assert.deepEqual(t.get("View-Heads"), [headsOf(graph, new Set(order.slice(0, i + 1))).join(" ")]);
131 assert.deepEqual(
132 t.get("Reason"),
133 atom.reasons.length > 0
134 ? atom.reasons.map((r) => `${id} ${r.kind} ${r.to}: ${r.text.replace(/\s*\n\s*/g, " ")}`)
135 : undefined,
136 );
137 });
138 // The reason's line break became a space; the parallel atoms show as several heads.
139 const readme = graph.atoms().find((a) => a.message === "document the new b")!;
140 assert.ok(
141 trailers[order.indexOf(readme.id)]!.get("Reason")![0]!.endsWith("the readme quotes b so they move together"),
142 );
143 assert.ok(trailers.some((t) => t.get("View-Heads")![0]!.split(" ").length >= 3));
144 });
146 it("uses the atom's author, a derived email, and the atom's time", () => {
147 const log = git(dir, ["log", "--reverse", "--format=%an|%ae|%at|%cn|%ct|%s"]).trim().split("\n");
148 order.forEach((id, i) => {
149 const atom = graph.atom(id);
150 const [an, ae, at, cn, ct, subject] = log[i]!.split("|");
151 assert.equal(an, atom.author);
152 assert.equal(cn, atom.author);
153 assert.equal(ae, gitEmail(atom.author));
154 assert.equal(Number(at), Math.floor(atom.time / 1000));
155 assert.equal(Number(ct), Math.floor(atom.time / 1000));
156 assert.equal(subject, atom.message.split("\n")[0]);
157 });
158 assert.equal(gitEmail("Ann Lee"), "ann-lee@atoms.invalid");
159 assert.equal(gitEmail("<>"), "unknown@atoms.invalid");
160 });
161});
163describe("determinism", () => {
164 const repo = sample();
165 const graph = repo.graph;
166 const tip = history(graph, repo.shared).at(-1)!.id;
168 it("gives identical hashes across runs and across input orders", async () => {
169 const rng = new Rng(7);
170 const inputs: Iterable<AtomId>[] = [
171 repo.shared,
172 [...repo.shared].reverse(),
173 new Set(rng.shuffle([...repo.shared])),
174 rng.shuffle([...repo.shared]),
175 ];
176 const runs: string[][] = [];
177 for (const input of inputs) runs.push((await writeView(graph, input, freshPath("view"))).commits.map((c) => c.oid));
178 for (const run of runs.slice(1)) assert.deepEqual(run, runs[0]);
179 });
181 it("gives the same hashes for a ref and its closure given as a set", async () => {
182 const closure = graph.closure(tip);
183 const byRef = await writeView(graph, tip, freshPath("view"));
184 const bySet = await writeView(graph, new Rng(3).shuffle([...closure]), freshPath("view"));
185 assert.deepEqual(
186 byRef.commits.map((c) => c.oid),
187 bySet.commits.map((c) => c.oid),
188 );
189 assert.deepEqual(
190 byRef.set,
191 [...closure].sort((a, b) => graph.atom(a).seq - graph.atom(b).seq),
192 );
193 });
195 it("gives identical hashes by label too, and in the plan whatever the input order", async () => {
196 const one = await writeView(graph, repo.shared, freshPath("view"), { byLabel: true });
197 const two = await writeView(graph, [...repo.shared].reverse(), freshPath("view"), { byLabel: true });
198 assert.deepEqual(
199 one.commits.map((c) => c.oid),
200 two.commits.map((c) => c.oid),
201 );
202 assert.deepEqual(planView(graph, repo.shared), planView(graph, new Rng(9).shuffle([...repo.shared])));
203 });
205 it("gives different hashes for a different set", async () => {
206 const a = await writeView(graph, repo.shared, freshPath("view"));
207 const b = await writeView(graph, tip, freshPath("view"));
208 assert.notEqual(a.head, b.head);
209 });
210});
212describe("by-label view", () => {
213 const repo = sample();
214 const graph = repo.graph;
215 let result: ViewResult;
216 const dir = freshPath("view");
218 it("writes a0, then one commit per label in dependency order, then the rest", async () => {
219 result = await writeView(graph, repo.shared, dir, { byLabel: true });
220 const [root, ...rest] = result.commits;
221 assert.deepEqual(root!.atoms, ["a0"]);
222 // Labels by their heads' priority: util's head made a file from nothing
223 // (lamport 0), b-change's head sits two atoms up.
224 assert.deepEqual(
225 rest.map((c) => c.label),
226 ["util", "b-change", undefined],
227 );
228 // Each label commit adds exactly the label's contents not already covered.
229 const bChange = rest.find((c) => c.label === "b-change")!;
230 assert.deepEqual(bChange.atoms, labelContents(graph, graph.label("b-change")!));
231 const util = rest.find((c) => c.label === "util")!;
232 assert.deepEqual(util.atoms, labelContents(graph, graph.label("util")!));
233 // The last commit holds everything no label covered.
234 const leftover = rest.at(-1)!;
235 assert.equal(leftover.label, undefined);
236 const covered = new Set(result.commits.slice(0, -1).flatMap((c) => c.atoms));
237 assert.deepEqual(new Set(leftover.atoms), new Set([...repo.shared].filter((id) => !covered.has(id))));
238 assert.equal(result.commits.flatMap((c) => c.atoms).length, repo.shared.size);
239 });
241 it("orders a label after the labels its atoms depend on", () => {
242 const graph2 = sample().graph;
243 // A label whose head depends on b-change's head must come after it.
244 const readme = graph2.label("b-change")!.head;
245 graph2.setLabel({ name: "aaa-first-by-name", head: readme, title: "same head", message: "" });
246 const b = graph2.atoms().find((a) => a.message === "b is two hundred")!.id;
247 graph2.setLabel({ name: "zzz-b-only", head: b, title: "b only", message: "" });
248 const plan = planView(graph2, graph2.closure(readme), { byLabel: true });
249 const names = plan.commits.map((c) => c.label);
250 assert.ok(names.indexOf("zzz-b-only") < names.indexOf("b-change"));
251 assert.ok(names.indexOf("zzz-b-only") < names.indexOf("aaa-first-by-name"));
252 // Same head: both get a commit; the second adds nothing.
253 const same = plan.commits.filter((c) => c.label === "b-change" || c.label === "aaa-first-by-name");
254 assert.equal(same.length, 2);
255 assert.deepEqual(same[1]!.atoms, []);
256 });
258 it("gives each commit the projection of everything up to it", async () => {
259 const plan = planView(graph, repo.shared, { byLabel: true });
260 for (let i = 0; i < result.commits.length; i++) {
261 const expected = sorted(project(graph, plan.order.slice(0, plan.commits[i]!.count)));
262 assert.deepEqual(await commitFiles(dir, result.commits[i]!.oid), expected);
263 }
264 assert.deepEqual(workingFiles(dir), sorted(project(graph, repo.shared)));
265 });
267 it("writes the label title and message, and Label, Atoms and View-Heads trailers", () => {
268 const trailers = gitTrailers(dir);
269 const bIndex = result.commits.findIndex((c) => c.label === "b-change");
270 assert.deepEqual(trailers[bIndex]!.get("Label"), ["b-change"]);
271 assert.deepEqual(trailers[bIndex]!.get("Atoms"), [result.commits[bIndex]!.atoms.join(" ")]);
272 assert.ok(trailers[bIndex]!.get("Reason")![0]!.includes("together"));
273 assert.ok(trailers.every((t) => (t.get("View-Heads") ?? []).length === 1));
274 const body = git(dir, ["show", "-s", "--format=%B", result.commits[bIndex]!.oid]);
275 assert.ok(body.startsWith("Change b\n\nb and its docs\n\nLabel: b-change\n"));
276 const subjects = git(dir, ["log", "--reverse", "--format=%s"]).trim().split("\n");
277 assert.equal(subjects.at(-1), "Atoms outside any label");
278 });
279});
281describe("view errors", () => {
282 const repo = sample();
283 it("refuses a set that is not closed", async () => {
284 const readme = repo.graph.atoms().find((a) => a.message === "document the new b")!;
285 await assert.rejects(writeView(repo.graph, ["a0", readme.id], freshPath("view")), (err: unknown) => {
286 assert.ok(err instanceof GitViewError);
287 assert.equal(err.code, "not-closed");
288 return true;
289 });
290 });
292 it("refuses an empty set and a directory with files in it", async () => {
293 await assert.rejects(writeView(repo.graph, [], freshPath("view")), { code: "empty-set" });
294 const dir = tempDir();
295 fs.writeFileSync(`${dir}/keep.txt`, "x\n");
296 await assert.rejects(writeView(repo.graph, "a0", dir), { code: "dir-not-empty" });
297 });
299 it("refuses paths git cannot hold", async () => {
300 const bad = Repo.init({ "a/../b.txt": "x\n" });
301 await assert.rejects(writeView(bad.graph, "a0", freshPath("view")), { code: "bad-path" });
302 const clash = Repo.init({ a: "x\n", "a/b": "y\n" });
303 await assert.rejects(writeView(clash.graph, "a0", freshPath("view")), { code: "bad-path" });
304 });
306 it("passes unknown refs through as engine errors", async () => {
307 await assert.rejects(writeView(repo.graph, "no-such-label", freshPath("view")), { code: "unknown-ref" });
308 });
309});