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
show on this site's /mcp
CLI
abso show 186 --json
JSON
/christopher/abso-core/versions/186?format=json

Read a version of shared without some earlier versions: abso show <N> --without A,B shows what differs and abso export <dir> --version N --without A,B writes the files. The server's GET without?version=&versions= checks the set left exactly as asked: when a version it keeps builds on one left out, it refuses with that chain, the files and the wider set that works, and never widens it. Atoms keep their ids and authors; shared and its log don't change; the same ask gives the same tree hash.

of shared·candidates··Not checked

Version 185 · Files at version 186

17 files, 640 lines added, 17 removed.

--- a/client/src/api.ts
+++ b/client/src/api.ts
@@ -50,6 +50,7 @@
5050 Where,
5151 WhereAnswer,
5252 WhyAnswer,
53+ WithoutAnswer,
5354} from "./history-answers.ts";
5455import type {
5556 Ask,
@@ -878,6 +879,11 @@
878879 return this.json("GET", `/compare?${query({ from, to, ...where })}`);
879880 }
880881
882+ /** Version `version` of shared with `versions` left out, or the refusal naming what builds on them. */
883+ without(version: number, versions: readonly number[]): Promise<WithoutAnswer> {
884+ return this.json("GET", `/without?${query({ version, versions: versions.join(",") })}`);
885+ }
881887 /** A message to the project's other agents (or those named), delivered once as news. */
882888 starting(
883889 text: string | null,
--- a/client/src/at.ts
+++ b/client/src/at.ts
@@ -25,19 +25,20 @@
2525 readonly modes: Map<string, FullMode>;
2626}
2727
28−/** Each file as it is on one side of a change (`before`), applied to the snapshot. */
29−function applyBefore(s: Snapshot, changes: readonly FileChange[]): void {
28+/** Each file as it is on one side of a change (`before` unless said), applied to the snapshot. */
29+export function applySide(s: Snapshot, changes: readonly FileChange[], side: "before" | "after" = "before"): void {
3030 for (const f of changes) {
3131 if (isLocalOnly(f.path)) continue;
32− const blob = f.blob?.before ?? null;
32+ const blob = f.blob?.[side] ?? null;
33+ const text = f[side];
3334 if (blob !== null) s.files.set(f.path, { blob });
34− else if (f.before !== null) s.files.set(f.path, { text: f.before });
35+ else if (text !== null) s.files.set(f.path, { text });
3536 else {
3637 s.files.delete(f.path);
3738 s.modes.delete(f.path);
3839 continue;
3940 }
40− if (f.mode) s.modes.set(f.path, { exec: f.mode.before.exec === true, link: f.mode.before.link ?? null });
41+ if (f.mode) s.modes.set(f.path, { exec: f.mode[side].exec === true, link: f.mode[side].link ?? null });
4142 }
4243}
4344
@@ -56,9 +57,9 @@
5657 for (const [rel, sha] of readKnownBlobs(root)) s.files.set(rel, { blob: sha });
5758 for (const [rel, mode] of readKnownModes(root)) if (s.files.has(rel)) s.modes.set(rel, mode);
5859 // Its base: the draft's changes taken back out.
59− applyBefore(s, diff.files);
60+ applySide(s, diff.files);
6061 // Version N: what differs from the base, as it was at N.
61− if (version !== diff.base) applyBefore(s, (await api.compare(version, diff.base, where)).files);
62+ if (version !== diff.base) applySide(s, (await api.compare(version, diff.base, where)).files);
6263 return s;
6364}
6465
--- a/client/src/changes.ts
+++ b/client/src/changes.ts
@@ -28,6 +28,7 @@
2828import { byWhom } from "./history-answers.ts";
2929import { applyMode, PLAIN, readKnownModes, writeKnownModes } from "./modes.ts";
3030import { refusedText, screenAnswer } from "./safety.ts";
31+import { refusalText, withoutArg, withoutHeading } from "./without.ts";
3132
3233/** The space to read: --draft (where "shared" means shared), else the one this agent is in (shared, in a folder with no agent). */
3334function space(args: Parsed, agent: string): Where {
@@ -425,6 +426,49 @@
425426 return { text: lines.join("\n"), json: { ...answer } };
426427}
427428
429+/** abso show <version>[:<file>] --without <versions>: what differs with them left out, or that file then. */
430+async function showWithout(
431+ api: Api,
432+ root: string,
433+ cwd: string,
434+ word: string,
435+ where: Where,
436+ leave: readonly number[],
437+): Promise<Output> {
438+ if ("draft" in where && where.draft !== null) throw new UsageError("--without reads shared, not a named draft");
439+ const colon = word.indexOf(":");
440+ const v = version(colon >= 0 ? word.slice(0, colon) : word);
441+ const path = colon >= 0 ? fileArg(root, cwd, word.slice(colon + 1)) : undefined;
442+ const answer = await api.without(v, leave);
443+ if (!answer.ok)
444+ return {
445+ exit: EXIT.refused,
446+ text: refusalText(answer, (vs) => `abso show ${word} --without ${vs.join(",")}`),
447+ json: { ...answer },
448+ };
449+ if (path !== undefined) {
450+ const file = answer.files.find((f) => f.path === path);
451+ if (file === undefined) {
452+ const same = await api.fileAt(path, v, { draft: null });
453+ if (same.text !== null) return { text: same.text, json: { ...same, without: answer.without } };
454+ } else if (file.after !== null) return { text: file.after, json: { ...file, without: answer.without } };
455+ return {
456+ exit: EXIT.error,
457+ text: `${path} isn't in version ${v} of shared without them.`,
458+ json: { path, version: v, without: answer.without },
459+ };
460+ }
461+ const changed = pairRenames(answer.files);
462+ const d = diffs(changed);
463+ const lines = [
464+ ...withoutHeading(answer),
465+ changed.length === 0 ? `No file differs from version ${v}.` : `Compared with version ${v}: ${totals(changed)}.`,
466+ `The files hash to ${answer.tree}; the same ask gives the same hash. Shared doesn't change.`,
467+ ...d.text,
468+ ];
469+ return { text: lines.join("\n"), json: { ...answer, files: d.json } };
470+}
428472export async function runShow(args: Parsed, env: Env): Promise<Output> {
429473 if (args.positionals.length !== 1)
430474 throw new UsageError("show takes one version: abso show <version> or abso show <version>:<file>");
@@ -432,6 +476,8 @@
432476 const word = args.positionals[0]!;
433477 const colon = word.indexOf(":");
434478 const where = space(args, config.agent);
479+ const leave = withoutArg(args);
480+ if (leave !== undefined) return showWithout(api, root, env.cwd, word, where, leave);
435481
436482 if (colon >= 0) {
437483 const v = version(word.slice(0, colon));
--- a/client/src/export.ts
+++ b/client/src/export.ts
@@ -14,11 +14,12 @@
1414import { dirname, join, resolve } from "node:path";
1515import type { Where } from "./api.ts";
1616import { type Parsed, str, UsageError } from "./args.ts";
17−import { globTest, snapshotAt, snapshotEntries } from "./at.ts";
18−import { type Env, type Output, open, plural } from "./commands.ts";
17+import { applySide, globTest, snapshotAt, snapshotEntries } from "./at.ts";
18+import { type Env, EXIT, type Output, open, plural } from "./commands.ts";
1919import { ignoredHere } from "./fetch.ts";
2020import { loadIgnore, relativeTo } from "./folder.ts";
2121import { type Refused, unsafePath } from "./safety.ts";
22+import { refusalText, versionsText, withoutArg } from "./without.ts";
2223
2324/** The file an export leaves in its folder: what it holds, and the sign that the folder is one export may replace. */
2425export const EXPORT_STAMP = ".abso-export";
@@ -81,8 +82,11 @@
8182 const rawVersion = str(args, "version");
8283 if (rawVersion !== undefined && !/^\d+$/.test(rawVersion))
8384 throw new UsageError(`--version is a version number (got ${JSON.stringify(rawVersion)})`);
85+ const leave = withoutArg(args);
8486 const diff = await api.diff();
8587 const where: Where = { draft: diff.draft };
88+ if (leave !== undefined && diff.draft !== null)
89+ throw new UsageError(`--without reads shared, and this folder is on draft ${diff.draft}`);
8690 // The listing names the version (the newest by default) and every file it holds; a server from before it answers 404.
8791 const listing = await api
8892 .filesAt(diff.draft, rawVersion === undefined ? undefined : Number(rawVersion))
@@ -106,6 +110,18 @@
106110 });
107111 }
108112 }
113+ // Without some versions: the server says what differs from this version, as it is without them.
114+ const without = leave === undefined ? undefined : await api.without(version, leave);
115+ if (without !== undefined && !without.ok)
116+ return {
117+ exit: EXIT.refused,
118+ text: refusalText(
119+ without,
120+ (vs) => `abso export ${args.positionals[0]} --version ${version} --without ${vs.join(",")}`,
121+ ),
122+ json: { ...without },
123+ };
124+ if (without !== undefined) applySide(snap, without.files, "after");
109125 const entries = await snapshotEntries(api, snap);
110126 // Built before anything is removed, so a failed export leaves an earlier one whole.
111127 const keepGlob = str(args, "keep");
@@ -135,13 +151,14 @@
135151 project: config.project,
136152 space: diff.draft ?? "shared",
137153 version,
154+ ...(without !== undefined ? { without: without.without.map((w) => w.version), tree: without.tree } : {}),
138155 files: written,
139156 exportedAt: new Date().toISOString(),
140157 };
141158 writeFileSync(join(target, EXPORT_STAMP), `${JSON.stringify(stamp)}\n`);
142159 return {
143160 text: [
144− `Exported version ${version} of ${space} to ${target}: ${plural(written, "file")}. ${EXPORT_STAMP} there names the version; abso export to the same folder replaces it.`,
161+ `Exported version ${version} of ${space}${without !== undefined ? ` without ${versionsText(without.without.map((w) => w.version))}` : ""} to ${target}: ${plural(written, "file")}. ${EXPORT_STAMP} there names the version; abso export to the same folder replaces it.`,
145162 ...(kept.length > 0 ? [`Kept from the earlier export: ${kept.join(", ")}.`] : []),
146163 ...(skipped.length > 0
147164 ? [`Not exported (${skipped.length}):`, ...skipped.map((s) => ` ${s.path}: ${s.why}`)]
--- a/client/src/history-answers.ts
+++ b/client/src/history-answers.ts
@@ -73,6 +73,28 @@
7373 readonly files: readonly string[];
7474 }[];
7575 };
76+/** A version of shared without some earlier ones (abso show --without, abso export --without). */
77+export type WithoutAnswer =
78+ | {
79+ readonly ok: true;
80+ readonly version: number;
81+ readonly without: readonly VersionRef[];
82+ /** Every file that differs from the version: before, in it; after, without the others. */
83+ readonly files: readonly FileChange[];
84+ /** One hash of every file without them: the same ask always gives the same one. */
85+ readonly tree: string;
86+ }
87+ | {
88+ readonly ok: false;
89+ readonly version: number;
90+ readonly without: readonly VersionRef[];
91+ /** Versions it keeps that build on one it leaves out, each with what it builds on and where. */
92+ readonly dependents: readonly (VersionRef & {
93+ readonly needs: readonly { readonly version: number; readonly files: readonly string[] }[];
94+ })[];
95+ /** What to leave out for it to work: the versions asked, and every one that builds on them. */
96+ readonly suggestion: readonly number[];
97+ };
7698export type PluckAnswer =
7799 | { readonly ok: true; readonly version: number; readonly changes: number; readonly plucked: readonly unknown[] }
78100 | { readonly ok: false; readonly needs?: readonly VersionRef[]; readonly collisions?: readonly Collision[] };
--- a/client/src/main.ts
+++ b/client/src/main.ts
@@ -655,10 +655,10 @@
655655 run: runRestore,
656656 },
657657 export: {
658− flags: { version: "string", keep: "string" },
659− usage: "abso export <dir> [--version <N>] [--keep <glob>]",
658+ flags: { version: "string", keep: "string", without: "string" },
659+ usage: "abso export <dir> [--version <N>] [--without <version,...>] [--keep <glob>]",
660660 about:
661− "Write one pushed version of this folder's space (the newest unless --version) into a folder of its own, for a build that doesn't move. The folder must be empty, an earlier export (which it replaces, keeping node_modules and what --keep names), or one .absoignore leaves out; .avcs-export.json there names the version.",
661+ "Write one pushed version of this folder's space (the newest unless --version) into a folder of its own, for a build that doesn't move. The folder must be empty, an earlier export (which it replaces, keeping node_modules and what --keep names), or one .absoignore leaves out; .avcs-export.json there names the version. --without 37,38 writes the version of shared with those earlier versions left out, and names them there too; shared doesn't change, and it is refused, naming the chain, when a version it keeps builds on one left out.",
662662 run: runExport,
663663 },
664664 files: {
@@ -677,9 +677,10 @@
677677 run: runLog,
678678 },
679679 show: {
680− flags: { draft: "string" },
681− usage: "abso show <version> | abso show <version>:<file> [--draft <name>]",
682− about: "One version: who pushed it, why, and its diff. With :<file>, that file's text as it was then.",
680+ flags: { draft: "string", without: "string" },
681+ usage: "abso show <version> | abso show <version>:<file> [--draft <name>] [--without <version,...>]",
682+ about:
683+ "One version: who pushed it, why, and its diff. With :<file>, that file's text as it was then. --without 37,38 shows the version of shared with those earlier versions left out: what differs, and with :<file> that file. Shared doesn't change. Refused, naming the chain, when a version it keeps builds on one left out.",
683684 run: runShow,
684685 },
685686 announce: {
--- /dev/null
+++ b/client/src/without.ts
@@ -0,0 +1,53 @@
1+// --without <version,...> on abso show and abso export: a version of shared with some earlier versions left out.
2+// The server reads it; shared doesn't change. When a version kept builds on one left out, it is refused with
3+// that chain and the wider set that works, which is never taken without being asked.
4+
5+import type { VersionRef, WithoutAnswer } from "./api.ts";
6+import { type Parsed, str, UsageError } from "./args.ts";
7+
8+/** The versions --without names, sorted, or undefined without it. */
9+export function withoutArg(args: Parsed): number[] | undefined {
10+ const raw = str(args, "without");
11+ if (raw === undefined) return undefined;
12+ const words = raw
13+ .split(",")
14+ .map((w) => w.trim())
15+ .filter((w) => w !== "");
16+ if (words.length === 0 || words.some((w) => !/^\d+$/.test(w)))
17+ throw new UsageError(`--without takes version numbers, like --without 37,38 (got ${JSON.stringify(raw)})`);
18+ return [...new Set(words.map(Number))].toSorted((a, b) => a - b);
19+}
21+/** "version 37", "versions 37 and 38", "versions 37, 38 and 40". */
22+export function versionsText(versions: readonly number[]): string {
23+ if (versions.length === 1) return `version ${versions[0]}`;
24+ return `versions ${versions.slice(0, -1).join(", ")} and ${versions[versions.length - 1]}`;
25+}
27+function ref(v: VersionRef): string {
28+ return ` version ${v.version} by ${v.agent}: ${v.message}`;
29+}
31+/** The heading of an answer: the version and what it leaves out, one line each. */
32+export function withoutHeading(answer: WithoutAnswer): string[] {
33+ return [
34+ `Version ${answer.version} of shared without ${versionsText(answer.without.map((w) => w.version))}:`,
35+ ...answer.without.map(ref),
36+ ];
37+}
39+/** A refusal: which kept versions build on what is left out, and the ask that would work (`retry` writes it). */
40+export function refusalText(
41+ answer: Extract<WithoutAnswer, { ok: false }>,
42+ retry: (versions: readonly number[]) => string,
43+): string {
44+ const asked = answer.without.map((w) => w.version);
45+ return [
46+ `Version ${answer.version} of shared can't leave out ${versionsText(asked)}: versions it keeps build on ${asked.length === 1 ? "it" : "them"}.`,
47+ ...answer.dependents.flatMap((d) => [
48+ ref(d),
49+ ` builds on ${d.needs.map((n) => `version ${n.version} (${n.files.join(", ") || "no file of its own"})`).join(", ")}`,
50+ ]),
51+ `Leaving those out too works: ${retry(answer.suggestion)}`,
52+ ].join("\n");
53+}
--- a/client/test/client.test.ts
+++ b/client/test/client.test.ts
@@ -824,6 +824,46 @@
824824 );
825825 });
826826
827+ it("shows and exports a version without earlier ones, refuses one a kept version builds on, and leaves shared alone", async () => {
828+ const { name, folders } = await project({ "a.txt": "a\n", "b.txt": "b\n" }, "alice", "bob");
829+ const [alice, bob] = [folders.alice!, folders.bob!];
830+ write(alice, { "a.txt": "a, changed\n" });
831+ assert.equal((await avcs(alice, "push", "-m", "change a")).exit, 0);
832+ write(alice, { "b.txt": "b, changed\n" });
833+ assert.equal((await avcs(alice, "push", "-m", "change b")).exit, 0);
834+ write(alice, { "a.txt": "a, changed again\n" });
835+ assert.equal((await avcs(alice, "push", "-m", "change a again")).exit, 0);
836+ const before = shared(name);
838+ const shown = await text(bob, "show", "2", "--without", "1");
839+ assert.equal(shown.exit, 0, shown.stderr);
840+ assert.match(
841+ shown.stdout,
842+ /^Version 2 of shared without version 1:\n {2}version 1 by alice: change a\nCompared with version 2: 1 file, 1 line added, 1 removed\.\nThe files hash to [0-9a-f]{64}; the same ask gives the same hash\. Shared doesn't change\./,
843+ );
844+ assert.match(shown.stdout, /-a, changed\n\+a\n/);
845+ assert.equal((await text(bob, "show", "2:a.txt", "--without", "1")).stdout, "a\n");
846+ assert.equal((await text(bob, "show", "2:b.txt", "--without", "1")).stdout, "b, changed\n");
848+ const refused = await text(bob, "show", "3", "--without", "1");
849+ assert.equal(refused.exit, 2);
850+ assert.equal(
851+ refused.stdout,
852+ "Version 3 of shared can't leave out version 1: versions it keeps build on it.\n version 3 by alice: change a again\n builds on version 1 (a.txt)\nLeaving those out too works: abso show 3 --without 1,3\n",
853+ );
854+ const out = join(temp(), "without");
855+ const blocked = await avcs(bob, "export", out, "--version", "3", "--without", "1");
856+ assert.equal(blocked.exit, 2);
857+ assert.deepEqual(blocked.json.suggestion, [1, 3]);
858+ const exported = await avcs(bob, "export", out, "--version", "3", "--without", "1,3");
859+ assert.equal(exported.exit, 0, exported.out);
860+ assert.deepEqual(exported.json.without, [1, 3]);
861+ assert.equal(readFileSync(join(out, "a.txt"), "utf8"), "a\n");
862+ assert.equal(readFileSync(join(out, "b.txt"), "utf8"), "b, changed\n");
863+ assert.deepEqual(shared(name), before, "shared doesn't change");
864+ assert.equal((await text(bob, "show", "3", "--without", "x")).exit, 1);
865+ });
827867 it("refuses a push that builds on lines a drop took out, plainly, with exit 2", async () => {
828868 const { folders } = await project({ "a.txt": "one\ntwo\n" }, "alice", "bob");
829869 const [alice, bob] = [folders.alice!, folders.bob!];
--- a/client/test/fake-server.ts
+++ b/client/test/fake-server.ts
@@ -271,7 +271,7 @@
271271 return;
272272 }
273273 const m =
274− /^\/p\/([^/]+)\/(init|status|queue|change\/\d+|changes|notes|ci\/revoke|ci|blame|why|where|labels|files|diff|log|show|file|compare|a\/([^/]+)\/(edit|record|publish|sync|run|draft|land|draft-sync|diff|restore|announce|news|starting|reader|drop|pluck|amend|label|files|unqueue|note|note-close|move))$/.exec(
274+ /^\/p\/([^/]+)\/(init|status|queue|change\/\d+|changes|notes|ci\/revoke|ci|blame|why|where|labels|files|diff|log|show|file|compare|without|a\/([^/]+)\/(edit|record|publish|sync|run|draft|land|draft-sync|diff|restore|announce|news|starting|reader|drop|pluck|amend|label|files|unqueue|note|note-close|move))$/.exec(
275275 url.pathname,
276276 );
277277 if (!m) return send(res, 404, { error: "no such route; see docs/v2-slice1.md" });
@@ -440,6 +440,20 @@
440440 return send(res, code === "bad-request" ? 400 : 500, { error: e instanceof Error ? e.message : String(e) });
441441 }
442442 }
443+ if (op === "without") {
444+ // GET ?version=<n>&versions=<n,n>, as worker/project/http.ts routes it.
445+ const q = Object.fromEntries(url.searchParams) as Record<string, string | undefined>;
446+ try {
447+ return send(
448+ res,
449+ 200,
450+ hosted.project.without(Number(q.version), (q.versions ?? "").split(",").filter(Boolean).map(Number)),
451+ );
452+ } catch (e) {
453+ const code = (e as { code?: string }).code;
454+ return send(res, code === "bad-request" ? 400 : 500, { error: e instanceof Error ? e.message : String(e) });
455+ }
456+ }
443457 if (op === "log" || op === "show" || op === "file" || op === "compare") {
444458 // As the Worker routes them: ?draft=<name>, shared when absent.
445459 const q = Object.fromEntries(url.searchParams) as Record<string, string | undefined>;
--- a/server/src/engine-project.ts
+++ b/server/src/engine-project.ts
@@ -522,6 +522,9 @@
522522 compare(from: number, to: number, draft: string | null, agent?: string) {
523523 return this.project.compare(from, to, { draft, ...(agent ? { agent } : {}) });
524524 }
525+ without(version: number, versions: readonly number[]) {
526+ return this.project.without(version, versions);
527+ }
525528 show(version: number, draft: string | null, agent?: string) {
526529 return this.project.show(version, { draft, ...(agent ? { agent } : {}) });
527530 }
--- a/server/src/project-object.ts
+++ b/server/src/project-object.ts
@@ -49,6 +49,7 @@
4949 "file",
5050 "files",
5151 "compare",
52+ "without",
5253 "where",
5354 "feed",
5455 "drafts",
--- a/server/src/router.ts
+++ b/server/src/router.ts
@@ -53,6 +53,7 @@
5353 "file",
5454 "files",
5555 "compare",
56+ "without",
5657 "where",
5758 "feed",
5859 "drafts",
--- a/worker/project/http.ts
+++ b/worker/project/http.ts
@@ -350,6 +350,17 @@
350350 const limit = q.limit !== undefined && Number.isInteger(Number(q.limit)) ? Number(q.limit) : undefined;
351351 return { status: 200, body: history.refusals(q.agent || undefined, limit) };
352352 }
353+ if (op === "without") {
354+ // GET ?version=<n>&versions=<n,n>: version n of shared with those versions left out (without.ts).
355+ const q = (body ?? {}) as Record<string, string | undefined>;
356+ const history = project as ProjectCalls & Partial<ProjectHistory>;
357+ if (!history.without) return fail(501, "without needs the engine");
358+ const version = q.version !== undefined && /^\d+$/.test(q.version) ? Number(q.version) : undefined;
359+ const versions = (q.versions ?? "").split(",").filter((s) => s.trim() !== "");
360+ if (version === undefined || versions.length === 0 || versions.some((s) => !/^\s*\d+\s*$/.test(s)))
361+ return fail(400, "without needs ?version=<number>&versions=<number,number>");
362+ return { status: 200, body: history.without(version, versions.map(Number)) };
363+ }
353364 if (op === "log" || op === "show" || op === "file" || op === "compare") {
354365 // GETs: ?draft=<name> (shared when absent); log ?limit, ?path; show ?version; file ?path, ?version; compare ?from, ?to.
355366 const q = (body ?? {}) as Record<string, string | undefined>;
--- a/worker/project/project-api.ts
+++ b/worker/project/project-api.ts
@@ -157,6 +157,8 @@
157157 fileAt(path: string, version: number, draft: string | null, agent?: string): unknown;
158158 /** Every file that differs between two versions (#27). */
159159 compare(from: number, to: number, draft: string | null, agent?: string): unknown;
160+ /** Version `version` of shared without the versions in `versions` (without.ts). */
161+ without(version: number, versions: readonly number[]): unknown;
160162 /** One version: who, why, and each file before and after (#27). */
161163 show(version: number, draft: string | null, agent?: string): unknown;
162164 /** What an agent's unpublished changes do, file by file (#27). */
--- a/worker/project/project.ts
+++ b/worker/project/project.ts
@@ -202,6 +202,7 @@
202202 wholeRules as hostedWholeRules,
203203 type WholeHost,
204204} from "./whole-files.ts";
205+import { without as hostedWithout, type WithoutHost } from "./without.ts";
205206import { WriterAgents } from "./writer-agents.ts";
206207
207208export { MemoryStore } from "./memory-store.ts";
@@ -1798,6 +1799,21 @@
17981799 return versionCompare(this.#logHost, ...args);
17991800 }
18001801
1802+ /** A version of shared without some earlier versions, or the refusal naming what builds on them (without.ts). */
1803+ without(version: number, versions: readonly number[]): ReturnType<typeof hostedWithout> {
1804+ const host: WithoutHost = {
1805+ graph: this.#graph,
1806+ shared: () => this.#shared,
1807+ needInit: () => this.#needInit(),
1808+ checkVersion: (space, v) => this.#checkVersion(space, v),
1809+ viewAt: (space, v) => this.#viewAt(space, v),
1810+ at: (space, v) => this.#at(space, v),
1811+ closed: (set) => this.#closed(set),
1812+ touchedFiles: (ids, views) => this.#touchedFiles(ids, views),
1813+ };
1814+ return hostedWithout(host, version, versions);
1815+ }
18011817 /** A version of shared (or of a named draft) as a ReadView (version-log.ts). */
18021818 viewAt(...args: Tail<Parameters<typeof versionViewAt>>): ReturnType<typeof versionViewAt> {
18031819 return versionViewAt(this.#logHost, ...args);
--- /dev/null
+++ b/worker/project/test/without.test.ts
@@ -0,0 +1,206 @@
1+// A version without others: the files of one version of shared with some earlier versions left out. A read:
2+// shared and its log never change. Refused, naming the chain, when a version kept builds on one left out.
3+
4+import assert from "node:assert/strict";
5+import { test } from "node:test";
6+import { MemoryStore, Project, ProjectError } from "../project.ts";
7+import { treeHash } from "../tree.ts";
8+
9+const START = { "a.ts": "one\ntwo\nthree\n", "b.ts": "alpha\nbeta\n" };
11+function setup() {
12+ const store = new MemoryStore();
13+ const project = new Project(store, { hasBlob: () => true });
14+ project.init(START, 0);
15+ for (const a of ["ann", "bob", "cat"]) project.sync(a);
16+ return { project, store };
17+}
19+/** ann publishes v1 (a.ts), bob v2 (b.ts), cat v3 (a new c.ts): three versions that don't build on each other. */
20+function threeVersions(project: Project): void {
21+ project.edit("ann", { file: "a.ts", old: "two", new: "TWO" }, 1);
22+ project.publish("ann", "Shout two", 2);
23+ project.edit("bob", { file: "b.ts", old: "beta", new: "BETA" }, 3);
24+ project.publish("bob", "Shout beta", 4);
25+ project.record("cat", { "c.ts": "gamma\n" }, 5);
26+ project.publish("cat", "Add c", 6);
27+}
29+const badRequest = (f: () => unknown): string => {
30+ try {
31+ f();
32+ } catch (e) {
33+ if (e instanceof ProjectError && e.code === "bad-request") return e.message;
34+ throw e;
35+ }
36+ return "no error";
37+};
39+test("leaving out an independent version takes only its change out; the others stay as they are", () => {
40+ const { project, store } = setup();
41+ threeVersions(project);
42+ const entries = store.entries.length;
43+ const answer = project.without(3, [1]);
44+ assert.equal(answer.ok, true);
45+ assert.ok(answer.ok);
46+ assert.deepEqual(answer.without, [{ version: 1, agent: "ann", message: "Shout two" }]);
47+ assert.deepEqual(answer.files, [{ path: "a.ts", before: "one\nTWO\nthree\n", after: "one\ntwo\nthree\n" }]);
48+ assert.equal(
49+ answer.tree,
50+ treeHash({ files: { "a.ts": "one\ntwo\nthree\n", "b.ts": "alpha\nBETA\n", "c.ts": "gamma\n" } }),
51+ );
52+ // Shared is unchanged: same version, same files, nothing written to the log.
53+ assert.equal(project.version, 3);
54+ assert.deepEqual(project.files(), { "a.ts": "one\nTWO\nthree\n", "b.ts": "alpha\nBETA\n", "c.ts": "gamma\n" });
55+ assert.equal(store.entries.length, entries);
56+ // Two left out at once.
57+ const two = project.without(3, [3, 1]);
58+ assert.ok(two.ok);
59+ assert.deepEqual(
60+ two.without.map((w) => w.version),
61+ [1, 3],
62+ );
63+ assert.deepEqual(
64+ two.files.map((f) => [f.path, f.after]),
65+ [
66+ ["a.ts", "one\ntwo\nthree\n"],
67+ ["c.ts", null],
68+ ],
69+ );
70+});
72+test("the same ask gives the same answer, and shared moving on doesn't change it", () => {
73+ const { project } = setup();
74+ threeVersions(project);
75+ const first = project.without(3, [2]);
76+ assert.deepEqual(project.without(3, [2]), first);
77+ project.sync("ann");
78+ project.edit("ann", { file: "c.ts", old: "gamma", new: "GAMMA" }, 7);
79+ project.publish("ann", "Shout gamma", 8);
80+ assert.deepEqual(project.without(3, [2]), first);
81+ // Asked of the newer version, the newer change is in it.
82+ const later = project.without(4, [2]);
83+ assert.ok(later.ok && first.ok);
84+ assert.notEqual(later.tree, first.tree);
85+});
87+test("leaving out a version a kept one builds on is refused, with the chain, the files and the wider set", () => {
88+ const { project, store } = setup();
89+ threeVersions(project);
90+ project.sync("cat");
91+ project.edit("cat", { file: "a.ts", old: "TWO", new: "TWO!" }, 7);
92+ project.publish("cat", "Louder", 8); // v4 builds on v1
93+ project.sync("bob");
94+ project.edit("bob", { file: "a.ts", old: "TWO!", new: "TWO!!" }, 9);
95+ project.publish("bob", "Louder still", 10); // v5 builds on v4
96+ const entries = store.entries.length;
97+ const refused = project.without(5, [1]);
98+ assert.deepEqual(refused, {
99+ ok: false,
100+ version: 5,
101+ without: [{ version: 1, agent: "ann", message: "Shout two" }],
102+ dependents: [
103+ { version: 4, agent: "cat", message: "Louder", needs: [{ version: 1, files: ["a.ts"] }] },
104+ { version: 5, agent: "bob", message: "Louder still", needs: [{ version: 4, files: ["a.ts"] }] },
105+ ],
106+ suggestion: [1, 4, 5],
107+ });
108+ assert.equal(store.entries.length, entries);
109+ assert.equal(project.version, 5);
110+ // The suggestion, asked for, works; it's never applied without being asked.
111+ const wider = project.without(5, refused.ok ? [] : refused.suggestion);
112+ assert.ok(wider.ok);
113+ assert.deepEqual(wider.files, [{ path: "a.ts", before: "one\nTWO!!\nthree\n", after: "one\ntwo\nthree\n" }]);
114+ // Before the dependent version, leaving it out is fine.
115+ assert.equal(project.without(3, [1]).ok, true);
116+});
118+test("a deletion left out brings the lines back; a rename left out keeps the old name; a move left out puts lines back", () => {
119+ const { project } = setup();
120+ project.edit("ann", { file: "a.ts", old: "two\n", new: "" }, 1);
121+ project.publish("ann", "No two", 2);
122+ project.record("bob", { "b.ts": null, "c.ts": START["b.ts"] }, 3);
123+ project.publish("bob", "Rename b to c", 4);
124+ project.sync("cat");
125+ project.move("cat", "a.ts", "src/a.ts", 5);
126+ project.publish("cat", "Move a into src", 6);
127+ assert.deepEqual(project.files(), { "src/a.ts": "one\nthree\n", "c.ts": "alpha\nbeta\n" });
129+ const noDelete = project.without(3, [1]);
130+ assert.ok(noDelete.ok);
131+ assert.deepEqual(
132+ noDelete.files.map((f) => [f.path, f.after]),
133+ [["src/a.ts", "one\ntwo\nthree\n"]],
134+ );
135+ const noRename = project.without(3, [2]);
136+ assert.ok(noRename.ok);
137+ assert.deepEqual(
138+ noRename.files.map((f) => [f.path, f.before, f.after]),
139+ [
140+ ["b.ts", null, "alpha\nbeta\n"],
141+ ["c.ts", "alpha\nbeta\n", null],
142+ ],
143+ );
144+ const noMove = project.without(3, [3]);
145+ assert.ok(noMove.ok);
146+ assert.deepEqual(
147+ noMove.files.map((f) => [f.path, f.after]),
148+ [
149+ ["a.ts", "one\nthree\n"],
150+ ["src/a.ts", null],
151+ ],
152+ );
153+});
155+test("a binary file's change and an executable bit left out go back to what they were", () => {
156+ const A = "a".repeat(64);
157+ const B = "b".repeat(64);
158+ const store = new MemoryStore();
159+ const project = new Project(store, { hasBlob: () => true });
160+ project.init({ "run.sh": "echo hi\n" }, 0, {}, { "logo.png": A });
161+ project.sync("ann");
162+ project.record("ann", {}, 1, {}, { "logo.png": B });
163+ project.publish("ann", "New logo", 2);
164+ project.record("ann", {}, 3, { "run.sh": { exec: true } });
165+ project.publish("ann", "Make run.sh runnable", 4);
166+ const noLogo = project.without(2, [1]);
167+ assert.ok(noLogo.ok);
168+ assert.deepEqual(
169+ noLogo.files.map((f) => [f.path, f.blob]),
170+ [["logo.png", { before: B, after: A }]],
171+ );
172+ const noExec = project.without(2, [2]);
173+ assert.ok(noExec.ok);
174+ assert.deepEqual(
175+ noExec.files.map((f) => [f.path, f.mode?.after.exec ?? false]),
176+ [["run.sh", false]],
177+ );
178+});
180+test("versions it can't leave out are refused plainly", () => {
181+ const { project } = setup();
182+ threeVersions(project);
183+ assert.equal(project.drop("cat", [2], "Undo beta", 7).ok, true); // v4 drops v2
184+ assert.match(
185+ badRequest(() => project.without(3, [4])),
186+ /comes after version 3/,
187+ );
188+ assert.match(
189+ badRequest(() => project.without(4, [0])),
190+ /version 0 is the start/,
191+ );
192+ assert.match(
193+ badRequest(() => project.without(4, [4])),
194+ /is a drop/,
195+ );
196+ assert.match(
197+ badRequest(() => project.without(4, [2])),
198+ /isn't in version 4: version 4 dropped it/,
199+ );
200+ assert.match(
201+ badRequest(() => project.without(4, [])),
202+ /versions to leave out/,
203+ );
204+ // Before the drop, it's there to leave out.
205+ assert.equal(project.without(3, [2]).ok, true);
206+});
--- /dev/null
+++ b/worker/project/without.ts
@@ -0,0 +1,183 @@
1+// A version of shared without some earlier versions: the files that version's atoms make when the atoms those
2+// versions added are left out. Shared doesn't change, and nothing is written: it is a read. The atoms keep
3+// their ids and authors; nothing is replayed or renumbered.
4+//
5+// The set left is checked exactly as asked. When a kept version builds on a left-out one, the answer is a
6+// refusal naming that chain, the files and the wider set that would work. It is never widened silently, and
7+// never closed again by a helper that would bring a left-out atom back.
8+
9+import { type AtomId, type Graph, type ReadView, View } from "../../src/engine/index.ts";
10+import { ProjectError } from "./project-error.ts";
11+import type { FileChange } from "./project-types.ts";
12+import type { Space } from "./spaces.ts";
13+import { treeHash } from "./tree.ts";
14+import { changesBetween, modesOf } from "./view-changes.ts";
16+/** What a version without others needs from a project. */
17+export interface WithoutHost {
18+ readonly graph: Graph;
19+ shared(): Space;
20+ needInit(): void;
21+ checkVersion(space: Space, version: number): void;
22+ viewAt(space: Space, version: number): ReadView;
23+ at(space: Space, version: number): ReadonlySet<AtomId>;
24+ /** The set as a view of it reads it: with any discarded atom a publish still depends on. */
25+ closed(set: ReadonlySet<AtomId>): ReadonlySet<AtomId>;
26+ touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>;
27+}
29+/** A version, as the answer names it. */
30+export interface VersionNamed {
31+ version: number;
32+ agent: string;
33+ message: string;
34+}
36+/** A kept version that builds on a left-out one: the versions it builds on, and in which files. */
37+export interface BuildsOn extends VersionNamed {
38+ needs: { version: number; files: string[] }[];
39+}
41+export type WithoutAnswer =
42+ | {
43+ ok: true;
44+ version: number;
45+ without: VersionNamed[];
46+ /** Every file that differs from the version as it is: before, in it; after, without the others. */
47+ files: FileChange[];
48+ /** The tree hash (tree.ts) of every file without them: the same ask always gives the same hash. */
49+ tree: string;
50+ }
51+ | {
52+ ok: false;
53+ version: number;
54+ without: VersionNamed[];
55+ /** Kept versions that build on left-out ones, oldest first: each with what it builds on. */
56+ dependents: BuildsOn[];
57+ /** The versions to leave out for it to work: these and every dependent. A suggestion, never applied. */
58+ suggestion: number[];
59+ };
61+/**
62+ * Version `version` of shared without the versions in `without`: what its
63+ * files are when those versions' atoms are left out. Refused, with the
64+ * chain, when a version kept builds on one left out.
65+ */
66+export function without(host: WithoutHost, version: number, versions: readonly number[]): WithoutAnswer {
67+ host.needInit();
68+ const shared = host.shared();
69+ if (!Number.isInteger(version)) throw new ProjectError("bad-request", "version must be a number");
70+ host.checkVersion(shared, version);
71+ if (!Array.isArray(versions) || versions.length === 0)
72+ throw new ProjectError("bad-request", "without needs the versions to leave out");
73+ const g = host.graph;
74+ const asked = [...new Set(versions)].toSorted((a, b) => a - b);
75+ const base = host.at(shared, version);
76+ const out = new Set<AtomId>();
77+ for (const v of asked) {
78+ if (!Number.isInteger(v) || v < 1)
79+ throw new ProjectError(
80+ "bad-request",
81+ `there is no version ${String(v)} to leave out (version 0 is the start, which everything builds on)`,
82+ );
83+ if (v > version)
84+ throw new ProjectError("bad-request", `version ${v} comes after version ${version}, so it isn't in it`);
85+ const p = shared.versions[v]!;
86+ if (p.atoms.length === 0)
87+ throw new ProjectError(
88+ "bad-request",
89+ `version ${v} added nothing (it is a drop), so there is nothing to leave out`,
90+ );
91+ const left = p.atoms.filter((id) => base.has(id));
92+ if (left.length === 0)
93+ throw new ProjectError(
94+ "bad-request",
95+ `version ${v} isn't in version ${version}: version ${shared.droppedIn.get(p.atoms[0]!)} dropped it`,
96+ );
97+ for (const id of left) out.add(id);
98+ }
99+ const describe = (v: number): VersionNamed => ({
100+ version: v,
101+ agent: shared.versions[v]!.agent,
102+ message: shared.versions[v]!.message,
103+ });
104+ const kept = new Set<AtomId>();
105+ for (const id of host.closed(base)) if (!out.has(id)) kept.add(id);
107+ // Everything kept that builds on what is left out, and the step that reached it.
108+ const gone = new Set(out);
109+ const steps: { from: AtomId; to: AtomId }[] = [];
110+ const stack = [...out];
111+ while (stack.length > 0) {
112+ const id = stack.pop()!;
113+ for (const d of g.dependentsOf(id)) {
114+ if (!kept.has(d)) continue;
115+ steps.push({ from: d, to: id });
116+ if (gone.has(d)) continue;
117+ gone.add(d);
118+ stack.push(d);
119+ }
120+ }
121+ if (gone.size > out.size) {
122+ // A discarded atom a publish still needs has no version of its own: it counts with the version that needs it.
123+ const versionOf = (id: AtomId): number | undefined => shared.publishedIn.get(id);
124+ const needs = new Map<number, Map<number, Set<string>>>();
125+ const resolved = (id: AtomId, seen = new Set<AtomId>()): number[] => {
126+ const v = versionOf(id);
127+ if (v !== undefined) return [v];
128+ if (seen.has(id)) return [];
129+ seen.add(id);
130+ return [...new Set(steps.filter((s) => s.from === id).flatMap((s) => resolved(s.to, seen)))];
131+ };
132+ for (const { from, to } of steps) {
133+ const dv = versionOf(from);
134+ if (dv === undefined) continue;
135+ const files = g.filesOf(from).length > 0 ? g.filesOf(from) : g.filesOf(to);
136+ for (const nv of resolved(to)) {
137+ if (nv === dv) continue;
138+ let of = needs.get(dv);
139+ if (!of) needs.set(dv, (of = new Map()));
140+ let set = of.get(nv);
141+ if (!set) of.set(nv, (set = new Set()));
142+ for (const f of files) set.add(f);
143+ }
144+ }
145+ const dependents = [...needs.keys()]
146+ .filter((v) => !asked.includes(v))
147+ .toSorted((a, b) => a - b)
148+ .map((v) => ({
149+ ...describe(v),
150+ needs: [...needs.get(v)!]
151+ .toSorted(([a], [b]) => a - b)
152+ .map(([n, files]) => ({ version: n, files: [...files].toSorted() })),
153+ }));
154+ return {
155+ ok: false,
156+ version,
157+ without: asked.map(describe),
158+ dependents,
159+ suggestion: [...new Set([...asked, ...dependents.map((d) => d.version)])].toSorted((a, b) => a - b),
160+ };
161+ }
163+ // The set is checked; the engine's View refuses one that isn't closed, so nothing left out comes back.
164+ const before = host.viewAt(shared, version);
165+ const after = new View(g, kept);
166+ const files = changesBetween(before, after, host.touchedFiles(out, [before, after]));
167+ const all = after.paths();
168+ const blobs: Record<string, string> = {};
169+ const texts: Record<string, string> = {};
170+ for (const path of all) {
171+ const blob = after.attrs(path).blob;
172+ if (blob !== null) blobs[path] = blob;
173+ else texts[path] = after.text(path);
174+ }
175+ const modes = modesOf(after);
176+ return {
177+ ok: true,
178+ version,
179+ without: asked.map(describe),
180+ files,
181+ tree: treeHash({ files: texts, blobs, modes }),
182+ };
183+}