- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/test/install.test.ts?version=286&format=json
502 linesFirst import 76% · speed 14% · review 7% · pinch 3%Last change pinch in version 281, 9 versions changed it
You're reading version 286. The newest is 318, and 1 version since then changed this file.
1// Installing a mod (src/install.ts, #29): a staged copy that passed its check
2// goes in file by file with renames, plugin.json last; what it replaces is
3// kept for a rollback; a failed check or a failed rename leaves the mod as it
4// was. Every install here goes into a scratch folder. And which client this
5// is (src/version.ts): the commit, read from .git the way git reads it.
7import assert from "node:assert/strict";
8import { spawnSync } from "node:child_process";
9import {
10 copyFileSync,
11 existsSync,
12 mkdirSync,
13 mkdtempSync,
14 readdirSync,
15 readFileSync,
16 renameSync,
17 rmSync,
18 statSync,
19 utimesSync,
20 writeFileSync,
21} from "node:fs";
22import { tmpdir } from "node:os";
23import { dirname, join, relative } from "node:path";
24import { after, describe, it } from "node:test";
25import { Api } from "../src/api.ts";
26import { clientVersion, headCommit } from "../src/client-version.ts";
27import {
28 AVCS_MOD,
29 installerCommand,
30 installMod,
31 keptModCommit,
32 type ModSpec,
33 modsBehindText,
34 retireOldMod,
35 rollbackMod,
36 versionFor,
37 versionReport,
38} from "../src/install.ts";
39import { main } from "../src/main.ts";
41const hasGit = spawnSync("git", ["--version"]).status === 0;
42const dirs: string[] = [];
43after(() => {
44 for (const d of dirs) rmSync(d, { recursive: true, force: true, maxRetries: 5 });
45});
47function temp(): string {
48 const d = mkdtempSync(join(tmpdir(), "avcs-install-test-"));
49 dirs.push(d);
50 return d;
51}
53const FILES = ["src/core.ts", "hooks/stamp.ts", "hooks/register.ts", "hooks/hooks.json", ".claude-plugin/plugin.json"];
54const pass = () => undefined;
55const at = (dir: string, rel: string) => join(dir, ...rel.split("/"));
56const read = (dir: string, rel: string) => readFileSync(at(dir, rel), "utf8");
57const write = (dir: string, rel: string, text: string) => {
58 mkdirSync(dirname(at(dir, rel)), { recursive: true });
59 writeFileSync(at(dir, rel), text);
60};
62/** A mod's source folder: a small mod shaped like avcs, with these texts in place of the defaults. */
63function source(texts: Record<string, string> = {}): ModSpec {
64 const from = temp();
65 const all: Record<string, string> = {
66 "src/core.ts": "export const core = 1\n",
67 "hooks/stamp.ts": "// Which mod this is.\nexport const STAMP: string | undefined = undefined\n",
68 "hooks/register.ts": "import { core } from '../src/core.ts'\n",
69 "hooks/hooks.json": '{ "modules": ["./register.ts"] }\n',
70 ".claude-plugin/plugin.json": '{ "name": "avcs", "version": "0.1.0", "description": "a mod" }\n',
71 ...texts,
72 };
73 for (const [rel, text] of Object.entries(all)) write(from, rel, text);
74 return { name: "avcs", from, files: FILES };
75}
77/** Every file under dir, relative and sorted. */
78function tree(dir: string): string[] {
79 return readdirSync(dir, { recursive: true, withFileTypes: true })
80 .filter((e) => e.isFile())
81 .map((e) => relative(dir, join(e.parentPath, e.name)).replace(/\\/g, "/"))
82 .sort();
83}
85const contents = (dir: string) => Object.fromEntries(tree(dir).map((rel) => [rel, read(dir, rel)]));
86const record = (dir: string) =>
87 JSON.parse(read(dir, ".avcs-install.json")) as {
88 version: string;
89 files: string[];
90 prev?: { version: string; files: string[] };
91 moving?: string;
92 };
94describe("installing a mod", () => {
95 it("stamps the version into plugin.json and stamp.ts, and leaves nothing staged behind", () => {
96 const spec = source();
97 const target = join(temp(), "avcs");
98 const r = installMod(spec, { target, check: pass, commit: "702c616" });
99 assert.deepEqual(r, { changed: true, version: "0.1.0+702c616", previous: undefined, files: 5 });
100 assert.deepEqual(JSON.parse(read(target, ".claude-plugin/plugin.json")), {
101 name: "avcs",
102 version: "0.1.0+702c616",
103 description: "a mod",
104 });
105 assert.equal(
106 read(target, "hooks/stamp.ts"),
107 "// Which mod this is.\nexport const STAMP: string | undefined = '0.1.0+702c616'\n",
108 );
109 assert.equal(read(target, "src/core.ts"), "export const core = 1\n");
110 assert.deepEqual(tree(target), [".avcs-install.json", ...FILES].sort());
111 assert.deepEqual(
112 { ...record(target), at: undefined, from: undefined },
113 { mod: "avcs", version: "0.1.0+702c616", files: FILES, at: undefined, from: undefined },
114 );
115 });
117 it("moves the files in by rename, what the hook imports first and plugin.json last", () => {
118 const spec = source();
119 const target = join(temp(), "avcs");
120 installMod(spec, { target, check: pass, commit: "aaaaaaa" });
121 write(spec.from, "src/core.ts", "export const core = 2\n");
122 const order: string[] = [];
123 installMod(spec, {
124 target,
125 check: pass,
126 commit: "bbbbbbb",
127 rename: (from, to) => {
128 assert.ok(from.endsWith(".next"));
129 order.push(relative(target, to).replace(/\\/g, "/"));
130 renameSync(from, to);
131 },
132 });
133 assert.deepEqual(order, FILES);
134 });
136 it("checks the staged copy, stamped, and when the check fails changes nothing", () => {
137 const spec = source();
138 const target = join(temp(), "avcs");
139 installMod(spec, { target, check: pass, commit: "aaaaaaa" });
140 const before = contents(target);
141 write(spec.from, "src/core.ts", "export const core = 2\n");
142 let staged = "";
143 const failing = (dir: string) => {
144 staged = read(dir, "hooks/stamp.ts") + read(dir, "src/core.ts");
145 return "2 tests failed";
146 };
147 assert.throws(
148 () => installMod(spec, { target, check: failing, commit: "bbbbbbb" }),
149 /failed its check, so nothing was changed:\n2 tests failed/,
150 );
151 assert.match(staged, /'0\.1\.0\+bbbbbbb'[\s\S]*core = 2/);
152 assert.deepEqual(contents(target), before);
153 });
155 it("leaves no folder behind when a first install fails its check", () => {
156 const target = join(temp(), "avcs");
157 assert.throws(() => installMod(source(), { target, check: () => "no", commit: "aaaaaaa" }), /nothing was changed/);
158 assert.equal(existsSync(target), false);
159 });
161 it("changes nothing, and checks nothing, when the same files are installed again", () => {
162 const spec = source();
163 const target = join(temp(), "avcs");
164 installMod(spec, { target, check: pass, commit: "aaaaaaa" });
165 const mtime = statSync(at(target, "hooks/register.ts")).mtimeMs;
166 let checked = false;
167 const again = installMod(spec, { target, check: () => ((checked = true), undefined), commit: "aaaaaaa" });
168 assert.equal(again.changed, false);
169 assert.equal(checked, false);
170 assert.equal(statSync(at(target, "hooks/register.ts")).mtimeMs, mtime);
171 });
173 it("keeps what it replaces; a rollback puts it back, and a second rollback undoes the first", () => {
174 const spec = source();
175 const target = join(temp(), "avcs");
176 installMod(spec, { target, check: pass, commit: "aaaaaaa" });
177 write(spec.from, "src/core.ts", "export const core = 2\n");
178 const r = installMod(spec, { target, check: pass, commit: "bbbbbbb" });
179 assert.equal(r.previous, "0.1.0+aaaaaaa");
180 assert.equal(read(target, "src/core.ts.prev"), "export const core = 1\n");
182 const back = rollbackMod(spec, { target });
183 assert.deepEqual(back, { changed: true, version: "0.1.0+aaaaaaa", previous: "0.1.0+bbbbbbb", files: 5 });
184 assert.equal(read(target, "src/core.ts"), "export const core = 1\n");
185 assert.equal(JSON.parse(read(target, ".claude-plugin/plugin.json")).version, "0.1.0+aaaaaaa");
186 assert.match(read(target, "hooks/stamp.ts"), /'0\.1\.0\+aaaaaaa'/);
188 const forward = rollbackMod(spec, { target });
189 assert.equal(forward.version, "0.1.0+bbbbbbb");
190 assert.equal(read(target, "src/core.ts"), "export const core = 2\n");
191 assert.equal(record(target).prev?.version, "0.1.0+aaaaaaa");
192 });
194 it("puts back the files already moved when a rename fails midway", () => {
195 const spec = source();
196 const target = join(temp(), "avcs");
197 installMod(spec, { target, check: pass, commit: "aaaaaaa" });
198 const before = Object.fromEntries(FILES.map((rel) => [rel, read(target, rel)]));
199 write(spec.from, "src/core.ts", "export const core = 2\n");
200 write(spec.from, "hooks/register.ts", "import { core } from '../src/core.ts'\nexport const two = core\n");
201 let n = 0;
202 const flaky = (from: string, to: string) => {
203 if (++n === 3) throw Object.assign(new Error("EPERM: operation not permitted, rename"), { code: "EPERM" });
204 renameSync(from, to);
205 };
206 assert.throws(() => installMod(spec, { target, check: pass, commit: "bbbbbbb", rename: flaky }), /EPERM/);
207 assert.deepEqual(Object.fromEntries(FILES.map((rel) => [rel, read(target, rel)])), before);
208 assert.deepEqual(
209 tree(target).filter((f) => f.endsWith(".next")),
210 [],
211 );
212 assert.equal(record(target).version, "0.1.0+aaaaaaa");
213 assert.equal(record(target).moving, undefined);
214 });
216 it("keeps a mod installed before .avcs-install.json for a rollback", () => {
217 const spec = source();
218 const target = join(temp(), "avcs");
219 // The old installer copied four files and wrote nothing else.
220 for (const rel of FILES.filter((f) => f !== "hooks/stamp.ts")) {
221 mkdirSync(dirname(at(target, rel)), { recursive: true });
222 copyFileSync(at(spec.from, rel), at(target, rel));
223 }
224 const r = installMod(spec, { target, check: pass, commit: "bbbbbbb" });
225 assert.equal(r.previous, "0.1.0");
226 const back = rollbackMod(spec, { target });
227 assert.equal(back.version, "0.1.0");
228 assert.equal(JSON.parse(read(target, ".claude-plugin/plugin.json")).version, "0.1.0");
229 assert.equal(existsSync(at(target, "hooks/stamp.ts")), false);
230 });
232 it("after an install that stopped midway, keeps the last whole install for a rollback", () => {
233 const spec = source();
234 const target = join(temp(), "avcs");
235 installMod(spec, { target, check: pass, commit: "aaaaaaa" });
236 write(spec.from, "src/core.ts", "export const core = 2\n");
237 installMod(spec, { target, check: pass, commit: "bbbbbbb" });
238 // An install of ccccccc that died after its first rename: core.ts is new, the rest is bbbbbbb.
239 for (const rel of FILES) copyFileSync(at(target, rel), at(target, `${rel}.prev`));
240 writeFileSync(
241 at(target, ".avcs-install.json"),
242 JSON.stringify({ ...record(target), prev: { ...record(target), prev: undefined }, moving: "0.1.0+ccccccc" }),
243 );
244 write(target, "src/core.ts", "export const core = 3\n");
246 write(spec.from, "src/core.ts", "export const core = 4\n");
247 const r = installMod(spec, { target, check: pass, commit: "ddddddd" });
248 assert.equal(r.previous, "0.1.0+bbbbbbb");
249 assert.equal(read(target, "src/core.ts.prev"), "export const core = 2\n");
250 rollbackMod(spec, { target });
251 assert.equal(read(target, "src/core.ts"), "export const core = 2\n");
252 });
254 it("refuses while another install holds the lock, and takes over a lock left by one that died", () => {
255 const spec = source();
256 const target = join(temp(), "avcs");
257 installMod(spec, { target, check: pass, commit: "aaaaaaa" });
258 write(spec.from, "src/core.ts", "export const core = 2\n");
259 const lock = at(target, ".avcs-install.lock");
260 writeFileSync(lock, "");
261 assert.throws(() => installMod(spec, { target, check: pass, commit: "bbbbbbb" }), /another install is running/);
262 assert.throws(() => rollbackMod(spec, { target }), /another install is running/);
263 const old = new Date(Date.now() - 11 * 60_000);
264 utimesSync(lock, old, old);
265 assert.equal(installMod(spec, { target, check: pass, commit: "bbbbbbb" }).changed, true);
266 assert.equal(existsSync(lock), false);
267 });
269 it("says so when there is nothing to roll back to", () => {
270 const spec = source();
271 const target = join(temp(), "avcs");
272 assert.throws(() => rollbackMod(spec, { target }), /nothing is installed/);
273 installMod(spec, { target, check: pass, commit: "aaaaaaa" });
274 assert.throws(() => rollbackMod(spec, { target }), /no earlier install is kept/);
275 });
277 it("stamps plugin.json's version plus the last commit that changed the mod's files, and .dirty when they differ from it", {
278 skip: !hasGit,
279 }, () => {
280 const spec = source();
281 const git = (...args: string[]) =>
282 spawnSync("git", ["-c", "user.name=t", "-c", "user.email=t@t", "-C", spec.from, ...args], {
283 encoding: "utf8",
284 }).stdout.trim();
285 git("init", "-q");
286 git("add", ".");
287 git("commit", "-q", "-m", "mod");
288 const mod = git("rev-parse", "--short=7", "HEAD");
289 assert.equal(versionFor(spec), `0.1.0+${mod}`);
290 // A commit that changes none of the mod's files leaves the stamp, so a reinstall changes nothing.
291 write(spec.from, "README.md", "not part of the mod\n");
292 assert.equal(versionFor(spec), `0.1.0+${mod}`);
293 git("add", ".");
294 git("commit", "-q", "-m", "docs");
295 assert.equal(versionFor(spec), `0.1.0+${mod}`);
296 const target = join(temp(), "avcs");
297 installMod(spec, { target, check: pass });
298 assert.equal(installMod(spec, { target, check: pass }).changed, false);
299 write(spec.from, "src/core.ts", "export const core = 2\n");
300 assert.equal(versionFor(spec), `0.1.0+${mod}.dirty`);
301 git("commit", "-q", "-am", "core");
302 assert.equal(versionFor(spec), `0.1.0+${git("rev-parse", "--short=7", "HEAD")}`);
303 // Outside a git checkout there is no commit to add.
304 assert.equal(versionFor(spec, null), "0.1.0");
305 });
307 it("keeps the mod's commit between runs, and asks git again when the checkout or a file moves, or a file is too new to trust", {
308 skip: !hasGit,
309 }, () => {
310 const spec = source();
311 const home = temp();
312 const kept = join(home, ".abso", "mod-commits.json");
313 const git = (...args: string[]) =>
314 spawnSync("git", ["-c", "user.name=t", "-c", "user.email=t@t", "-C", spec.from, ...args], {
315 encoding: "utf8",
316 }).stdout.trim();
317 // Every mod file minutes old, so a kept answer can be trusted. Each call sets a whole minute earlier
318 // than the last: git's own index compares times by the second, and a same-size edit given the time
319 // git last saw would look unchanged to git itself.
320 let minutes = 0;
321 const age = () => {
322 minutes += 1;
323 const old = new Date(Date.now() - minutes * 60_000);
324 for (const rel of FILES) utimesSync(at(spec.from, rel), old, old);
325 };
326 // Swaps every kept answer for a made-up one: what comes back says whether git ran.
327 const plant = () => {
328 const file = JSON.parse(readFileSync(kept, "utf8"));
329 for (const k of Object.keys(file.mods)) file.mods[k].commit = "fffffff";
330 writeFileSync(kept, JSON.stringify(file));
331 };
332 // Not a git checkout yet: no commit, and nothing kept.
333 assert.equal(keptModCommit(spec, home), null);
334 assert.equal(existsSync(kept), false);
335 git("init", "-q");
336 git("add", ".");
337 git("commit", "-q", "-m", "mod");
338 const mod = git("rev-parse", "--short=7", "HEAD");
339 age();
340 assert.equal(keptModCommit(spec, home), mod);
341 plant();
342 assert.equal(keptModCommit(spec, home), "fffffff", "a kept answer is used while nothing moved");
344 // A file changed in the same moment the answer was kept is never trusted, even when its size and time match.
345 // A time a minute ahead stays too new however long the run takes.
346 write(spec.from, "src/core.ts", "export const core = 2\n");
347 const soon = new Date(Date.now() + 60_000);
348 utimesSync(at(spec.from, "src/core.ts"), soon, soon);
349 assert.equal(keptModCommit(spec, home), `${mod}.dirty`);
350 plant();
351 assert.equal(keptModCommit(spec, home), `${mod}.dirty`, "too new to trust: git runs again");
353 // An edit that keeps the size, with its time set back a minute, still isn't the time that was kept.
354 age();
355 assert.equal(keptModCommit(spec, home), `${mod}.dirty`);
356 plant();
357 write(spec.from, "src/core.ts", "export const core = 3\n");
358 age();
359 assert.equal(keptModCommit(spec, home), `${mod}.dirty`);
361 // A commit moves the checkout.
362 git("commit", "-q", "-am", "core");
363 age();
364 const next = git("rev-parse", "--short=7", "HEAD");
365 assert.equal(keptModCommit(spec, home), next);
366 plant();
367 git("commit", "-q", "--allow-empty", "-m", "empty");
368 assert.equal(keptModCommit(spec, home), next, "a new commit asks git again");
370 // A file it can't read, or doesn't know the format of, is the same as none.
371 plant();
372 writeFileSync(kept, JSON.stringify({ format: 2, mods: JSON.parse(readFileSync(kept, "utf8")).mods }));
373 assert.equal(keptModCommit(spec, home), next);
374 writeFileSync(kept, "not json");
375 assert.equal(keptModCommit(spec, home), next);
376 });
377});
379describe("which client this is", () => {
380 const git = (cwd: string, ...args: string[]) =>
381 spawnSync(
382 "git",
383 ["-c", "user.name=t", "-c", "user.email=t@t", "-c", "init.defaultBranch=main", "-C", cwd, ...args],
384 { encoding: "utf8" },
385 ).stdout.trim();
387 it("reads the commit from .git as git does: a branch, a packed branch, a detached head, a worktree", {
388 skip: !hasGit,
389 }, () => {
390 const repo = temp();
391 git(repo, "init", "-q");
392 write(repo, "a/b/file.txt", "one\n");
393 git(repo, "add", ".");
394 git(repo, "commit", "-q", "-m", "one");
395 assert.equal(headCommit(join(repo, "a", "b")), git(repo, "rev-parse", "--short=7", "HEAD"));
396 write(repo, "a/b/file.txt", "two\n");
397 git(repo, "commit", "-q", "-am", "two");
398 git(repo, "pack-refs", "--all");
399 assert.equal(existsSync(join(repo, ".git", "refs", "heads", "main")), false);
400 assert.equal(headCommit(repo), git(repo, "rev-parse", "--short=7", "HEAD"));
401 const first = git(repo, "rev-parse", "--short=7", "HEAD~1");
402 git(repo, "checkout", "-q", "--detach", "HEAD~1");
403 assert.equal(headCommit(repo), first);
404 const wt = join(temp(), "wt");
405 git(repo, "worktree", "add", "-q", "-b", "side", wt, "main");
406 write(wt, "a/b/file.txt", "three\n");
407 git(wt, "commit", "-q", "-am", "three");
408 assert.equal(headCommit(join(wt, "a")), git(wt, "rev-parse", "--short=7", "HEAD"));
409 assert.notEqual(headCommit(wt), headCommit(repo));
410 });
412 it("has no commit outside a repository", () => {
413 assert.equal(headCommit(temp()), undefined);
414 });
416 it("avcs --version names this client's version and the mods installed, and which are from another commit", async () => {
417 const config = temp();
418 const spec = source();
419 installMod(spec, {
420 target: join(config, "skills", "abso-hooks"),
421 check: pass,
422 commit: "aaaaaaa",
423 now: new Date("2026-10-05T04:30:00Z"),
424 });
425 const out = await main(["--version"], { cwd: config, env: { CLAUDE_CONFIG_DIR: config }, write: () => {} });
426 const [client, mod, view] = out.stdout.trimEnd().split("\n");
427 assert.equal(out.exit, 0);
428 assert.equal(client, `abso ${clientVersion()} (${dirname(import.meta.dirname)})`);
429 assert.match(
430 mod!,
431 /^the abso-hooks mod: 0\.1\.0\+aaaaaaa in .*skills[\\/]abso-hooks, installed 2026-10-05 04:30 UTC; this client has 0.2.0(\+[0-9a-f]{7}(\.dirty)?)?: /,
432 );
433 assert.ok(mod!.endsWith(`: ${installerCommand("install-mod.ts")} installs it`), mod);
434 assert.equal(view, `the abso-view mod: not installed (${installerCommand("install-view.ts")})`);
435 const json = JSON.parse(
436 (await main(["--version", "--json"], { cwd: config, env: { CLAUDE_CONFIG_DIR: config }, write: () => {} }))
437 .stdout,
438 );
439 assert.equal(json.client, clientVersion());
440 assert.equal(json.mods[0].version, "0.1.0+aaaaaaa");
441 });
443 it("moves the old avcs mod folder out of the skills folder, not deleting it, once abso-hooks is in", () => {
444 const config = temp();
445 const old = join(config, "skills", "avcs");
446 write(old, ".claude-plugin/plugin.json", '{"name":"avcs","version":"0.1.0"}');
447 const home = temp();
448 const was = process.env.USERPROFILE;
449 const was2 = process.env.HOME;
450 process.env.USERPROFILE = home;
451 process.env.HOME = home;
452 try {
453 const to = retireOldMod(AVCS_MOD, { CLAUDE_CONFIG_DIR: config });
454 assert.ok(to?.startsWith(join(home, ".abso", "retired-mods")));
455 assert.equal(existsSync(old), false);
456 assert.equal(existsSync(join(to!, ".claude-plugin", "plugin.json")), true);
457 assert.equal(retireOldMod(AVCS_MOD, { CLAUDE_CONFIG_DIR: config }), undefined);
458 } finally {
459 if (was === undefined) delete process.env.USERPROFILE;
460 else process.env.USERPROFILE = was;
461 if (was2 === undefined) delete process.env.HOME;
462 else process.env.HOME = was2;
463 }
464 });
466 it("status says when an installed mod is behind this client, where the client knows its commit (abso issue 41)", () => {
467 const config = temp();
468 const env = { CLAUDE_CONFIG_DIR: config };
469 assert.deepEqual(modsBehindText(env), [], "nothing installed, nothing to say");
470 installMod(source(), {
471 target: join(config, "skills", "abso-hooks"),
472 check: pass,
473 commit: "aaaaaaa",
474 now: new Date("2026-10-05T04:30:00Z"),
475 });
476 const current = (versionReport(env).json.mods as { current: string }[])[0]!.current;
477 if (/\+[0-9a-f]{7}$/.test(current))
478 assert.deepEqual(modsBehindText(env), [
479 `The ${AVCS_MOD.name} mod installed on this machine is 0.1.0+aaaaaaa, and this client has ${current}: ${installerCommand("install-mod.ts")} installs it (new chats load it).`,
480 ]);
481 // A client outside git (an abso folder, a box) can't tell, so it says nothing.
482 else assert.deepEqual(modsBehindText(env), []);
483 });
485 it("the command-line client says which client it is with every call", () => {
486 const headers = new Api({
487 server: "https://avcs.test",
488 project: "p",
489 agent: "a",
490 token: "t",
491 } as ConstructorParameters<typeof Api>[0]).headers("application/json");
492 assert.equal(headers["x-abso-client"], `abso-cli/${clientVersion()}`);
493 assert.match(clientVersion(), /^\d+\.\d+\.\d+(\+[0-9a-f]{7})?$/);
494 });
496 it("the npm package's client gives the package's version", () => {
497 const url = new URL("../src/client-version.ts", import.meta.url).href;
498 const script = `globalThis.__ABSO_PACKAGE_VERSION__ = "0.58.0"; const m = await import(${JSON.stringify(url)}); console.log(m.clientVersion());`;
499 const r = spawnSync(process.execPath, ["--input-type=module", "-e", script], { encoding: "utf8" });
500 assert.equal(r.stdout.trim(), "0.58.0", r.stderr);
501 });
502});