- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/install.ts?draft=names-only-client&format=json
556 linesFirst import 87% · speed 11% · pinch 2% · review 1%Last change pinch in version 1, 1 version changed it
1// Installing a mod without breaking the sessions that run it (#29). The abso-hooks
2// and abso-view mods are folders in Claude Code's skills folder, which every
3// session on the machine loads when it starts (an open chat keeps the mod it
4// started with, #37). So an install (client/install-mod.ts, client/install-view.ts):
5//
6// 1. Stages the new files in a temp folder. plugin.json's version gets the
7// last commit that changed the mod's own files (0.1.0+702c616, or
8// 0.1.0+702c616.dirty when they differ from it), and hooks/stamp.ts says
9// the same, so the mod sends it with each call to the server
10// (X-Abso-Client). A commit that changes none of them changes nothing to
11// install, and nothing to restart for.
12// 2. Checks the staged copy: `claude plugin validate`, then the mod's own
13// tests in Claude Code's plugin test kit. If either fails, nothing in the
14// installed folder changes.
15// 3. Keeps each installed file as <file>.prev, then moves each new file into
16// place with a rename, so no session reads a half-written file: what the
17// hook imports first, plugin.json last. If a rename fails, the files
18// already moved are put back.
19//
20// The renames follow each other within a few milliseconds, but a session can
21// still start between two of them. With what the hook imports going in
22// first, a new hook never loads without its imports; a core.ts that drops an
23// export the old hook uses can fail that one start, and a restart after the
24// install brings the whole new mod.
25//
26// A rollback swaps the .prev files back in, and the files it replaces become
27// the .prev ones, so a second rollback undoes the first. .avcs-install.json
28// in the mod's folder says what is installed and what the .prev files hold.
29// `abso --version` reports the installed mods (versionReport).
31import { spawnSync } from "node:child_process";
32import {
33 closeSync,
34 copyFileSync,
35 existsSync,
36 mkdirSync,
37 mkdtempSync,
38 openSync,
39 readFileSync,
40 renameSync,
41 rmdirSync,
42 rmSync,
43 statSync,
44 writeFileSync,
45} from "node:fs";
46import { homedir, tmpdir } from "node:os";
47import { dirname, join, resolve } from "node:path";
48import { CLIENT_DIR, clientPlace, clientVersion, headCommit } from "./client-version.ts";
50export interface ModSpec {
51 /** The mod's name, as its plugin.json has it. */
52 readonly name: string;
53 /** The folder its files come from. */
54 readonly from: string;
55 /** Its files, relative to `from`, in the order they go into place: what the hook imports first, plugin.json last. */
56 readonly files: readonly string[];
57 /** Its tests for the plugin test kit, relative to `from`: staged for the check, never installed. */
58 readonly test?: string;
59}
61/** One install, as .avcs-install.json records it. */
62export interface Install {
63 readonly version: string;
64 /** In the order they went into place. */
65 readonly files: readonly string[];
66 readonly from: string;
67 readonly at: string;
68}
70export interface InstallRecord extends Install {
71 readonly mod: string;
72 /** What the .prev files hold. */
73 readonly prev?: Install;
74 /** Set while files are being moved into place; still set means an install stopped midway. */
75 readonly moving?: string;
76}
78export interface Installed {
79 /** False when the folder already had exactly these files. */
80 readonly changed: boolean;
81 readonly version: string;
82 /** The version the .prev files now hold. */
83 readonly previous: string | undefined;
84 readonly files: number;
85}
87export interface InstallOptions {
88 /** The mod's folder: in the skills folder, or a scratch folder. */
89 readonly target: string;
90 /** Checks a staged copy of the mod: undefined when it passes, else why not. */
91 readonly check: (dir: string) => string | undefined;
92 /** For tests: the commit to stamp (null: none), instead of asking git. */
93 readonly commit?: string | null;
94 /** For tests: the rename that moves each file into place. */
95 readonly rename?: (from: string, to: string) => void;
96 readonly now?: Date;
97}
99const RECORD = ".avcs-install.json";
100const LOCK = ".avcs-install.lock";
101const MANIFEST = ".claude-plugin/plugin.json";
102const STAMP_FILE = "hooks/stamp.ts";
103/** A lock older than this was left by an install that died. */
104const STALE_LOCK_MS = 10 * 60_000;
106const at = (dir: string, rel: string, suffix = "") => join(dir, ...rel.split("/")) + suffix;
108/** The abso mod: what the hook imports first, plugin.json last. src/core.ts is the only client file it imports. */
109export const HOOKS_MOD: ModSpec = {
110 name: "abso-hooks",
111 from: CLIENT_DIR,
112 files: ["src/core.ts", "hooks/stamp.ts", "hooks/register.ts", "hooks/hooks.json", ".claude-plugin/plugin.json"],
113 test: "hooks/register.test.ts",
114};
116/** The abso-view mod (#12), from client/view. */
117export const VIEW_MOD: ModSpec = {
118 name: "abso-view",
119 from: join(CLIENT_DIR, "view"),
120 files: ["types/index.d.ts", "hooks/stamp.ts", "hooks/register.tsx", "hooks/hooks.json", ".claude-plugin/plugin.json"],
121 test: "hooks/register.test.ts",
122};
124/** Where Claude Code's skills folder keeps a mod. */
125export const skillsFolder = (name: string, env: Readonly<Record<string, string | undefined>> = process.env) =>
126 join(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "skills", name);
128export const modInstalled = (env: Readonly<Record<string, string | undefined>> = process.env) =>
129 existsSync(at(skillsFolder(HOOKS_MOD.name, env), MANIFEST));
131/** The version an install of `spec` gets: plugin.json's, plus the last commit that changed its files (and .dirty when they differ from it). */
132export function versionFor(spec: ModSpec, commit?: string | null): string {
133 const manifest = JSON.parse(readFileSync(at(spec.from, MANIFEST), "utf8")) as { version?: unknown };
134 const base = String(manifest.version ?? "0.0.0").split("+")[0]!;
135 const c = commit === undefined ? modCommit(spec) : commit;
136 return c ? `${base}+${c}` : base;
137}
139function modCommit(spec: ModSpec): string | null {
140 const git = (...args: string[]) => spawnSync("git", ["-C", spec.from, ...args], { encoding: "utf8" });
141 const last = git("log", "-1", "--format=%H", "--", ...spec.files);
142 if (last.status !== 0 || !/^[0-9a-f]{40}/.test(last.stdout)) return null;
143 const changed = git("status", "--porcelain", "--", ...spec.files).stdout.trim() !== "";
144 return `${last.stdout.slice(0, 7)}${changed ? ".dirty" : ""}`;
145}
147/** A file changed this close to when an answer was kept can't be told apart from one changed just after it. */
148const RACY_MS = 2_000;
150interface KeptModCommit {
151 readonly head: string;
152 readonly files: readonly string[];
153 readonly at: number;
154 readonly commit: string | null;
155}
157/**
158 * modCommit for the version report, which `abso status` asks on every run: it runs git twice per mod, so
159 * the answer is kept in ~/.abso/mod-commits.json. A kept answer holds while the checkout's commit (read
160 * from .git, without git) and each of the mod's files (size, modified time, inode) are as they were, and
161 * every file was changed clearly before the answer was kept; anything else asks git again. Outside a git
162 * checkout there is no commit, and git isn't run at all.
163 */
164export function keptModCommit(spec: ModSpec, home: string = homedir()): string | null {
165 const head = headCommit(spec.from);
166 if (head === undefined) return null;
167 const at = Date.now();
168 const files = spec.files.map((rel) => {
169 try {
170 const s = statSync(join(spec.from, ...rel.split("/")));
171 return `${s.size}:${s.mtimeMs}:${s.ino}`;
172 } catch {
173 return "-";
174 }
175 });
176 const newest = Math.max(...files.map((f) => (f === "-" ? 0 : Number(f.split(":")[1]))));
177 const path = join(home, ".abso", "mod-commits.json");
178 const key = `${resolve(spec.from)}|${spec.files.join("|")}`;
179 let kept: Record<string, KeptModCommit> = {};
180 try {
181 const parsed = JSON.parse(readFileSync(path, "utf8")) as { format?: unknown; mods?: unknown };
182 if (parsed.format === 1 && typeof parsed.mods === "object" && parsed.mods !== null)
183 kept = parsed.mods as Record<string, KeptModCommit>;
184 } catch {}
185 const was = kept[key];
186 if (
187 was !== undefined &&
188 was.head === head &&
189 Array.isArray(was.files) &&
190 was.files.join() === files.join() &&
191 newest < was.at - RACY_MS
192 )
193 return was.commit;
194 const commit = modCommit(spec);
195 try {
196 mkdirSync(dirname(path), { recursive: true });
197 const next = `${path}.${process.pid}.tmp`;
198 writeFileSync(next, JSON.stringify({ format: 1, mods: { ...kept, [key]: { head, files, at, commit } } }));
199 renameSync(next, path);
200 } catch {
201 // Best effort: the next run asks git again.
202 }
203 return commit;
204}
206/** The files to install, stamped with `version`, in install order. */
207function filesFor(spec: ModSpec, version: string): Map<string, Buffer> {
208 if (!/^[\w.+-]+$/.test(version)) throw new Error(`can't stamp the version ${JSON.stringify(version)}`);
209 const out = new Map<string, Buffer>();
210 for (const rel of spec.files) {
211 let data = readFileSync(at(spec.from, rel));
212 if (rel === MANIFEST) {
213 const manifest = JSON.parse(data.toString("utf8")) as Record<string, unknown>;
214 data = Buffer.from(`${JSON.stringify({ ...manifest, version }, null, 2)}\n`);
215 } else if (rel === STAMP_FILE) {
216 const text = data.toString("utf8");
217 const stamped = text.replace(/(STAMP[^=\n]*=\s*)undefined/, `$1'${version}'`);
218 if (stamped === text) throw new Error(`${rel} has no "STAMP ... = undefined" line to stamp`);
219 data = Buffer.from(stamped);
220 }
221 out.set(rel, data);
222 }
223 return out;
224}
226function readRecord(target: string): InstallRecord | undefined {
227 try {
228 return JSON.parse(readFileSync(join(target, RECORD), "utf8")) as InstallRecord;
229 } catch {
230 return undefined;
231 }
232}
234function writeRecord(target: string, record: InstallRecord): void {
235 writeFileSync(join(target, `${RECORD}.next`), `${JSON.stringify(record, null, 2)}\n`);
236 renameRetrying(join(target, `${RECORD}.next`), join(target, RECORD));
237}
239/** What is installed now. A folder from before .avcs-install.json: the spec's files that are there. */
240function installedNow(spec: ModSpec, target: string, record: InstallRecord | undefined): Install | undefined {
241 const files = (record?.files ?? spec.files).filter((rel) => existsSync(at(target, rel)));
242 if (files.length === 0) return undefined;
243 if (record) return { version: record.version, files, from: record.from, at: record.at };
244 let version = "unknown";
245 try {
246 version = String(
247 (JSON.parse(readFileSync(at(target, MANIFEST), "utf8")) as { version?: unknown }).version ?? version,
248 );
249 } catch {}
250 return { version, files, from: "unknown", at: "unknown" };
251}
253/** Sleeps without an event loop, between tries of a rename. */
254function pause(ms: number): void {
255 Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
256}
258/** A rename, tried for about a second while Windows says another process has the file open. */
259function renameRetrying(from: string, to: string): void {
260 for (let i = 0; ; i++) {
261 try {
262 renameSync(from, to);
263 return;
264 } catch (err) {
265 const code = (err as NodeJS.ErrnoException).code ?? "";
266 if (i >= 20 || !["EPERM", "EBUSY", "EACCES"].includes(code)) throw err;
267 pause(50);
268 }
269 }
270}
272/** Holds the mod folder's lock while fn runs. */
273function locked<T>(target: string, fn: () => T): T {
274 const file = join(target, LOCK);
275 try {
276 if (Date.now() - statSync(file).mtimeMs > STALE_LOCK_MS) rmSync(file, { force: true });
277 } catch {}
278 try {
279 closeSync(openSync(file, "wx"));
280 } catch {
281 throw new Error(`another install is running in ${target} (it holds ${LOCK}; if none is, delete that file)`);
282 }
283 try {
284 return fn();
285 } finally {
286 rmSync(file, { force: true });
287 }
288}
290/**
291 * Moves `next` into place in the mod's folder, keeping the files that were
292 * there as .prev files. Each file goes in with a rename, in `next`'s order;
293 * if one fails, the ones already moved are put back and the error is thrown.
294 */
295function moveIn(
296 spec: ModSpec,
297 target: string,
298 next: ReadonlyMap<string, Buffer>,
299 install: Install,
300 rename: (from: string, to: string) => void,
301): Install | undefined {
302 const record = readRecord(target);
303 const current = installedNow(spec, target, record);
304 // After an install that stopped midway, the folder is a mix and the .prev files still hold the last whole install.
305 const prev = record?.moving ? record.prev : current;
306 if (!record?.moving) {
307 for (const rel of new Set([...(record?.prev?.files ?? []), ...(current?.files ?? [])]))
308 rmSync(at(target, rel, ".prev"), { force: true });
309 for (const rel of current?.files ?? []) copyFileSync(at(target, rel), at(target, rel, ".prev"));
310 }
311 const before: InstallRecord = { mod: spec.name, ...(current ?? install), ...(prev ? { prev } : {}) };
312 writeRecord(target, { ...before, moving: install.version });
314 const moved: string[] = [];
315 try {
316 for (const [rel, data] of next) {
317 mkdirSync(dirname(at(target, rel)), { recursive: true });
318 writeFileSync(at(target, rel, ".next"), data);
319 }
320 for (const rel of next.keys()) {
321 rename(at(target, rel, ".next"), at(target, rel));
322 moved.push(rel);
323 }
324 } catch (err) {
325 for (const rel of moved.reverse()) {
326 if (prev?.files.includes(rel)) {
327 copyFileSync(at(target, rel, ".prev"), at(target, rel, ".next"));
328 renameRetrying(at(target, rel, ".next"), at(target, rel));
329 } else {
330 rmSync(at(target, rel), { force: true });
331 }
332 }
333 for (const rel of next.keys()) rmSync(at(target, rel, ".next"), { force: true });
334 if (current) writeRecord(target, before);
335 else rmSync(join(target, RECORD), { force: true });
336 throw err;
337 }
338 // Files the old install had and this one doesn't.
339 for (const rel of current?.files ?? []) if (!next.has(rel)) rmSync(at(target, rel), { force: true });
340 writeRecord(target, { mod: spec.name, ...install, ...(prev ? { prev } : {}) });
341 return prev;
342}
344/** Whether the folder holds exactly `next`. */
345function holds(target: string, files: readonly string[], next: ReadonlyMap<string, Buffer>): boolean {
346 return (
347 files.length === next.size && files.every((rel) => next.get(rel)?.equals(readFileSync(at(target, rel))) ?? false)
348 );
349}
351/** Removes the folders a first install made, if they are empty. */
352function removeEmpty(target: string, files: Iterable<string>): void {
353 const dirs = new Set<string>();
354 for (const rel of files) for (let d = dirname(at(target, rel)); d.length > target.length; d = dirname(d)) dirs.add(d);
355 for (const d of [...dirs, target].sort((a, b) => b.length - a.length)) {
356 try {
357 rmdirSync(d);
358 } catch {}
359 }
360}
362/** Installs the mod from `spec.from` into `options.target` (see the top of this file). */
363export function installMod(spec: ModSpec, options: InstallOptions): Installed {
364 const target = resolve(options.target);
365 const version = versionFor(spec, options.commit);
366 const next = filesFor(spec, version);
367 const existed = existsSync(target);
368 mkdirSync(target, { recursive: true });
369 try {
370 return locked(target, () => {
371 const record = readRecord(target);
372 const current = installedNow(spec, target, record);
373 if (!record?.moving && current && holds(target, current.files, next)) {
374 return { changed: false, version, previous: record?.prev?.version, files: next.size };
375 }
376 const staged = mkdtempSync(join(tmpdir(), `${spec.name}-install-`));
377 try {
378 for (const [rel, data] of next) {
379 mkdirSync(dirname(at(staged, rel)), { recursive: true });
380 writeFileSync(at(staged, rel), data);
381 }
382 const why = options.check(staged);
383 if (why !== undefined) throw new Error(`the staged copy failed its check, so nothing was changed:\n${why}`);
384 } finally {
385 rmSync(staged, { recursive: true, force: true });
386 }
387 const install: Install = {
388 version,
389 files: [...next.keys()],
390 from: spec.from,
391 at: (options.now ?? new Date()).toISOString(),
392 };
393 const prev = moveIn(spec, target, next, install, options.rename ?? renameRetrying);
394 return { changed: true, version, previous: prev?.version, files: next.size };
395 });
396 } catch (err) {
397 // A first install that didn't happen leaves no folder behind.
398 if (!existed) removeEmpty(target, next.keys());
399 throw err;
400 }
401}
403/** Puts the install kept in the .prev files back; the one it replaces becomes the .prev one. */
404export function rollbackMod(spec: ModSpec, options: Pick<InstallOptions, "target" | "rename" | "now">): Installed {
405 const target = resolve(options.target);
406 if (!existsSync(target)) throw new Error(`nothing is installed in ${target}`);
407 return locked(target, () => {
408 const record = readRecord(target);
409 const prev = record?.prev;
410 if (!prev) throw new Error(`no earlier install is kept in ${target}`);
411 const missing = prev.files.filter((rel) => !existsSync(at(target, rel, ".prev")));
412 if (missing.length > 0)
413 throw new Error(
414 `the earlier install's ${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} missing from ${target}`,
415 );
416 const next = new Map(prev.files.map((rel) => [rel, readFileSync(at(target, rel, ".prev"))]));
417 const kept = moveIn(spec, target, next, prev, options.rename ?? renameRetrying);
418 return { changed: true, version: prev.version, previous: kept?.version, files: next.size };
419 });
420}
422/** `claude plugin validate`, then the mod's own tests in Claude Code's plugin test kit, on a staged copy. */
423export function checkWithClaude(spec: ModSpec): (dir: string) => string | undefined {
424 // claude is a .cmd on Windows, so it runs through the shell; the folder is quoted.
425 const claude = (what: string, dir: string) =>
426 spawnSync(`claude plugin ${what} "${dir}"`, { shell: true, encoding: "utf8", timeout: 180_000 });
427 const tail = (r: { stdout: string; stderr: string }) =>
428 `${r.stdout ?? ""}${r.stderr ?? ""}`.trim().split("\n").slice(-15).join("\n");
429 return (dir) => {
430 const valid = claude("validate", dir);
431 if (valid.status !== 0) return `claude plugin validate failed (--unchecked skips the check):\n${tail(valid)}`;
432 if (spec.test === undefined) return undefined;
433 copyFileSync(at(spec.from, spec.test), at(dir, spec.test));
434 const tests = claude("test", dir);
435 if (tests.status !== 0) return `the mod's tests failed on the staged copy:\n${tail(tests)}`;
436 return undefined;
437 };
438}
440/** The installers' command line: [folder] [--rollback] [--unchecked]. */
441export function runInstaller(
442 spec: ModSpec,
443 script: string,
444 defaultTarget: string,
445 argv: readonly string[] = process.argv.slice(2),
446): void {
447 const options = argv.filter((a) => a.startsWith("--"));
448 const folders = argv.filter((a) => !a.startsWith("--"));
449 const unknown = options.find((o) => o !== "--rollback" && o !== "--unchecked");
450 if (unknown !== undefined || folders.length > 1) {
451 console.error(
452 `usage: node client/${script} [folder] [--rollback] [--unchecked]${unknown ? ` (unknown option ${unknown})` : ""}`,
453 );
454 process.exit(2);
455 }
456 const target = resolve(folders[0] ?? defaultTarget);
457 try {
458 if (options.includes("--rollback")) {
459 const r = rollbackMod(spec, { target });
460 console.log(
461 `Rolled the ${spec.name} mod back to ${r.version} in ${target}. ${r.previous ? `${r.previous} is kept; --rollback again puts it back. ` : ""}Restart open chats to load it.`,
462 );
463 return;
464 }
465 const unchecked = options.includes("--unchecked");
466 const r = installMod(spec, { target, check: unchecked ? () => undefined : checkWithClaude(spec) });
467 // Only for the real skills folder: an install to another folder leaves the old mod alone.
468 if (!r.changed) {
469 console.log(`The ${spec.name} mod ${r.version} is already installed in ${target}; nothing changed.`);
470 return;
471 }
472 const kept = r.previous ? ` The one it replaced (${r.previous}) is kept; --rollback puts it back.` : "";
473 console.log(
474 `Installed the ${spec.name} mod ${r.version} in ${target} (${r.files} files${unchecked ? ", unchecked" : ", validated and tested first"}).${kept} New chats load it; restart open ones to load it.`,
475 );
476 } catch (err) {
477 console.error(
478 `The ${spec.name} mod was not ${options.includes("--rollback") ? "rolled back" : "installed"}: ${(err as Error).message}`,
479 );
480 process.exit(1);
481 }
482}
484export interface ModInstall {
485 readonly name: string;
486 readonly folder: string;
487 /** Undefined when it isn't installed. */
488 readonly version: string | undefined;
489 /** When it was installed (mods installed before .avcs-install.json have none). */
490 readonly at: string | undefined;
491 /** What an install from this client would stamp now. */
492 readonly current: string;
493}
495/** `abso --version`: this client, and the mods installed on this machine, compared with this client's. */
496export function versionReport(env: Readonly<Record<string, string | undefined>>): {
497 text: string;
498 json: Record<string, unknown>;
499} {
500 const client = clientVersion();
501 const lines = [`abso ${client} (${clientPlace()})`];
502 const mods: ModInstall[] = [];
503 for (const [spec, installer] of [
504 [HOOKS_MOD, "install-mod.ts"],
505 [VIEW_MOD, "install-view.ts"],
506 ] as const) {
507 const folder = skillsFolder(spec.name, env);
508 const field = (rel: string, key: string): string | undefined => {
509 try {
510 const value = (JSON.parse(readFileSync(at(folder, rel), "utf8")) as Record<string, unknown>)[key];
511 return typeof value === "string" ? value : undefined;
512 } catch {
513 return undefined;
514 }
515 };
516 const m: ModInstall = {
517 name: spec.name,
518 folder,
519 version: field(MANIFEST, "version"),
520 at: field(RECORD, "at"),
521 current: (() => {
522 try {
523 return versionFor(spec, keptModCommit(spec));
524 } catch {
525 return "not in this copy";
526 }
527 })(),
528 };
529 mods.push(m);
530 if (m.version === undefined) {
531 lines.push(`the ${m.name} mod: not installed (node client/${installer})`);
532 continue;
533 }
534 const when = m.at ? `, installed ${m.at.slice(0, 16).replace("T", " ")} UTC` : "";
535 const behind =
536 m.version === m.current ? "" : `; this client has ${m.current}: node client/${installer} installs it`;
537 lines.push(`the ${m.name} mod: ${m.version} in ${m.folder}${when}${behind}`);
538 }
539 return { text: lines.join("\n"), json: { client, folder: CLIENT_DIR, mods } };
540}
542/**
543 * For `abso status` (abso issue 41: every chat ran a mod a day behind main,
544 * and only `--version` would have said so): each installed mod this client
545 * would install differently. Says nothing unless this client knows its mod's
546 * commit (a git checkout, as the shared one is) and the installed one has one.
547 */
548export function modsBehindText(env: Readonly<Record<string, string | undefined>>): string[] {
549 const installers: Record<string, string> = { [HOOKS_MOD.name]: "install-mod.ts", [VIEW_MOD.name]: "install-view.ts" };
550 return (versionReport(env).json.mods as ModInstall[])
551 .filter((m) => m.version?.includes("+") && /\+[0-9a-f]{7}$/.test(m.current) && m.version !== m.current)
552 .map(
553 (m) =>
554 `The ${m.name} mod installed on this machine is ${m.version}, and this client has ${m.current}: node client/${installers[m.name]} installs it (new chats load it).`,
555 );
556}