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